code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
#ifndef IMAGECONVERTER_HPP #define IMAGECONVERTER_HPP #include <QImage> #include <QDebug> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include "Logger.hpp" class ImageConverter { public: ImageConverter() = default; static QImage Mat2QImage(const cv::Mat &cvImage); static cv::Mat QImage2Mat(const QImage& image); }; #endif // IMAGECONVERTER_HPP
czimbortibor/Large-annotated-image-collection-management
utils/ImageConverter.hpp
C++
gpl-3.0
378
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Description Interpolation class dealing with transfer of data between two primitivePatches \*---------------------------------------------------------------------------*/ #include "PatchToPatchInterpolation_.H" #include <OpenFOAM/demandDrivenData.H> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // template<class FromPatch, class ToPatch> const scalar PatchToPatchInterpolation<FromPatch, ToPatch>::directHitTol = 1e-5; // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // template<class FromPatch, class ToPatch> const labelList& PatchToPatchInterpolation<FromPatch, ToPatch>::pointAddr() const { if (!pointAddressingPtr_) { calcPointAddressing(); } return *pointAddressingPtr_; } template<class FromPatch, class ToPatch> const FieldField<Field, scalar>& PatchToPatchInterpolation<FromPatch, ToPatch>::pointWeights() const { if (!pointWeightsPtr_) { calcPointAddressing(); } return *pointWeightsPtr_; } template<class FromPatch, class ToPatch> const labelList& PatchToPatchInterpolation<FromPatch, ToPatch>::faceAddr() const { if (!faceAddressingPtr_) { calcFaceAddressing(); } return *faceAddressingPtr_; } template<class FromPatch, class ToPatch> const FieldField<Field, scalar>& PatchToPatchInterpolation<FromPatch, ToPatch>::faceWeights() const { if (!faceWeightsPtr_) { calcFaceAddressing(); } return *faceWeightsPtr_; } template<class FromPatch, class ToPatch> void PatchToPatchInterpolation<FromPatch, ToPatch>::clearOut() { deleteDemandDrivenData(pointAddressingPtr_); deleteDemandDrivenData(pointWeightsPtr_); deleteDemandDrivenData(pointDistancePtr_); deleteDemandDrivenData(faceAddressingPtr_); deleteDemandDrivenData(faceWeightsPtr_); deleteDemandDrivenData(faceDistancePtr_); } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Construct from components template<class FromPatch, class ToPatch> PatchToPatchInterpolation<FromPatch, ToPatch>::PatchToPatchInterpolation ( const FromPatch& fromPatch, const ToPatch& toPatch, intersection::algorithm alg, const intersection::direction dir ) : fromPatch_(fromPatch), toPatch_(toPatch), alg_(alg), dir_(dir), pointAddressingPtr_(NULL), pointWeightsPtr_(NULL), pointDistancePtr_(NULL), faceAddressingPtr_(NULL), faceWeightsPtr_(NULL), faceDistancePtr_(NULL) {} // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // template<class FromPatch, class ToPatch> PatchToPatchInterpolation<FromPatch, ToPatch>::~PatchToPatchInterpolation() { clearOut(); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class FromPatch, class ToPatch> const scalarField& PatchToPatchInterpolation<FromPatch, ToPatch> ::pointDistanceToIntersection() const { if (!pointDistancePtr_) { calcPointAddressing(); } return *pointDistancePtr_; } template<class FromPatch, class ToPatch> const scalarField& PatchToPatchInterpolation<FromPatch, ToPatch> ::faceDistanceToIntersection() const { if (!faceDistancePtr_) { calcFaceAddressing(); } return *faceDistancePtr_; } template<class FromPatch, class ToPatch> bool PatchToPatchInterpolation<FromPatch, ToPatch>::movePoints() { clearOut(); return true; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // # include <OpenFOAM/CalcPatchToPatchWeights.C> # include <OpenFOAM/PatchToPatchInterpolate.C> // ************************ vim: set sw=4 sts=4 et: ************************ //
themiwi/freefoam-debian
src/OpenFOAM/interpolations/patchToPatchInterpolation/PatchToPatchInterpolation_.C
C++
gpl-3.0
5,000
/** @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ import"../iron-iconset-svg.js";import{html as c}from"../../polymer/lib/utils/html-tag.js";const t=c`<iron-iconset-svg name="svg-sample-icons" size="100"> <svg> <defs> <g id="codepen"> <path class="outer-ring" d="M50,0C22.385,0,0,22.385,0,50c0,27.615,22.385,50,50,50c27.614,0,50-22.385,50-50C100,22.385,77.615,0,50,0z M50,91.789 C26.958,91.789,8.212,73.042,8.212,50C8.212,26.958,26.958,8.212,50,8.212c23.042,0,41.788,18.747,41.788,41.789 C91.788,73.042,73.042,91.789,50,91.789z"></path> <path class="inner-logo" d="M80.893,40.234c-0.006-0.039-0.016-0.076-0.022-0.115c-0.013-0.075-0.027-0.15-0.046-0.223 c-0.012-0.044-0.028-0.086-0.042-0.128c-0.021-0.065-0.042-0.13-0.068-0.193c-0.018-0.044-0.039-0.088-0.059-0.13 c-0.028-0.06-0.057-0.119-0.09-0.175c-0.024-0.042-0.051-0.083-0.076-0.124c-0.036-0.055-0.073-0.109-0.112-0.161 c-0.029-0.039-0.06-0.078-0.091-0.115c-0.042-0.049-0.086-0.098-0.132-0.143c-0.035-0.036-0.069-0.072-0.106-0.104 c-0.049-0.044-0.099-0.086-0.15-0.127c-0.04-0.031-0.079-0.062-0.12-0.091c-0.016-0.01-0.029-0.023-0.044-0.033L51.474,19.531 c-0.893-0.595-2.055-0.595-2.947,0L20.267,38.371c-0.015,0.01-0.028,0.023-0.044,0.033c-0.042,0.029-0.081,0.06-0.12,0.091 c-0.052,0.041-0.102,0.083-0.15,0.127c-0.037,0.032-0.071,0.068-0.106,0.104c-0.046,0.045-0.09,0.094-0.132,0.143 c-0.031,0.038-0.062,0.077-0.092,0.115c-0.039,0.052-0.076,0.106-0.111,0.161c-0.027,0.041-0.052,0.082-0.076,0.124 c-0.033,0.057-0.062,0.115-0.09,0.175c-0.021,0.042-0.042,0.086-0.06,0.13c-0.026,0.063-0.047,0.128-0.068,0.193 c-0.014,0.042-0.029,0.084-0.042,0.128c-0.02,0.073-0.032,0.148-0.046,0.223c-0.006,0.039-0.016,0.076-0.021,0.115 c-0.016,0.114-0.024,0.229-0.024,0.346V59.42c0,0.117,0.009,0.233,0.024,0.348c0.005,0.038,0.015,0.077,0.021,0.114 c0.014,0.075,0.027,0.149,0.046,0.223c0.012,0.043,0.028,0.086,0.042,0.128c0.021,0.065,0.042,0.13,0.068,0.195 c0.018,0.044,0.039,0.086,0.06,0.129c0.028,0.06,0.058,0.118,0.09,0.177c0.024,0.041,0.049,0.082,0.076,0.122 c0.035,0.056,0.072,0.109,0.111,0.161c0.029,0.041,0.061,0.078,0.092,0.115c0.042,0.049,0.086,0.098,0.132,0.144 c0.035,0.036,0.069,0.071,0.106,0.104c0.048,0.044,0.099,0.086,0.15,0.127c0.039,0.031,0.078,0.062,0.12,0.091 c0.016,0.01,0.029,0.023,0.044,0.032l28.259,18.84c0.446,0.297,0.96,0.447,1.474,0.447c0.513,0,1.027-0.149,1.473-0.447 l28.259-18.84c0.015-0.009,0.028-0.022,0.044-0.032c0.042-0.029,0.081-0.06,0.12-0.091c0.051-0.041,0.102-0.083,0.15-0.127 c0.037-0.033,0.071-0.068,0.106-0.104c0.046-0.046,0.09-0.095,0.132-0.144c0.031-0.037,0.062-0.075,0.091-0.115 c0.04-0.052,0.076-0.105,0.112-0.161c0.025-0.041,0.051-0.081,0.076-0.122c0.033-0.059,0.062-0.117,0.09-0.177 c0.02-0.042,0.041-0.085,0.059-0.129c0.026-0.065,0.047-0.13,0.068-0.195c0.014-0.042,0.03-0.085,0.042-0.128 c0.02-0.074,0.033-0.148,0.046-0.223c0.006-0.037,0.016-0.076,0.022-0.114c0.014-0.115,0.023-0.231,0.023-0.348V40.581 C80.916,40.464,80.907,40.348,80.893,40.234z M52.657,26.707l20.817,13.877l-9.298,6.221l-11.519-7.706V26.707z M47.343,26.707 v12.393l-11.518,7.706l-9.299-6.221L47.343,26.707z M24.398,45.554L31.046,50l-6.648,4.446V45.554z M47.343,73.294L26.525,59.417 l9.299-6.219l11.518,7.704V73.294z M50,56.286L40.603,50L50,43.715L59.397,50L50,56.286z M52.657,73.294V60.902l11.519-7.704 l9.298,6.219L52.657,73.294z M75.602,54.447L68.955,50l6.647-4.446V54.447z"></path> </g> <path id="twitter" d="M100.001,17.942c-3.681,1.688-7.633,2.826-11.783,3.339 c4.236-2.624,7.49-6.779,9.021-11.73c-3.965,2.432-8.354,4.193-13.026,5.146C80.47,10.575,75.138,8,69.234,8 c-11.33,0-20.518,9.494-20.518,21.205c0,1.662,0.183,3.281,0.533,4.833c-17.052-0.884-32.168-9.326-42.288-22.155 c-1.767,3.133-2.778,6.773-2.778,10.659c0,7.357,3.622,13.849,9.127,17.65c-3.363-0.109-6.525-1.064-9.293-2.651 c-0.002,0.089-0.002,0.178-0.002,0.268c0,10.272,7.072,18.845,16.458,20.793c-1.721,0.484-3.534,0.744-5.405,0.744 c-1.322,0-2.606-0.134-3.859-0.379c2.609,8.424,10.187,14.555,19.166,14.726c-7.021,5.688-15.867,9.077-25.48,9.077 c-1.656,0-3.289-0.102-4.895-0.297C9.08,88.491,19.865,92,31.449,92c37.737,0,58.374-32.312,58.374-60.336 c0-0.92-0.02-1.834-0.059-2.743C93.771,25.929,97.251,22.195,100.001,17.942L100.001,17.942z"></path> <g id="youtube"> <path class="youtube" d="M98.77,27.492c-1.225-5.064-5.576-8.799-10.811-9.354C75.561,16.818,63.01,15.993,50.514,16 c-12.495-0.007-25.045,0.816-37.446,2.139c-5.235,0.557-9.583,4.289-10.806,9.354C0.522,34.704,0.5,42.574,0.5,50.001 c0,7.426,0,15.296,1.741,22.509c1.224,5.061,5.572,8.799,10.807,9.352c12.399,1.32,24.949,2.145,37.446,2.14 c12.494,0.005,25.047-0.817,37.443-2.14c5.234-0.555,9.586-4.291,10.81-9.352c1.741-7.213,1.753-15.083,1.753-22.509 S100.51,34.704,98.77,27.492 M67.549,52.203L43.977,64.391c-2.344,1.213-4.262,0.119-4.262-2.428V38.036 c0-2.548,1.917-3.644,4.262-2.429l23.572,12.188C69.896,49.008,69.896,50.992,67.549,52.203"></path> </g> </defs> </svg> </iron-iconset-svg>`;document.head.appendChild(t.content);
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es6/node_modules/@polymer/iron-iconset-svg/demo/svg-sample-icons.js
JavaScript
gpl-3.0
5,629
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangorest.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
IntroSDE/introsde
projects/tutorial_django_rest_framework_2017/djangorest/manage.py
Python
gpl-3.0
808
package de.spiritaner.maz.controller.approval; import de.spiritaner.maz.controller.meta.ApprovalTypeOverviewController; import de.spiritaner.maz.model.Approval; import de.spiritaner.maz.model.meta.ApprovalType; import de.spiritaner.maz.util.database.CoreDatabase; import de.spiritaner.maz.util.validator.ComboBoxValidator; import de.spiritaner.maz.view.renderer.MetaClassListCell; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import org.apache.log4j.Logger; import org.controlsfx.control.ToggleSwitch; import javax.persistence.EntityManager; import java.net.URL; import java.util.Collection; import java.util.ResourceBundle; public class ApprovalEditorController implements Initializable { final static Logger logger = Logger.getLogger(ApprovalEditorController.class); @FXML private Button addNewApprovalTypeButton; @FXML private ToggleSwitch approvedToggleSwitch; @FXML private ComboBox<ApprovalType> approvalTypeComboBox; private boolean readOnly = false; private ComboBoxValidator<ApprovalType> approvalTypeValidator; public void initialize(URL location, ResourceBundle resources) { approvalTypeValidator = new ComboBoxValidator<>(approvalTypeComboBox).fieldName("Einwilligungsart").isSelected(true).validateOnChange(); approvalTypeComboBox.setCellFactory(column -> new MetaClassListCell<>()); approvalTypeComboBox.setButtonCell(new MetaClassListCell<>()); loadApprovalType(); } public void setAll(Approval approval) { approvedToggleSwitch.setSelected(approval.isApproved()); approvalTypeComboBox.setValue(approval.getApprovalType()); } public Approval getAll(Approval approval) { if (approval == null) approval = new Approval(); approval.setApproved(approvedToggleSwitch.isSelected()); approval.setApprovalType(approvalTypeComboBox.getValue()); return approval; } public void setReadonly(boolean readonly) { this.readOnly = readonly; approvedToggleSwitch.setDisable(readonly); approvalTypeComboBox.setDisable(readonly); addNewApprovalTypeButton.setDisable(readonly); } public void loadApprovalType() { EntityManager em = CoreDatabase.getFactory().createEntityManager(); Collection<ApprovalType> result = em.createNamedQuery("ApprovalType.findAllWithIdGreaterThanThree", ApprovalType.class).getResultList(); ApprovalType selectedBefore = approvalTypeComboBox.getValue(); approvalTypeComboBox.getItems().clear(); approvalTypeComboBox.getItems().addAll(FXCollections.observableArrayList(result)); approvalTypeComboBox.setValue(selectedBefore); } public boolean isValid() { boolean approvalTypeValid = approvalTypeValidator.validate(); return approvalTypeValid; } public void addNewApprovalType(ActionEvent actionEvent) { new ApprovalTypeOverviewController().create(actionEvent); loadApprovalType(); } public boolean isReadOnly() { return readOnly; } }
fschwab/maz-db
database/src/main/java/de/spiritaner/maz/controller/approval/ApprovalEditorController.java
Java
gpl-3.0
3,009
<?php namespace khovdgov\includes; class PrintFaceController { private $options = ""; private $salt = ".ecd8ea1E3F745eC329f"; public $loggedUserDetails = ""; private $itemOnPerPage = "10"; private $dbMan; private $toolMan; public $site_params; public $App_Config; public $reg_countries; public $sys_trans_lang; public function __construct() { $this->dbMan = new \khovdgov\includes\MysqliDb(); //$this->toolMan = new \khovdgov\includes\ToolsController(); } public function hello() { return "<b>hi, it works</b>"; } public function printReadPost($readPostSlug) { $backData = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_slug", $readPostSlug); $this->dbMan->orderBy("post_updated", "DESC"); $cols = array("code_post", "post_title", "post_slug", "post_preview", "post_content", "post_updated"); $kho_posts = $this->dbMan->get('kho_posts', 1, $cols); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postTitle = $kho_posts[$i]['post_title']; $postPreview = $kho_posts[$i]['post_preview']; $postUpdated = $kho_posts[$i]['post_updated']; $postContent = $kho_posts[$i]['post_content']; $backData .= "<a href='#' class='featured-img'><img src='http://placehold.it/620x375' alt=''></a> <h1 class='post-title'>$postTitle</h1> " . $this->cn_htmltrans($postContent, "html") . " <div class='post-meta'> <span class='comments'><a href='#'>24</a></span> <span class='author'><a href='#'>nextwpthemes</a></span> <span class='date'><a href='#'>13 Jan 2013</a></span> </div>"; $i++; } return $backData; } public function printCarouselEightPosts($newsCategoryCode) { $backData = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_cat", 8004); $this->dbMan->orderBy("post_updated", "DESC"); $cols = array("code_post", "post_title", "post_slug", "post_preview", "post_updated"); $kho_posts = $this->dbMan->get('kho_posts', 8, $cols); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postTitle = $kho_posts[$i]['post_title']; $postSlug = $kho_posts[$i]['post_slug']; $postPreview = $kho_posts[$i]['post_preview']; $postUpdated = $kho_posts[$i]['post_updated']; $backData .= "<div class='four column carousel-item'> <a href='" . WEB_ROOT . "post/$postSlug/'><img src='http://placehold.it/300x250' alt=''></a> <div class='post-container'> <h2 class='post-title'>$postTitle</h2> <div class='post-content'> <p>$postPreview</p> </div> </div> <div class='post-meta'> <span class='comments'><a href='#'>24</a></span> <span class='date'><a href='#'>$postUpdated</a></span> </div> </div>"; $i++; } return $backData; } public function printCategoryFourPosts($newsCategoryCode) { $backData0 = ""; $backData1 = ""; $backData2 = ""; $categoryName = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_cat", 8005); //$this->dbMan->orderBy("post_updated", "DESC"); //$cols = array("code_post", "post_title", "post_slug", "post_preview", "post_updated"); //$kho_posts = $this->dbMan->get('kho_posts', 4, $cols); //$countRecords = $this->dbMan->count; $params = Array($newsCategoryCode, 'mn', 'mn'); $queryString = "SELECT khopos.*, hkocat.cat_name FROM kho_posts AS khopos INNER JOIN kho_category AS hkocat ON khopos.code_cat = ? AND khopos.lang_iso_code = ? AND khopos.code_cat = hkocat.code_cat AND hkocat.lang_iso_code = ? ORDER BY khopos.post_updated DESC LIMIT 4"; $kho_posts = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postTitle = $kho_posts[$i]['post_title']; $postSlug = $kho_posts[$i]['post_slug']; $postPreview = $kho_posts[$i]['post_preview']; $postUpdated = $kho_posts[$i]['post_updated']; $categoryName = $kho_posts[$i]['cat_name']; if ($i == 0) { $backData1 .= "<div class='post-image'> <a href='" . WEB_ROOT . "post/$postSlug/'><img src='http://placehold.it/300x220' alt=''></a> </div> <div class='post-container'> <h2 class='post-title'>$postTitle</h2> <div class='post-content'> <p>$postPreview</p> </div> </div> <div class='post-meta'> <span class='comments'><a href='#'>24</a></span> <span class='author'><a href='#'>nextwpthemes</a></span> <span class='date'><a href='#'>13 Jan 2013</a></span> </div>"; } else { $backData2 .= "<li> <a href='" . WEB_ROOT . "post/$postSlug/'><img src='http://placehold.it/50x50' alt=''></a> <h3 class='post-title'><a href='" . WEB_ROOT . "post/$postSlug/'>$postTitle</a></h3> <span class='date'><a href='#'>$postUpdated</a></span> </li>"; } $i++; } $backData0 .= "<h4 class='cat-title'><a href='#'>$categoryName</a></h4>"; $backData0 .= $backData1; $backData0 .= "<div class='other-posts'> <ul class='no-bullet'>"; $backData0 .= $backData2; $backData0 .= "</ul> </div>"; return $backData0; } public function printPopularPosts() { $backData = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->orderBy("post_read_count", "DESC"); $cols = array("code_post", "post_title", "post_slug", "post_updated"); $kho_posts = $this->dbMan->get('kho_posts', 4, $cols); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postTitle = $kho_posts[$i]['post_title']; $postSlug = $kho_posts[$i]['post_slug']; $postUpdated = $kho_posts[$i]['post_updated']; $backData .= "<li> <a href='" . WEB_ROOT . "post/$postSlug/'><img alt='' src='http://placehold.it/60x60'></a> <h3><a href='" . WEB_ROOT . "post/$postSlug/'>$postTitle</a></h3> <div class='post-date'>$postUpdated</div> </li>"; $i++; } return $backData; } public function printRecentPosts() { $backData = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_type", "featured"); $this->dbMan->orderBy("post_updated", "DESC"); $cols = array("code_post", "post_title", "post_slug", "post_updated"); $kho_posts = $this->dbMan->get('kho_posts', 4, $cols); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postTitle = $kho_posts[$i]['post_title']; $postSlug = $kho_posts[$i]['post_slug']; $postUpdated = $kho_posts[$i]['post_updated']; $backData .= "<li> <a href='" . WEB_ROOT . "post/$postSlug/'><img alt='' src='http://placehold.it/60x60'></a> <h3><a href='" . WEB_ROOT . "post/$postSlug/'>$postTitle</a></h3> <div class='post-date'>$postUpdated</div> </li>"; $i++; } return $backData; } public function printFrontSlidePosts() { $backData = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_type", "featured"); $this->dbMan->orderBy("post_updated", "DESC"); $cols = array("code_post", "post_title", "post_preview", "post_slug"); $kho_posts = $this->dbMan->get('kho_posts', 5, $cols); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postTitle = $kho_posts[$i]['post_title']; $postSlug = $kho_posts[$i]['post_slug']; $postPreview = $kho_posts[$i]['post_preview']; $backData .= "<li> <a href='" . WEB_ROOT . "post/$postSlug/'><img alt='$postTitle' src='http://placehold.it/620x350'></a> <div class='flex-caption'> <div class='desc'> <h1><a href='" . WEB_ROOT . "post/$postSlug/'>$postTitle</a></h1> <p>$postPreview</p> </div> </div> </li>"; $i++; } return $backData; } public function printPostNames() { $backData = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->orderBy("post_updated", "DESC"); //$this->dbMan->where("code_post", $postID); $kho_posts = $this->dbMan->get('kho_posts'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backData .= $kho_posts[$i]['post_title'] . "<br/>"; $i++; } return $backData; } public function cn_htmltrans($string, $type = "text") { $trans = get_html_translation_table(HTML_ENTITIES); if ($type == "text") { $string = addslashes($string); return strtr($string, $trans); } else { $trans = array_flip($trans); $string = stripslashes($string); return strtr($string, $trans); } } ///---------------------- another application functions ---------------------------------------------------- public function loadAjaxCommentsByPost($postID) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->orderBy("comment_registered", "DESC"); $this->dbMan->where("code_post", $postID); $mglx_comments = $this->dbMan->get('mglx_comments'); $countRecords = $this->dbMan->count; $backdata .= "<h2 id='comments-title'>" . $countRecords . " comments</h2>"; $backdata .= "<ul class='commentlist'>"; $i = 0; while ($i < $countRecords) { $commentRegDate = strtotime($mglx_comments[$i]['comment_registered']); $backdata .= "<li id='li-comment-18' class='comment even thread-odd thread-alt depth-1'> <article class='comment' id='comment-18'> <a href='' class='comment-avatar'> <img width='45' height='45' class='avatar avatar-45 photo' srcset='//mongoliax.mn/assets/images/comment_avatar_90x90.jpg' src='//mongoliax.mn/assets/images/comment_avatar_45x45.jpg' alt='comment author'> </a> <div class='comment-content'> <footer> <span class='fn'>" . $mglx_comments[$i]['comment_author'] . "</span> <!--<a href='http://mongoliax.mn/2013/12/multiple-devices/#comment-18'>--> <time datetime='2014-02-05T16:23:18+00:00' pubdate=''>" . date("M d, Y H:i", $commentRegDate) . "</time> <!--</a>--> </footer> <p>" . $mglx_comments[$i]['comment_content'] . "</p> <!--<a aria-label='Reply to nama' onclick='return addComment.moveForm( & quot; comment - 18 & quot; , & quot; 18 & quot; , & quot; respond & quot; , & quot; 112 & quot; )' href='http://mongoliax.mn/2013/12/multiple-devices/?replytocom=18#respond' class='comment-reply-link' rel='nofollow'>Reply</a>--> </div> </article> </li>"; $i++; } $backdata .= "</ul>"; //return json_encode($mglx_comments); return $backdata; } public function printReadPostRelatedPostsHTML($postSlug) { $backdata = ""; $backdataInWhile = ""; $readPostCode = -1; $cols = array("code_post", "post_tags"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_slug", $postSlug); $news_post = $this->dbMan->get('mglx_post', 1, $cols); $countRecords = $this->dbMan->count; if (!empty($news_post[0]['post_tags']) && $countRecords > 0) { $readPostCode = $news_post[0]['code_post']; $postTags = explode(",", $news_post[0]['post_tags'], -1); $likeQueries = ""; //$last_key = end(array_keys($postTags)); $last_key = key(array_slice($postTags, -1, 1, true)); foreach ($postTags as $key => $value) { //echo($value); $likeQueries .= ("post_tags LIKE '%{$value}%'" . (($key != $last_key) ? " OR " : "")); } $params1 = Array($readPostCode, $this->App_Config['current_web_app_lang']); $queryString1 = "SELECT * FROM mglx_post WHERE (" . $likeQueries . ") AND code_post != ? AND lang_iso_code = ? ORDER BY RAND() LIMIT 4"; $news_post1 = $this->dbMan->rawQuery($queryString1, $params1); $countRecords1 = $this->dbMan->count; $i = 0; while ($i < $countRecords1) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post1[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post1[$i]['post_images']); //$postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post1[$i]['post_title']; //$postPreview = $news_post[$i]['post_preview']; //$postTags = explode(",", $news_post[$i]['post_tags'], -1); //$catName = $news_post[$i]['cat_name']; //$catSlug = $news_post[$i]['cat_slug']; if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X200." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdataInWhile .= "<li class='col-xs-3 post'> <div class='block-top'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='150' width='200'> <div class='overlay'><i class=''></i></div> </a> </div> <div class='block-content'> <h4 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h4> </div> </li>"; $i++; } if ($i > 0) { $backdata .= "<div class='related-posts'> <h3>төсөөтэй мэдээнүүд</h3> <ul class='row block'>"; $backdata .= $backdataInWhile; $backdata .= "</ul> </div>"; } } return $backdata; } public function printFeaturedPostHTML() { $backdata = ""; $params = Array($this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_name, MGLCAT.cat_slug " . "FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.post_featured = 1 " . "AND MGLPOS.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 5"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; //$postTags = explode(",", $news_post[$i]['post_tags'], -1); $catName = $news_post[$i]['cat_name']; $catSlug = $news_post[$i]['cat_slug']; if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); if ($i == 0) { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X520." . $postImageParts[1]; } else { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X390." . $postImageParts[1]; } $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } if ($i == 0) { $backdata .= "<div class='post col-sm-6 cat-6'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='400' width='520'> </a> <header> <span class='entry-category'> <a href='" . WEB_ROOT . "category/{$catSlug}/'>{$catName}</a> </span> <h2> <a href='{$postReadLink}'>{$postTitle}</a> </h2> </header> </div>"; } else { $backdata .= "<div class='post col-sm-3 col-xs-6 cat-6'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='300' width='390'> </a> <header> <h2> <a href='{$postReadLink}'>{$postTitle}</a> </h2> </header> </div>"; } $i++; } return $backdata; } public function printSearchResultsHTML($searchValue) { $backdata = ""; $params = Array($this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_name, MGLCAT.cat_slug FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON (MGLPOS.post_title LIKE '%" . $searchValue . "%' " . "OR MGLPOS.post_preview LIKE '%" . $searchValue . "%' " . "OR MGLPOS.post_content LIKE '%" . $searchValue . "%') " . "AND MGLPOS.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLCAT.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 100"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; //$postTags = explode(",", $news_post[$i]['post_tags'], -1); $catName = $news_post[$i]['cat_name']; $catSlug = $news_post[$i]['cat_slug']; if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X300." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<article class=' cat-6 post-142 post type-post status-publish format-standard has-post-thumbnail hentry category-travel tag-featured tag-winter tag-city' id='post-142'> <div class='entry-image'> <div class='entry-category'> <a href='" . WEB_ROOT . "category/{$catSlug}/'>{$catName}</a> </div> <a href='{$postReadLink}'> <img width='200' height='150' alt='{$postTitle}' src='{$postFirstImage}'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='entry-main'> <h2 class='entry-title'> <a href='{$postReadLink}'>{$postTitle}</a> </h2> <div class='entry-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_updated']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> <span class='vcard'> <a href='" . WEB_ROOT . "author/admin/' class='url fn'> <i class='fa fa-user'></i> <span>Батсайхан</span> </a> </span> </div> <div class='entry-content'> " . $postPreview . " </div> </div> <div class='clear'></div> </article>"; $i++; } if ($i == 0) { $backdata = "дээрх түлхүүр үгээр ямар нэгэн мэдээлэл олдсонгүй!. "; } return $backdata; } public function printFrontEntertainmentAndPhotographyHTML($menuCode1, $menuCode2) { $backdata = ""; $backdata1 = ""; $backdata2 = ""; $params = Array($menuCode1, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_slug, MGLCAT.cat_name FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.code_cat = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 4"; $news_post1 = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; if ($countRecords > 0) { $backdata1 .= "<div class='col-sm-6 cat-2'> <header> <h2 class='block-title'> <a href='" . WEB_ROOT . "category/{$news_post1[0]['cat_slug']}/'>{$news_post1[0]['cat_name']}<i class='fa fa-angle-right'></i></a> </h2> <div class='block-more'> <a href='" . WEB_ROOT . "category/{$news_post1[0]['cat_slug']}/' title='View all posts in {$news_post1[0]['cat_name']}'> <i class='fa fa-list-ul'></i> </a> <a href='" . WEB_ROOT . "category/{$news_post1[0]['cat_slug']}/feed/' title='Subscribe to {$news_post1[0]['cat_name']}'> <i class='fa fa-rss'></i> </a> </div> </header> <ul>"; $i = 0; while ($i < $countRecords) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post1[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post1[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post1[$i]['post_updated'])); $postTitle = $news_post1[$i]['post_title']; $postPreview = $news_post1[$i]['post_preview']; $postTags = explode(",", $news_post1[$i]['post_tags'], -1); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); if ($i == 0) { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X480." . $postImageParts[1]; } else { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X70." . $postImageParts[1]; } $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } if ($i == 0) { $backdata1 .= "<li class='post'> <div class='block-top'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='285' width='480'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h3 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h3> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post1[$i]['post_title']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> </div> </div> </li>"; } else { $backdata1 .= "<li class='post'> <div class='block-side'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='70' width='70'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h4 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h4> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post1[$i]['post_title']}'>{$postDate}</time> </a> </span> </div> </div> <div class='clear'></div> </li>"; } $i++; } $backdata1 .= "</ul> </div>"; } //-------------- second category starts from here ----------------- $params2 = Array($menuCode2, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString2 = "SELECT MGLPOS.*, MGLCAT.cat_slug, MGLCAT.cat_name FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.code_cat = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 4"; $news_post2 = $this->dbMan->rawQuery($queryString2, $params2); $countRecords2 = $this->dbMan->count; if ($countRecords2 > 0) { $backdata2 .= "<div class='col-sm-6 cat-2'> <header> <h2 class='block-title'> <a href='" . WEB_ROOT . "category/{$news_post2[0]['cat_slug']}/'>{$news_post2[0]['cat_name']}<i class='fa fa-angle-right'></i></a> </h2> <div class='block-more'> <a href='" . WEB_ROOT . "category/{$news_post2[0]['cat_slug']}/' title='View all posts in {$news_post2[0]['cat_name']}'> <i class='fa fa-list-ul'></i> </a> <a href='" . WEB_ROOT . "category/{$news_post2[0]['cat_slug']}/feed/' title='Subscribe to {$news_post2[0]['cat_name']}'> <i class='fa fa-rss'></i> </a> </div> </header> <ul>"; $i = 0; while ($i < $countRecords2) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post2[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post2[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post2[$i]['post_updated'])); $postTitle = $news_post2[$i]['post_title']; $postPreview = $news_post2[$i]['post_preview']; $postTags = explode(",", $news_post2[$i]['post_tags'], -1); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); if ($i == 0) { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X480." . $postImageParts[1]; } else { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X70." . $postImageParts[1]; } $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } if ($i == 0) { $backdata2 .= "<li class='post'> <div class='block-top'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='285' width='480'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h3 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h3> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post2[$i]['post_title']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> </div> </div> </li>"; } else { $backdata2 .= "<li class='post'> <div class='block-side'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='70' width='70'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h4 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h4> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post2[$i]['post_title']}'>{$postDate}</time> </a> </span> </div> </div> <div class='clear'></div> </li>"; } $i++; } $backdata2 .= "</ul> </div>"; } $backdata .= "<div class='row block block-4'>"; $backdata .= $backdata1; $backdata .= $backdata2; $backdata .= "</div>"; return $backdata; } public function printFrontScienceAndTechnologyHTML($menuCode) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $params = Array($menuCode, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_slug, MGLCAT.cat_name FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.code_cat = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 4"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; if ($countRecords > 0) { $backdata .= "<div class='block block-1 cat-7'> <header> <h2 class='block-title'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/'>{$news_post[0]['cat_name']}<i class='fa fa-angle-right'></i></a> </h2> <div class='block-more'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/' title='View all posts in {$news_post[0]['cat_name']}'> <i class='fa fa-list-ul'></i> </a> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/feed/' title='Subscribe to {$news_post[0]['cat_name']}'> <i class='fa fa-rss'></i> </a> </div> </header> <ul>"; $i = 0; while ($i < $countRecords) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; $postTags = explode(",", $news_post[$i]['post_tags'], -1); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X200." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<li class='post'> <div class='block-side'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='150' width='200'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h3 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h3> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_title']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> </div> <div class='block-excerpt'>{$postPreview}... </div> </div> <div class='clear'></div> </li>"; $i++; } $backdata .= "</ul> </div>"; } return $backdata; } public function printFrontTravelHTML($menuCode) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $params = Array($menuCode, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_slug, MGLCAT.cat_name FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.code_cat = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 8"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; if ($countRecords > 0) { $backdata .= "<div class='row block block-3 cat-6'> <header class='col-lg-12'> <h2 class='block-title'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/'>{$news_post[0]['cat_name']}<i class='fa fa-angle-right'></i></a> </h2> <div class='block-more'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/' title='View all posts in {$news_post[0]['cat_name']}'> <i class='fa fa-list-ul'></i> </a> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/feed/' title='Subscribe to {$news_post[0]['cat_name']}'> <i class='fa fa-rss'></i> </a> </div> </header> <ul>"; $i = 0; while ($i < $countRecords) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; $postTags = explode(",", $news_post[$i]['post_tags'], -1); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X200." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<li class='col-lg-3 col-md-4 col-sm-3 col-xs-4 post'> <div class='block-top'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='150' width='200'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h4 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h4> </div> </li>"; $i++; } $backdata .= "</ul> </div>"; } return $backdata; } public function printFrontArtAndGamesHTML($menuCode) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $params = Array($menuCode, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_slug, MGLCAT.cat_name FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.code_cat = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 5"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; if ($countRecords > 0) { $backdata .= "<div class='row block block-5 cat-3'> <header class='col-lg-12'> <h2 class='block-title'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/'>{$news_post[0]['cat_name']}<i class='fa fa-angle-right'></i></a> </h2> <div class='block-more'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/' title='View all posts in {$news_post[0]['cat_name']}'> <i class='fa fa-list-ul'></i> </a> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/feed/' title='Subscribe to {$news_post[0]['cat_name']}'> <i class='fa fa-rss'></i> </a> </div> </header>"; $i = 0; while ($i < $countRecords) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; $postTags = explode(",", $news_post[$i]['post_tags'], -1); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); if ($i == 0) { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X480." . $postImageParts[1]; } else { $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X70." . $postImageParts[1]; } $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } if ($i == 0) { $backdata .= "<div class='col-sm-6'> <ul> <li class='post'> <div class='block-top'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='285' width='480'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h3 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h3> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_updated']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#comments'> <i class='fa fa-comments-o'></i> 1 </a> </span> </div> <div class='block-excerpt'>{$postPreview}… </div> </div> </li> </ul> </div> <div class='col-sm-6'> <ul>"; } else { $backdata .= "<li class='post'> <div class='block-side'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='70' width='70'> <div class='overlay'><i class='fa fa-gg'></i></div> </a> </div> <div class='block-content'> <h4 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h4> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_updated']}'>{$postDate}</time> </a> </span> </div> </div> <div class='clear'></div> </li>"; } $i++; } $backdata .= "</ul> </div> </div>"; } return $backdata; } public function printFrontHealthAndFitnessHTML($menuCode) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $params = Array($menuCode, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_slug, MGLCAT.cat_name FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.code_cat = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 4"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; if ($countRecords > 0) { $backdata .= "<div class='row block block-2 cat-4'> <header class='col-lg-12'> <h2 class='block-title'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/'>{$news_post[0]['cat_name']}<i class='fa fa-angle-right'></i></a> </h2> <div class='block-more'> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/all/' title='View all posts in {$news_post[0]['cat_name']}'> <i class='fa fa-list-ul'></i> </a> <a href='" . WEB_ROOT . "category/{$news_post[0]['cat_slug']}/feed/' title='Subscribe to {$news_post[0]['cat_name']}'> <i class='fa fa-rss'></i> </a> </div> </header> <ul>"; $i = 0; while ($i < $countRecords) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; $postTags = explode(",", $news_post[$i]['post_tags'], -1); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X480." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<li class='col-sm-6 post'> <div class='block-top'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='285' width='480'> <div class='overlay'><i class='fa fa-gg'></i> </div> </a> </div> <div class='block-content'> <h3 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h3> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_images']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> </div> </div> </li>"; $i++; } $backdata .= "</ul> </div>"; } return $backdata; } public function printReadPostCommentsHTML($postSlug) { $backdata = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_slug", $postSlug); $news_post = $this->dbMan->get('mglx_post', 1); $countRecords = $this->dbMan->count; if ($countRecords > 0 && $news_post[0]['post_with_comment'] == 1) { $postCode = $news_post[0]['code_post']; $backdata .= "<div id='respond' class='comment-respond'> <h3 id='reply-title' class='comment-reply-title'>Хариулт үлдээх <small> <a rel='nofollow' id='cancel-comment-reply-link' href='http://mongoliax.mn/2014/01/winter-night-city/#respond' style='display:none;'>Cancel reply</a> </small> </h3> <form method='post' id='commentform' class='comment-form'> <p class='comment-notes'> <span id='email-notes'>Сэтгэдэл бичихдээ эхлээд бодоод дараа нь бичнэ үү.</span><br/><span class='required'>*</span> тэмдэгтэй талбарт заавал мэдээлэл оруулан! </p> <p class='comment-form-author'> <label for='commentAuthor'>нэр <span class='required'>*</span></label> <input id='commentAuthor' name='commentAuthor' size='30' maxlength='30' aria-required='true' type='text'> </p> <p class='comment-form-comment'> <label for='commentContent'>тайлбар<span class='required'>*</span></label> <textarea id='commentContent' name='commentContent' cols='45' rows='8' aria-required='true' required='required' maxlength='700'></textarea> <br/> <span id='commentContentCharsCounts'>700 ширхэг үсгийн хязгаартай</span> </p> <!-- <p class='comment-form-email'> <label for='email'>Email <span class='required'>*</span></label> <input id='email' name='email' size='30' aria-describedby='email-notes' aria-required='true' required='required' type='text'> </p> <p class='comment-form-url'> <label for='url'>Website</label> <input id='url' name='url' size='30' type='text'> </p> --> <p class='comment-form-captcha'> <img src=" . $_SESSION['captcha']['image_src'] . " alt='secret code'><br/> <label for='commentCaptcha'>дээрх кодыг бичнэ үү <span class='required'>*</span></label> <input id='commentCaptcha' name='commentCaptcha' size='10' type='text' maxlength='4' required='required'> <span id='commentEntranceStatus'></span> </p> <p class='form-submit'> <input name='postCommentSubmit' id='postCommentSubmit' class='submit' value='Post Comment' type='submit'> <input name='commentPostID' value='" . $postCode . "' id='commentPostID' type='hidden' readonly> <input name='comment_parent' id='comment_parent' value='0' type='hidden'> </p> </form> </div>"; } return $backdata; } public function printReadPostAuthorHTML($postSlug) { $backdata = ""; $params = Array($postSlug, $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLOFF.code_officer, MGLOFF.officer_slug, MGLOFF.officer_realname, MGLOFF.officer_email, MGLOFF.officer_website, MGLOFF.officer_facebook, MGLOFF.officer_twitter, MGLOFF.officer_youtube, MGLOFF.officer_googleplus, MGLOFF.officer_displaynote " . "FROM mglx_officers AS MGLOFF " . "INNER JOIN mglx_post AS MGLPOS " . "ON MGLPOS.post_slug = ? " . "AND MGLPOS.lang_iso_code = ? " . "AND MGLPOS.code_officer = MGLOFF.code_officer " . "AND MGLOFF.officer_status = 1 " . "AND MGLOFF.officer_on_page = 1 LIMIT 1"; $mgl_officer = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<div class='author-info'> <h3>оруулсан</h3> <div class='author-avatar'> <img alt='author' src='" . IMG_PATH . "icon-author.png' class='avatar avatar-50 photo' height='50' width='50'> </div> <div class='author-link'> <h4> <a href='' title='Visit John Doe’s website' rel='author external'>{$mgl_officer[$i]['officer_realname']}</a> </h4> <a href='http://mongoliax.mn/author/{$mgl_officer[$i]['officer_slug']}/' rel='author'> {$mgl_officer[$i]['officer_realname']} - н бусад мэдээг үзэх<span class='meta-nav'>→</span> </a> </div> <div class='clear'></div> <div class='author-description'> " . $mgl_officer[$i]['officer_displaynote'] . " </div> <div class='author-website'> " . (!empty($mgl_officer[$i]['officer_website']) ? "<i class='fa fa-external-link'></i><a href='{$mgl_officer[$i]['officer_website']}' target='_blank'>{$mgl_officer[$i]['officer_website']}</a>" : "") . " </div> <div class='widget_g7_social'> <ul class='horizontal circle'> " . (!empty($mgl_officer[$i]['officer_facebook']) ? "<li class='social-facebook'> <a href='{$mgl_officer[$i]['officer_facebook']}' title='Facebook' target='_blank'> <span class='social-box'> <i class='fa fa-facebook'></i> </span> </a> </li>" : "") . " " . (!empty($mgl_officer[$i]['officer_googleplus']) ? "<li class='social-google'> <a href='$mgl_officer[$i]['officer_googleplus']' title='Google' target='_blank'> <span class='social-box'> <i class='fa fa-google-plus'></i> </span> </a> </li>" : "") . " " . (!empty($mgl_officer[$i]['officer_youtube']) ? "<li class='social-pinterest'> <a href='{$mgl_officer[$i]['officer_youtube']}' title='Youtube' target='_blank'> <span class='social-box'> <i class='fa fa-youtube'></i> </span> </a> </li>" : "") . " " . (!empty($mgl_officer[$i]['officer_twitter']) ? "<li class='social-twitter'> <a href='{$mgl_officer[$i]['officer_twitter']}' title='Twitter' target='_blank'> <span class='social-box'> <i class='fa fa-twitter'></i> </span> </a> </li>" : "") . " </ul> <div class='clear'></div> </div> </div>"; $i++; } return $backdata; } public function printReadArticleOgTags($postSlug) { $backdata = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_slug", $postSlug); $news_post = $this->dbMan->get('mglx_post', 1); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $postImage = ""; //$postID = $news_post[$i]['post_id']; //$postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); //$postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; //$postTags = explode(",", $news_post[$i]['post_tags'], -1); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X480." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $i++; } $postOgImageDetails = $this->getGoogleShortenURL($postFirstImage); //$backdata .= "<meta property='fb:admins' content='1234' />"; $backdata .= "<meta property='fb:app_id' content='1560639754228006' />"; $backdata .= "<meta property='og:url' content='" . $this->App_Config['PAGE_CURRENT_FULL_LINK'] . "' />"; $backdata .= "<meta property='og:type' content='article' />"; $backdata .= "<meta property='og:title' content='" . $postTitle . "' />"; $backdata .= "<meta property='og:description' content='" . $postPreview . "' />"; $backdata .= "<meta property='og:image' content='" . $postOgImageDetails->id . "' />"; return $backdata; } public function getPostCommentStatus($postSlug) { $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_slug", $postSlug); $news_post = $this->dbMan->getOne('mglx_post', 'post_with_comment'); $countRecords = $this->dbMan->count; if ($countRecords > 0 && !empty($news_post)) { return $news_post['post_with_comment']; } else { return 0; } } public function printReadPostContentHTML($postSlug) { $backdata = ""; $postTagsHTML = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("post_slug", $postSlug); $news_post = $this->dbMan->get('mglx_post', 1); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $postImage = ""; $postID = $news_post[$i]['post_id']; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; $postTags = explode(",", $news_post[$i]['post_tags'], -1); $postContent = $this->tool->cn_htmltrans($news_post[$i]['post_content'], 'html'); //if you find a way that could solve below ../ to / in htacces when remove the line. $postContent = str_replace("../", "/", $postContent); if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X720." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<header class='entry-header'> <div class='entry-image'> <img src='{$postFirstImage}' alt='{$postTitle}' height='320' width='720'> </div> <h1 class='entry-title' itemprop='name'>{$postTitle}</h1> <div class='entry-meta'> <span class='entry-category'> <a href='http://mongoliax.mn/category/travel/' rel='category tag'>Travel</a> </span> <span class='entry-date updated'> <a href='http://mongoliax.mn/2014/01/winter-night-city/'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_updated']}' itemprop='datePublished'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='http://mongoliax.mn/2014/01/winter-night-city/#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> <span class='vcard'> <a class='url fn' href='http://mongoliax.mn/author/batsaihan/'> <i class='fa fa-user'></i> <span itemprop='author'>Батсайхан</span> </a> </span> </div> </header> <div class='entry-content' itemprop='articleBody'> " . $postContent . " </div>"; //$last_key = end(array_keys($postTags)); $last_key = key(array_slice($postTags, -1, 1, true)); foreach ($postTags as $key => $value) { $postTagsHTML .= "<a href='" . WEB_ROOT . "tag/{$value}/' rel='tag'>{$value} </a>"; if ($key != $last_key) { $postTagsHTML .= ", "; } } /* $backdata .= "<footer class='entry-footer'> <div class='tags'> " . (!empty($postTagsHTML) ? "<i class='fa fa-tags'></i> " . $postTagsHTML : "") . " </div> <nav class='next-prev clearfix'> <div class='nav-previous'> <div>Previous Post</div> <a rel='prev' href='#'>Mobile Cloud Computing Communication</a> </div> <div class='nav-next'> <div>Next Post</div> <a rel='next' href='#'>How to Improve Your iPhone’s Battery Life</a> </div> </nav> </footer>";reply 1988 */ $getURLDetails = $this->getGoogleShortenURL($this->App_Config['PAGE_CURRENT_FULL_LINK']); $shortURL = "http://mongoliax.mn/"; if (!empty($getURLDetails->id)) { $shortURL = $getURLDetails->id; } //href="javascript:fbShare('http://jsfiddle.net/stichoza/EYxTJ/', 'Fb Share', 'Facebook share popup', 'http://goo.gl/dS52U', 520, 350)" $backdata .= "<div><a href='http://www.facebook.com/sharer.php?u=" . $this->App_Config['PAGE_CURRENT_FULL_LINK'] . "&t=" . $postTitle . "' class='facebook-sharing' target='_blank'>Share on Facebook</a>" //$backdata .= "<div><a href='javascript:fbShare(\"" . "http://jsfiddle.net/stichoza/EYxTJ/" . "\", \"" . "Fb Share" . "\", \"" . "Facebook share popup" . "\", \"" . "http://goo.gl/dS52U" . "\", 520, 450)' class='facebook-sharing'>Share on Facebook</a>" . "<a href='https://twitter.com/intent/tweet?url=" . $shortURL . "&text=" . $postTitle . "' class='twitter-sharing' target='_blank'>Share on Twitter</a></div>"; //. "<a href='https://twitter.com/intent/tweet?url=" . $shortURL . "&text=" . $postTitle . "&hashtags=Mongoliax&original_referer=http://mongoliax.mn/' class='twitter-sharing' target='_blank'>Share on Twitter</a></div>"; $backdata .= "<footer class='entry-footer'> <div class='tags'> " . (!empty($postTagsHTML) ? "<i class='fa fa-tags'></i> " . $postTagsHTML : "") . " </div> " . $this->getReadPostNextAndPrevouisPosts($postID) . " </footer>"; $i++; } if ($i == 0) { $backdata = "<header class='entry-header'> <div class='entry-image'> <img src='http://mongoliax.mn/wp-content/uploads/sites/3/2014/01/tumblr_mxrv62sm2I1st5lhmo1_1280a-720x320.jpg' alt='Winter Night City' height='320' width='720'> </div> <h3 class='entry-title' itemprop='name'>хандалтанд тохирсон мэдээлэл олдсонгүй!.</h3> </header>"; } return $backdata; } public function getGoogleShortenURL($pageLongURL) { $apiKey = $this->App_Config['GOOGLE_SERVER_API_KEY_1']; // You can get API key here : Login to google and // go to http://code.google.com/apis/console/ // Find API key under credentials under APIs & auth. // You will need to do necessary things to get key there. :) // *** No need to modify any of the code line below. *** $postData = array('longUrl' => $pageLongURL, 'key' => $apiKey); $jsonData = json_encode($postData); $curlObj = curl_init(); curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key=' . $apiKey); curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curlObj, CURLOPT_HEADER, 0); curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json')); curl_setopt($curlObj, CURLOPT_POST, 1); curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData); $response = curl_exec($curlObj); $json = json_decode($response); curl_close($curlObj); return $json; } private function getReadPostNextAndPrevouisPosts($readPostID) { $backdata = "<nav class='next-prev clearfix'>"; /* //below line was important $queryString = "SELECT MP0.* FROM mglx_post AS MP0 WHERE (" . "MP0.post_id = IFNULL((SELECT min(MP1.post_id) FROM mglx_post AS MP1 WHERE MP1.post_id > 8),0) " . "AND MP0.lang_iso_code = 'mn' " . "OR " . "MP0.post_id = IFNULL((SELECT max(MP2.post_id) FROM mglx_post AS MP2 WHERE MP2.post_id < 8),0) " . "AND MP0.lang_iso_code = 'mn'" . ") ORDER BY MP0.post_id ASC LIMIT 2"; */ $cols = Array("post_title", "post_slug"); $this->dbMan->orderBy("post_id", "DESC"); $this->dbMan->where("post_id < " . $readPostID); $this->dbMan->where("lang_iso_code", "mn"); $news_Prevouis_post = $this->dbMan->get("mglx_post", 1, $cols); //------------------------------------- $this->dbMan->orderBy("post_id", "ASC"); $this->dbMan->where("post_id > " . $readPostID); $this->dbMan->where("lang_iso_code", "mn"); $news_Next_post = $this->dbMan->get("mglx_post", 1, $cols); if (!empty($news_Prevouis_post)) { $backdata .= "<div class='nav-previous'> <div>Previous Post</div> <a rel='prev' href='" . WEB_ROOT . "post/" . $news_Prevouis_post[0]['post_slug'] . "/'>{$news_Prevouis_post[0]['post_title']}</a> </div>"; } if (!empty($news_Next_post)) { $backdata .= "<div class='nav-next'> <div>Next Post</div> <a rel='next' href='" . WEB_ROOT . "post/" . $news_Next_post[0]['post_slug'] . "/'>{$news_Next_post[0]['post_title']}</a> </div>"; } $backdata .= "</nav>"; return $backdata; } public function printRecentPostsHTML() { $backdata = ""; $this->dbMan->orderBy("post_updated", "DESC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $news_post = $this->dbMan->get('mglx_post', 4); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $postTitle = $news_post[$i]['post_title']; $postPreview = $news_post[$i]['post_preview']; if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X300." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<li class='cat-6 post2'> <div class='block-top'> <a href='{$postReadLink}'> <img src='{$postFirstImage}' alt='{$postTitle}' height='150' width='300'> <div class='overlay'> <i class='fa fa-gg'></i> </div> </a> </div> <div class='block-content'> <h4 class='block-heading'> <a href='{$postReadLink}'>{$postTitle}</a> </h4> <div class='block-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_updated']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> </div> <div class='clear'></div> <div class='block-excerpt'>{$postPreview}…</div> </div> </li>"; $i++; } return $backdata; } public function printMenuPostsPagination($menuSlug) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $params = Array($menuSlug, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_slug FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.cat_slug = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ?"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; if ($countRecords > 10) { $backdata = "<div class='pagination'> <span class='current'>1</span> <a class='inactive' href='http://mongoliax.mn/blog/blog-grid-2-columns-sidebar/page/2/'>2</a> <a class='inactive' href='http://mongoliax.mn/blog/blog-grid-2-columns-sidebar/page/3/'>3</a> <a class='inactive' href='http://mongoliax.mn/blog/blog-grid-2-columns-sidebar/page/4/'>4</a> <a class='inactive' href='http://mongoliax.mn/blog/blog-grid-2-columns-sidebar/page/5/'>5</a> <a class='inactive' href='http://mongoliax.mn/blog/blog-grid-2-columns-sidebar/page/6/'>6</a> </div>"; } return $backdata; } public function printTagPostsHTML($tagSlug) { $backdata = "<div class='posts blog-grid'> <div class='row'>"; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $params = Array($this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $tagSlug = str_replace("/", "", $tagSlug); $likeParam = "'%" . $tagSlug . "%'"; $queryString = "SELECT MGLPOS.*, MGLCAT.cat_name, MGLCAT.cat_slug FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLPOS.post_tags LIKE " . $likeParam . " " . "AND MGLPOS.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLCAT.lang_iso_code = ? " . "ORDER BY MGLPOS.post_updated DESC LIMIT 100"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $catName = $news_post[$i]['cat_name']; $catSlug = $news_post[$i]['cat_slug']; if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X480." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<article class='col-sm-6 cat-6 post-142 post type-post status-publish format-standard has-post-thumbnail hentry category-travel tag-featured tag-winter tag-city' id='post-142'> <div class='entry-image'> <div class='entry-category'> <a href='" . WEB_ROOT . "category/{$catSlug}/'>{$catName}</a> </div> <a href='{$postReadLink}'> <img width='480' height='285' alt='{$news_post[$i]['post_title']}' src='{$postFirstImage}'> <div class='overlay'> <i class='fa fa-gg'></i> </div> </a> </div> <div class='entry-main'> <h2 class='entry-title'> <a href='{$postReadLink}'>{$news_post[$i]['post_title']}</a> </h2> <div class='entry-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_updated']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> </div> </div> </article>"; $i++; } $backdata .= "</div> </div>"; return $backdata; } public function printCategoryPostsHTML($menuSlug) { $backdata = "<div class='posts blog-grid'> <div class='row'>"; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $params = Array($menuSlug, $this->App_Config['current_web_app_lang'], $this->App_Config['current_web_app_lang']); $queryString = "SELECT MGLPOS.*, MGLCAT.cat_name, MGLCAT.cat_slug FROM mglx_post AS MGLPOS " . "INNER JOIN mglx_category AS MGLCAT " . "ON MGLCAT.cat_slug = ? " . "AND MGLCAT.lang_iso_code = ? " . "AND MGLPOS.code_cat = MGLCAT.code_cat " . "AND MGLPOS.lang_iso_code = ?"; $news_post = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $postImage = ""; $postReadLink = WEB_ROOT . "post/" . $news_post[$i]['post_slug'] . "/"; $postImages = explode(";", $news_post[$i]['post_images']); $postDate = date("M d Y", strtotime($news_post[$i]['post_updated'])); $catName = $news_post[$i]['cat_name']; $catSlug = $news_post[$i]['cat_slug']; if (isset($postImages[0])) { $postImageParts = explode(".", $postImages[0]); //PIC_NEWS_2016_01_1451650097_690086_X520.jpg $imgUploadMonth = substr($postImages[0], 9, 7); $postImage = $imgUploadMonth . "/" . $postImageParts[0] . "_X480." . $postImageParts[1]; $postFirstImage = WEB_ROOT . $this->App_Config['phone_ads_img_upload_path'] . $postImage; } $backdata .= "<article class='col-sm-6 cat-6 post-142 post type-post status-publish format-standard has-post-thumbnail hentry category-travel tag-featured tag-winter tag-city' id='post-142'> <div class='entry-image'> <div class='entry-category'> <a href='" . WEB_ROOT . "category/{$catSlug}/'>{$catName}</a> </div> <a href='{$postReadLink}'> <img width='480' height='285' alt='{$news_post[$i]['post_title']}' src='{$postFirstImage}'> <div class='overlay'> <i class='fa fa-gg'></i> </div> </a> </div> <div class='entry-main'> <h2 class='entry-title'> <a href='{$postReadLink}'>{$news_post[$i]['post_title']}</a> </h2> <div class='entry-meta'> <span class='entry-date updated'> <a href='{$postReadLink}'> <i class='fa fa-clock-o'></i> <time datetime='{$news_post[$i]['post_updated']}'>{$postDate}</time> </a> </span> <span class='entry-comments'> <a href='{$postReadLink}#respond'> <i class='fa fa-comments-o'></i> 0 </a> </span> </div> </div> </article>"; $i++; } $backdata .= "</div> </div>"; return $backdata; } public function printTopMenuHTML() { $backdata = "<nav id='mainnav'> <ul id='mainmenu'>"; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $news_categories = $this->dbMan->get('mglx_category'); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $backdata .= "<li> <a class='parent' href='" . $this->App_Config['WEB_ROOT_WITH_LANG'] . "category/" . $news_categories[$i]['cat_slug'] . "/'>" . $news_categories[$i]['cat_name'] . "</a> </li>"; $i++; } $backdata .= "</ul> </nav>"; return $backdata; } public function printNewsSiteMenusForEdit() { $backdata = "<select class='form-control selectpicker' name='select_NewsSite_Category' id='select_NewsSite_Category'>"; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("code_news", $editComNewsCode); $news_categories = $this->dbMan->get('mglx_category'); $countRecords = $this->dbMan->count; $backdata .= "<option value='none'> - сонгох - </option>"; $i = 0; while ($countRecords > $i) { $backdata .= "<option value='{$news_categories[$i]['code_cat']}'>" . $news_categories[$i]['cat_name'] . "</option>"; $i++; } $backdata .= "</select>"; return $backdata; } public function loadJSON_siteNewsMenus($newsSiteMenuCode) { //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_cat", $newsSiteMenuCode); $mglx_category = $this->dbMan->get('mglx_category'); $countRecords = $this->dbMan->count; return "ok"; } private function nn_has_children($rows, $id) { foreach ($rows as $row) { if ($row['cat_parent'] == $id) return true; } return false; } private function nn_build_menu($rows, $parent = 0) { $result = "<ul>"; foreach ($rows as $row) { if ($row['cat_parent'] == $parent) { if ($this->nn_has_children($rows, $row['code_cat'])) { $result .= "<li class='ulliCPProductMenu'><a href='#'>{$row['cat_name']}</a><label><input type='checkbox' class='tc tc-success' name='name_type[1][]' value='" . $row['code_cat'] . "'><span class='labels'></span></label>"; //$result .= "<li class='ulliCPProductMenu'><a>{$row['cat_name']}</a>"; //$result.= "<li>{$row['cat_name']}"; $result .= $this->nn_build_menu($rows, $row['code_cat']); } else { $result .= "<li class='ulliCPProductMenu'><a href='#'>{$row['cat_name']}</a><label><input type='checkbox' class='tc tc-success' data-newsm02='{$row['code_cat']}' name='name_type[1][]' value='" . $row['code_cat'] . "'><span class='labels'></span></label>"; } $result .= "</li>"; } } $result .= "</ul>"; return $result; } public function printNewsMenusCategories() { $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("cat_parent", 8000); $mglx_category = $this->dbMan->get('mglx_category'); $countRecords = $this->dbMan->count; return $this->nn_build_menu($mglx_category, 8000); } // ---- old --- old --- old --- old --- ---- old --- old --- old --- old --- ---- old --- old --- old --- old --- ---- old --- old --- old --- old --- ---- old --- old --- old --- old --- public function loadAjaxStoreDataByCode($selectedStoreCode) { $this->dbMan->where("code_store", $selectedStoreCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_stores = $this->dbMan->getOne('gobi_stores'); if (empty($gobi_stores)) { return "no"; } else { return json_encode($gobi_stores); } } public function ajaxLoadKeptModelData($givenModelNumber) { $params = Array($givenModelNumber, $this->App_Config['current_web_app_lang']); $queryString = "SELECT * FROM gobi_models WHERE model_number1 = ? AND lang_iso_code = ?"; $gobi_models = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { //$backdata[$i]['value'] = $gobi_models[$i]['model_number1']; //$backdata[$i]['label'] = $gobi_models[$i]['model_number1']; $i++; } return json_encode($gobi_models); } public function loadAllModelNumbersIntoAutoComplete() { $backdata = array(); $params = Array($this->App_Config['current_web_app_lang']); $queryString = "SELECT code_model, model_number1 FROM gobi_models WHERE lang_iso_code = ?"; $gobi_models = $this->dbMan->rawQuery($queryString, $params); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata[$i]['value'] = $gobi_models[$i]['model_number1']; $backdata[$i]['label'] = $gobi_models[$i]['model_number1']; $i++; } return json_encode($backdata); } public function printStoreTableByCountry($selectedCountryCode) { $backdata = "<table class='table table-bordered table-hover tc-table'> <thead> <tr> <th>Shop name</th> <th class='hidden-xs'>Country</th> <th class='hidden-xs'>Clicks</th> <th class='hidden-xs'><i class='fa fa-dollar'></i> Earned</th> <th class='hidden-xs'>Translate</th> <th class='col-medium center'>Action</th> </tr> </thead> <tbody>"; $selectedCountryCode = strtolower($selectedCountryCode); $this->dbMan->where("store_country_code", $selectedCountryCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_stores = $this->dbMan->get('gobi_stores'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= " <tr> <td>{$gobi_stores[$i]['store_name']}</td> <td class='hidden-xs'>{$gobi_stores[$i]['store_country_code']}</td> <td class='hidden-xs'>387</td> <td class='hidden-xs'>$70</td> <td class='hidden-xs'><span class='label label-paid arrowed-in-right arrowed-in'>Yes</span></td> <td class='col-medium center'> <div class='btn-group btn-group-xs '> <a href='#' onclick='loadCountryDataByCodeJS(\"" . $gobi_stores[$i]['code_store'] . "\")' class='btn btn-inverse'><i class='fa fa-pencil icon-only'></i></a> <a href='#' class='btn btn-danger'><i class='fa fa-times icon-only'></i></a> </div> </td> </tr>"; $i++; } $backdata .= "</tbody> </table>"; return $backdata; } public function printOptionsModolCollection() { $backdata = "<select class='form-control selectpicker' name='model_collection' id='model_collection'>"; $backdata .= "<option value='none'> - сонгох - </option>"; //$this->dbMan->where("color_fashion", $givenColorCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_collections = $this->dbMan->get('gobi_collections'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='" . $gobi_collections[$i]['code_coll'] . "'>" . $gobi_collections[$i]['coll_name'] . "</option>"; $i++; } $backdata .= "</select>"; return $backdata; } public function ajaxLoadCheckModelExistenceByCode($givenModelNumber) { $this->dbMan->where("model_number1", $givenModelNumber); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_models = $this->dbMan->getOne('gobi_models'); if (empty($gobi_models)) { return "no"; } else { return "yes"; } } public function ajaxLoadCheckWhatColorCode($givenColorCode) { $backdata = ""; $this->dbMan->where("color_fashion", $givenColorCode); //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_models = $this->dbMan->get('gobi_colors'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<div style='width:40px; height:40px; margin:10px; background:" . $gobi_models[$i]['color_computer'] . ";'></div>"; $i++; } if ($i == 0) { $backdata .= "<b>no color found.</b>"; } return $backdata; } public function printOldCatalogHTML() { $backdata = "<select class='form-control selectpicker' name='chooseOldCatalog' id='chooseOldCatalog'>"; $backdata .= "<option value='none'> - сонгох - </option>"; //$this->dbMan->orderBy("size_guide_updated", "DESC"); //$this->dbMan->where("code_model_ref", $selectedReferCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_catalogs = $this->dbMan->get('gobi_catalogs'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='{$gobi_catalogs[$i]['code_camp_cat']}'>{$gobi_catalogs[$i]['camp_cat_name']}</option>"; //$backdata .= "<option value='{$gobi_model_sizes[$i]['code_size_guide']}'>{$gobi_model_sizes[$i]['size_guide_title']}</option>"; $i++; } $backdata .= "</select>"; return $backdata; } public function printOldLookbookHTML() { $backdata = "<select class='form-control selectpicker' name='chooseOldCatalog' id='chooseOldCatalog'>"; $backdata .= "<option value='none'> - сонгох - </option>"; //$this->dbMan->orderBy("size_guide_updated", "DESC"); //$this->dbMan->where("code_model_ref", $selectedReferCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_lookbooks = $this->dbMan->get('gobi_lookbooks'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='{$gobi_lookbooks[$i]['code_lookbook']}'>{$gobi_lookbooks[$i]['lookbook_name']}</option>"; //$backdata .= "<option value='{$gobi_model_sizes[$i]['code_size_guide']}'>{$gobi_model_sizes[$i]['size_guide_title']}</option>"; $i++; } $backdata .= "</select>"; return $backdata; } public function ajaxLoadModelSizeGuideByCode($selectedSizeCode) { //$this->dbMan->orderBy("size_guide_updated", "DESC"); $this->dbMan->where("code_size_guide", $selectedSizeCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_model_sizes = $this->dbMan->getOne('gobi_model_sizes'); //$countRecords = $this->dbMan->count; $gobi_model_sizes['size_guide_content'] = $this->tool->cn_htmltrans($gobi_model_sizes['size_guide_content'], "html"); return json_encode($gobi_model_sizes); } public function printAllModelSizeGuidesHTML() { $backdata = "<select class='form-control selectpicker' name='selected_model_size' id='selected_model_size'> <option value='none'> - select - </option>"; $this->dbMan->orderBy("size_guide_updated", "DESC"); //$this->dbMan->where("code_model_ref", $selectedReferCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_model_sizes = $this->dbMan->get('gobi_model_sizes'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='{$gobi_model_sizes[$i]['code_size_guide']}'>{$gobi_model_sizes[$i]['size_guide_title']}</option>"; $i++; } $backdata .= "</select>"; return $backdata; } public function printNewModelCareGuides() { $backdata = "<select class='form-control selectpicker' name='selectedCareGuideCode' id='selectedCareGuideCode'> <option value='none'>- хоосон -</option>"; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("color_fashion", $model_color); $gobi_model_cares = $this->dbMan->get('gobi_model_cares'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='{$gobi_model_cares[$i]['code_care_guide']}'>" . $gobi_model_cares[$i]['care_guide_title'] . "</option>"; $i++; } $backdata .= "</select>"; return $backdata; } public function printNewModelSizeGuides() { $backdata = "<select class='form-control selectpicker' name='selectedSizeGuideCode' id='selectedSizeGuideCode'> <option value='none'>- хоосон -</option>"; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("color_fashion", $model_color); $gobi_model_sizes = $this->dbMan->get('gobi_model_sizes'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='{$gobi_model_sizes[$i]['code_size_guide']}'>" . $gobi_model_sizes[$i]['size_guide_title'] . "</option>"; $i++; } $backdata .= "</select>"; return $backdata; } public function ajaxLoadModelReferenceData($selectedReferCode) { $backdata = ""; /* gobi_model_reference code_model_ref smallint(4) No model_ref_title varchar(500) No model_ref_content text No lang_iso_code char(2) No model_ref_registered datetime No model_ref_updated */ //$this->dbMan->orderBy("job_opento", "DESC"); $this->dbMan->where("code_model_ref", $selectedReferCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_model_reference = $this->dbMan->getOne('gobi_model_reference'); $countRecords = $this->dbMan->count; if (!empty($gobi_model_reference)) { $gobi_model_reference['model_ref_content'] = $this->tool->cn_htmltrans($gobi_model_reference['model_ref_content'], "html"); return json_encode($gobi_model_reference); } else { return $backdata; } } public function ajaxLoadModelCareGuide($selectedCareCode) { $backdata = ""; //$this->dbMan->orderBy("job_opento", "DESC"); $this->dbMan->where("code_care_guide", $selectedCareCode); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $gobi_model_cares = $this->dbMan->getOne('gobi_model_cares'); $countRecords = $this->dbMan->count; if (!empty($gobi_model_cares)) { $gobi_model_cares['care_guide_content'] = $this->tool->cn_htmltrans($gobi_model_cares['care_guide_content'], "html"); return json_encode($gobi_model_cares); } else { return $backdata; } } private function getComputerColor($model_color) { $backdata = "#FFFFFF"; $this->dbMan->where("color_fashion", $model_color); $gobi_colors = $this->dbMan->get('gobi_colors', 1); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $backdata = $gobi_colors[$i]['color_computer']; $i++; } return $backdata; } private function cn_has_children($rows, $id) { foreach ($rows as $row) { if ($row['cat_parent'] == $id) return true; } return false; } public function loadAjaxJDailyNewsTableByCode($dailyNewsMenuCode) { return $dailyNewsMenuCode . " in func"; } public function printNewsSiteMenuForEdit() { $backdata = ""; foreach ($this->reg_countries as $key => $value) { $backdata .= "<div class='form-group'> <label class='col-sm-4 control-label'>{$value}</label> <div class='col-sm-8'> <input type='text' class='form-control' name='lang_news_menu_{$key}' id='lang_news_menu_{$key}' placeholder='{$value} хэлээр бичнэ үү'> </div> </div>"; } return $backdata; } public function printOldJobsHTML() { $backdata = "<table id='SampleDT' class='datatable table table-hover table-striped table-bordered tc-table'> <thead> <tr> <th>код</th> <th>нэр</th> <th>тайлбар</th> <th>нээх огноо</th> <th>хаах огноо</th> <th>үйлдэл</th> </tr> </thead> <tbody>"; //$this->dbMan->where("code_cat", $newsSiteMenuCode); $this->dbMan->orderBy("job_opento", "DESC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $hr_jobs = $this->dbMan->get('hr_jobs'); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $backdata .= "<tr> <td>{$hr_jobs[$i]['code_job']}</td> <td>{$hr_jobs[$i]['job_name']}</td> <td>{$hr_jobs[$i]['job_intro']}</td> <td>" . $this->tool->date_formatter($hr_jobs[$i]['job_openfrom'], "Y.m.d") . "</td> <td>" . $this->tool->date_formatter($hr_jobs[$i]['job_opento'], "Y.m.d") . "</td> <td> <div class='btn-group btn-group-xs '> <a class='btn btn-inverse' onclick='loadAjaxJobData(\"" . $hr_jobs[$i]['code_job'] . "\")'><i class='fa fa-pencil icon-only'></i></a> <a class='btn btn-danger'><i class='fa fa-times icon-only'></i></a> </div> </td> </tr>"; $i++; } $backdata .= "</tbody> </table>"; return $backdata; } public function loadAjaxJobDataByCode($loadJobCode) { $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_job", $loadJobCode); $hr_jobs = $this->dbMan->getOne('hr_jobs'); //$countRecords = $this->dbMan->count; $hr_jobs['job_requirement'] = $this->tool->cn_htmltrans($hr_jobs['job_requirement'], "html"); return json_encode($hr_jobs); } private function cn_build_menu($rows, $parent = 0) { $result = "<ul>"; foreach ($rows as $row) { if ($row['cat_parent'] == $parent) { if ($this->cn_has_children($rows, $row['code_cat'])) { $result .= "<li class='ulliCPProductMenu'><a href='#'>{$row['cat_name']}</a><label><input type='checkbox' class='tc tc-success' name='name_type[1][]' value='" . $row['code_cat'] . "'><span class='labels'></span></label>"; //$result .= "<li class='ulliCPProductMenu'><a>{$row['cat_name']}</a>"; //$result.= "<li>{$row['cat_name']}"; $result .= $this->cn_build_menu($rows, $row['code_cat']); } else { $result .= "<li class='ulliCPProductMenu'><a href='#'>{$row['cat_name']}</a><label><input type='checkbox' class='tc tc-success' name='name_type[1][]' value='" . $row['code_cat'] . "'><span class='labels'></span></label>"; } $result .= "</li>"; } } $result .= "</ul>"; return $result; } public function getEditCompanyNewsDetails($editComNewsCode) { $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_news", $editComNewsCode); $company_news = $this->dbMan->getOne('company_news'); $countRecords = $this->dbMan->count; $company_news['news_content'] = $this->tool->cn_htmltrans($company_news['news_content'], "html"); return json_encode($company_news); } public function printAjaxLoadedCompanyNewsByCategory($codeCatNews) { $singleImageX150 = "<img src='" . WEBROOT . $this->App_Config['server_images_path'] . "no_image_275x275.jpg" . "' width='100' height='100'/>"; $backdata = "<table id='SampleDT' class='datatable table table-hover table-striped table-bordered tc-table'> <thead> <tr> <th>{$this->sys_trans_lang['code']}</th> <th>{$this->sys_trans_lang['name']}</th> <th>{$this->sys_trans_lang['net_slug']}</th> <th>{$this->sys_trans_lang['picture']}</th> <th>status</th> <th>{$this->sys_trans_lang['action']}</th> </tr> </thead> <tbody>"; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_cat", $codeCatNews); $company_news = $this->dbMan->get('company_news'); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $arr_news_images = explode(";", $company_news[$i]['news_images'], -1); $hhh = ""; if (isset($arr_news_images[0])) { $singleImage = $arr_news_images[0]; $uploadedYearMonth = substr($singleImage, 9, 7); $singleImage = explode(".", $singleImage); //PIC_COMP_2015_05_1432603753_267269_X150.jpg $singleImageX150 = $singleImage[0] . "_X150" . "." . $singleImage[1]; $singleImageX150 = $hhh = $this->App_Config['media_root_path'] . $this->App_Config['company_img_upload_path'] . $uploadedYearMonth . "/" . $singleImageX150; $singleImageX150 = "<img src='" . $singleImageX150 . "' width='100' height='100'/>"; } $backdata .= "<tr> <td>{$company_news[$i]['code_news']}</td> <td>{$company_news[$i]['news_title']}</td> <td>{$company_news[$i]['news_slug']}</td> <td>{$singleImageX150}</td> <td>" . $this->getCompanyNewsTranslationStatus($company_news[$i]['code_news']) . "</td> <td class='col-medium center'> <div class='btn-group btn-group-xs '> <a class='btn btn-inverse' onclick='editCompanyNewsByCode(\"" . $company_news[$i]['code_news'] . "\")'><i class='fa fa-pencil icon-only'></i></a> <a href='#' class='btn btn-danger'><i class='fa fa-times icon-only'></i></a> </div> </td> </tr>"; $i++; } $backdata .= "</tbody> </table>"; return $backdata; } private function getCompanyNewsTranslationStatus($companyNewsCode) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_news", $companyNewsCode); $company_news = $this->dbMan->get('company_news'); $countRecords = $this->dbMan->count; //$app_config['web_active_langues'] $i = 0; while ($countRecords > $i) { if (in_array($company_news[$i]['lang_iso_code'], $this->App_Config['web_active_langues'])) { $flagPath = WEBROOT . $this->App_Config['server_images_path'] . "flags/flag_32_" . $company_news[$i]['lang_iso_code'] . ".png"; if ($company_news[$i]['is_trans_approved'] == 1) { $backdata .= "<span style='background: #72af46; padding:3px 3px 6px; margin:0 4px 0 0;'><img src='{$flagPath}'/></span>"; } else { $backdata .= "<span style='background: #03A9F4; padding:3px 3px 6px; margin:0 4px 0 0;'><img src='{$flagPath}'/></span>"; } } $i++; } return $backdata; } public function printAllDailyNewsByMenu($checkedNewsMenuCode) { $backdata = "<table class='table table-bordered table-hover tc-table'> <thead> <tr> <th class='hidden-xs'>код</th> <th class='hidden-xs'>гарчиг</th> <th class='hidden-xs'>Нет хаяг</th> <th class='hidden-xs'>зураг</th> <th class='hidden-xs'>бүсад орчуулга</th> <th class='hidden-xs'>байдал</th> <th class='col-medium center'>үйлдэл</th> </tr> </thead> <tbody>"; $this->dbMan->orderBy("dnews_updated", "DESC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_cat", $checkedNewsMenuCode); $news_daily = $this->dbMan->get('news_daily'); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $dnews_images = explode(";", $news_daily[$i]['dnews_images'], -1); $dnewsImage_src = ""; if (isset($dnews_images[0])) { $dnews_first_image = $dnews_images[0]; $tempDNewsImageParts = explode(".", $dnews_first_image); $dnewsFirstImageName = $tempDNewsImageParts[0] . "_X150" . "." . $tempDNewsImageParts[1]; //PIC_NEWS_2015_05_1432701053_101948_X150.jpg $dnewsImageNameYearMonth = substr($dnewsFirstImageName, 9, 7); $dnewsImage_src = $this->App_Config['media_root_path'] . $this->App_Config['news_img_upload_path'] . $dnewsImageNameYearMonth . "/" . $dnewsFirstImageName; } $newsTranslationStatus = ""; $newsTranslationStatusText = ""; if ($news_daily[$i]['is_trans_approved'] == 1) { $newsTranslationStatus = "<a class='btn btn-success' onclick='shiftDailyNewsInEditForm(\"" . $news_daily[$i]['code_news'] . "\")' title='орчуулага баталлагдсан. хэрэв батлагдаагүй бол дарж засварт оруулан уу'><i class='fa fa-check'></i></a>"; $newsTranslationStatusText = "<span class='label label-paid arrowed-in-right arrowed-in'>translated</span>"; } else if ($news_daily[$i]['is_trans_approved'] == 0) { $newsTranslationStatus = "<a class='btn btn-info' onclick='shiftDailyNewsInLiveForm(\"" . $news_daily[$i]['code_news'] . "\")' title='орчуулага дуусаагүй. хэрэв дууссан бол дарж батална уу'><i class='fa fa-pencil-square-o'></i></a>"; $newsTranslationStatusText = "<span class='label label-pending arrowed-in-right arrowed-in'>not translated</span>"; } $backdata .= "<tr> <td class='hidden-xs'>{$news_daily[$i]['code_news']}</td> <td class='hidden-xs'>{$news_daily[$i]['dnews_name']}</td> <td class='hidden-xs'>{$news_daily[$i]['dnews_slug']}</td> <td class='hidden-xs'><img src='{$dnewsImage_src}'/></td> <td class='hidden-xs'>" . $this->getNewsTranslationStatus($news_daily[$i]['code_news']) . "</td> <td class='hidden-xs'>{$newsTranslationStatusText}</td> <td class='col-medium center'> <div class='btn-group btn-group-xs '> <a class='btn btn-inverse' onclick='loadEditDailyNewsByCode(\"" . $news_daily[$i]['code_news'] . "\")'><i class='fa fa-pencil icon-only'></i></a> <a class='btn btn-danger'><i class='fa fa-times icon-only'></i></a> {$newsTranslationStatus} </div> </td> </tr>"; $i++; } $backdata .= "</tbody> </table>"; return $backdata; } private function getNewsTranslationStatus($dailyNewsCode) { $backdata = ""; //$this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_news", $dailyNewsCode); $news_daily = $this->dbMan->get('news_daily'); $countRecords = $this->dbMan->count; //$app_config['web_active_langues'] $i = 0; while ($countRecords > $i) { if (in_array($news_daily[$i]['lang_iso_code'], $this->App_Config['web_active_langues'])) { $flagPath = WEBROOT . $this->App_Config['server_images_path'] . "flags/flag_32_" . $news_daily[$i]['lang_iso_code'] . ".png"; if ($news_daily[$i]['is_trans_approved'] == 1) { $backdata .= "<span style='background: #72af46; padding:3px 3px 6px; margin:0 4px 0 0;'><img src='{$flagPath}'/></span>"; } else { $backdata .= "<span style='background: #03A9F4; padding:3px 3px 6px; margin:0 4px 0 0;'><img src='{$flagPath}'/></span>"; } } $i++; } return $backdata; } public function loadDailyNewsDataByAjaxData($tobeLoadCode) { $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("code_news", $tobeLoadCode); $news_daily = $this->dbMan->getOne('news_daily'); $countRecords = $this->dbMan->count; $news_daily['dnews_content'] = $this->tool->cn_htmltrans($news_daily['dnews_content'], "html"); return json_encode($news_daily); } public function printCompanyNewNewsCategories() { $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("cat_parent", 7000); $company_categories = $this->dbMan->get('company_categories'); $countRecords = $this->dbMan->count; return $this->cn_build_menu($company_categories, 7000); } public function printCompanyMenuHTML() { $backdata = ""; $backdata = "<select class='form-control selectpicker' name='new_company_menu' id='new_company_menu'> <option value='none'> - сонгох - </option>"; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("has_child", 1); $company_categories = $this->dbMan->get('company_categories'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='" . $company_categories[$i]['code_cat'] . "'>" . $company_categories[$i]['cat_name'] . "</option>"; $i++; } $backdata .= "</select>"; return $backdata; } private function proView_has_children($rows, $id) { foreach ($rows as $row) { if ($row['product_menu_parent'] == $id) return true; } return false; } private function proView_build_menu($rows, $parent = 0) { $result = "<optgroup label='Picnic'>"; foreach ($rows as $row) { if ($row['product_menu_parent'] == $parent) { //echo("---------{$row['product_menu_name']}<br/>"); if ($this->proView_has_children($rows, $row['code_product_menu'])) { //$result .= "<li class='ulliCPProductMenu'>{$row['product_menu_name']}"; //echo("---------{$row['product_menu_name']}<br/>"); //$result .= $this->proView_has_children($rows, $row['code_product_menu']); } else { //$result .= "<li class='ulliCPProductMenu'>{$row['product_menu_name']}"; //echo("---------------------------<br/>"); $result .= "<option>{$row['product_menu_name']}</option>"; } //$result .= "</li>"; //$result .= "</optgroup>"; } } $result .= "</optgroup>"; //echo($result); return $result; } public function printViewProductsByCategory() { /* <select class='form-control selectpicker'> <optgroup label='Picnic'> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </optgroup> <optgroup label='Camping'> <option>Tent</option> <option>Flashlight</option> <option>Toilet Paper</option> <option>Toilet Paper</option> <option>Toilet Paper</option> <option>Toilet Paper</option> <option>Toilet Paper</option> <option>Toilet Paper</option> <option>Toilet Paper</option> </optgroup> </select> */ $backdata = "<select class='form-control selectpicker'>"; //$this->dbMan->orderBy("code_comp_type ", "ASC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("model_number1", $modelNumber); $product_menus = $this->dbMan->get('product_menus'); $countRecords = $this->dbMan->count; //echo("<pre>"); //print_r($product_menus); //echo("</pre>"); $backdata .= $this->proView_build_menu($product_menus, 5000); $backdata .= "</select>"; return $backdata; } private function getProductImage($productCodeImage) { $this->dbMan->where("code_image", $productCodeImage); $cols = array("image_path"); $products_images = $this->dbMan->getOne('products_images', $cols); return $products_images; } public function printFilteredProducts() { $backdata = ""; $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("model_number1", $modelNumber); $gobi_products = $this->dbMan->get('gobi_products'); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $productImagePath = $this->getProductImage($gobi_products[$i]['code_image'])['image_path']; $tempProductImage = explode(".", $productImagePath); if (count($tempProductImage) > 1) { //PIC_PRO_2015_07_1437981111_243349_X1050 $imageUploadYearMonth = substr($tempProductImage[0], 8, 7); $productFirstImageName = $tempProductImage[0] . "_X150" . "." . $tempProductImage[1]; $productImage_10 = $this->App_Config['media_root_path'] . $this->App_Config['product_img_upload_path'] . $imageUploadYearMonth . "/" . $productFirstImageName; } else { $productImage_10 = WEBROOT . $this->App_Config['server_images_path'] . "no_picture.jpg"; } $backdata .= " <tr> <td>{$gobi_products[$i]['product_title']}</td> <td><img src='{$productImage_10}' width='150'></td> <td>{$gobi_products[$i]['product_slug']}</td> <td><span class='label label-paid arrowed-in-right arrowed-in'>идэвхтэй</span></td> <td class='col-medium center'> <div class='btn-group btn-group-xs '> <a href='?page=edit_product&proCode={$gobi_products[$i]['code_product']}' class='btn btn-inverse'><i class='fa fa-pencil icon-only'></i></a> <a class='btn btn-danger' onclick='removeThisProduct({$gobi_products[$i]['code_product']})'><i class='fa fa-times icon-only'></i></a> <a class='btn btn-info' onclick='updateThisProductPrice({$gobi_products[$i]['code_product']})'><i class='fa fa-usd icon-only'></i></a> </div> </td> </tr>"; $i++; } return $backdata; } public function printMenuForEdit() { $backdata = ""; foreach ($this->reg_countries as $key => $value) { $backdata .= "<div class='form-group'> <label class='col-sm-4 control-label'>{$value}</label> <div class='col-sm-8'> <input type='text' class='form-control' name='lang_menu_{$key}' id='lang_menu_{$key}' placeholder='{$value} хэлээр бичнэ үү'> </div> </div>"; } return $backdata; } public function loadCompanyMenuData($editCompanyMenuCode) { //SELECT * FROM product_menus WHERE code_product_menu = 5010 $this->dbMan->where("code_cat", $editCompanyMenuCode); $company_categories = $this->dbMan->get('company_categories'); $countRecords = $this->dbMan->count; return json_encode($company_categories); } public function isSlugExists($newProductSlug) { /* //$this->dbMan->orderBy("code_comp_type ", "ASC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("product_slug", $newProductSlug); $this->dbMan->where("product_slug LIKE '{$newProductSlug}%'"); //$db->where ("id != companyId"); $cols = Array ("product_slug"); $gobi_products = $this->dbMan->getOne('gobi_products', $cols); $countRecords = $this->dbMan->count; */ //$newProductSlug .= "-" . $this->App_Config['product_link_slug_ext'] . rand(100, 999); $tempSlug = $newProductSlug . "-" . $this->App_Config['product_link_slug_ext'] . rand(100, 999); $params = Array($tempSlug); $gobi_products = $this->dbMan->rawQuery("SELECT product_slug FROM gobi_products WHERE product_slug LIKE '{$tempSlug}%' AND lang_iso_code = '{$this->App_Config['current_web_app_lang']}'", NULL); $countRecords = $this->dbMan->count; //echo("<pre>"); //print_r($gobi_products); //echo("</pre>"); if ($countRecords > 0) { $newProductSlug = $this->isSlugExists($newProductSlug); } else { return $tempSlug; } } public function fillNewProductForm($modelNumber) { $backdata = "will be null"; //$this->dbMan->orderBy("code_comp_type ", "ASC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("model_number1", $modelNumber); $gobi_models = $this->dbMan->get('gobi_models', 1); $countRecords = $this->dbMan->count; if (!empty($gobi_models)) { $modelImageName = $gobi_models[0]['model_image']; //PIC_MOD_2015_04 $modelImageNameYearMonth = substr($modelImageName, 8, 7); //$gobi_models[0]['model_name'] = $modelImageNameYearMonth; $gobi_models[0]['model_image'] = $this->App_Config['media_root_path'] . $this->App_Config['model_img_upload_path'] . $modelImageNameYearMonth . "/" . $modelImageName; $model_colors = explode(",", $gobi_models[0]['model_colors']); $colorModel = ""; foreach ($model_colors as $model_color) { $numSignModelColor = $this->getComputerColor($model_color); $noNumSignModelColor = substr($numSignModelColor, 1); $colorModel .= "<div data-color-type='" . $noNumSignModelColor . "' style='background:" . $numSignModelColor . ";' class='smallcolor'></div>"; } $gobi_models[0]['computer_colors'] = $colorModel; //<div data-color-type='364698' style='background:#364698' class='smallcolor'></div> //$gobi_models[0]['model_name'] = $gobi_models[0]['model_image']; /* $i = 0; while ($i < $countRecords) { $optNameLabel = $gobi_models[$i]['name_type_name']; $optNameCode = $gobi_models[$i]['code_comp_type']; $backdata .= "<option value='" . $optNameCode . "'>" . $optNameLabel . "</option>"; $i++; } */ return json_encode($gobi_models); } else { return "null"; } } public function loadProductImagesToSortPanel($codeImage) { $backdata = ""; $this->dbMan->orderBy("image_order", "ASC"); $this->dbMan->where("code_image", $codeImage); $products_images = $this->dbMan->get('products_images'); $countRecords = $this->dbMan->count; $backdata .= "<ul id='image_boxes'>"; $i = 0; while ($countRecords > $i) { $modelImageName = $products_images[$i]['image_path']; $productID_Image = $products_images[$i]['id_image']; $productCode_Image = $products_images[$i]['code_image']; $perProductImageParts = explode(".", $modelImageName); $perProductImage = $perProductImageParts[0] . "_X150" . "." . $perProductImageParts[1]; $modelImageNameYearMonth = substr($modelImageName, 8, 7); $perProductImageLast = $this->App_Config['media_root_path'] . $this->App_Config['product_img_upload_path'] . $modelImageNameYearMonth . "/" . $perProductImage; //PIC_PRO_2015_05_1431590513_707129.jpg //PIC_PRO_2015_05_1431767249_316659_X150.jpg $backdata .= "<li class='image_box'><span onclick='removeProductSingleImage(\"" . $productID_Image . "\", \"" . $productCode_Image . "\")' title='" . $productID_Image . " дугаартай зургийг устгах үйлдэл' class='productImageRemover'>X</span> <img src='" . $perProductImageLast . "' class='sortable_boxes'/></li>"; $i++; } $backdata .= "</ul>"; return $backdata; } private function has_children($rows, $id) { foreach ($rows as $row) { if ($row['product_menu_parent'] == $id) return true; } return false; } private function build_menu($rows, $parent = 0, $isRootCheck, $proCodeMenu) { $result = "<ul class='ulCPProductMenu'>"; foreach ($rows as $row) { //echo($ro w[' product_menu_parent']); if ($row['product_menu_parent'] == $parent) { //$result .= "<li class=' ulliCPProductMenu'><a href='?id = {$row['code_product_menu']}'>{$row['product_menu_name']}</a><label><input type='checkbox' class='tc tc-success'><span class='labels'></span></label>"; if ($this->has_children($rows, $row['code_product_menu'])) { if ($isRootCheck) { $result .= "<li class='ulliCPProductMenu'><a href='#'>{$row['product_menu_name']}</a><label><input type='checkbox' class='tc tc-success' name='name_type[1][]' value='" . $row['code_product_menu'] . "'><span class='labels'></span></label>"; } else { $result .= "<li class='ulliCPProductMenu'><a>{$row['product_menu_name']}</a>"; } $result .= $this->build_menu($rows, $row['code_product_menu'], $isRootCheck, $proCodeMenu); } else { if (!empty($proCodeMenu)) { $result .= "<li class='ulliCPProductMenu'><a href='#'>{$row['product_menu_name']}</a><label><input type='checkbox' class='tc tc-success' name='name_type[1][]' value='" . $row['code_product_menu'] . "' " . ($proCodeMenu == $row['code_product_menu'] ? "checked" : "") . "><span class='labels'></span></label>"; } else { $result .= "<li class='ulliCPProductMenu'><a href='#'>{$row['product_menu_name']}</a><label><input type='checkbox' class='tc tc-success' name='name_type[1][]' value='" . $row['code_product_menu'] . "'><span class='labels'></span></label>"; } } $result .= "</li>"; } } $result .= "</ul>"; return $result; } public function getSingleModelDetailsByLang($modelCode, $iso_lang) { $this->dbMan->where("lang_iso_code", $iso_lang); $this->dbMan->where("code_model", $modelCode); $gobi_models = $this->dbMan->getOne('gobi_models'); $countRecords = $this->dbMan->count; return $gobi_models; } public function getSingleProductDetailsByLang($proCode, $iso_lang) { $this->dbMan->where("lang_iso_code", $iso_lang); $this->dbMan->where("code_product", $proCode); $gobi_products = $this->dbMan->getOne('gobi_products'); $countRecords = $this->dbMan->count; return $gobi_products; } public function getProductMenus($isRootCheck = FALSE, $proCodeMenu = NULL) { $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); //$this->dbMan->where("product_menu_parent ", 5000); $product_menus = $this->dbMan->get('product_menus'); $countRecords = $this->dbMan->count; //echo("<pre>"); //echo($this->App_Config['current_web_app_lang']); //print_r($product_menus); //echo("</pre>"); return $this->build_menu($product_menus, 5000, $isRootCheck, $proCodeMenu); } private function getCatalogOptions($parentCompCode) { $backdata1 = ""; $this->dbMan->orderBy("code_comp_type ", "ASC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("parent_name_type", $parentCompCode); $gobi_name_types1 = $this->dbMan->get('gobi_name_types'); $countRecords1 = $this->dbMan->count; $i1 = 0; while ($i1 < $countRecords1) { $optNameLabel = $gobi_name_types1[$i1]['name_type_name']; $optNameCode = $gobi_name_types1[$i1]['code_comp_type']; $backdata1 .= "<option value='" . $optNameCode . "'>" . $optNameLabel . "</option>"; $i1++; } return $backdata1; } public function getCatalogForModelHTML() { $backdata = ""; $this->dbMan->orderBy("code_comp_type ", "ASC"); $this->dbMan->where("lang_iso_code", $this->App_Config['current_web_app_lang']); $this->dbMan->where("parent_name_type", 1000); $gobi_name_types = $this->dbMan->get('gobi_name_types'); $countRecords = $this->dbMan->count; $i = 0; $backdata .= "<select class='form-control selectpicker' name='select_name_catalog' id='select_name_catalog'>"; while ($i < $countRecords) { $optGroupLabel = $gobi_name_types[$i]['name_type_name']; $backdata .= "<optgroup label='" . $optGroupLabel . "'>"; $backdata .= $this->getCatalogOptions($gobi_name_types[$i]['code_comp_type']); $backdata .= "</optgroup>"; $i++; } $backdata .= "</select>"; return $backdata; } public function printLastItemsBox($gapaMenuID) { $backdata = "<ul class='lastestPriceList'>"; $params = Array($gapaMenuID); $sellers_price = $this->dbMan->rawQuery("SELECT SEPR.*, USMA.market_name FROM sellers_price AS SEPR INNER JOIN son_menus AS SOMS INNER JOIN child_menus AS CHME INNER JOIN supermarkets AS USMA ON SOMS.parentmenu_code = ? AND SOMS.sonmenu_code = CHME.sonmenu_code AND CHME.childmenu_code = SEPR.childmenu_code AND SEPR.market_code = USMA.market_code ORDER BY item_updated DESC LIMIT 20", $params); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $priceItemPhoto = ""; if (empty($sellers_price[$i]['item_photo'])) { $priceItemPhoto = $this->site_params['site_web_url'] . "images/no_photo.png"; } else { $priceItemPhoto = $this->site_params['product_image_path'] . $sellers_price[$i]['moba_code'] . "/" . "thumble_" . $sellers_price[$i]['item_photo']; if (!is_file($priceItemPhoto)) { $priceItemPhoto = $this->site_params['site_web_url'] . "images/no_photo.png"; } else { $priceItemPhoto = $this->site_params['web_product_image_path'] . $sellers_price[$i]['moba_code'] . "/" . "thumble_" . $sellers_price[$i]['item_photo']; } } $span1 = "<a href='#'><span class='lastProductIMG'><img src='" . $priceItemPhoto . "' /></span></a>"; $span2 = "<span class='lastProductName'>" . $sellers_price[$i]['item_name'] . "</span>"; $span3 = "<span class='lastProductMarket'>" . $sellers_price[$i]['market_name'] . "</span>"; //$span4 = "<span class='lastProductPrice'>" . $sellers_price[$i]['seller_price'] . "</span>"; $span5 = "<span class='lastProductDate'>" . (new DateTime($sellers_price[$i]['item_updated']))->format('Y.m.d') . "</span>"; $span6 = "<a href=''><span class='viewLastProductDate'>үзэх</span></a>"; $backdata .= "<li> " . $span1 . $span2 . $span3 . $span5 . $span6 . "</li>"; $i++; } $backdata .= "</ul>"; return $backdata; } private function calculateAveragePrice($weekly_prices) { //average $backPrice = 0; $dividerCount = 0; foreach ($weekly_prices as $perPrice) { $hasAverageValues = strpos($perPrice['wepi_price'], "-"); if ($hasAverageValues === false) { $backPrice += intval($perPrice['wepi_price']); $dividerCount++; } else { $wepi_price_pieces = explode("-", $perPrice['wepi_price']); //echo $wepi_price_pieces[0]; //echo $wepi_price_pieces[1]; $backPrice += (intval($wepi_price_pieces[0]) + intval($wepi_price_pieces[1])); $dividerCount += 2; } //echo $perPrice['wepi_p0rice']; } if ($dividerCount > 0) { $backPrice = round(($backPrice / $dividerCount)); } return $backPrice; //round(($backPrice / $dividerCount)); } private function getJsonChartPricesDates($dataPoints_code) { $backArray1 = array(); $this->dbMan->orderBy("wede_registered", "ASC"); $weekly_dates = $this->dbMan->get('weekly_dates'); $countRecordsJ = $this->dbMan->count; $j = 0; while ($countRecordsJ > $j) { $this->dbMan->orderBy("wepi_registered", "DESC"); $this->dbMan->where("chart_id", $dataPoints_code); $wedeDate1 = $weekly_dates[$j]['wede_registered'] . " 00:00:00"; $wedeDate2 = $weekly_dates[$j]['wede_registered'] . " 23:59:59"; $this->dbMan->where('wepi_registered', Array($wedeDate1, $wedeDate2), 'BETWEEN'); $weekly_prices = $this->dbMan->get('weekly_prices'); $countRecords5 = $this->dbMan->count; $tempArr2 = array(); $d = new DateTime($weekly_dates[$j]['wede_registered']); //$timestamp = $d->getTimestamp(); // Unix timestamp $formatted_date = $d->format('Y m d'); // 2003-10-16 //$tempArr2["x"] = strtotime($weekly_dates[$j]['wede_registered']); $tempArr2["x"] = $weekly_dates[$j]['wede_registered']; $tempArr2["y"] = $this->calculateAveragePrice($weekly_prices); $backArray1[$j] = $tempArr2; $j++; } return $backArray1; } public function printChartsJSON_vegetable() { $backArray = array(); $this->dbMan->orderBy("wecha_registered", "DESC"); $this->dbMan->where("wecha_isload", 1); $this->dbMan->where("wety_code", "vt"); $weekly_charts = $this->dbMan->get('weekly_charts'); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $temparr = array(); $temparr['type'] = $weekly_charts[$i]['wecha_type']; $temparr['showInLegend'] = $weekly_charts[$i]['wecha_showInLegend']; $temparr['name'] = $weekly_charts[$i]['wecha_name']; $temparr['lineThickness'] = $weekly_charts[$i]['wecha_lineThickness']; $temparr['markerType'] = $weekly_charts[$i]['wecha_markerType']; $temparr['color'] = $weekly_charts[$i]['wecha_color']; $dataPoints_code = $weekly_charts[$i]['wecha_dataPoints']; $temparr['dataPoints'] = $this->getJsonChartPricesDates($dataPoints_code); $backArray[$i] = $temparr; $i++; } return json_encode($backArray); } public function printColor() { $backdata = ""; /* gobi_colors Column Type Null Default Comments MIME id_color int(11) No color_fashion char(10) Yes NULL color_computer char(10) Yes NULL color_registered datetime Yes NULL color_updated */ //$this->dbMan->orderBy("wede_registered", "DESC"); $gobi_colors = $this->dbMan->get('gobi_colors'); $countRecords = $this->dbMan->count; /* if ($countRecords > 0) { //$d = new DateTime($weekly_dates[0]['wede_registered']); //$timestamp = $d->getTimestamp(); // Unix timestamp //$formatted_date = $d->format('Y-m-d'); // 2003-10-16 //$backdata = "<span class='priceListDays'>шинэчилсэн: " . $d->format("Y") . " он " . $d->format("m") . " сарын " . $d->format("d") . "</span>"; echo("<div>" . $gobi_colors[][] . " - <span style='background:#000000;width:50px;height:50px;'></span></div>"); } * */ $i = 0; while ($countRecords > $i) { $backdata .= "<div>" . $gobi_colors[$i]['color_fashion'] . " - <div style='background:" . $gobi_colors[$i]['color_computer'] . ";width:50px;height:50px;'></div></div>"; $i++; } return $backdata; } public function printChartsJSON() { $backArray = array(); $this->dbMan->orderBy("wecha_registered", "DESC"); $this->dbMan->where("wecha_isload", 1); $this->dbMan->where("wety_code", "mt"); $weekly_charts = $this->dbMan->get('weekly_charts'); $countRecords = $this->dbMan->count; $i = 0; while ($countRecords > $i) { $temparr = array(); $temparr['type'] = $weekly_charts[$i]['wecha_type']; $temparr['showInLegend'] = $weekly_charts[$i]['wecha_showInLegend']; $temparr['name'] = $weekly_charts[$i]['wecha_name']; $temparr['lineThickness'] = $weekly_charts[$i]['wecha_lineThickness']; $temparr['markerType'] = $weekly_charts[$i]['wecha_markerType']; $temparr['color'] = $weekly_charts[$i]['wecha_color']; $dataPoints_code = $weekly_charts[$i]['wecha_dataPoints']; $temparr['dataPoints'] = $this->getJsonChartPricesDates($dataPoints_code); $backArray[$i] = $temparr; $i++; } return json_encode($backArray); } public function printPublishedDate() { //<span class="priceListDays">шинэчилсэн: 2015 он 1 сарын 30</span> $this->dbMan->orderBy("wede_registered", "DESC"); $weekly_dates = $this->dbMan->get('weekly_dates', 1); $countRecords = $this->dbMan->count; if ($countRecords > 0) { $d = new DateTime($weekly_dates[0]['wede_registered']); //$timestamp = $d->getTimestamp(); // Unix timestamp //$formatted_date = $d->format('Y-m-d'); // 2003-10-16 $backdata = "<span class='priceListDays'>шинэчилсэн: " . $d->format("Y") . " он " . $d->format("m") . " сарын " . $d->format("d") . "</span>"; } return $backdata; } public function printPublicPricesList($priceType, $tabColos, $scrollOrder) { $backdata = "<div id='" . $scrollOrder . "' class='scroll-text'><ul class='" . $tabColos . "'>"; $this->dbMan->orderBy("wepi_registered", "DESC"); $this->dbMan->where("wepi_type", $priceType); $nowDate = date("Y-m-d H:i:s"); $this->dbMan->where("wepi_deadline", $nowDate, ">"); $weekly_prices = $this->dbMan->get('weekly_prices'); $countRecords = $this->dbMan->count; //echo($countRecords."<br/>"); $i = 0; if ($countRecords > 0) { while ($i < $countRecords) { $backdata .= "<li><span>" . $this->getMarketName($weekly_prices[$i]['market_code']) . "</span>-<span>" . $weekly_prices[$i]['wepi_name'] . "</span><span>" . $weekly_prices[$i]['wepi_price'] . "</span></li>"; $i++; } } else { $backdata .= "<li><span>мэдээлэл алга байна</span></li>"; } $backdata .= "</ul></div>"; return $backdata; } private function getMarketName($marketCode) { $backdata = "none"; $this->dbMan->where("market_code", $marketCode); $supermarkets = $this->dbMan->get('supermarkets', 1); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata = $supermarkets[$i]['market_name']; $i++; } return $backdata; } public function printOneMarketDetailHTML($market_code) { //$this->where("market_code", $market_code); //$supermarkets = $this->getOne("supermarkets"); return "<div class='textOnGlass'>" . $this->printUserLinkMap() . "</div>"; } public function getFrontNotificationMessage($messageType = "alert", $messageValue = NULL) { if ($messageType === "success") { return "<div class='frontAlert frontSuccess'>" . $messageValue . "</div>"; } else if ($messageType === "warning") { return "<div class='frontAlert frontWarning'>" . $messageValue . "</div>"; } else { return "<div class='frontAlert frontDanger'>" . $messageValue . "</div>"; } } public function getNotificationMessage($messageType = "alert", $messageValue = NULL) { if ($messageType === "success") { return "<div class='alert alert-success fade in '> <i class='glyphicon glyphicon-info-sign'></i> <button data-dismiss='alert' class='close' type='button'>×</button>" . $messageValue . "</div>"; } else if ($messageType === "warning") { return "<div class='alert alert-warning fade in '> <i class='fa fa-cloud-download alert-icon'></i> <button data-dismiss='alert' class='close' type='button'>×</button>" . $messageValue . "</div>"; } else { return "<div class='alert alert-danger fade in '> <i class='glyphicon glyphicon-info-sign'></i> <button data-dismiss='alert' class='close' type='button'>×</button>" . $messageValue . "</div>"; } } private function fillPriceTestData() { $i = 0; $markets = array("SM776", "SM120", "SM538", "SM803", "SM740", "SM217", "SM139"); $childmenus = array("CMN2158", "CMN2282", "CMN2306", "CMN2577", "CMN4311"); while ($i < 700) { $data = Array( "market_code" => $markets[RAND(0, 6)], "childmenu_code" => $childmenus[RAND(0, 4)], "seller_price" => RAND(500, 50000), "price_registered" => date("Y-m-d H:i:s") ); $id = $this->dbMan->insert('sellers_price', $data); $i++; } } private function getMenuGroups($parentmenuid, $gapa_name_en, $marketID) { $backdata = ""; $this->dbMan->where("parentmenu_code", $parentmenuid); $son_menus = $this->dbMan->get('son_menus'); $countRecords1 = $this->dbMan->count; $sonHTML = ""; $i = 0; while ($i < $countRecords1) { $sonHTML .= "<h2 class='title'>" . $son_menus[$i]['sonmenu_name'] . "</h2>"; $sonHTML .= $this->getSonMenusHTML($son_menus[$i]['sonmenu_code'], $marketID, $gapa_name_en); $i++; } $backdata .= $sonHTML; return $backdata; } private function showInfinityLoadDataOneChild($market, $childmenu, $page, $limit) { $backdata = array(); if ($page == 1) { $start = 0; } else { $start = ($page - 1) * $limit; } $params = Array($market, $childmenu, $start, $limit); $sellers_price = $this->dbMan->rawQuery("SELECT * FROM sellers_price WHERE market_code = ? AND childmenu_code = ? ORDER BY price_registered LIMIT ?, ?", $params); $countRecords1 = $this->dbMan->count; if ($countRecords1 > 0) { $i = 0; while ($countRecords1 > $i) { $backdata["code_" . $i] = $sellers_price[$i]['item_code']; $backdata["usercode_" . $i] = $sellers_price[$i]['moba_code']; $backdata["price_" . $i] = $sellers_price[$i]['seller_price']; $backdata["name_" . $i] = $sellers_price[$i]['item_name']; $backdata["photo_" . $i] = $sellers_price[$i]['item_photo']; $item_content = $sellers_price[$i]['item_content']; /* if (strlen($item_content) > 200) { $backdata["content_" . $i] = $this->tool->cn_htmltrans(substr($item_content, 0, 200), "html") . "..."; } else { $backdata["content_" . $i] = $this->tool->cn_htmltrans($item_content, "html"); } */ $backdata["content_" . $i] = $this->tool->cn_htmltrans($item_content, "html"); $backdata["phone_" . $i] = $sellers_price[$i]['seller_phone']; $i++; } $backdata["nextpage"] = ($page + 1); $backdata["isload"] = "true"; $backdata["status"] = "progress"; } else { $backdata["isload"] = "false"; $backdata["status"] = "finished"; } return $backdata; } public function printOneChildContentByOneMarket($market, $childmenu, $page) { $backdata = array(); $backdata[$market] = $this->showInfinityLoadDataOneChild($market, $childmenu, $page, $this->itemOnPerPage); return json_encode($backdata); } private function printMarketDetails($marketCode) { $backdata = "мэдээлэл алга байна"; $this->dbMan->where("market_code", $marketCode); $market_details = $this->dbMan->get("market_details", 1); $recordsCount = $this->dbMan->count; $i = 0; while ($recordsCount > $i) { $backdata = "нэр: " . $market_details[$i]["mardel_name"]; $marketPicture = ($market_details[$i]["mardel_pictures"] == "" ? "images/no_photo.jpg" : "markets/images/" . $market_details[$i]["mardel_pictures"] ); $marketMap = ($market_details[$i]["mardel_pictures"] == "" ? "images/no_photo.jpg" : "markets/images/" . $market_details[$i]["mardel_mappic"] ); $backdata .= "<img src='" . WEBURL . $marketPicture . "' >"; $backdata .= "<img src='" . WEBURL . $marketMap . "' >"; $i++; } return $backdata; } public function printOneChildContentByOneMarketHTML($marketCode) { $backdata = "<div class = 'home_content_table'>"; $headerNames = array("барааны нэр", "энэ захын мэдээлэл", "зарын хэсэг", "зарын хэсэг"); $i = 0; while ($i < 4) { $tableHead = ""; if ($i === 0) { $tableHead = "<div class='oneitemonmarket'>"; $tableHead .= "<div class='box_header'>" . $headerNames[$i] . " </div>"; $tableHead .= "<div id='box_" . $i . "'></div>"; } if ($i === 1) { $tableHead = "<div class='oneitemonmarket marketInfo fixedFloat'>"; $tableHead .= "<div class='box_header'>" . $headerNames[$i] . " </div>"; $tableHead .= $this->printMarketDetails($marketCode); } if ($i === 2) { $tableHead = "<div class='oneitemonmarket fixedFloat'>"; $tableHead .= "<div class='box_header'>" . $headerNames[$i] . " </div>"; $tableHead .= "<img src='" . WEBURL . "banners/images/banner_00001.jpg' /><br/>"; } if ($i === 3) { $tableHead = "<div class='oneitemonmarket fixedFloat'>"; $tableHead .= "<div class='box_header'>" . $headerNames[$i] . " </div>"; $tableHead .= "<img src='" . WEBURL . "banners/images/banner_00002.jpg' />"; } $tableHead .= "</div>"; $backdata .= $tableHead; $i++; } $backdata .= "</div>"; return $backdata; } private function showInfinityLoadData($page, $limit, $marketID, $childMenuID) { $backdata = array(); if ($page == 1) { $start = 0; } else { $start = ($page - 1) * $limit; } //$params = Array(1, 'admin'); $sellers_price = $this->dbMan->rawQuery("SELECT * FROM sellers_price WHERE market_code = '" . $marketID . "' AND childmenu_code = '" . $childMenuID . "' ORDER BY price_registered LIMIT " . $start . ", " . $limit . "", ""); $countRecords1 = $this->dbMan->count; $i = 0; if ($countRecords1 > 0) { while ($i < $countRecords1) { $backdata["price_" . $i] = $sellers_price[$i]['seller_price']; $backdata["code_" . $i] = $sellers_price[$i]['item_code']; $backdata["name_" . $i] = $sellers_price[$i]['item_name']; $backdata["photo_" . $i] = $sellers_price[$i]['item_photo']; $backdata["updated_" . $i] = date("Y-m-d", strtotime($sellers_price[$i]['item_updated'])); if (strlen($sellers_price[$i]['item_content']) > 200) { //$backdata["content_" . $i] = $this->tool->cn_htmltrans(substr($sellers_price[$i]['item_content'], 0, 200), "html"); $backdata["content_" . $i] = "200 aas ix бө абрөах бөахлыбөа быөа быө абөа бө аыбө абы"; } else { //$backdata["content_" . $i] = $this->tool->cn_htmltrans($sellers_price[$i]['item_content'], "html"); $backdata["content_" . $i] = "200 aas baga өа ыөа ыбөаыбө аыбөа бөа бөа бы өабыө "; } $backdata["phone_" . $i] = $sellers_price[$i]['seller_phone']; $i++; } $backdata["nextpage"] = ($page + 1); $backdata["isload"] = "true"; $backdata["status"] = "progress"; } else { $backdata["isload"] = "false"; $backdata["status"] = "finished"; } return $backdata; } public function printOneChildContentByAllMarket($childMenuID, $page) { $backdata = array(); //$this->dbMan->where("parentmenu_code", $parentMenu); $supermarkets = $this->dbMan->get('supermarkets'); $countRecords = $this->dbMan->count; $i = 0; $perMarket = array(); while ($i < $countRecords) { $marketID = $supermarkets[$i]['market_code']; $market_name = $supermarkets[$i]['market_name']; $perMarket[$marketID] = $this->showInfinityLoadData($page, $this->itemOnPerPage, $marketID, $childMenuID); $i++; } $backdata["markets"] = $perMarket; return json_encode($backdata); } public function printUserLinkMap() { //sdfsd sdf asf asdf sdf sdf asd $homeLink = "<a href='" . WEBROOT . "'>эхлэл</a>"; if ((isset($_REQUEST['supermenu']) && $_REQUEST['supermenu'] != "home")) { $this->dbMan->where("gapa_name_en", $_REQUEST['supermenu']); $gapa_menus = $this->dbMan->get('gapa_menus', 1); //$countRecords = $this->dbMan->count; $superMenu = " >> <a href='" . WEBROOT . "menu/" . $gapa_menus[0]['gapa_name_en'] . "/'>" . $gapa_menus[0]['gapa_name'] . "</a>"; $superMenuLink = $homeLink . $superMenu; if (isset($_REQUEST['childmenu']) && !isset($_REQUEST['market'])) { $this->dbMan->where("childmenu_code", $_REQUEST['childmenu']); $child_menus = $this->dbMan->get('child_menus', 1); //$countRecords = $this->dbMan->count; return ($superMenuLink . " >> " . $child_menus[0]['childmenu_name'] . ""); } else if (isset($_REQUEST['childmenu']) && isset($_REQUEST['market'])) { $this->dbMan->where("market_code", $_REQUEST['market']); $supermarkets = $this->dbMan->get('supermarkets', 1); //$countRecords = $this->dbMan->count; $marketMenu = " >> <a href='" . WEBROOT . "market/" . $supermarkets[0]['market_code'] . "/'>" . $supermarkets[0]['market_name'] . "</a>"; $superMenuLink = $homeLink . $marketMenu . $superMenu; if (isset($_REQUEST['childmenu'])) { $this->dbMan->where("childmenu_code", $_REQUEST['childmenu']); $child_menus = $this->dbMan->get('child_menus', 1); //$countRecords = $this->dbMan->count; return ($superMenuLink . " >> " . $child_menus[0]['childmenu_name'] . ""); } else { return $superMenuLink; } } else { return $superMenuLink; } } else { if (isset($_REQUEST['market'])) { $this->dbMan->where("market_code", $_REQUEST['market']); $supermarkets = $this->dbMan->get('supermarkets', 1); //$countRecords = $this->dbMan->count; $marketMenu = " >> " . $supermarkets[0]['market_name'] . ""; return $homeLink . $marketMenu; } //return "no map links"; } //print_r($_GET); } public function printOneChildContentByAllMarketHTML() { $backdata = "<div class='whiteBackground'><div class='pagespan container_Horizontal'> <div class='wrap_Horizontal'> <div class='textOnGlass'>" . $this->printUserLinkMap() . "</div> <div class='frame_Horizontal' id='centered'> <ul class='container_listUL' class='clearfix'>"; //$this->dbMan->where("sonmenu_code", $sonmenuid); //$this->dbMan->orderBy("gapa_order ", "asc"); $supermarkets = $this->dbMan->get('supermarkets'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $tableHead = "<li>"; $marketID = $supermarkets[$i]['market_code']; $market_name = $supermarkets[$i]['market_name']; $tableHead .= "<div class='box_header'>" . $market_name . "</div>"; $tableHead .= "<div><div id='box_" . $marketID . "'></div></div>"; $tableHead .= "</li>"; $backdata .= $tableHead; $i++; } $backdata .= "</ul> </div> <div class='controls_Horizontal'> <button disabled='disabled' class='btn prev disabled'><i class='icon-chevron-left'></i> зүүн</button> <button class='btn next'>баруун <i class='icon-chevron-right'></i></button> </div> </div> </div></div>"; return $backdata; } /* public function printOneChildContentByAllMarketHTML() { $backdata = "<div class = 'home_content_table'>"; //$this->dbMan->where("sonmenu_code", $sonmenuid); //$this->dbMan->orderBy("gapa_order ", "asc"); $supermarkets = $this->dbMan->get('supermarkets'); $countRecords = $this->dbMan->count; //$tableBody = "<tr>"; $i = 0; while ($i < $countRecords) { $tableHead = "<div class='onebyallmarket'>"; $marketID = $supermarkets[$i]['market_code']; $market_name = $supermarkets[$i]['market_name']; $tableHead .= "<div class='box_header'>" . $market_name . "</div>"; $tableHead .= "<div><div id='box_" . $marketID . "'></div></div>"; $tableHead .= "</div>"; $backdata .= $tableHead; // . $tableBody; $i++; } //$tableBody .= "</tr>"; $backdata .= "</div>"; return $backdata; } */ public function printOneMarketContent($market) { $backdata = "<div class='whiteBackground'><div class='textOnGlass'>" . $this->printUserLinkMap() . "</div><div class = 'home_content_table'>"; //$this->dbMan->where("sonmenu_code", $sonmenuid); $this->dbMan->orderBy("gapa_order ", "asc"); $gapa_menus = $this->dbMan->get('gapa_menus'); $countRecords0 = $this->dbMan->count; $i = 0; $perDIV = ""; while ($i < $countRecords0) { $perDIV = "<div class='allmenuonemarket'>"; //$backdata .= $gapa_menus[$i]['gapa_name']."<br/>"; $gapa_code = $gapa_menus[$i]['gapa_code']; $gapa_name_en = $gapa_menus[$i]['gapa_name_en']; $perDIV .= "<div>" . $this->getMenuGroups($gapa_code, $gapa_name_en, $market) . "</div>"; $perDIV .= "</div>"; $backdata .= $perDIV; $i++; } $backdata .= "</div></div>"; return $backdata; } private function getSonMenusHTML($sonmenuid, $marketID, $gapa_name_en) { $backdata = "<ul class='onePackageBox'>"; $this->dbMan->where("sonmenu_code", $sonmenuid); $child_menus = $this->dbMan->get('child_menus'); $countRecords2 = $this->dbMan->count; $i = 0; while ($i < $countRecords2) { $backdata .= "<li><a href = '" . WEBURL . "menu/" . $gapa_name_en . "/market/" . $marketID . "/chmenu/" . $child_menus[$i]['childmenu_code'] . "/' > " . $child_menus[$i]['childmenu_name'] . "</a></li>"; $i++; } $backdata .= "</ul>"; return $backdata; } public function printNewItemHTML($htmlTitle = "зах сонгох") { $backdata = "<label for='selectMarkets'>" . $htmlTitle . "</label> <select class='form-control' id='selectMarkets' name='selectMarkets'> <option value='none'> - сонгох - </option>"; $supermarkets = $this->dbMan->get('supermarkets'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $market_name = $supermarkets[$i]['market_name']; $market_code = $supermarkets[$i]['market_code']; $backdata .= "<option value='" . $market_code . "'>" . $market_name . "</option>"; $i++; } $backdata .= "</select><p class='group_status'>та өөрийн ажилладаг худалдааны төвийг сонгоогүй байна.</p>"; return $backdata; } private function getChildMenuOptions($someID) { $backdata = ""; $this->dbMan->where("sonmenu_code", $someID); $child_menus = $this->dbMan->get('child_menus'); $countRecords2 = $this->dbMan->count; $i = 0; while ($i < $countRecords2) { $backdata .= "<option value='" . $child_menus[$i]['childmenu_code'] . "' >" . $this->space10 . $child_menus[$i]['childmenu_name'] . "</option>"; //$backdata .= $this->getChildMenuOptions($child_menus[$i]['sonmenu_code']); $i++; } return $backdata; } private function getSonMenuOptions($gapaID) { $backdata = ""; $this->dbMan->where("parentmenu_code", $gapaID); $son_menus = $this->dbMan->get('son_menus'); $countRecords1 = $this->dbMan->count; $i = 0; while ($i < $countRecords1) { $backdata .= "<option value='" . $son_menus[$i]['sonmenu_code'] . "' disabled>" . $this->space5 . $son_menus[$i]['sonmenu_name'] . "</option>"; $backdata .= $this->getChildMenuOptions($son_menus[$i]['sonmenu_code']); $i++; } return $backdata; } public function printNewItemContainsMenuHTML() { $backdata = "<label for='selectGroupItem'>бүлэг сонгох</label> <select class='form-control' id='selectGroupItem' name='selectGroupItem'> <option value='none'> - сонгох - </option>"; $gapa_menus = $this->dbMan->get('gapa_menus'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $backdata .= "<option value='" . $gapa_menus[$i]['gapa_code'] . "' disabled>" . $this->space2 . $gapa_menus[$i]['gapa_name'] . "</option>"; $backdata .= $this->getSonMenuOptions($gapa_menus[$i]['gapa_code']); $i++; } $backdata .= "</select>"; return $backdata; } public function printHomeContent($menuTypeCode, $supermenu) { $backdata = "<div class='whiteBackground'><div class='pagespan container_Horizontal'> <div class='wrap_Horizontal'> <div class='textOnGlass'>" . $this->printUserLinkMap() . "</div> <div class='scrollbar'> <div style='transform: translateZ(0px) translateX(114px); width: 190px;' class='handle'> <div class='mousearea'></div> </div> </div> <div class='frame_Horizontal' id='centered'> <ul class='container_listUL' class='clearfix'>"; //$this->dbMan->where("parentmenu_code", $parentMenu); $supermarkets = $this->dbMan->get('supermarkets'); $countRecords = $this->dbMan->count; $htmlBox = ""; $i = 0; while ($i < $countRecords) { $marketID = $supermarkets[$i]['market_code']; if ($menuTypeCode == "all") { $htmlBox = "<div class='box_header'>" . $supermarkets[$i]['market_name'] . "</div>"; $htmlBox .= $this->getMenuGroups("PMN1111", $supermenu, $marketID); $htmlBox .= $this->getMenuGroups("PMN2222", $supermenu, $marketID); $htmlBox .= $this->getMenuGroups("PMN3333", $supermenu, $marketID); $backdata .= "<li>" . $htmlBox . "</li>"; } else { $htmlBox = "<div class='box_header'>" . $supermarkets[$i]['market_name'] . "</div>"; $backdata .= "<li >" . $htmlBox . $this->getMenuGroups($menuTypeCode, $supermenu, $marketID) . "</li>"; } $i++; } $backdata .= "</ul> </div> <div class='controls_Horizontal'> <button disabled='disabled' class='btn prev disabled'><i class='icon-chevron-left'></i> зүүн</button> <button class='btn next'>баруун <i class='icon-chevron-right'></i></button> </div> </div> </div></div>"; return $backdata; } public function printMenu() { $backdata = "<li class = 'parent'><a href = '" . WEBURL . "menu/home/' > эхлэл</a><ul class = 'sub'>"; $supermarkets = $this->dbMan->get('supermarkets'); $countRow = $this->dbMan->count; $i = 0; while ($i < $countRow) { $backdata .= "<li><a href = '" . WEBURL . "market/" . $supermarkets[$i]['market_code'] . "/' > " . $supermarkets[$i]['market_name'] . "</a></li>"; //$backdata .= "<li><a href = '" . WEBROOT . "?market=" . $supermarkets[$i]['market_code'] . "' > " . $supermarkets[$i]['market_name'] . "</a></li>"; $i++; } $backdata .= "</ul></li>"; return $backdata; } private function getChildMenusHTML($sonmenuid, $parentlink) { $backdata = ""; $this->dbMan->where("sonmenu_code", $sonmenuid); $child_menus = $this->dbMan->get('child_menus'); $countRecords = $this->dbMan->count; $i = 0; while ($i < $countRecords) { $childmenu_code = $child_menus[$i]['childmenu_code']; $childmenu_name = $child_menus[$i]['childmenu_name']; $backdata .= "<li><a href = '" . WEBURL . "menu/" . $parentlink . "/chmenu/" . $childmenu_code . "/' > " . $childmenu_name . "</a></li>"; $i++; }//&supermenu=" + $parentlink + " return $backdata; } public function printWideMenu($parentMenu, $parentName, $parentlink) { $backdata = "<li class = 'parent megamenu promo'> <a href = '" . WEBURL . "menu/" . $parentlink . "/' > " . $parentName . " <!--<span class = 'item-new'>New(5)</span>--></a> <ul class = 'sub'> <li class = 'sub-wrapper'> <div class = 'sub-list'>"; $this->dbMan->where("parentmenu_code", $parentMenu); $son_menus = $this->dbMan->get('son_menus'); $countRow = $this->dbMan->count; $i = 0; while ($i < $countRow) { $backdata .= "<div class = 'box closed'> <h2 class = 'title'>" . $son_menus[$i]['sonmenu_name'] . "</h2> <ul>"; $backdata .= $this->getChildMenusHTML($son_menus[$i]['sonmenu_code'], $parentlink); $backdata .= "</ul> </div>"; $i++; } $backdata .= "</div> <div class = 'promo-block'> <a href = '#'> <img src = '" . WEBURL . "images/megamenu-big.png' alt = '' height = '457' width = '253'> </a> </div> </li> </ul> </li>"; return $backdata; } public function printLiveMenu($parentMenu, $parentName, $parentlink) { $backdata = "<li class = 'parent'><a href = '?supermenu=" . $parentlink . "' > " . $parentName . "<!--<span class = 'item-new'>New</span>--></a><ul class = 'sub'>"; $this->dbMan->where("parentmenu_code", $parentMenu); $son_menus = $this->dbMan->get('son_menus'); $countRow = $this->dbMan->count; $i = 0; while ($i < $countRow) { $backdata .= "<li><a href = '#'>" . $son_menus[$i]['sonmenu_name'] . "</a></li>"; $i++; } $backdata .= "</ul></li>"; return $backdata; } } ?>
delgerbb/orbitnews
includes/PrintFaceController.php
PHP
gpl-3.0
178,080
package com.foreach.poc.charts.core; import com.foreach.poc.charts.model.ChartsResult; import com.foreach.poc.charts.model.TagEvent; import org.apache.flink.api.common.operators.Order; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.tuple.Tuple3; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; /** * SimpleChartsPipeline specialization. Extends Charts pipeline * and implements a custom cleansing and transformation logic. */ public class SimpleChartsPipeline extends ChartsPipeline implements DataPipeline<TagEvent>, Serializable { public SimpleChartsPipeline(PipelineConf conf) { super(conf); env.registerType(ChartsResult.class); } /** * Filtering invalid input data. * Initially removing TagEvents without trackId * The cleansing logic can be encapsulated here * @param input * @return */ @Override public DataSet<Tuple3<Long, Integer, TagEvent>> cleansing(DataSet<?> input) { log.info("Cleansing Phase. Removing invalid TagEvent's"); return ((DataSet<TagEvent>) input) .filter(t -> t.trackId > 0) // Removing all the events with invalid trackids .map( t -> new Tuple3<>(t.trackId, 1, t)) // getting tuples .returns(new TypeHint<Tuple3<Long, Integer, TagEvent>>(){}); } /** * Data transformation. * The method group by trackId, sum the number of occurrences, sort the output * and get the top elements defined by the user. * @param input * @return */ @Override public DataSet<ChartsResult> transformation(DataSet<?> input) { log.info("Transformation Phase. Computing the tags"); return input .groupBy(0) // Grouping by trackId .sum(1) // Sum the occurrences of each grouped item .sortPartition(1, Order.DESCENDING).setParallelism(1) // Sort by count .first(pipelineConf.args.getLimit()) .map( t -> { Tuple3<Long, Integer, TagEvent> tuple= (Tuple3<Long, Integer, TagEvent>) t; return new ChartsResult(tuple.f0, tuple.f1, tuple.f2); }) .returns(new TypeHint<ChartsResult>(){}); } @Override public boolean persistence(DataSet<?> input) { return false; } /** * Pipeline runner. This static method orchestrates the pipeline execution stages. * @param conf * @throws Exception */ public static void run(PipelineConf conf) throws Exception { SimpleChartsPipeline pipeline= new SimpleChartsPipeline(conf); DataSet<TagEvent> inputTags= pipeline.ingestion(); DataSet<Tuple3<Long, Integer, TagEvent>> cleanTags = pipeline.cleansing(inputTags); DataSet<ChartsResult> topTags= pipeline.transformation(cleanTags); System.out.println("CHART POSITION , TRACK TITLE , ARTIST NAME , COUNT"); AtomicInteger position= new AtomicInteger(0); topTags.collect().forEach( t -> System.out.println("#" + position.incrementAndGet() + ", " + t.toString()) ); } }
aaitor/flink-charts
src/main/java/com/foreach/poc/charts/core/SimpleChartsPipeline.java
Java
gpl-3.0
3,254
/* Storybook: Scene-based software for novelists and authors. Copyright (C) 2008 - 2011 Martin Mustun 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 ch.intertec.storybook.playground.swing.undo; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import net.miginfocom.swing.MigLayout; import ch.intertec.storybook.toolkit.swing.undo.UndoableTextArea; import ch.intertec.storybook.toolkit.swing.undo.UndoableTextField; @SuppressWarnings("serial") public class PgUndo extends JFrame { private UndoableTextArea taTest; private UndoableTextField tfTest; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new PgUndo(); } }); } public PgUndo() { super("undo / redo"); setSize(400, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); initGUI(); setVisible(true); } private void initGUI() { setLayout(new MigLayout("fill,wrap")); tfTest = new UndoableTextField(); tfTest.setDragEnabled(true); taTest = new UndoableTextArea(); taTest.setLineWrap(true); taTest.setDragEnabled(true); taTest.setText("press Ctrl-Z to undo, Ctrl-Y to redo"); taTest.getUndoManager().discardAllEdits(); JScrollPane scroller = new JScrollPane(taTest); JButton btUndo = new JButton(); btUndo.setAction(taTest.getUndoAction()); JButton btRedo = new JButton(); btRedo.setAction(taTest.getRedoAction()); add(tfTest, "growx"); add(scroller, "gapy 10,grow"); add(btUndo, "split 2"); add(btRedo); } }
tmhorne/storybook
src/ch/intertec/storybook/playground/swing/undo/PgUndo.java
Java
gpl-3.0
2,224
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-antimalware-tool WebShell- ID 635'; $TAGCLEAR='evals*(*@*s*stripslashess*(*s*@*$_'; $TAGBASE64='ZXZhbHMqKCpAKnMqc3RyaXBzbGFzaGVzcyooKnMqQCokXw=='; $TAGHEX='6576616c732a282a402a732a7374726970736c6173686573732a282a732a402a245f'; $TAGHEXPHP=''; $TAGURI='evals%2A%28%2A%40%2As%2Astripslashess%2A%28%2As%2A%40%2A%24_'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='09/09/2019'; $LINK='Webexploitscan.org'; $ACTIVED='1'; $VSTATR='WebShell';
libre/webexploitscan
wes/data/rules/fullscan/09092019-php-antimalware-tool-635-WebShell.php
PHP
gpl-3.0
879
<?php namespace sisVentas\Http\Controllers\Auth; use sisVentas\Http\Controllers\Controller; use Illuminate\Foundation\Auth\SendsPasswordResetEmails; class ForgotPasswordController extends Controller { /* |-------------------------------------------------------------------------- | Password Reset Controller |-------------------------------------------------------------------------- | | This controller is responsible for handling password reset emails and | includes a trait which assists in sending these notifications from | your application to your users. Feel free to explore this trait. | */ use SendsPasswordResetEmails; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } }
natata0816/Prueba
CursoLaravel/sisVentas/app/Http/Controllers/Auth/ForgotPasswordController.php
PHP
gpl-3.0
846
/* * EffectChams.cpp * * Created on: Apr 16, 2017 * Author: nullifiedcat */ #include <visual/EffectChams.hpp> #include <MiscTemporary.hpp> #include <settings/Bool.hpp> #include "common.hpp" #include "Backtrack.hpp" namespace effect_chams { static settings::Boolean flat{ "chams.flat", "false" }; static settings::Boolean health{ "chams.health", "false" }; static settings::Boolean teammates{ "chams.show.teammates", "false" }; static settings::Boolean disguised{ "chams.show.disguised", "true" }; static settings::Boolean players{ "chams.show.players", "true" }; static settings::Boolean medkits{ "chams.show.medkits", "false" }; static settings::Boolean ammobox{ "chams.show.ammoboxes", "false" }; static settings::Boolean buildings{ "chams.show.buildings", "true" }; static settings::Boolean stickies{ "chams.show.stickies", "true" }; static settings::Boolean teammate_buildings{ "chams.show.teammate-buildings", "false" }; static settings::Boolean recursive{ "chams.recursive", "true" }; static settings::Boolean weapons_white{ "chams.white-weapons", "true" }; static settings::Boolean legit{ "chams.legit", "false" }; static settings::Boolean singlepass{ "chams.single-pass", "false" }; static settings::Boolean chamsself{ "chams.self", "true" }; static settings::Boolean disco_chams{ "chams.disco", "false" }; settings::Boolean enable{ "chams.enable", "false" }; CatCommand fix_black_chams("fix_black_chams", "Fix Black Chams", []() { effect_chams::g_EffectChams.Shutdown(); effect_chams::g_EffectChams.Init(); }); void EffectChams::Init() { #if !ENFORCE_STREAM_SAFETY if (init) return; logging::Info("Init EffectChams..."); { KeyValues *kv = new KeyValues("UnlitGeneric"); kv->SetString("$basetexture", "vgui/white_additive"); kv->SetInt("$ignorez", 0); mat_unlit.Init("__cathook_echams_unlit", kv); } { KeyValues *kv = new KeyValues("UnlitGeneric"); kv->SetString("$basetexture", "vgui/white_additive"); kv->SetInt("$ignorez", 1); mat_unlit_z.Init("__cathook_echams_unlit_z", kv); } { KeyValues *kv = new KeyValues("VertexLitGeneric"); kv->SetString("$basetexture", "vgui/white_additive"); kv->SetInt("$ignorez", 0); kv->SetInt("$halflambert", 1); mat_lit.Init("__cathook_echams_lit", kv); } { KeyValues *kv = new KeyValues("VertexLitGeneric"); kv->SetString("$basetexture", "vgui/white_additive"); kv->SetInt("$ignorez", 1); kv->SetInt("$halflambert", 1); mat_lit_z.Init("__cathook_echams_lit_z", kv); } logging::Info("Init done!"); init = true; #endif } void EffectChams::BeginRenderChams() { #if !ENFORCE_STREAM_SAFETY drawing = true; CMatRenderContextPtr ptr(GET_RENDER_CONTEXT); g_IVRenderView->SetBlend(1.0f); #endif } void EffectChams::EndRenderChams() { #if !ENFORCE_STREAM_SAFETY drawing = false; CMatRenderContextPtr ptr(GET_RENDER_CONTEXT); g_IVModelRender->ForcedMaterialOverride(nullptr); #endif } static rgba_t data[PLAYER_ARRAY_SIZE] = { colors::empty }; void EffectChams::SetEntityColor(CachedEntity *ent, rgba_t color) { if (ent->m_IDX > MAX_PLAYERS || ent->m_IDX < 0) return; data[ent->m_IDX] = color; } static Timer t{}; static int prevcolor = -1; rgba_t EffectChams::ChamsColor(IClientEntity *entity) { if (!isHackActive() || !*effect_chams::enable) return colors::empty; CachedEntity *ent = ENTITY(entity->entindex()); if (disco_chams) { static rgba_t disco{ 0, 0, 0, 0 }; if (t.test_and_set(200)) { int color = rand() % 20; while (color == prevcolor) color = rand() % 20; prevcolor = color; switch (color) { case 2: disco = colors::pink; break; case 3: disco = colors::red; break; case 4: disco = colors::blu; break; case 5: disco = colors::red_b; break; case 6: disco = colors::blu_b; break; case 7: disco = colors::red_v; break; case 8: disco = colors::blu_v; break; case 9: disco = colors::red_u; break; case 10: disco = colors::blu_u; break; case 0: case 1: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: float color1 = rand() % 256; float color2 = rand() % 256; float color3 = rand() % 256; disco = { color1, color2, color3, 255.0f }; } } return disco; } if (ent->m_IDX <= MAX_PLAYERS && ent->m_IDX >= 0) { if (data[entity->entindex()] != colors::empty) { auto toret = data[entity->entindex()]; data[entity->entindex()] = colors::empty; return toret; } } if (CE_BAD(ent)) return colors::white; if (re::C_BaseCombatWeapon::IsBaseCombatWeapon(entity)) { IClientEntity *owner = re::C_TFWeaponBase::GetOwnerViaInterface(entity); if (owner) { return ChamsColor(owner); } } switch (ent->m_Type()) { case ENTITY_BUILDING: if (!ent->m_bEnemy() && !(teammates || teammate_buildings) && ent != LOCAL_E) { return colors::empty; } if (health) { return colors::Health_dimgreen(ent->m_iHealth(), ent->m_iMaxHealth()); } break; case ENTITY_PLAYER: if (!players) return colors::empty; if (health) { return colors::Health_dimgreen(ent->m_iHealth(), ent->m_iMaxHealth()); } break; default: break; } return colors::EntityF(ent); } bool EffectChams::ShouldRenderChams(IClientEntity *entity) { #if ENFORCE_STREAM_SAFETY return false; #endif if (!isHackActive() || !*effect_chams::enable || CE_BAD(LOCAL_E)) return false; if (entity->entindex() < 0) return false; CachedEntity *ent = ENTITY(entity->entindex()); if (!chamsself && ent->m_IDX == LOCAL_E->m_IDX) return false; switch (ent->m_Type()) { case ENTITY_BUILDING: if (!buildings) return false; if (!ent->m_bEnemy() && !(teammate_buildings || teammates)) return false; if (ent->m_iHealth() == 0 || !ent->m_iHealth()) return false; if (CE_BYTE(LOCAL_E, netvar.m_bCarryingObject) && ent->m_IDX == HandleToIDX(CE_INT(LOCAL_E, netvar.m_hCarriedObject))) return false; return true; case ENTITY_PLAYER: if (!players) return false; if (!disguised && IsPlayerDisguised(ent)) return false; if (!teammates && !ent->m_bEnemy() && playerlist::IsDefault(ent)) return false; if (CE_BYTE(ent, netvar.iLifeState)) return false; return true; break; case ENTITY_PROJECTILE: if (!ent->m_bEnemy()) return false; if (stickies && ent->m_iClassID() == CL_CLASS(CTFGrenadePipebombProjectile)) { return true; } break; case ENTITY_GENERIC: switch (ent->m_ItemType()) { case ITEM_HEALTH_LARGE: case ITEM_HEALTH_MEDIUM: case ITEM_HEALTH_SMALL: return *medkits; case ITEM_AMMO_LARGE: case ITEM_AMMO_MEDIUM: case ITEM_AMMO_SMALL: return *ammobox; default: break; } break; default: break; } return false; } void EffectChams::RenderChamsRecursive(IClientEntity *entity) { #if !ENFORCE_STREAM_SAFETY if (!isHackActive() || !*effect_chams::enable) return; entity->DrawModel(1); if (!*recursive) return; IClientEntity *attach; int passes = 0; attach = g_IEntityList->GetClientEntity(*(int *) ((uintptr_t) entity + netvar.m_Collision - 24) & 0xFFF); while (attach && passes++ < 32) { if (attach->ShouldDraw()) { if (entity->GetClientClass()->m_ClassID == RCC_PLAYER && re::C_BaseCombatWeapon::IsBaseCombatWeapon(attach)) { if (weapons_white) { rgba_t mod_original; g_IVRenderView->GetColorModulation(mod_original.rgba); g_IVRenderView->SetColorModulation(colors::white); attach->DrawModel(1); g_IVRenderView->SetColorModulation(mod_original.rgba); } else { attach->DrawModel(1); } } else attach->DrawModel(1); } attach = g_IEntityList->GetClientEntity(*(int *) ((uintptr_t) attach + netvar.m_Collision - 20) & 0xFFF); } #endif } void EffectChams::RenderChams(IClientEntity *entity) { #if !ENFORCE_STREAM_SAFETY if (!isHackActive() || !*effect_chams::enable) return; CMatRenderContextPtr ptr(GET_RENDER_CONTEXT); if (ShouldRenderChams(entity)) { rgba_t color = ChamsColor(entity); rgba_t color_2 = color * 0.6f; if (!legit) { mat_unlit_z->AlphaModulate(1.0f); ptr->DepthRange(0.0f, 0.01f); g_IVRenderView->SetColorModulation(color_2); g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit_z : mat_lit_z); RenderChamsRecursive(entity); } if (legit || !singlepass) { mat_unlit->AlphaModulate(1.0f); g_IVRenderView->SetColorModulation(color); ptr->DepthRange(0.0f, 1.0f); g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit : mat_lit); RenderChamsRecursive(entity); } } #endif } void EffectChams::Render(int x, int y, int w, int h) { #if !ENFORCE_STREAM_SAFETY PROF_SECTION(DRAW_chams); if (!isHackActive() || disable_visuals) return; if (!effect_chams::enable && !(hacks::tf2::backtrack::chams && hacks::tf2::backtrack::isBacktrackEnabled)) return; if (g_Settings.bInvalid) return; if (!init && effect_chams::enable) Init(); if (!isHackActive() || (g_IEngine->IsTakingScreenshot() && clean_screenshots)) return; if (hacks::tf2::backtrack::chams && hacks::tf2::backtrack::isBacktrackEnabled) { CMatRenderContextPtr ptr(GET_RENDER_CONTEXT); BeginRenderChams(); // Don't mark as normal chams drawing drawing = false; for (int i = 1; i <= g_IEngine->GetMaxClients(); i++) { CachedEntity *ent = ENTITY(i); if (CE_BAD(ent) || i == g_IEngine->GetLocalPlayer() || !ent->m_bAlivePlayer() || ent->m_Type() != ENTITY_PLAYER) continue; // Entity won't draw in some cases so help the chams a bit hacks::tf2::backtrack::isDrawing = true; RAW_ENT(ent)->DrawModel(1); hacks::tf2::backtrack::isDrawing = false; } EndRenderChams(); } if (!effect_chams::enable) return; CMatRenderContextPtr ptr(GET_RENDER_CONTEXT); BeginRenderChams(); for (int i = 1; i <= HIGHEST_ENTITY; i++) { IClientEntity *entity = g_IEntityList->GetClientEntity(i); if (!entity || entity->IsDormant() || CE_BAD(ENTITY(i))) continue; RenderChams(entity); } EndRenderChams(); #endif } EffectChams g_EffectChams; CScreenSpaceEffectRegistration *g_pEffectChams = nullptr; static InitRoutine init([]() { EC::Register( EC::LevelShutdown, []() { g_EffectChams.Shutdown(); }, "chams"); if (g_ppScreenSpaceRegistrationHead && g_pScreenSpaceEffects) { effect_chams::g_pEffectChams = new CScreenSpaceEffectRegistration("_cathook_chams", &effect_chams::g_EffectChams); g_pScreenSpaceEffects->EnableScreenSpaceEffect("_cathook_chams"); } }); } // namespace effect_chams
nullifiedcat/cathook
src/visual/EffectChams.cpp
C++
gpl-3.0
12,523
/* * Copyright (C) 2014 Robert Stark * * 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 de.rs.scrumit.controller; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zk.ui.select.annotation.WireVariable; import org.zkoss.zul.Include; import de.rs.scrumit.component.BaseComponentComposer; import de.rs.scrumit.entity.ApplicationNavigationEntryModel; import de.rs.scrumit.service.MenuService; @VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class) public class MainIncludeComposer extends BaseComponentComposer { private static final long serialVersionUID = 1L; @WireVariable("menuService") MenuService menuService; @Wire Include mainInclude; public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); subscribe("onProjectSelectionChange", new EventListener<Event>() { @Override public void onEvent(Event event) throws Exception { String src = mainInclude.getSrc(); mainInclude.setSrc(null); mainInclude.setSrc(src); } }); ApplicationNavigationEntryModel navigationEntry = menuService.getCurrentPage(); String target = navigationEntry.getTarget(); mainInclude.setSrc(target); } }
StarkoMania/scrum-it
src/main/java/de/rs/scrumit/controller/MainIncludeComposer.java
Java
gpl-3.0
2,033
/* ************************************************************************ Copyright: License: Authors: ************************************************************************ */ qx.Theme.define("qjide.theme.Font", { extend : qx.theme.modern.Font, fonts : { } });
martin-saurer/qjide
qooxdoo/qjide/source/class/qjide/theme/Font.js
JavaScript
gpl-3.0
305
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ja"> <context> <name></name> <message id="id-new-event"> <location filename="../src/EventDialog.qml" line="43"/> <source>New Event</source> <translation>新しいイベント</translation> </message> <message id="id-edit-event"> <location filename="../src/EventDialog.qml" line="45"/> <source>Edit Event</source> <translation>イベントを編集</translation> </message> <message id="id-title-field"> <location filename="../src/EventDialog.qml" line="90"/> <source>Title</source> <translation>タイトル</translation> </message> <message id="id-untitled-event"> <location filename="../src/EventDialog.qml" line="128"/> <source>Untitled event</source> <translation>無題のイベント</translation> </message> <message id="id-events-recap"> <location filename="../src/main.qml" line="238"/> <source>%1 Events on %2 %3/%4/%5</source> <translation>%1 のイベント %2 %3/%4/%5</translation> </message> <message id="id-app-launcher-name"> <location filename="asteroid-calendar.desktop.h" line="6"/> <source>Agenda</source> <translation>日程</translation> </message> <message id="id-month-page"> <location filename="../src/MonthSelector.qml" line="28"/> <source>Month</source> <translation>月</translation> </message> </context> </TS>
AsteroidOS/asteroid-calendar
i18n/asteroid-calendar.ja.ts
TypeScript
gpl-3.0
1,550
import { Component, OnDestroy, OnInit, Self } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Subscription, combineLatest } from 'rxjs'; import { switchMap, scan } from 'rxjs/operators'; import * as moment from 'moment'; import { PullRequest, And, Like } from '../../../../../framework'; import { AllorsFilterService, ErrorService, MediaService, ContextService, NavigationService, Action, RefreshService, MetaService } from '../../../../../angular'; import { Sorter, TableRow, Table, NavigateService, DeleteService } from '../../../..'; import { Person } from '../../../../../domain'; import { ObjectService } from '../../../../../angular/base/object/object.service'; interface Row extends TableRow { object: Person; name: string; email: string; phone: string; lastModifiedDate: string; } @Component({ templateUrl: './person-list.component.html', providers: [ContextService, AllorsFilterService] }) export class PersonListComponent implements OnInit, OnDestroy { public title = 'People'; table: Table<Row>; delete: Action; private subscription: Subscription; constructor( @Self() public allors: ContextService, @Self() private filterService: AllorsFilterService, public metaService: MetaService, public factoryService: ObjectService, public refreshService: RefreshService, public navigateService: NavigateService, public deleteService: DeleteService, public navigation: NavigationService, public mediaService: MediaService, private errorService: ErrorService, titleService: Title) { titleService.setTitle(this.title); this.delete = deleteService.delete(allors.context); this.delete.result.subscribe((v) => { this.table.selection.clear(); }); this.table = new Table({ selection: true, columns: [ { name: 'name', sort: true}, { name: 'email', sort: true }, { name: 'phone', sort: true }, 'lastModifiedDate' ], actions: [ navigateService.overview(), this.delete ], defaultAction: navigateService.overview(), }); } public ngOnInit(): void { const { m, pull, x } = this.metaService; const predicate = new And([ new Like({ roleType: m.Person.FirstName, parameter: 'firstName' }), new Like({ roleType: m.Person.LastName, parameter: 'lasttName' }), // new ContainedIn({ // propertyType: m.Person.GeneralCorrespondence, // extent: new Filter({ // objectType: m.PostalAddress, // predicate: new ContainedIn({ // propertyType: m.PostalAddress.Country, // extent: new Filter({ // objectType: m.Country, // predicate: new Like({roleType: m.Country.Name, parameter: 'countryName'}) // }) // }) // }) // }) ]); this.filterService.init(predicate); const sorter = new Sorter( { name: [m.Person.FirstName, m.Person.LastName], lastModifiedDate: m.Person.LastModifiedDate, } ); this.subscription = combineLatest(this.refreshService.refresh$, this.filterService.filterFields$, this.table.sort$, this.table.pager$) .pipe( scan(([previousRefresh, previousFilterFields], [refresh, filterFields, sort, pageEvent]) => { return [ refresh, filterFields, sort, (previousRefresh !== refresh || filterFields !== previousFilterFields) ? Object.assign({ pageIndex: 0 }, pageEvent) : pageEvent, ]; }, []), switchMap(([, filterFields, sort, pageEvent]) => { const pulls = [ pull.Person({ predicate, sort: sorter.create(sort), include: { Salutation: x, Picture: x, GeneralPhoneNumber: x, GeneralEmail: x, }, arguments: this.filterService.arguments(filterFields), skip: pageEvent.pageIndex * pageEvent.pageSize, take: pageEvent.pageSize, })]; return this.allors.context.load('Pull', new PullRequest({ pulls })); }) ) .subscribe((loaded) => { this.allors.context.reset(); const people = loaded.collections.People as Person[]; this.table.total = loaded.values.People_total; this.table.data = people.map((v) => { return { object: v, name: v.displayName, email: v.displayEmail, phone: v.displayPhone, lastModifiedDate: moment(v.LastModifiedDate).fromNow() } as Row; }); }, this.errorService.handler); } public ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } }
Allors/apps
Domains/Apps/Workspace/Typescript/Intranet/src/allors/material/apps/objects/person/list/person-list.component.ts
TypeScript
gpl-3.0
4,882
"use strict"; /* * Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com> * This file is part of "Ancilla Libary". * * "Ancilla Libary" 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. * * "Ancilla Libary" 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 "Ancilla Libary". If not, see <http://www.gnu.org/licenses/>. */ let _ = require('lodash'); let Bluebird = require('bluebird'); let winston = require('winston'); let Chalk = require('chalk'); let Constant = require('./Constants.js'); class Logger { constructor( oLoggerOptions, oTargetToExtend ){ this.__oOptions = {}; this.config( _.extend({ sID: 'logger', sLevel: 'debug', bRemote: null, iRemotePort: 3000, bSilent: false, //sLogPath: './' + __filename + '.log', sLogPath: null, iLogMaxSize: 500000, // kB iLogMaxFiles: 1, sHeader: null, sHeaderStyleBackground: 'black', sHeaderStyleColor: 'white', bUseRandomStyle4Header: false, }, oLoggerOptions ) ); this._bRemoteEnabled = false; // Extending target with log methods if needed if( oTargetToExtend ){ this.extend( this.getID(), oTargetToExtend ); } } config( oDefaultOptions ){ // Merging curren default options with default options from argument this.__oOptions = _.extend( this.__oOptions, oDefaultOptions ); } setLevel( sLevel ){ console.error( '---->TODO Logger set Level', sLevel ); } add( sID, sHeader, oOptions ){ oOptions = this.__buildLoggerOptions( oOptions ); // Setting Header style if needed this.__setRandomStyle( oOptions ); let _Logger = this; if( !winston.loggers.loggers[ sID ] ){ // Creating Sub logger let _aTransports = [ new (winston.transports.Console)({ level: oOptions.sLevel, silent: oOptions.bSilent, colorize: true, prettyPrint: true, timestamp: true }) ]; if( oOptions.sLogPath ){ this.__oTransportLogFile = ( this.__oTransportLogFile ? this.__oTransportLogFile : new (winston.transports.File)({ level: oOptions.sLevel, filename: oOptions.sLogPath, maxsize: oOptions.iLogMaxSize, // 500 kB maxFiles: oOptions.iLogMaxFiles, prettyPrint: true, timestamp: true, json: false, tailable: true, zippedArchive: true, exitOnError: false })); _aTransports.push( this.__oTransportLogFile ); } winston.loggers.add( sID, { transports: _aTransports } ); } this.__addRemoteTransport( sID, oOptions ); winston.loggers.get( sID ).filters.push( function( sHeader ){ return function(iLevel, sMsg){ return ( sHeader ? '[ ' + sHeader + ' ] ' : '' ) + sMsg; }; }( ( oOptions.sHeader ?_Logger.__getTag( oOptions ) : null ) ) ); // if( oOptions.sLogPath ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on file: "%s"...', sID, oOptions.sLevel, oOptions.sLogPath ); } if( oOptions.sRemote ){ winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" using remote transport "%s"...', sID, oOptions.sLevel, oOptions.sRemote ); } winston.loggers.get( sID ).info( 'Log ID "%s" logging level "%s" on console...', sID, oOptions.sLevel ); } __addRemoteTransport( _sLoggerID, oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ this.__oTransportLogRemote = ( this.__oTransportLogRemote ? this.__oTransportLogRemote : new (require('./Logger.Transports/' + oOptions.sRemote +'.js'))({ sLevel: oOptions.sLevel })); /* // TODO: Correct way ( but we can't create more instance of the same transport... how to deal with it ? ) let _Transport = require('./Logger.Transports/' + oOptions.sRemote +'.js'); winston.loggers.loggers[ _sLoggerID ].add( _Transport, { sLevel: oOptions.sLevel }); */ // TODO: Wrong way ( since we can't create more instance of the same transport we are following this solution ) let _sID = this.__oTransportLogRemote.getID(); winston.loggers.loggers[ _sLoggerID ].transports[ _sID ] = this.__oTransportLogRemote; winston.loggers.loggers[ _sLoggerID ]._names = winston.loggers.loggers[ _sLoggerID ]._names.concat( _sID ); return this.__oTransportLogRemote.ready(); } return Bluebird.resolve(); } enableRemoteTransport( oOptions ){ oOptions = _.extend({ sRemote: false }, oOptions ); if( oOptions.sRemote && ( oOptions.sRemote === 'mqtt' || oOptions.sRemote === 'ws' )){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _bFound = false; let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ _bFound = true; } } if( !_bFound ){ // Adding remote transport if needed _aPromises.push( this.__addRemoteTransport( _sLoggerID, oOptions ) ); } } } return Bluebird.all( _aPromises ); } else { Bluebird.reject( Constant._ERROR_GENERIC_UNKNOWN ); } } disableRemoteTransport(){ let _aPromises = [ Bluebird.resolve() ]; let _oLoggers = winston.loggers.loggers; for( let _sLoggerID in _oLoggers ){ if( _oLoggers.hasOwnProperty( _sLoggerID ) ){ let _oTransports = _oLoggers[ _sLoggerID ].transports; for( let _sTransportID in _oTransports ){ if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){ // Killing Transport _aPromises.push( _oTransports[ _sTransportID ].destroy() ); delete _oTransports[ _sTransportID ]; } } } } return Bluebird.all( _aPromises ); } extend( sID, oTarget, oOptions ) { if( oTarget ){ // Bypassing .get because it will create an empty logger if sID is not present let _Logger = winston.loggers.loggers[ sID ];//let _Logger = winston.loggers.get( sID ); if( !_Logger ){ this.add( sID, oOptions.sHeader, oOptions ); _Logger = winston.loggers.get( sID ); } [ 'silly', 'debug', 'verbose', 'info', 'warn', 'error' ].forEach( function( sMethod ){ oTarget[ sMethod ] = function(){ return _Logger[ sMethod ].apply( _Logger, arguments ); }; }); } else { this.error( 'Unable to extend with logging functions ( ID: "%s" ), the target: ', sID, oTarget ); } return this; } get( sID ){ if( !sID ){ sID = this.getID(); } return winston.loggers.get( sID ); } __buildLoggerOptions( oOptions ){ return _.extend( this.__oOptions, oOptions ); } __getRandomItemFromArray( aArray, aFilterArray ){ if( !aFilterArray ){ aFilterArray = []; } let _aFilteredArray = aArray.filter(function( sElement ){ for( let _sElement in aFilterArray ){ if( aFilterArray.hasOwnProperty( _sElement ) ){ if( _sElement === sElement ){ return false; } } } return true; }); return _aFilteredArray[ Math.floor( Math.random() * _aFilteredArray.length ) ]; } __setRandomStyle( oOptions ){ if( oOptions.bUseRandomStyle4Header ){ /* let _aMofiers = [ 'reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough' ]; */ let _aColours = [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray' ]; let _aBackground = [ 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite' ]; //let _sModifier = this.__getRandomItemFromArray( _aMofiers ); oOptions.sHeaderStyleColor = this.__getRandomItemFromArray( _aColours ); oOptions.sHeaderStyleBackground = this.__getRandomItemFromArray( _aBackground ); } } __getTag( oOptions ){ return Chalk.styles[ oOptions.sHeaderStyleBackground ].open + Chalk.styles[ oOptions.sHeaderStyleColor ].open + oOptions.sHeader + Chalk.styles[ oOptions.sHeaderStyleColor ].close + Chalk.styles[ oOptions.sHeaderStyleBackground ].close; } } module.exports = Logger;
KingRial/Ancilla-Server
lib/Logger.js
JavaScript
gpl-3.0
9,102
Bitrix 16.5 Business Demo = 960ce51ec777d11100d45602c96d3b96
gohdan/DFC
known_files/hashes/bitrix/modules/sale/lang/ru/general/affiliate_plan_section.php
PHP
gpl-3.0
61
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TAMU.GeoInnovation.PointIntersectors.Census.MySql")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TAMU.GeoInnovation.PointIntersectors.Census.MySql")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("418C093A-8D74-43AB-B62E-9B611AD43708")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
TamuGeoInnovation/TAMU.GeoInnovation.PointIntersectors.Census.MySql
src/Main/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,274
for i in range(0): i += 1 for j in range(0, 1, 3): j += 1 for k in range(9, 1, -9): k += 1 for n in range(0, 1.1): # Error on this line n += 1 for m in range(4, 5): m += 1
RyanDJLee/pyta
examples/invalid_range_index_example.py
Python
gpl-3.0
197
/** * Yaafe extension for the Cultural Broadcasting Archive. * * Copyright (c) 2012 University of Applied Sciences Ð Institute for Creative Media Technologies * * Author : Ewald Wieser B.Sc. (fhstp.ac.at) * * Co-Authors : * Dipl.-Ing. (FH) Matthias Husinsky (fhstp.ac.at) * FH-Prof. Dipl.-Ing. Markus Seidl (fhstp.ac.at) * * Contributes to : * Dr. Klaus Seyerlehner (jku.at) * * This file is an extension for Standard-Yaafe, developed for Music * detection with the Continuous Frequency Activation Feature (CFA) for * the Cultural Broadcasting Archive (CBA). * * Yaafe 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 of the License, or * (at your option) any later version. * * Yaafe 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 program. If not, see <http://www.gnu.org/licenses/>. */ #include "AccumulateSameValues.h" #include <Eigen/Dense> using namespace Eigen; namespace YAAFE { AccumulateSameValues::AccumulateSameValues() { } AccumulateSameValues::~AccumulateSameValues() { } bool AccumulateSameValues::init(const ParameterMap& params, const Ports<StreamInfo>& inp) { assert(inp.size()==1); const StreamInfo& in = inp[0].data; outStreamInfo().add(StreamInfo(in,2)); return true; } bool AccumulateSameValues::process(Ports<InputBuffer*>& inp, Ports<OutputBuffer*>& outp) { assert(inp.size()==1); InputBuffer* in = inp[0].data; if (in->empty()) return false; assert(outp.size()==1); OutputBuffer* out = outp[0].data; double sum = 1; double* inData; while (!in->empty()) { inData = in->readToken(); if (inData[0] == inData[1]) sum++; // accumulate same values else{ double* outData = out->writeToken(); outData[0] = sum; // write values outData[1] = inData[0]; sum = 1; } in->consumeToken(); } if (sum > 1){ // write last value double* outData = out->writeToken(); outData[0] = sum-1; outData[1] = inData[0]; } return true; } }
mcrg-fhstp/cba-yaafe-extension
src_cpp/cba-yaafe-extension/audio/AccumulateSameValues.cpp
C++
gpl-3.0
2,571
import { Meteor } from "meteor/meteor"; import { Template } from "meteor/templating"; import { Roles } from "meteor/alanning:roles"; import { ReactiveVar } from "meteor/reactive-var"; import { Reaction } from "/client/api"; import { i18next } from "/client/api"; import * as Collections from "/lib/collections"; import { Components } from "@reactioncommerce/reaction-components"; /** * onCreated: Account Profile View */ Template.accountProfile.onCreated(() => { const template = Template.instance(); template.userHasPassword = ReactiveVar(false); Meteor.call("accounts/currentUserHasPassword", (error, result) => { template.userHasPassword.set(result); }); // hide actionView if open, doesn't relate to profile page Reaction.hideActionView(); }); /** * Helpers: Account Profile View */ Template.accountProfile.helpers({ UpdateEmail() { return { component: Components.UpdateEmail }; }, ReactionAvatar() { return { component: Components.ReactionAvatar }; }, /** * User has password * @return {Boolean} return true if the current user has a password, false otherwise */ userHasPassword() { return Template.instance().userHasPassword.get(); }, /** * User's order history * @return {Array|null} an array of available orders for the user */ userOrders() { const orderSub = Meteor.subscribe("AccountOrders", Meteor.userId()); if (orderSub.ready()) { return Collections.Orders.find({ userId: Meteor.userId() }, { sort: { createdAt: -1 }, limit: 25 }); } }, /** * User's account profile * @return {Object} account profile */ account() { return Collections.Accounts.findOne(); }, /** * User's display name * @return {String} display name */ displayName() { const userId = Meteor.userId() || {}; const user = Collections.Accounts.findOne(userId); if (user) { if (user.name) { return user.name; } else if (user.username) { return user.username; } else if (user.profile && user.profile.name) { return user.profile.name; } } if (Roles.userIsInRole(user._id || user.userId, "account/profile", Reaction.getShopId())) { return i18next.t("accountsUI.guest", { defaultValue: "Guest" }); } }, /** * Returns the address book default view * @return {String} "addressBookGrid" || "addressBookAdd" */ addressBookView: function () { const account = Collections.Accounts.findOne(); if (account.profile) { return "addressBookGrid"; } return "addressBookAdd"; }, isMarketplaceGuest: function () { return (Reaction.hasMarketplaceAccess("guest") && !Reaction.hasAdminAccess()); }, isMarketplaceSeller: function () { return (Reaction.hasMarketplaceAccess() && !Reaction.hasOwnerAccess()); } });
xxbooking/reaction
imports/plugins/core/accounts/client/templates/profile/profile.js
JavaScript
gpl-3.0
2,915
using iRacingDirector.Plugin; using System; using System.Drawing; using System.Drawing.Drawing2D; namespace JockeOverlays { public static class MyPluginExtensions { public static string FormattedForLeaderboard(this string shortName) { var length = Math.Min(4, shortName.Length); return shortName.Substring(0, length).ToUpper(); } public static GraphicRect DrawBlackBackground(this GraphicRect rr) { return rr .WithBrush(Styles.TransparentLightBlack) .WithPen(Styles.WhitePen) .DrawRectangleWithoutBorder(); } public static GraphicRect DrawGrayBackground(this GraphicRect rr) { return rr .WithBrush(Styles.TransparentLightGray) .WithPen(Styles.WhitePen) .DrawRectangleWithoutBorder(); } public static GraphicRect DrawWhiteText(this GraphicRect rr, string text, StringAlignment alignment) { rr.WithBrush(Styles.WhiteBrush) .WithStringFormat(alignment) .DrawText(text); return rr; } public static GraphicRect WithFontSizeOf(this GraphicRect rr, int fontSize) { return rr .WithFont(Settings.FontName, fontSize, FontStyle.Regular); } public static GraphicRect DrawWhiteGradiantBox(this GraphicRect rr) { return rr .WithLinearGradientBrush(Color.DarkGray, Color.White, LinearGradientMode.Vertical) .WithPen(Styles.BlackPen) .DrawRectangleWithBorder() .WithBrush(Styles.BlackBrush); } public static GraphicRect DrawRedGradiantBox(this GraphicRect rr) { return rr .WithHeight(rr.Rectangle.Height + 3) .MoveUp(3) .WithLinearGradientBrush(Styles.RedBannerDark, Styles.RedBannerLight, LinearGradientMode.Vertical) .DrawRoundRectangle(5) .WithBrush(Styles.WhiteBrush); } } }
vipoo/iRacingReplayOverlay.net
plugins/JockeOverlays/MyPlugin.Extensions.cs
C#
gpl-3.0
2,154
import axios from 'axios' const basePath = '/api' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' export default { Utils: { getYearsChoiceList: (app, model) => axios({ url: `${basePath}/${app}/${model}/years/`, method: 'GET' }), getModelOrderedList: (app, model, ordering = '', page = 1, query_string = '') => axios({ url: `${basePath}/${app}/${model}/?o=${ordering}&page=${page}${query_string}`, method: 'GET' }), getModelList: (app, model, page = 1, query_string = '') => axios({ url: `${basePath}/${app}/${model}/?page=${page}${query_string}`, method: 'GET' }), getModel: (app, model, id) => axios({ url: `${basePath}/${app}/${model}/${id}/`, method: 'GET' }), getModelAction: (app, model, id, action) => axios({ url: `${basePath}/${app}/${model}/${id}/${action}/`, method: 'GET' }), getModelListAction: (app, model, action, page = 1) => axios({ url: `${basePath}/${app}/${model}/${action}/?page=${page}`, method: 'GET' }), getByMetadata: (m, query_string = '') => axios({ url: `${basePath}/${m.app}/${m.model}/${m.id}${m.id !== '' ? '/' : ''}${m.action}${m.action !== '' ? '/' : ''}${query_string !== '' ? '?' : ''}${query_string}`, method: 'GET' }) } }
cmjatai/cmj
_frontend/v1/src/resources/index.js
JavaScript
gpl-3.0
1,346
package librecon; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. import android.os.Parcel; import android.os.Parcelable; import java.util.Locale; /** * Entity mapped to table SCHEDULE. */ public class Schedule implements Parcelable { private Long id; private String nameEs; private String nameEu; private String nameEn; private String date; private String descriptionEs; private String descriptionEu; private String descriptionEn; private String picUrl; private String picUrlSquare; private String startDatetime; private String finishDatetime; private String links; private String tags; private String location; private String targetDate; private String color; private String speakers; public Schedule() { } public Schedule(Long id) { this.id = id; } public Schedule(Long id, String nameEs, String nameEu, String nameEn, String date, String descriptionEs, String descriptionEu, String descriptionEn, String picUrl, String picUrlSquare, String startDatetime, String finishDatetime, String links, String tags, String location, String targetDate, String color) { this.id = id; this.nameEs = nameEs; this.nameEu = nameEu; this.nameEn = nameEn; this.date = date; this.descriptionEs = descriptionEs; this.descriptionEu = descriptionEu; this.descriptionEn = descriptionEn; this.picUrl = picUrl; this.picUrlSquare = picUrlSquare; this.startDatetime = startDatetime; this.finishDatetime = finishDatetime; this.links = links; this.tags = tags; this.location = location; this.targetDate = targetDate; this.color = color; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNameEs() { return nameEs; } public void setNameEs(String nameEs) { this.nameEs = nameEs; } public String getNameEu() { return nameEu; } public void setNameEu(String nameEu) { this.nameEu = nameEu; } public String getNameEn() { return nameEn; } public void setNameEn(String nameEn) { this.nameEn = nameEn; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getDescriptionEs() { return descriptionEs; } public void setDescriptionEs(String descriptionEs) { this.descriptionEs = descriptionEs; } public String getDescriptionEu() { return descriptionEu; } public void setDescriptionEu(String descriptionEu) { this.descriptionEu = descriptionEu; } public String getDescriptionEn() { return descriptionEn; } public void setDescriptionEn(String descriptionEn) { this.descriptionEn = descriptionEn; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getPicUrlSquare() { return picUrlSquare; } public void setPicUrlSquare(String picUrlSquare) { this.picUrlSquare = picUrlSquare; } public String getStartDatetime() { return startDatetime; } public void setStartDatetime(String startDatetime) { this.startDatetime = startDatetime; } public String getFinishDatetime() { return finishDatetime; } public void setFinishDatetime(String finishDatetime) { this.finishDatetime = finishDatetime; } public String getLinks() { return links; } public void setLinks(String links) { this.links = links; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getTargetDate() { return targetDate; } public void setTargetDate(String targetDate) { this.targetDate = targetDate; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getName() { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); if (language.equals("eu")) return this.nameEu; else if (language.equals("en")) return this.nameEn; else return this.nameEs; } public String getDescription() { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); if (language.equals("eu")) return this.descriptionEu; else if (language.equals("en")) return this.descriptionEn; else return this.descriptionEs; } public String getSpeakers() { return this.speakers; } public void setSpeakers(String speakers) { this.speakers = speakers; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeValue(this.id); dest.writeString(this.nameEs); dest.writeString(this.nameEu); dest.writeString(this.nameEn); dest.writeString(this.date); dest.writeString(this.descriptionEs); dest.writeString(this.descriptionEu); dest.writeString(this.descriptionEn); dest.writeString(this.picUrl); dest.writeString(this.picUrlSquare); dest.writeString(this.startDatetime); dest.writeString(this.finishDatetime); dest.writeString(this.links); dest.writeString(this.tags); dest.writeString(this.location); dest.writeString(this.targetDate); dest.writeString(this.color); } private Schedule(Parcel in) { this.id = (Long) in.readValue(Long.class.getClassLoader()); this.nameEs = in.readString(); this.nameEu = in.readString(); this.nameEn = in.readString(); this.date = in.readString(); this.descriptionEs = in.readString(); this.descriptionEu = in.readString(); this.descriptionEn = in.readString(); this.picUrl = in.readString(); this.picUrlSquare = in.readString(); this.startDatetime = in.readString(); this.finishDatetime = in.readString(); this.links = in.readString(); this.tags = in.readString(); this.location = in.readString(); this.targetDate = in.readString(); this.color = in.readString(); } public static final Creator<Schedule> CREATOR = new Creator<Schedule>() { public Schedule createFromParcel(Parcel source) { return new Schedule(source); } public Schedule[] newArray(int size) { return new Schedule[size]; } }; }
irontec/LibreCon-app
mobile/android/app/src/main/java-gen/librecon/Schedule.java
Java
gpl-3.0
7,468
/*----------------------------------------------------------------------*/ /* The name says it all */ /*----------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/ /* Subroutines */ /*-----------------------------------------------------------------------*/ function filterTasks(occ_code) { var results = []; for (var i = 0; i < taskData.length; i++) { if (taskData[i].fedscope_occ_code == occ_code) { newObject = {}; newObject = taskData[i]; newObject.hours = freq2hours(newObject.category); results.push(newObject); } } return results; } /*-----------------------------------------------------------------------*/ /* Convert frequency categories to hours */ /*-----------------------------------------------------------------------*/ function freq2hours(category) { var hours = 0; switch(category) { case "1": hours = .5; break; case "2": hours = 1; break; case "3": hours = 12; break; case "4": hours = 52; break; case "5": hours = 260; break; case "6": hours = 520; break; case "7": hours = 1043; break; default: console.log("Unknown frequency category: " + category); break; } return hours; } /*-----------------------------------------------------------------------*/ /* refresh the pie chart when you pass in a new occ code */ /*-----------------------------------------------------------------------*/ function refreshPie(newOccCode) { filteredTaskData = []; filteredTaskData = filterTasks(newOccCode); pieChartHandle.data(filteredTaskData) .draw(); $('#pie_heading').html("Hours per task for occupation " + newOccCode); }
pviechnicki/taskExplorer
js/helper_functions.js
JavaScript
gpl-3.0
1,881
/** * * $Id: NetworkNode.java 669 2010-06-14 14:53:38Z twanschik $ * * @version $Rev: 669 $ * @author $Author: twanschik $ * @date $Date: 2010-06-14 16:53:38 +0200 (Mo, 14 Jun 2010) $ * */ package org.hswgt.teachingbox.core.rl.network; import java.io.Serializable; import org.hswgt.teachingbox.core.rl.tools.Copyable; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.impl.DenseDoubleMatrix1D; import java.util.LinkedList; import java.util.List; // Abstract class representing a node in a network. Currently all nodes hold a // position so put it into the NetworkNode itself. public abstract class NetworkNode implements Copyable<NetworkNode>, Serializable { private static final long serialVersionUID = -1375335252449897775L; protected DoubleMatrix1D position; // dimension indicates how much dimensions this node covers protected int dimension = 0; protected List<NetworkNodeObserver> observers = new LinkedList<NetworkNodeObserver>(); protected Network net = null; // abstract method to implement public abstract double getValue(DoubleMatrix1D state); public double getValue(double[] state) { return getValue(new DenseDoubleMatrix1D(state)); } public DoubleMatrix1D getPosition() { return position.copy(); } public void setPosition(DoubleMatrix1D position) { boolean notify = true; if (this.position != null && this.position.equals(position)) notify = false; this.position = position.copy(); if (notify) this.notifyShapeChanged(); } public void setPosition(double[] position) { this.setPosition(new DenseDoubleMatrix1D(position)); } public void notifyPositionChanged() { for (NetworkNodeObserver observer: observers) observer.positionChanged(this); } // classes derived from NetworkNode should call notifyShapeChanged // if the change the shape. For RBFs this should be called if sigma changes! public void notifyShapeChanged() { for (NetworkNodeObserver observer: observers) observer.shapeChanged(this); } /** * Attaches an observer to this * * @param obs The observer to attach */ public void addObserver(final NetworkNodeObserver obs) { if( !this.observers.contains(obs) ) this.observers.add(obs); } /** * Remove an observer from this * @param obs The observer to detach */ public void removeObserver(final NetworkNodeObserver obs) { this.observers.remove(obs); } public Network getNet() { return net; } public void setNet(Network net) { this.net = net; } public int getDimension() { return dimension; } }
ieugen/Teachingbox
src/org/hswgt/teachingbox/core/rl/network/NetworkNode.java
Java
gpl-3.0
2,818
package com.fr.design.extra; import com.fr.design.dialog.BasicPane; import com.fr.general.Inter; import java.awt.BorderLayout; import java.awt.Component; /** * @author richie * @date 2015-03-09 * @since 8.0 * 应用中心的构建采用JavaScript代码来动态实现,但是不总是依赖于服务器端的HTML * 采用JDK提供的JavaScript引擎,实际是用JavaScript语法实现Java端的功能,并通过JavaScript引擎动态调用 * JavaScript放在安装目录下的scripts/store目录下,检测到新版本的时候,可以通过更新这个目录下的文件实现热更新 * 不直接嵌入WebView组件的原因是什么呢? * 因为如果直接嵌入WebView,和设计器的交互就需要预先设定好,这样灵活性会差很多,而如果使用JavaScript引擎, * 就可以直接在JavaScript中和WebView组件做交互,而同时JavaScript中可以调用任何的设计器API. */ public class ShopManagerPane extends BasicPane { public ShopManagerPane(Component webPane) { setLayout(new BorderLayout()); add(webPane, BorderLayout.CENTER); } @Override protected String title4PopupWindow() { return Inter.getLocText("FR-Designer-Plugin_Manager"); } }
fanruan/finereport-design
designer_base/src/com/fr/design/extra/ShopManagerPane.java
Java
gpl-3.0
1,223
/* A GTK+ wrapper around the cainteoir::ref_entry class. * * Copyright (C) 2015 Reece H. Dunn * * This file is part of cainteoir-gtk. * * cainteoir-gtk 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. * * cainteoir-gtk 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 cainteoir-gtk. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <gtk/gtk.h> #include <cainteoir-gtk/cainteoir_document_index.h> #include <cainteoir-gtk/cainteoir_document_view.h> #include <cainteoir/document.hpp> #include "cainteoir_document_private.h" #include "cainteoir_document_index_private.h" #include "extensions/glib.h" namespace rdf = cainteoir::rdf; enum IndexColumns { INDEX_ENTRY_PTR, INDEX_GUTTER, INDEX_TITLE, INDEX_ANCHOR, INDEX_DISPLAY, INDEX_COUNT }; struct CainteoirDocumentIndexPrivate { GtkTreeStore *store; GtkTreeSelection *selection; std::vector<cainteoir::ref_entry> index; const cainteoir::ref_entry *active; GtkTreeIter active_iter; CainteoirDocumentIndexPrivate() : active(nullptr) { store = gtk_tree_store_new(INDEX_COUNT, G_TYPE_POINTER, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); } }; G_DEFINE_TYPE_WITH_PRIVATE(CainteoirDocumentIndex, cainteoir_document_index, GTK_TYPE_TREE_VIEW) #define CAINTEOIR_DOCUMENT_INDEX_PRIVATE(object) \ ((CainteoirDocumentIndexPrivate *)cainteoir_document_index_get_instance_private(CAINTEOIR_DOCUMENT_INDEX(object))) GXT_DEFINE_TYPE_CONSTRUCTION(CainteoirDocumentIndex, cainteoir_document_index, CAINTEOIR_DOCUMENT_INDEX) static void cainteoir_document_index_class_init(CainteoirDocumentIndexClass *klass) { GObjectClass *object = G_OBJECT_CLASS(klass); object->finalize = cainteoir_document_index_finalize; } static const rdf::uri & uri_from_selected_item(GtkTreeModel *model, GList *item, bool advance) { static const rdf::uri empty_uri = {}; GtkTreeIter iter; if (item && gtk_tree_model_get_iter(model, &iter, (GtkTreePath *)item->data)) { if (advance) { if (!gtk_tree_model_iter_next(model, &iter)) return empty_uri; } const cainteoir::ref_entry *entry = nullptr; gtk_tree_model_get(model, &iter, INDEX_ENTRY_PTR, &entry, -1); return entry->location; } return empty_uri; } static bool find_ref_entry(GtkTreeModel *model, GtkTreeIter &iter, const cainteoir::ref_entry *value) { if (!gtk_tree_model_get_iter_first(model, &iter)) return false; do { const cainteoir::ref_entry *entry = nullptr; gtk_tree_model_get(model, &iter, INDEX_ENTRY_PTR, &entry, -1); if (entry == value) return true; } while (gtk_tree_model_iter_next(model, &iter)); return false; } static void on_cursor_changed(GtkTreeView *view, void *data) { GtkTreeSelection *toc_selection = gtk_tree_view_get_selection(view); GtkTreeModel *model = gtk_tree_view_get_model(view); GList *selected = gtk_tree_selection_get_selected_rows(toc_selection, nullptr); GList *item = g_list_first(selected); GtkTreeIter iter; if (item && gtk_tree_model_get_iter(model, &iter, (GtkTreePath *)item->data)) { gchar *anchor = nullptr; gtk_tree_model_get(model, &iter, INDEX_ANCHOR, &anchor, -1); cainteoir_document_view_scroll_to_anchor(CAINTEOIR_DOCUMENT_VIEW(data), anchor); g_free(anchor); } } static void add_icon_column(GtkTreeView *treeview, int i) { GtkCellRenderer *renderer = gtk_cell_renderer_pixbuf_new(); GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes("", renderer, "icon-name", i, nullptr); gtk_tree_view_append_column(treeview, column); } static void add_text_column(GtkTreeView *treeview, int i) { GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes("", renderer, "text", i, nullptr); gtk_tree_view_append_column(treeview, column); } GtkWidget * cainteoir_document_index_new(CainteoirDocumentView *view) { CainteoirDocumentIndex *self = CAINTEOIR_DOCUMENT_INDEX(g_object_new(CAINTEOIR_TYPE_DOCUMENT_INDEX, nullptr)); CainteoirDocumentIndexPrivate *priv = CAINTEOIR_DOCUMENT_INDEX_PRIVATE(self); gtk_tree_view_set_model(GTK_TREE_VIEW(self), GTK_TREE_MODEL(priv->store)); add_icon_column(GTK_TREE_VIEW(self), INDEX_GUTTER); add_text_column(GTK_TREE_VIEW(self), INDEX_DISPLAY); gtk_tree_view_set_rubber_banding(GTK_TREE_VIEW(self), TRUE); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(self), FALSE); gtk_tree_view_set_tooltip_column(GTK_TREE_VIEW(self), INDEX_TITLE); priv->selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(self)); gtk_tree_selection_set_mode(priv->selection, GTK_SELECTION_MULTIPLE); g_signal_connect(GTK_TREE_VIEW(self), "cursor-changed", G_CALLBACK(on_cursor_changed), view); return GTK_WIDGET(self); } void cainteoir_document_index_build(CainteoirDocumentIndex *index, CainteoirDocument *doc, const gchar *index_type) { CainteoirDocumentIndexPrivate *priv = CAINTEOIR_DOCUMENT_INDEX_PRIVATE(index); gtk_tree_store_clear(priv->store); if (!index_type) return; rdf::graph &metadata = *cainteoir_document_get_rdf_metadata(doc); rdf::uri &subject = *cainteoir_document_get_subject(doc); priv->index = cainteoir::navigation(metadata, subject, rdf::href(index_type)); if (priv->index.empty()) return; GtkTreeIter row; int initial_depth = priv->index.front().depth; for (const auto &entry : priv->index) { std::ostringstream title; for (const auto &i : cainteoir::range<int>(initial_depth, entry.depth)) title << "... "; title << entry.title; std::ostringstream tooltip; for (auto c : entry.title) switch (c) { case '&': tooltip << "&amp;"; break; case '<': tooltip << "&lt;"; break; case '>': tooltip << "&gt;"; break; default: tooltip << c; break; } gtk_tree_store_append(priv->store, &row, nullptr); gtk_tree_store_set(priv->store, &row, INDEX_ENTRY_PTR, &entry, INDEX_GUTTER, "", INDEX_TITLE, tooltip.str().c_str(), INDEX_ANCHOR, entry.location.str().c_str(), INDEX_DISPLAY, title.str().c_str(), -1); } } gboolean cainteoir_document_index_is_empty(CainteoirDocumentIndex *index) { CainteoirDocumentIndexPrivate *priv = CAINTEOIR_DOCUMENT_INDEX_PRIVATE(index); GtkTreeIter iter; return gtk_tree_model_get_iter_first(GTK_TREE_MODEL(priv->store), &iter) == FALSE ? TRUE : FALSE; } const std::vector<cainteoir::ref_entry> * cainteoir_document_index_get_listing(CainteoirDocumentIndex *index) { return &CAINTEOIR_DOCUMENT_INDEX_PRIVATE(index)->index; } void cainteoir_document_index_set_playing(CainteoirDocumentIndex *index, const cainteoir::ref_entry &entry) { CainteoirDocumentIndexPrivate *priv = CAINTEOIR_DOCUMENT_INDEX_PRIVATE(index); if (&entry == priv->active) return; if (priv->active) gtk_tree_store_set(priv->store, &priv->active_iter, INDEX_GUTTER, "", -1); if (!find_ref_entry(GTK_TREE_MODEL(priv->store), priv->active_iter, &entry)) return; gtk_tree_store_set(priv->store, &priv->active_iter, INDEX_GUTTER, "media-playback-start", -1); priv->active = &entry; } cainteoir_document_index_selection cainteoir_document_index_get_selection_uri(CainteoirDocumentIndex *index) { CainteoirDocumentIndexPrivate *priv = CAINTEOIR_DOCUMENT_INDEX_PRIVATE(index); GList *selected = gtk_tree_selection_get_selected_rows(priv->selection, nullptr); rdf::uri from; rdf::uri to; switch (g_list_length(selected)) { case 0: // read all ... break; case 1: // read from selected item ... from = uri_from_selected_item(GTK_TREE_MODEL(priv->store), g_list_first(selected), false); break; default: // read selected range ... from = uri_from_selected_item(GTK_TREE_MODEL(priv->store), g_list_first(selected), false); to = uri_from_selected_item(GTK_TREE_MODEL(priv->store), g_list_last(selected), true); break; } g_list_foreach(selected, (GFunc)gtk_tree_path_free, nullptr); g_list_free(selected); return { from, to }; }
rhdunn/cainteoir-gtk
src/libcainteoir-gtk/cainteoir_document_index.cpp
C++
gpl-3.0
8,391
package org.alvarogp.nettop.common.di.components; import org.alvarogp.nettop.common.di.modules.ActivityModule; import org.alvarogp.nettop.common.di.scopes.PerActivity; import dagger.Component; @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { }
alvarogzp/net-top
app/src/main/java/org/alvarogp/nettop/common/di/components/ActivityComponent.java
Java
gpl-3.0
334
<?php function index_ALL(Web $w) { History::add("Bend Home"); }
careck/bendms
bend/actions/index.php
PHP
gpl-3.0
69
#include "Display.h" #include <memory> #include <GL/glew.h> #include <SFML/Graphics.hpp> /* Display source file * Used for handling and managing the display portion of the engine */ namespace Display { constexpr static int Width = 640; constexpr static int Height = 480; std::unique_ptr<sf::RenderWindow> window; void init() { sf::ContextSettings settings; settings.depthBits = 24; // Set the openGL settings.majorVersion = 4; settings.minorVersion = 4; window = std::make_unique<sf::RenderWindow>(sf::VideoMode(Width, Height), "qDoom", sf::Style::Close, settings); // Initialize GLEW and set the drawing area glewInit(); glViewport(0, 0, Width, Height); } void close() { window->close(); } void clear() { glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); } void update() { window->display(); } void checkClose() { sf::Event e; while(window->pollEvent(e)) { if(e.type == sf::Event::Closed) { close(); } } } bool isOpen() { return window->isOpen(); } }
EpsilonGroup/qDoom
src/Display.cpp
C++
gpl-3.0
1,237
package com.slensky.focussis.parser; import android.support.annotation.NonNull; import android.util.Log; import android.util.SparseArray; import com.slensky.focussis.data.Demographic; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedSet; import java.util.TreeSet; /** * Created by slensky on 3/24/18. */ public class DemographicParser extends FocusPageParser { private static final String TAG = "DemographicParser"; private JSONArray result0; // contains basic information like first/last name private JSONArray result1; // custom demographic fields, e.g. nickname, locker #, bus # private JSONArray result2; // parental permissions @Override public Demographic parse(String jsonStr) throws JSONException { JSONArray json = new JSONArray(jsonStr); result0 = json.getJSONObject(0).getJSONArray("result"); result1 = json.getJSONObject(1).getJSONArray("result"); result2 = json.getJSONObject(2).getJSONArray("result"); // Get basic user info which should always be present (result0) String first = findField(result0, "First Name", "students|first_name", "first_name").getString("value"); Object middleObj = findField(result0, "Middle Name", "students|middle_name", "middle_name").get("value"); String middle = JSONObject.NULL.equals(middleObj) ? null : (String) middleObj; String last = findField(result0, "Last Name", "students|last_name", "last_name").getString("value"); String name = first + " " + (middle != null ? middle + " " : "") + last; int passLength = findField(result0, "Password", "students|password", "password").getString("value").length(); // Collect all custom field titles and values (result1) Map<String, String> customFields = new LinkedHashMap<>(); for (int i = 0; i < result1.length(); i++) { if (!(result1.get(i) instanceof JSONObject)) { continue; } JSONObject field = result1.getJSONObject(i); if (field.has("title") && field.has("value") && !JSONObject.NULL.equals(field.get("value"))) { String value = field.getString("value"); try { if (field.has("options") && field.get("options") instanceof JSONArray) { JSONArray options = field.getJSONArray("options"); for (int j = 0; j < options.length(); j++) { if (options.get(j) instanceof JSONObject && options.getJSONObject(j).getString("value").equals(value)) { value = options.getJSONObject(j).getString("text"); break; } } } } catch (JSONException e) { Log.w(TAG, "JSONException while attempting to parseRequirements options for custom field " + field.getString("title")); Log.w(TAG, field.toString(2)); e.printStackTrace(); } customFields.put(field.getString("title").trim(), value.trim()); } } // Collect all parental document/permission information (result2) // sort the table by the sort_order element so that data fields will be after their headers SortedSet<JSONObject> formsPermissionsBySortOrder = new TreeSet<>(new Comparator<JSONObject>() { @Override public int compare(JSONObject o1, JSONObject o2) { try { return o1.getInt("sort_order") - o2.getInt("sort_order"); } catch (JSONException e) { return 0; // should never happen, we ensure objects have this property before inserting them } } }); Map<String, Boolean> parentalForms = new LinkedHashMap<>(); Map<String, Boolean> parentalPermissions = new LinkedHashMap<>(); for (int i = 0; i < result2.length(); i++) { JSONObject o = result2.getJSONObject(i); if (o.has("title") && o.has("value") && o.has("type") && o.has("sort_order")) { formsPermissionsBySortOrder.add(o); } } boolean isFormsSection = false; boolean isPermissionsSection = false; for (JSONObject o : formsPermissionsBySortOrder) { if (o.getString("type").equals("holder")) { // "holder" type seems to be a header if (o.getString("title").toLowerCase().contains("documents")) { isPermissionsSection = false; isFormsSection = true; } else if (o.getString("title").toLowerCase().contains("permissions")) { isPermissionsSection = true; isFormsSection = false; } else { Log.w(TAG, "Unrecognized holder " + o.getString("title")); } } else if (o.getString("type").equals("checkbox")) { String title = o.getString("title").trim(); String v = o.getString("value"); boolean value = v.equals("1") || v.equals("true"); if (isFormsSection) { parentalForms.put(title, value); } else if (isPermissionsSection) { parentalPermissions.put(title, value); } } } return new Demographic(name, passLength, customFields, parentalForms, parentalPermissions); } // searches through the given result to find the field that has either the title, id, or column_name given // prefers to find a matching title, then matching id, then matching columnName private JSONObject findField(@NonNull JSONArray result, @NonNull String title, @NonNull String id, @NonNull String columnName) throws JSONException { // result title for (int i = 0; i < result.length(); i++) { if (!(result.get(i) instanceof JSONObject)) { continue; } JSONObject field = result.getJSONObject(i); if (field.getString("title").equals(title)) { Log.v(TAG, String.format("\"%s\" retrieved via title", title)); return field; } } // result id for (int i = 0; i < result.length(); i++) { if (!(result.get(i) instanceof JSONObject)) { continue; } JSONObject field = result.getJSONObject(i); if (field.getString("id").equals(id)) { Log.v(TAG, String.format("\"%s\" retrieved via id", title)); return field; } } // result columnName for (int i = 0; i < result.length(); i++) { if (!(result.get(i) instanceof JSONObject)) { continue; } JSONObject field = result.getJSONObject(i); if (field.getString("column_name").equals(columnName)) { Log.v(TAG, String.format("\"%s\" retrieved via column_name", title)); return field; } } throw new NoSuchElementException(String.format("Field title %s, id %s, column_name %s could not be found", title, id, columnName)); } private String getTextFromOptions(JSONObject field, String defaultText) throws JSONException { if (!field.has("options")) { throw new NoSuchElementException("Requested field does not have options"); } String value = field.getString("value"); JSONArray options = field.getJSONArray("options"); for (int i = 0; i < options.length(); i++) { JSONObject option = options.getJSONObject(i); if (option.getString("value").equals(value)) { return option.getString("text"); } } // get title for warning log string String title = "[title not in json]"; if (field.has("title")) { title = field.getString("title"); } Log.w(TAG, String.format("Using defaultText for field title %s", title)); return defaultText; } }
kidcontact/FocusSIS
app/src/main/java/com/slensky/focussis/parser/DemographicParser.java
Java
gpl-3.0
8,492
Bitrix 16.5 Business Demo = aaeba0b697addeaf01e4cbabb76ccdfd
gohdan/DFC
known_files/hashes/bitrix/modules/bitrix.sitecorporate/install/wizards/bitrix/corp_services/site/templates/corp_services/components/bitrix/system.auth.form/auth/template.php
PHP
gpl-3.0
61
package cj.ladders.lib; public class Reference { public static final String MOD_ID = "ladders"; public static final String MOD_NAME = "Simply Ladders"; public static final String VERSION = "0.0.1"; public static final String TEXTURES = MOD_ID + ":"; }
SiDzej/Simply-Ladders
common/cj/ladders/lib/Reference.java
Java
gpl-3.0
260
using Pathfinding; using System; using System.Collections.Generic; using UnityEngine; public class EnemyPathAI : MonoBehaviour { public static EnemyPathAI instance; //The point to move to public Vector3 target; private Seeker seeker; //The calculated path public Path path; //The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextWaypointDistance = 3; //The waypoint we are currently moving towards private int currentWaypoint = 0; public void Start() { if ( instance == null ) { instance = this; } else if ( instance != this ) { Destroy( gameObject ); } seeker = GetComponent<Seeker>(); //Start a new path to the targetPosition, return the result to the OnPathComplete function InvokeRepeating( "RunPath", 0f, .25f ); } private void RunPath() { target = GameManager.instance.GetEnemy().CurrentTarget; seeker.StartPath( transform.position, target, OnPathComplete ); } public void OnPathComplete( Path p ) { if ( !p.error ) { path = p; //Reset the waypoint counter currentWaypoint = 0; } } public void RunUpdate() { if ( path == null ) { //We have no path to move after yet return; } //Check if we are close enough to the next waypoint //If we are, proceed to follow the next waypoint try { if ( Vector2.Distance( transform.position, path.vectorPath[currentWaypoint] ) < nextWaypointDistance ) { currentWaypoint++; } } catch (ArgumentOutOfRangeException e) { Debug.Log(e); Debug.Log( "Shit, currentwaypoint is " + currentWaypoint + " but size of path.vectorPath.Count is " + path.vectorPath.Count ); } if ( currentWaypoint >= path.vectorPath.Count ) { return; } //Direction to the next waypoint Vector2 dir2 = ( path.vectorPath[currentWaypoint] - transform.position ).normalized; float newX = 0f; float newY = 0f; if (Mathf.Abs(dir2.x) > Mathf.Abs( dir2.y ) ) { newX = Mathf.Sign( dir2.x ); newY = 0f; } else { newX = 0f; newY = Mathf.Sign( dir2.y ); } Vector2 newDir = new Vector2( newX, newY ); try { GameManager.instance.GetEnemy().CurrentOrientation = GameManager.instance.GetEnemy().VectorOrientationDictionary.vDirToOrientationDictionary[newDir]; } catch ( KeyNotFoundException knf ) { GameManager.instance.GetEnemy().CurrentOrientation = OrientationEnum.DOWN; } } }
newhellstudios/medusa
Assets/Scripts/GameObjects/EnemyPathAI.cs
C#
gpl-3.0
2,793
/* Free Download Manager Copyright (c) 2003-2016 FreeDownloadManager.ORG */ #include "stdafx.h" #include "FdmApp.h" #include "Dlg_Download.h" #include "Downloads_Tasks.h" #include "DownloadsWnd.h" #include "Dlg_Download_OnHide.h" extern CDownloadsWnd* _pwndDownloads; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CDlg_Download::CDlg_Download(CWnd* pParent ) : CDialog(CDlg_Download::IDD, pParent), m_bUiLocked (false), m_bScheduleClose (false) { //{{AFX_DATA_INIT(CDlg_Download) //}}AFX_DATA_INIT } void CDlg_Download::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlg_Download) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlg_Download, CDialog) //{{AFX_MSG_MAP(CDlg_Download) ON_WM_TIMER() ON_WM_CTLCOLOR() ON_BN_CLICKED(IDC_HIDE, OnHide) ON_BN_CLICKED(IDC_AUTOCLOSE, OnAutoclose) ON_BN_CLICKED(IDC_STOP, OnStop) ON_BN_CLICKED(IDC_OPENFILE, OnOpenfile) ON_BN_CLICKED(IDC_OPENFOLDER, OnOpenfolder) ON_BN_CLICKED(IDC_AUTOLAUNCH, OnAutolaunch) //}}AFX_MSG_MAP END_MESSAGE_MAP() void CDlg_Download::Create(vmsDownloadSmartPtr dld) { m_dld = dld; CWnd wnd; wnd.m_hWnd = NULL; CDialog::Create (IDD_DOWNLOAD, &wnd); } CDlg_Download::~CDlg_Download() { } BOOL CDlg_Download::OnInitDialog() { CDialog::OnInitDialog(); m_wndProgress.Create (this); CRect rc; GetDlgItem (IDC__PROGRESS)->GetWindowRect (&rc); ScreenToClient (&rc); m_wndProgress.MoveWindow (&rc); m_wndProgress.m_dld = m_dld; LOGFONT lf; GetFont ()->GetLogFont (&lf); lf.lfWeight = FW_BOLD; m_fntBold.CreateFontIndirect (&lf); if (m_dld->pMgr->IsBittorrent ()) SetDlgItemText (IDC__URL_, LS (L_NAME)); ApplyLanguage (); SetTimer (1, 1000, NULL); CheckDlgButton (IDC_AUTOCLOSE, _App.DownloadDialog_AutoClose () ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton (IDC_AUTOLAUNCH, m_dld->pMgr->IsLaunchWhenDone () ? BST_CHECKED : BST_UNCHECKED); NeedUpdate (); SetTimer (2, 300, NULL); GetDlgItem (IDC_URL)->SetFont (&m_fntBold); GetDlgItem (IDC__RST)->SetFont (&m_fntBold); return TRUE; } void CDlg_Download::ApplyLanguage() { fsDlgLngInfo lnginfo [] = { fsDlgLngInfo (IDC__SAVEDIN_, L_SAVEDINFILE, TRUE), fsDlgLngInfo (IDC__FILESIZE_, L_FILESIZE, TRUE), fsDlgLngInfo (IDC__RESUMESUPPORT_, m_dld->pMgr->IsBittorrent () == FALSE ? L_RESUMESUPPORT : L_STATE, TRUE), fsDlgLngInfo (IDC__DOWNLOADED_, L_DOWNLOADED, TRUE), fsDlgLngInfo (IDC_SPEED_, L_SPEED, TRUE), fsDlgLngInfo (IDC_TIMELEFT_, L_TIMELEFT, TRUE), fsDlgLngInfo (IDC_AUTOCLOSE, L_CLOSEWINDOWWHENDONE), fsDlgLngInfo (IDC_OPENFOLDER, L_OPENFOLDER), fsDlgLngInfo (IDC_OPENFILE, L_LAUNCH), fsDlgLngInfo (IDC_STOP, L_STOP), fsDlgLngInfo (IDC_HIDE, L_HIDE), fsDlgLngInfo (IDC_AUTOLAUNCH, L_LAUNCHWHENDONE), }; _LngMgr.ApplyLanguage (this, lnginfo, sizeof (lnginfo) / sizeof (fsDlgLngInfo), L_DOWNLOAD); } void CDlg_Download::OnTimer(UINT nIDEvent) { if (nIDEvent == 2) { KillTimer (2); m_wndProgress.Invalidate (TRUE); return; } Update (); CDialog::OnTimer(nIDEvent); } void CDlg_Download::Update() { SetDlgItemText2 (IDC_URL, m_dld->pMgr->IsBittorrent () == FALSE ? m_dld->pMgr->get_URL () : m_dld->pMgr->GetBtDownloadMgr ()->get_TorrentName ()); SetDlgItemText2 (IDC__SAVEDIN, m_dld->pMgr->get_OutputFilePathName ()); SetDlgItemText2 (IDC__FILESIZE, CDownloads_Tasks::GetDownloadText (m_dld, 1)); int nProgress = (int) m_dld->pMgr->GetPercentDone (); if (m_dld->pMgr->IsBittorrent ()) { UINT64 nToDownload, nDownloaded; m_dld->pMgr->GetBtDownloadMgr ()->getPartialDownloadProgress (&nToDownload, &nDownloaded); if (nToDownload != m_dld->pMgr->GetLDFileSize ()) nProgress = nToDownload ? (int)((double)(INT64)nDownloaded / (INT64)nToDownload * 100) : 100; switch (m_dld->pMgr->GetBtDownloadMgr ()->get_State ()) { case BTDS_CHECKING_RESUME_DATA: case BTDS_CHECKING_FILES: case BTDS_ALLOCATING: SetDlgItemText2 (IDC__RST, LS (L_PREP_FILES_ONDISK_SHORT)); break; case BTDS_CONNECTING_TRACKER: SetDlgItemText2 (IDC__RST, LS (L_BT_TRACKER_ANNOUNCE)); break; case BTDS_DOWNLOADING: SetDlgItemText2 (IDC__RESUMESUPPORT_, LS (L_RESUMESUPPORT)); SetDlgItemText2 (IDC__RST, LS (L_YES)); break; } } else if (m_dld->pMgr->IsTp ()) { UINT64 uSize = m_dld->pMgr->GetLDFileSize (); if (uSize != _UI64_MAX && uSize != 0) { if (nProgress == -1) SetDlgItemText2 (IDC__RST, LS (L_NO)); else SetDlgItemText2 (IDC__RST, LS (L_YES)); } } else { switch (m_dld->pMgr->IsResumeSupported ()) { case RST_PRESENT: SetDlgItemText2 (IDC__RST, LS (L_YES)); break; case RST_NONE: SetDlgItemText2 (IDC__RST, LS (L_NO)); break; case RST_UNKNOWN: SetDlgItemText2 (IDC__RST, LS (L_UNKNOWN)); break; } } SetDlgItemText2 (IDC__DOWNLOADED, CDownloads_Tasks::GetDownloadText (m_dld, 2)); SetDlgItemText2 (IDC__SPEED, CDownloads_Tasks::GetDownloadText (m_dld, 5)); SetDlgItemText2 (IDC__TIMELEFT, CDownloads_Tasks::GetDownloadText (m_dld, 3)); TCHAR szName [10000] = _T(""); CDownloads_Tasks::GetFileName (m_dld, szName); CString str; switch (nProgress) { case 100: str.Format (_T("%s - %s"), szName, LS (L_DONE)); break; case -1: { UINT64 uDone = m_dld->pMgr->GetDownloadedBytesCount (); float val; TCHAR szDim [100]; BytesToXBytes (uDone, &val, szDim); str.Format (_T("%s - %.*g %s"), szName, val > 999 ? 4 : 3, val, szDim); break; } default: str.Format (_T("[%d%%] - %s"), nProgress, szName); break; } SetWindowText (str); m_wndProgress.Invalidate (FALSE); } void CDlg_Download::SetDlgItemText2(UINT nID, LPCTSTR pszText) { CString str; GetDlgItemText (nID, str); if (str != pszText) SetDlgItemText (nID, pszText); } HBRUSH CDlg_Download::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); pDC->SetBkMode (TRANSPARENT); if (GetDlgItem (IDC__RST)->m_hWnd == pWnd->m_hWnd) { if (m_dld->pMgr->IsBittorrent () == FALSE || m_dld->pMgr->GetBtDownloadMgr ()->get_State () == BTDS_DOWNLOADING) { switch (m_dld->pMgr->IsResumeSupported ()) { case RST_PRESENT: pDC->SetTextColor (RGB (0, 100, 0)); break; case RST_NONE: pDC->SetTextColor (RGB (150, 0, 0)); break; case RST_UNKNOWN: pDC->SetTextColor (RGB (150, 150, 0)); break; } } } return hbr; } void CDlg_Download::OnHide() { HWND hwndThis = m_hWnd; if (_App.DownloadDialog_DontAskOnHide () == FALSE && m_dld->pMgr->IsDone () == FALSE && m_dld->pMgr->IsRunning ()) { { vmsTHREAD_SAFE_SCOPE; m_bUiLocked = true; } CDlg_Download_OnHide dlg (this); auto result = _DlgMgr.DoModal (&dlg); { vmsTHREAD_SAFE_SCOPE; m_bUiLocked = false; } if (result == IDCANCEL) { { vmsTHREAD_SAFE_SCOPE; if (m_bScheduleClose) goto labelClose; } return; } if (!_pwndDownloads || !IsWindow (hwndThis)) return; switch (dlg.m_enResult) { case DDOR_SHOW: if (dlg.m_bDontAskAgain) _App.DownloadDialog_DontAskOnHide (TRUE); break; case DDOR_DONTSHOW: _App.DownloadDialog_Use (FALSE); _App.DownloadDialog_DontAskOnHide (TRUE); break; case DDOR_DONTSHOWFORTHISDLD: m_dld->dwFlags |= DLD_DONTSHOWDIALOG; m_dld->setDirty(); break; } } labelClose: if (_pwndDownloads) { m_dld->AddRef (); _pwndDownloads->PostMessage (WM_DW_CLOSEDLDDIALOG, 0, (LPARAM)(fsDownload*) m_dld); } } void CDlg_Download::OnAutoclose() { _App.DownloadDialog_AutoClose (IsDlgButtonChecked (IDC_AUTOCLOSE) == BST_CHECKED); } void CDlg_Download::NeedUpdate() { if (IsWindow (m_hWnd) == FALSE) return; if (m_dld->pMgr->IsRunning ()) SetDlgItemText (IDC_STOP, LS (L_STOP)); else SetDlgItemText (IDC_STOP, LS (L_START)); BOOL bDone = m_dld->pMgr->IsDone (); GetDlgItem (IDC_STOP)->EnableWindow (bDone == FALSE); GetDlgItem (IDC_OPENFILE)->EnableWindow (bDone); Update (); } void CDlg_Download::OnCancel() { OnHide (); } void CDlg_Download::OnStop() { DLDS_LIST vDlds; vDlds.push_back (m_dld); if (m_dld->pMgr->IsRunning()){ if (m_dld->isYouTube() && (MessageBox(LS(L_YOUTUBE_MESSAGE_ON_STOP), _T("Free Download Manager"), MB_OKCANCEL | MB_ICONWARNING) == IDCANCEL)) return; _DldsMgr.StopDownloads(vDlds, TRUE); } else _DldsMgr.StartDownloads (vDlds, TRUE); } void CDlg_Download::OnOpenfile() { _DldsMgr.LaunchDownload (m_dld); OnHide (); } void CDlg_Download::OnOpenfolder() { m_dld->pMgr->Do_OpenFolder (); if (m_dld->pMgr->IsDone ()) OnHide (); } void CDlg_Download::OnAutolaunch() { m_dld->pMgr->set_LaunchWhenDone (IsDlgButtonChecked (IDC_AUTOLAUNCH) == BST_CHECKED); }
mirror/freedownload
Dlg_Download.cpp
C++
gpl-3.0
9,112
/* * This file is part of Blue Power. * * Blue Power 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. * * Blue Power 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 Blue Power. If not, see <http://www.gnu.org/licenses/> */ package com.bluepowermod.network; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.World; import com.bluepowermod.network.messages.LocationDoublePacket; import com.bluepowermod.network.messages.LocationIntPacket; import com.bluepowermod.network.messages.MessageCircuitDatabaseTemplate; import com.bluepowermod.network.messages.MessageDebugBlock; import com.bluepowermod.network.messages.MessageGuiUpdate; import com.bluepowermod.network.messages.MessageMultipartRemove; import com.bluepowermod.network.messages.MessageSendClientServerTemplates; import com.bluepowermod.network.messages.MessageUpdateTextfield; import com.bluepowermod.util.Refs; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; /** * * @author MineMaarten */ public class NetworkHandler { public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(Refs.MODID); private static int discriminant; /* * The integer is the ID of the message, the Side is the side this message will be handled (received) on! */ public static void init() { INSTANCE.registerMessage(MessageGuiUpdate.class, MessageGuiUpdate.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageUpdateTextfield.class, MessageUpdateTextfield.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageMultipartRemove.class, MessageMultipartRemove.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageCircuitDatabaseTemplate.class, MessageCircuitDatabaseTemplate.class, discriminant++, Side.SERVER); INSTANCE.registerMessage(MessageCircuitDatabaseTemplate.class, MessageCircuitDatabaseTemplate.class, discriminant++, Side.CLIENT); INSTANCE.registerMessage(MessageDebugBlock.class, MessageDebugBlock.class, discriminant++, Side.CLIENT); INSTANCE.registerMessage(MessageSendClientServerTemplates.class, MessageSendClientServerTemplates.class, discriminant++, Side.CLIENT); } /* * public static void INSTANCE.registerMessage(Class<? extends AbstractPacket<? extends IMessage>> clazz){ INSTANCE.registerMessage(clazz, clazz, * discriminant++, Side.SERVER, discriminant++, Side.SERVER); } */ public static void sendToAll(IMessage message) { INSTANCE.sendToAll(message); } public static void sendTo(IMessage message, EntityPlayerMP player) { INSTANCE.sendTo(message, player); } @SuppressWarnings("rawtypes") public static void sendToAllAround(LocationIntPacket message, World world, double distance) { sendToAllAround(message, message.getTargetPoint(world, distance)); } @SuppressWarnings("rawtypes") public static void sendToAllAround(LocationIntPacket message, World world) { sendToAllAround(message, message.getTargetPoint(world)); } @SuppressWarnings("rawtypes") public static void sendToAllAround(LocationDoublePacket message, World world) { sendToAllAround(message, message.getTargetPoint(world)); } public static void sendToAllAround(IMessage message, NetworkRegistry.TargetPoint point) { INSTANCE.sendToAllAround(message, point); } public static void sendToDimension(IMessage message, int dimensionId) { INSTANCE.sendToDimension(message, dimensionId); } public static void sendToServer(IMessage message) { INSTANCE.sendToServer(message); } }
raulsmail/GlowPower
src/main/java/com/bluepowermod/network/NetworkHandler.java
Java
gpl-3.0
4,437
/* * Copyright (c) 2002-2015 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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 org.neo4j.graphdb; import org.neo4j.graphdb.index.RelationshipIndex; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableCollection; public class RelationshipIndexFacadeMethods { private static final FacadeMethod<RelationshipIndex> GET_WITH_FILTER = new FacadeMethod<RelationshipIndex>( "IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull, Node endNodeOrNull )" ) { @Override public void call( RelationshipIndex self ) { self.get( "foo", 42, null, null ); } }; private static final FacadeMethod<RelationshipIndex> QUERY_BY_KEY_WITH_FILTER = new FacadeMethod<RelationshipIndex>( "IndexHits<Relationship> query( String key, " + "Object queryOrQueryObjectOrNull, Node startNodeOrNull, Node endNodeOrNull )" ) { @Override public void call( RelationshipIndex self ) { self.query( "foo", 42, null, null ); } }; private static final FacadeMethod<RelationshipIndex> QUERY_WITH_FILTER = new FacadeMethod<RelationshipIndex>( "IndexHits<Relationship> query( Object queryOrQueryObjectOrNull, Node startNodeOrNull, " + "Node endNodeOrNull )" ) { @Override public void call( RelationshipIndex self ) { self.query( 42, null, null ); } }; private static final FacadeMethod<RelationshipIndex> GET = new FacadeMethod<RelationshipIndex>( "IndexHits<T>" + " get( String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.get( "foo", "bar" ); } }; private static final FacadeMethod<RelationshipIndex> QUERY_BY_KEY = new FacadeMethod<RelationshipIndex>( "IndexHits<T> query( String key, Object queryOrQueryObject )" ) { @Override public void call( RelationshipIndex self ) { self.query( "foo", "bar" ); } }; private static final FacadeMethod<RelationshipIndex> QUERY = new FacadeMethod<RelationshipIndex>( "IndexHits<T> query( Object queryOrQueryObject )" ) { @Override public void call( RelationshipIndex self ) { self.query( "foo" ); } }; private static final FacadeMethod<RelationshipIndex> ADD = new FacadeMethod<RelationshipIndex>( "void add( T " + "entity, String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.add( null, "foo", 42 ); } }; private static final FacadeMethod<RelationshipIndex> REMOVE_BY_KEY_AND_VALUE = new FacadeMethod<RelationshipIndex>( "void remove( T entity, String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.remove( null, "foo", 42 ); } }; private static final FacadeMethod<RelationshipIndex> REMOVE_BY_KEY = new FacadeMethod<RelationshipIndex>( "void remove( T entity, String key )" ) { @Override public void call( RelationshipIndex self ) { self.remove( null, "foo" ); } }; private static final FacadeMethod<RelationshipIndex> REMOVE = new FacadeMethod<RelationshipIndex>( "void " + "remove( T entity )" ) { @Override public void call( RelationshipIndex self ) { self.remove( null ); } }; private static final FacadeMethod<RelationshipIndex> DELETE = new FacadeMethod<RelationshipIndex>( "void delete()" ) { @Override public void call( RelationshipIndex self ) { self.delete(); } }; private static final FacadeMethod<RelationshipIndex> PUT_IF_ABSENT = new FacadeMethod<RelationshipIndex>( "T " + "putIfAbsent( T entity, String key, Object value )" ) { @Override public void call( RelationshipIndex self ) { self.putIfAbsent( null, "foo", 42 ); } }; static final Iterable<FacadeMethod<RelationshipIndex>> ALL_RELATIONSHIP_INDEX_FACADE_METHODS = unmodifiableCollection( asList( GET_WITH_FILTER, QUERY_BY_KEY_WITH_FILTER, QUERY_WITH_FILTER, GET, QUERY_BY_KEY, QUERY, ADD, REMOVE_BY_KEY_AND_VALUE, REMOVE_BY_KEY, REMOVE, DELETE, PUT_IF_ABSENT ) ); }
neo4j-contrib/neo4j-lucene5-index
src/test/java/org/neo4j/graphdb/RelationshipIndexFacadeMethods.java
Java
gpl-3.0
5,800
<?php defined('BASE_PATH') or die('No direct script access.');?> <?php require VIEWS_PATH.'header.php';?> <div id="main" class="wrapper"> <?php require VIEWS_PATH.'aside.php';?> <article> <header> <h2><?php echo $meta_title;?></h2> <p><?php echo $content;?>.</p> URL <?=Router::get_url('test_route',array('alphaonly',45565,'alpha_and_num'))?> </header> <h3>A smaller heading</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra. Pellentesque auctor neque quis nisl lacinia id rutrum lacus venenatis.</p> <h3>A smaller heading</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra. Pellentesque auctor neque quis nisl lacinia id rutrum lacus venenatis.</p> <footer> <h3>Article footfer</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices. Proin in est sed erat facilisis pharetra. Pellentesque auctor neque quis nisl lacinia id rutrum lacus venenatis.</p> </footer> </article> </div> <?php require VIEWS_PATH.'footer.php';?>
neo22s/jaf
themes/default/views/home.php
PHP
gpl-3.0
1,982
<?php /** * RemoveContactFromListTest * * PHP version 5 * * @category Class * @package SendinBlue\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * SendinBlue API * * SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable | * * OpenAPI spec version: 3.0.0 * Contact: contact@sendinblue.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.4.12 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the model. */ namespace SendinBlue\Client; /** * RemoveContactFromListTest Class Doc Comment * * @category Class * @description RemoveContactFromList * @package SendinBlue\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class RemoveContactFromListTest extends \PHPUnit_Framework_TestCase { /** * Setup before running any test case */ public static function setUpBeforeClass() { } /** * Setup before running each test case */ public function setUp() { } /** * Clean up after running each test case */ public function tearDown() { } /** * Clean up after running all test cases */ public static function tearDownAfterClass() { } /** * Test "RemoveContactFromList" */ public function testRemoveContactFromList() { } /** * Test attribute "emails" */ public function testPropertyEmails() { } /** * Test attribute "all" */ public function testPropertyAll() { } }
LoicLEMEUT/sendinblue
lib/api-v3-sdk/test/Model/RemoveContactFromListTest.php
PHP
gpl-3.0
2,553
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="fi_FI" sourcelanguage="en_US"> <context> <name>DebugLogModel</name> <message> <location filename="../private/debuglogwindow.cpp" line="273"/> <source>Timestamp</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogwindow.cpp" line="275"/> <source>Context</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogwindow.cpp" line="277"/> <source>Message</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DebugLogPopover</name> <message> <location filename="../private/debuglogpopover.ui" line="35"/> <source>Debug Log Item</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogpopover.cpp" line="37"/> <source>Timestamp</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogpopover.cpp" line="38"/> <source>Context</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogpopover.cpp" line="39"/> <source>Severity</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogpopover.cpp" line="40"/> <source>File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogpopover.cpp" line="40"/> <location filename="../private/debuglogpopover.cpp" line="41"/> <source>[unavailable]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogpopover.cpp" line="41"/> <source>Function</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DebugLogWindow</name> <message> <location filename="../private/debuglogwindow.ui" line="14"/> <source>Debug Log</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogwindow.ui" line="80"/> <source>Search Debug Log</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogwindow.ui" line="156"/> <source>Clear Log</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogwindow.ui" line="183"/> <source>Filter by Context</source> <translation type="unfinished"></translation> </message> <message> <location filename="../private/debuglogwindow.cpp" line="307"/> <source>context</source> <comment>Placeholder in search box</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>JobsPopover</name> <message> <location filename="../jobs/jobspopover.ui" line="35"/> <source>Jobs</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MAC_APPLICATION_MENU</name> <message> <location filename="../tapplication.cpp" line="97"/> <source>Services</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="98"/> <source>Hide %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="99"/> <source>Hide Others</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="100"/> <source>Show All</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="101"/> <source>Preferences...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="102"/> <location filename="../thelpmenu.cpp" line="46"/> <source>About %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="103"/> <source>Quit %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QCommandLineParser</name> <message> <location filename="../tapplication.cpp" line="106"/> <source>Displays version information.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="107"/> <source>Displays this help.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="108"/> <source>Unknown option &apos;%1&apos;.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="109"/> <source>Unknown options: %1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="110"/> <source>Missing value after &apos;%1&apos;.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="111"/> <source>Unexpected value after &apos;%1&apos;.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="112"/> <source>[options]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="113"/> <source>Usage: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="114"/> <source>Options:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="115"/> <source>Arguments:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>tAboutDialog</name> <message> <location filename="../taboutdialog.ui" line="194"/> <source>SOFTWARE</source> <translation type="unfinished"></translation> </message> <message> <location filename="../taboutdialog.ui" line="239"/> <source>COPYRIGHT</source> <translation type="unfinished"></translation> </message> <message> <location filename="../taboutdialog.ui" line="299"/> <source>OK</source> <translation type="unfinished"></translation> </message> <message> <location filename="../taboutdialog.cpp" line="15"/> <location filename="../taboutdialog.cpp" line="16"/> <source>About %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>tApplication</name> <message> <location filename="../tapplication.cpp" line="600"/> <source>Copyright © %1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="572"/> <location filename="../tapplication.cpp" line="575"/> <location filename="../tapplication.cpp" line="578"/> <location filename="../tapplication.cpp" line="581"/> <location filename="../tapplication.cpp" line="584"/> <location filename="../tapplication.cpp" line="587"/> <location filename="../tapplication.cpp" line="590"/> <location filename="../tapplication.cpp" line="593"/> <source>Licensed under the terms of the %1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="572"/> <source>GNU General Public License, version 3</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="575"/> <source>GNU General Public License, version 3, or later</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="578"/> <source>GNU General Public License, version 2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="581"/> <source>GNU General Public License, version 2, or later</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="584"/> <source>GNU Lesser General Public License, version 3</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="587"/> <source>GNU Lesser General Public License, version 3, or later</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="590"/> <source>GNU Lesser General Public License, version 2.1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tapplication.cpp" line="593"/> <source>GNU Lesser General Public License, version 2.1, or later</source> <translation type="unfinished"></translation> </message> </context> <context> <name>tHelpMenu</name> <message> <location filename="../thelpmenu.cpp" line="40"/> <source>%1 Help</source> <translation type="unfinished"></translation> </message> <message> <location filename="../thelpmenu.cpp" line="43"/> <source>File Bug</source> <translation type="unfinished"></translation> </message> <message> <location filename="../thelpmenu.cpp" line="44"/> <source>Sources</source> <translation type="unfinished"></translation> </message> <message> <location filename="../thelpmenu.cpp" line="45"/> <source>View Debug Log</source> <translation type="unfinished"></translation> </message> <message> <location filename="../thelpmenu.cpp" line="73"/> <source>Help</source> <translation type="unfinished"></translation> </message> </context> <context> <name>tInputDialog</name> <message> <location filename="../tinputdialog.ui" line="48"/> <source>Cancel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tinputdialog.ui" line="55"/> <source>OK</source> <translation type="unfinished"></translation> </message> </context> <context> <name>tLogger</name> <message> <location filename="../tlogger.cpp" line="105"/> <source>Debug</source> <comment>Severity Level</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../tlogger.cpp" line="107"/> <source>Warning</source> <comment>Severity Level</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../tlogger.cpp" line="109"/> <source>Critical</source> <comment>Severity Level</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../tlogger.cpp" line="111"/> <source>Fatal</source> <comment>Severity Level</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../tlogger.cpp" line="113"/> <source>Info</source> <comment>Severity Level</comment> <translation type="unfinished"></translation> </message> </context> </TS>
vicr123/the-libs
lib/translations/fi_FI.ts
TypeScript
gpl-3.0
12,697
/* * Hyperbox - Virtual Infrastructure Manager * Copyright (C) 2015 - Max Dor * * https://apps.kamax.io/hyperbox * * 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 io.kamax.hbox; import io.kamax.hbox.exception.HyperboxException; import io.kamax.tools.logging.Logger; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; public class ClassManager { private static Map<URL, Reflections> classes = new HashMap<URL, Reflections>(); static { Set<URL> urls = new HashSet<URL>(); for (URL url : ClasspathHelper.forJavaClassPath()) { if (url.getFile().endsWith(".jar") || url.getFile().endsWith(".class") || url.getFile().endsWith("/")) { urls.add(url); } } scan(urls); } private static void scan(Set<URL> urls, ClassLoader... loaders) { Long start = System.currentTimeMillis(); Reflections scan = new Reflections(new ConfigurationBuilder().addClassLoaders(loaders).setUrls(urls) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()) .setExecutorService(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()))); for (URL url : urls) { classes.put(url, scan); } Logger.debug("Scanning urls took " + (System.currentTimeMillis() - start) + " ms"); } public static void add(Set<URL> rawUrls, ClassLoader... loaders) { Set<URL> urls = new HashSet<URL>(); for (URL rawUrl : rawUrls) { if (!classes.containsKey(rawUrl)) { Logger.debug("Adding " + rawUrl.toString() + " to URL to scan"); urls.add(rawUrl); } } scan(urls, loaders); } public static void reload(Set<URL> rawUrls, ClassLoader... loaders) { scan(rawUrls, loaders); } public static void remove(Set<URL> urls) { for (URL url : urls) { classes.remove(url); Logger.debug("URL removed: " + url); } Logger.debug(classes.keySet().size() + " remaining URLs:"); for (URL url : classes.keySet()) { Logger.debug("\t" + url); } } @SuppressWarnings("unchecked") public static <T> T loadClass(Class<T> itWannabeClass, String it) { try { Class<T> itClass = (Class<T>) Class.forName(it); T itInstance = itClass.newInstance(); return itInstance; } catch (Exception e) { Logger.error("Failed to load " + it + " : " + e.getLocalizedMessage()); Logger.exception(e); throw new HyperboxException(e); } } public static <T> Set<Class<? extends T>> getSubTypes(Class<T> type) { Long start = System.currentTimeMillis(); Set<Class<? extends T>> classList = new HashSet<Class<? extends T>>(); for (Reflections data : classes.values()) { for (Class<? extends T> rawClass : data.getSubTypesOf(type)) { /* * Since we have modules, it is possible that several classes have the same name. * To avoid any conflict, we want to make sure only the good classes are returned. * * For the queried class type, if it comes from the system class loader (same as us), we have no problem * since that class type will be unique in the system. * * On the other hand, if the queried class type is not from the system class loader, it means it comes * from a module. In that case, we must only return results that are from the same class loader. */ if (ClassManager.class.getClassLoader().equals(type.getClassLoader()) || rawClass.getClassLoader().equals(type.getClassLoader())) { classList.addAll(data.getSubTypesOf(type)); } } } Logger.debug(type.getSimpleName() + " providers took " + (System.currentTimeMillis() - start) + " ms to find"); return classList; } public static <T> Set<Class<? extends T>> getAnnotatedSubTypes(Class<T> type, Class<? extends Annotation> note) { Long start = System.currentTimeMillis(); Set<Class<? extends T>> classList = new HashSet<Class<? extends T>>(); for (Class<? extends T> subType : getSubTypes(type)) { if (Modifier.isAbstract(subType.getModifiers())) { Logger.debug(subType.getName() + " is abstract and was ignored"); } else { for (Annotation subTypeNote : subType.getAnnotations()) { if (!subTypeNote.annotationType().equals(note)) { Logger.debug(subTypeNote.annotationType().getName() + " ignored, does not have annotation " + note.getName()); } else { Logger.debug("Found match for " + type.getName() + ": " + subType.getName()); classList.add(subType); } } } } Logger.debug(type.getSimpleName() + " providers took " + (System.currentTimeMillis() - start) + " ms to find"); return classList; } public static <T> Set<T> getQuiet(Class<T> type) { Set<T> loadedClasses = new HashSet<T>(); Set<Class<? extends T>> classes = getSubTypes(type); for (Class<? extends T> rawObject : classes) { try { if (!Modifier.isAbstract(rawObject.getModifiers())) { T view = rawObject.newInstance(); loadedClasses.add(view); } } catch (Exception e) { Logger.debug("Failed to load " + rawObject.getSimpleName() + " : " + e.getLocalizedMessage()); } } return loadedClasses; } public static <T> Set<T> getAtLeastOneOrFail(Class<T> type) throws HyperboxException { Set<T> objects = getQuiet(type); if (objects.isEmpty()) { throw new HyperboxException("Unable to find any match for " + type.getSimpleName()); } return objects; } public static <T> Set<T> getAllOrFail(Class<T> type) throws HyperboxException { try { Set<Class<? extends T>> classes = getSubTypes(type); Set<T> loadedClasses = new HashSet<T>(); for (Class<? extends T> rawObject : classes) { if (!Modifier.isAbstract(rawObject.getModifiers())) { T view = rawObject.newInstance(); loadedClasses.add(view); } } return loadedClasses; } catch (Exception e) { Logger.exception(e); throw new HyperboxException("Failed to load " + type.getSimpleName(), e); } } }
hyperbox/api
src/main/java/io/kamax/hbox/ClassManager.java
Java
gpl-3.0
7,888
package lab9; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Dell extends Product { private int mark_id ; public Dell() { super(); } public Dell(int id, String name, int quantity, float price, int markId){ super(id,name,quantity,price); this.mark_id = markId; } @Override void displayProduct() { System.out.println(getID() +"\t"+ getName()+"\t"+getQuantity()+"\t"+getPrice()+"\t"+getCost()); } void createProduct() { System.out.println("Nhap vao du lieu product"); try{ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Id : "); String s = bufferRead.readLine(); setID(Integer.parseInt(s)); System.out.println("Name: "); s = bufferRead.readLine(); setName(s); System.out.println("Quantity: "); s = bufferRead.readLine(); setQuantity(Integer.parseInt(s)); System.out.println("Price: "); setPrice(Float.parseFloat(s)); } catch(IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (MyException e) { e.getMessage(); } catch (Exception e) { e.printStackTrace(); } } float getCost(){ return getQuantity()*getPrice(); } void sortProduct(Product p[]){ } Product findProduct(int quantity, Product p[]) { return null; } public static void main(String[] args) { int n = 0; System.out.println("Nhap vao so phan tu"); BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); try { String s = bufferRead.readLine(); n = Integer.parseInt(s); } catch (Exception e) { e.printStackTrace(); } Dell pd[] = new Dell[n]; for(int i =0; i <n ; i++) { Dell d = new Dell(); d.createProduct(); pd[i] = d; } } public int getMark_id() { return mark_id; } public void setMark_id(int mark_id) { this.mark_id = mark_id; } }
zluuluyenz/mtech
js/lab9/Dell.java
Java
gpl-3.0
1,937
vti_encoding:SR|utf8-nl vti_timelastmodified:TW|14 Aug 2014 13:36:46 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|Office-PC\\Rafael vti_modifiedby:SR|Office-PC\\Rafael vti_timecreated:TR|01 Nov 2014 09:10:51 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|14 Aug 2014 13:36:46 -0000 vti_cacheddtm:TX|03 Nov 2015 21:10:29 -0000 vti_filesize:IR|58273 vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 13:36:46 -0000 vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:10:29 -0000
Vitronic/kaufreund.de
catalog/view/theme/theme436/js/elevate/_vti_cnf/jquery.elevatezoom.js
JavaScript
gpl-3.0
618
package mediamatrix.utils; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TreeSet; public class FileSearch { public static final int TYPE_FILE_OR_DIR = 1; public static final int TYPE_FILE = 2; public static final int TYPE_DIR = 3; public File[] listFiles(String directoryPath, String fileName) { if (fileName != null) { fileName = fileName.replace(".", "\\."); fileName = fileName.replace("*", ".*"); } return listFiles(directoryPath, fileName, TYPE_FILE, true, 0); } public File[] listFiles(String directoryPath, String fileNamePattern, int type, boolean isRecursive, int period) { File dir = new File(directoryPath); if (!dir.isDirectory()) { throw new IllegalArgumentException(); } File[] files = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; addFile(type, fileNamePattern, file, period); if (isRecursive && file.isDirectory()) { listFiles(file.getAbsolutePath(), fileNamePattern, type, isRecursive, period); } } } return set.toArray(new File[set.size()]); } private void addFile(int type, String match, File file, int period) { switch (type) { case TYPE_FILE: if (!file.isFile()) { return; } break; case TYPE_DIR: if (!file.isDirectory()) { return; } break; } if (match != null && !file.getName().matches(match)) { return; } if (period != 0) { Date lastModifiedDate = new Date(file.lastModified()); String lastModifiedDateStr = new SimpleDateFormat("yyyyMMdd").format(lastModifiedDate); long oneDayTime = 24L * 60L * 60L * 1000L; long periodTime = oneDayTime * Math.abs(period); Date designatedDate = new Date(System.currentTimeMillis() - periodTime); String designatedDateStr = new SimpleDateFormat("yyyyMMdd").format(designatedDate); if (period > 0) { if (lastModifiedDateStr.compareTo(designatedDateStr) < 0) { return; } } else { if (lastModifiedDateStr.compareTo(designatedDateStr) > 0) { return; } } } set.add(file); } private TreeSet<File> set = new TreeSet<File>(); public void clear() { set.clear(); } }
shuichi/MediaMatrix
src/main/java/mediamatrix/utils/FileSearch.java
Java
gpl-3.0
2,770
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | This file is where you may define all of the routes that are handled | by your application. Just tell Laravel the URIs it should respond | to using a Closure or controller method. Build something great! | */ Route::group(['middleware' => ['ConfigToSession']],function() { //首页 index. Route::get('/', 'UserController@index')->name('index'); //授权回调地址 authorization recall address. Route::get('oauth/recall/{authcode}', 'OAuthController@recall'); //通过Token从用户服务器上更新用户信息 Route::post('oauth/user/refresh', 'OAuthController@refreshUserInfo')->name('refreshUserInfo')->middleware('LoginStatusCheck'); Route::get('login', 'UserController@login')->name('login')->middleware('LoginStatusCheck'); Route::get('logout', 'UserController@logout')->name('logout')->middleware('LoginStatusCheck'); //修改房间信息 Route::post('room/edit', 'UserController@roomedit')->name('roomedit')->middleware('LoginStatusCheck'); //播放页 Route::get('room/{roomid}', 'RoomController@showRoom')->name('room')->where(['roomid'=>'[0-9]+']); Route::get('room/owner/{roomid}','RoomController@roomOwner')->name('roomOwner')->middleware('LoginStatusCheck')->where(['roomid'=>'[0-9]+']); Route::post('room/owner/{roomid}/toggleIndex','RoomController@toggleIndex')->name('roomToggleIndex')->where(['roomid'=>'[0-9]+']); Route::get('room/owner/edit','RoomController@showRoomEditSingle')->name('roomEditSingle')->middleware('LoginStatusCheck'); }); Route::get('error','Controller@error')->name('error'); /*Route::get('test',function(){ $host = "127.0.0.1"; $port = 1935; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create socket\n"); // 创建一个Socket $connection = socket_connect($socket, $host, $port) or die("Could not connet server\n"); // 连接 socket_write($socket, "hello socket") or die("Write failed\n"); // 数据传送 向服务器发送消息 //while ($buff = @socket_read($socket, 1024, PHP_NORMAL_READ)) { $buff = @socket_read($socket, 1024, PHP_NORMAL_READ); echo("Response was:" . $buff . "\n"); //} socket_close($socket); });*/
stevennight/Stevennight_Live
routes/web.php
PHP
gpl-3.0
2,390
# Default application mailer class ApplicationMailer < ActionMailer::Base default from: 'from@example.com' layout 'mailer' end
egglestn/quiz
app/mailers/application_mailer.rb
Ruby
gpl-3.0
131
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; using System.Collections; using System.Runtime.InteropServices; using System.Globalization; using System.Threading; using MissionPlanner.Utilities; using IronPython.Hosting; using log4net; using MissionPlanner.Controls; using MissionPlanner.Comms; using MissionPlanner.Log; using Transitions; using MissionPlanner.Warnings; namespace MissionPlanner { public partial class MainV2 : Form { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static class NativeMethods { // used to hide/show console window [DllImport("user32.dll")] public static extern int FindWindow(string szClass, string szTitle); [DllImport("user32.dll")] public static extern int ShowWindow(int Handle, int showState); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr RegisterDeviceNotification (IntPtr hRecipient, IntPtr NotificationFilter, Int32 Flags); // Import SetThreadExecutionState Win32 API and necessary flags [DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint esFlags); public const uint ES_CONTINUOUS = 0x80000000; public const uint ES_SYSTEM_REQUIRED = 0x00000001; static public int SW_SHOWNORMAL = 1; static public int SW_HIDE = 0; } static menuicons displayicons = new menuicons1(); public abstract class menuicons { public abstract Image fd { get; } public abstract Image fp { get; } public abstract Image initsetup { get; } public abstract Image config_tuning { get; } public abstract Image sim { get; } public abstract Image terminal { get; } public abstract Image help { get; } public abstract Image donate { get; } public abstract Image connect { get; } public abstract Image disconnect { get; } public abstract Image bg { get; } } public class menuicons1 : menuicons { public override Image fd { get { return global::MissionPlanner.Properties.Resources.light_flightdata_icon; } } public override Image fp { get { return global::MissionPlanner.Properties.Resources.light_flightplan_icon; } } public override Image initsetup { get { return global::MissionPlanner.Properties.Resources.light_initialsetup_icon; } } public override Image config_tuning { get { return global::MissionPlanner.Properties.Resources.light_tuningconfig_icon; } } public override Image sim { get { return global::MissionPlanner.Properties.Resources.light_simulation_icon; } } public override Image terminal { get { return global::MissionPlanner.Properties.Resources.light_terminal_icon; } } public override Image help { get { return global::MissionPlanner.Properties.Resources.light_help_icon; } } public override Image donate { get { return global::MissionPlanner.Properties.Resources.donate; } } public override Image connect { get { return global::MissionPlanner.Properties.Resources.light_connect_icon; } } public override Image disconnect { get { return global::MissionPlanner.Properties.Resources.light_disconnect_icon; } } public override Image bg { get { return global::MissionPlanner.Properties.Resources.bgdark; } } } public class menuicons2 : menuicons { public override Image fd { get { return global::MissionPlanner.Properties.Resources.dark_flightdata_icon; } } public override Image fp { get { return global::MissionPlanner.Properties.Resources.dark_flightplan_icon; } } public override Image initsetup { get { return global::MissionPlanner.Properties.Resources.dark_initialsetup_icon; } } public override Image config_tuning { get { return global::MissionPlanner.Properties.Resources.dark_tuningconfig_icon; } } public override Image sim { get { return global::MissionPlanner.Properties.Resources.dark_simulation_icon; } } public override Image terminal { get { return global::MissionPlanner.Properties.Resources.dark_terminal_icon; } } public override Image help { get { return global::MissionPlanner.Properties.Resources.dark_help_icon; } } public override Image donate { get { return global::MissionPlanner.Properties.Resources.donate; } } public override Image connect { get { return global::MissionPlanner.Properties.Resources.dark_connect_icon; } } public override Image disconnect { get { return global::MissionPlanner.Properties.Resources.dark_disconnect_icon; } } public override Image bg { get { return null; } } } Controls.MainSwitcher MyView; static bool _advanced = false; /// <summary> /// Control what is displayed /// </summary> public static Boolean Advanced { get { return _advanced; } set { _advanced = value; MissionPlanner.Controls.BackstageView.BackstageView.Advanced = value; if (AdvancedChanged != null) AdvancedChanged(null, EventArgs.Empty); } } public static bool ShowAirports { get; set; } public static bool ShowTFR { get; set; } private Utilities.adsb _adsb; public bool EnableADSB { get { return _adsb != null; } set { if (value == true) { _adsb = new Utilities.adsb(); if (Settings.Instance["adsbserver"] != null) Utilities.adsb.server = Settings.Instance["adsbserver"]; if (Settings.Instance["adsbport"] != null) Utilities.adsb.serverport = int.Parse(Settings.Instance["adsbport"].ToString()); } else { Utilities.adsb.Stop(); _adsb = null; } } } public static event EventHandler AdvancedChanged; /// <summary> /// Active Comport interface /// </summary> public static MAVLinkInterface comPort { get { return _comPort; } set { if (_comPort == value) return; _comPort = value; _comPort.MavChanged -= instance.comPort_MavChanged; _comPort.MavChanged += instance.comPort_MavChanged; instance.comPort_MavChanged(null, null); } } static MAVLinkInterface _comPort = new MAVLinkInterface(); /// <summary> /// passive comports /// </summary> public static List<MAVLinkInterface> Comports = new List<MAVLinkInterface>(); public delegate void WMDeviceChangeEventHandler(WM_DEVICECHANGE_enum cause); public event WMDeviceChangeEventHandler DeviceChanged; /// <summary> /// other planes in the area from adsb /// </summary> internal object adsblock = new object(); public Hashtable adsbPlanes = new Hashtable(); public Hashtable adsbPlaneAge = new Hashtable(); string titlebar; /// <summary> /// Comport name /// </summary> public static string comPortName = ""; /// <summary> /// mono detection /// </summary> public static bool MONO = false; /// <summary> /// speech engine enable /// </summary> public static bool speechEnable = false; /// <summary> /// spech engine static class /// </summary> public static Speech speechEngine = null; /// <summary> /// joystick static class /// </summary> public static Joystick.Joystick joystick = null; /// <summary> /// track last joystick packet sent. used to control rate /// </summary> DateTime lastjoystick = DateTime.Now; /// <summary> /// determine if we are running sitl /// </summary> public static bool sitl { get { if (MissionPlanner.Controls.SITL.SITLSEND == null) return false; if (MissionPlanner.Controls.SITL.SITLSEND.Client.Connected) return true; return false; } } /// <summary> /// hud background image grabber from a video stream - not realy that efficent. ie no hardware overlays etc. /// </summary> public static WebCamService.Capture cam = null; /// <summary> /// controls the main serial reader thread /// </summary> bool serialThread = false; bool pluginthreadrun = false; bool joystickthreadrun = false; Thread httpthread; Thread joystickthread; Thread serialreaderthread; Thread pluginthread; /// <summary> /// track the last heartbeat sent /// </summary> private DateTime heatbeatSend = DateTime.Now; /// <summary> /// used to call anything as needed. /// </summary> public static MainV2 instance = null; public static MainSwitcher View; /// <summary> /// store the time we first connect /// </summary> DateTime connecttime = DateTime.Now; DateTime nodatawarning = DateTime.Now; DateTime OpenTime = DateTime.Now; /// <summary> /// enum of firmwares /// </summary> public enum Firmwares { ArduPlane, ArduCopter2, ArduRover, Ateryx, ArduTracker, Gymbal, PX4 } DateTime connectButtonUpdate = DateTime.Now; /// <summary> /// declared here if i want a "single" instance of the form /// ie configuration gets reloaded on every click /// </summary> public GCSViews.FlightData FlightData; public GCSViews.FlightPlanner FlightPlanner; GCSViews.Simulation Simulation; private Form connectionStatsForm; private ConnectionStats _connectionStats; /// <summary> /// This 'Control' is the toolstrip control that holds the comport combo, baudrate combo etc /// Otiginally seperate controls, each hosted in a toolstip sqaure, combined into this custom /// control for layout reasons. /// </summary> static internal ConnectionControl _connectionControl; public void updateAdvanced(object sender, EventArgs e) { if (Advanced == false) { MenuTerminal.Visible = false; MenuSimulation.Visible = false; } else { MenuTerminal.Visible = true; MenuSimulation.Visible = true; } } public MainV2() { log.Info("Mainv2 ctor"); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); // set this before we reset it Settings.Instance["NUM_tracklength"] = "200"; // create one here - but override on load Settings.Instance["guid"] = Guid.NewGuid().ToString(); // load config LoadConfig(); // force language to be loaded L10N.GetConfigLang(); ShowAirports = true; // setup adsb Utilities.adsb.UpdatePlanePosition += adsb_UpdatePlanePosition; Form splash = Program.Splash; splash.Refresh(); Application.DoEvents(); instance = this; //disable dpi scaling if (Font.Name != "宋体") //Chinese displayed normally when scaling. But would be too small or large using this line of code. Font = new Font(Font.Name, 8.25f*96f/CreateGraphics().DpiX, Font.Style, Font.Unit, Font.GdiCharSet, Font.GdiVerticalFont); InitializeComponent(); MyView = new MainSwitcher(this); View = MyView; AdvancedChanged += updateAdvanced; //startup console TCPConsole.Write((byte) 'S'); _connectionControl = toolStripConnectionControl.ConnectionControl; _connectionControl.CMB_baudrate.TextChanged += this.CMB_baudrate_TextChanged; _connectionControl.CMB_serialport.SelectedIndexChanged += this.CMB_serialport_SelectedIndexChanged; _connectionControl.CMB_serialport.Click += this.CMB_serialport_Click; _connectionControl.ShowLinkStats += (sender, e) => ShowConnectionStatsForm(); srtm.datadirectory = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "srtm"; var t = Type.GetType("Mono.Runtime"); MONO = (t != null); speechEngine = new Speech(); Warnings.CustomWarning.defaultsrc = comPort.MAV.cs; Warnings.WarningEngine.Start(); // proxy loader - dll load now instead of on config form load new Transition(new TransitionType_EaseInEaseOut(2000)); foreach (object obj in Enum.GetValues(typeof (Firmwares))) { _connectionControl.TOOL_APMFirmware.Items.Add(obj); } if (_connectionControl.TOOL_APMFirmware.Items.Count > 0) _connectionControl.TOOL_APMFirmware.SelectedIndex = 0; comPort.BaseStream.BaudRate = 115200; PopulateSerialportList(); if (_connectionControl.CMB_serialport.Items.Count > 0) { _connectionControl.CMB_baudrate.SelectedIndex = 8; _connectionControl.CMB_serialport.SelectedIndex = 0; } // ** Done splash.Refresh(); Application.DoEvents(); string temp = Settings.Instance.ComPort; if (!string.IsNullOrEmpty(temp)) { _connectionControl.CMB_serialport.SelectedIndex = _connectionControl.CMB_serialport.FindString(temp); if (_connectionControl.CMB_serialport.SelectedIndex == -1) { _connectionControl.CMB_serialport.Text = temp; // allows ports that dont exist - yet } comPort.BaseStream.PortName = temp; comPortName = temp; } string temp2 = Settings.Instance.BaudRate; if (!string.IsNullOrEmpty(temp2)) { _connectionControl.CMB_baudrate.SelectedIndex = _connectionControl.CMB_baudrate.FindString(temp2); if (_connectionControl.CMB_baudrate.SelectedIndex == -1) { _connectionControl.CMB_baudrate.Text = temp2; } } string temp3 = Settings.Instance.APMFirmware; if (!string.IsNullOrEmpty(temp3)) { _connectionControl.TOOL_APMFirmware.SelectedIndex = _connectionControl.TOOL_APMFirmware.FindStringExact(temp3); if (_connectionControl.TOOL_APMFirmware.SelectedIndex == -1) _connectionControl.TOOL_APMFirmware.SelectedIndex = 0; MainV2.comPort.MAV.cs.firmware = (MainV2.Firmwares) Enum.Parse(typeof (MainV2.Firmwares), _connectionControl.TOOL_APMFirmware.Text); } MissionPlanner.Utilities.Tracking.cid = new Guid(Settings.Instance["guid"].ToString()); // setup guids for droneshare if (!Settings.Instance.ContainsKey("plane_guid")) Settings.Instance["plane_guid"] = Guid.NewGuid().ToString(); if (!Settings.Instance.ContainsKey("copter_guid")) Settings.Instance["copter_guid"] = Guid.NewGuid().ToString(); if (!Settings.Instance.ContainsKey("rover_guid")) Settings.Instance["rover_guid"] = Guid.NewGuid().ToString(); if (Settings.Instance.ContainsKey("language") && !string.IsNullOrEmpty(Settings.Instance["language"])) { changelanguage(CultureInfoEx.GetCultureInfo(Settings.Instance["language"])); } this.Text = splash.Text; titlebar = splash.Text; if (!MONO) // windows only { if (Settings.Instance["showconsole"] != null && Settings.Instance["showconsole"].ToString() == "True") { } else { int win = NativeMethods.FindWindow("ConsoleWindowClass", null); NativeMethods.ShowWindow(win, NativeMethods.SW_HIDE); // hide window } // prevent system from sleeping while mp open var previousExecutionState = NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED); } ChangeUnits(); if (Settings.Instance["theme"] != null) { try { ThemeManager.SetTheme( (ThemeManager.Themes) Enum.Parse(typeof (ThemeManager.Themes), Settings.Instance["theme"].ToString())); } catch (Exception exception) { log.Error(exception); } if (ThemeManager.CurrentTheme == ThemeManager.Themes.Custom) { try { ThemeManager.BGColor = Color.FromArgb(int.Parse(Settings.Instance["theme_bg"].ToString())); ThemeManager.ControlBGColor = Color.FromArgb(int.Parse(Settings.Instance["theme_ctlbg"].ToString())); ThemeManager.TextColor = Color.FromArgb(int.Parse(Settings.Instance["theme_text"].ToString())); ThemeManager.ButBG = Color.FromArgb(int.Parse(Settings.Instance["theme_butbg"].ToString())); ThemeManager.ButBorder = Color.FromArgb(int.Parse(Settings.Instance["theme_butbord"].ToString())); } catch { log.Error("Bad Custom theme - reset to standard"); ThemeManager.SetTheme(ThemeManager.Themes.BurntKermit); } } if (ThemeManager.CurrentTheme == ThemeManager.Themes.HighContrast) { switchlight(new menuicons2()); } } if (Settings.Instance["showairports"] != null) { MainV2.ShowAirports = bool.Parse(Settings.Instance["showairports"]); } // set default ShowTFR = true; // load saved if (Settings.Instance["showtfr"] != null) { MainV2.ShowTFR = Settings.Instance.GetBoolean("showtfr"); } if (Settings.Instance["enableadsb"] != null) { MainV2.instance.EnableADSB = Settings.Instance.GetBoolean("enableadsb"); } // load this before the other screens get loaded if (Settings.Instance["advancedview"] != null) { MainV2.Advanced = Settings.Instance.GetBoolean("advancedview"); } else { // existing user - enable advanced view if (Settings.Instance.Count > 3) { Settings.Instance["advancedview"] = true.ToString(); MainV2.Advanced = true; } else { Settings.Instance["advancedview"] = false.ToString(); } } try { log.Info("Create FD"); FlightData = new GCSViews.FlightData(); log.Info("Create FP"); FlightPlanner = new GCSViews.FlightPlanner(); //Configuration = new GCSViews.ConfigurationView.Setup(); log.Info("Create SIM"); Simulation = new GCSViews.Simulation(); //Firmware = new GCSViews.Firmware(); //Terminal = new GCSViews.Terminal(); FlightData.Width = MyView.Width; FlightPlanner.Width = MyView.Width; Simulation.Width = MyView.Width; } catch (ArgumentException e) { //http://www.microsoft.com/en-us/download/details.aspx?id=16083 //System.ArgumentException: Font 'Arial' does not support style 'Regular'. log.Fatal(e); CustomMessageBox.Show(e.ToString() + "\n\n Font Issues? Please install this http://www.microsoft.com/en-us/download/details.aspx?id=16083"); //splash.Close(); //this.Close(); Application.Exit(); } catch (Exception e) { log.Fatal(e); CustomMessageBox.Show("A Major error has occured : " + e.ToString()); Application.Exit(); } if (Settings.Instance["CHK_GDIPlus"] != null) GCSViews.FlightData.myhud.UseOpenGL = !bool.Parse(Settings.Instance["CHK_GDIPlus"].ToString()); if (Settings.Instance["CHK_hudshow"] != null) GCSViews.FlightData.myhud.hudon = bool.Parse(Settings.Instance["CHK_hudshow"].ToString()); try { if (Settings.Instance["MainLocX"] != null && Settings.Instance["MainLocY"] != null) { this.StartPosition = FormStartPosition.Manual; Point startpos = new Point(Settings.Instance.GetInt32("MainLocX"), Settings.Instance.GetInt32("MainLocY")); // fix common bug which happens when user removes a monitor, the app shows up // offscreen and it is very hard to move it onscreen. Also happens with // remote desktop a lot. So this only restores position if the position // is visible. foreach (Screen s in Screen.AllScreens) { if (s.WorkingArea.Contains(startpos)) { this.Location = startpos; break; } } } if (Settings.Instance["MainMaximised"] != null) { this.WindowState = (FormWindowState) Enum.Parse(typeof (FormWindowState), Settings.Instance["MainMaximised"]); // dont allow minimised start state if (this.WindowState == FormWindowState.Minimized) { this.WindowState = FormWindowState.Normal; this.Location = new Point(100, 100); } } if (Settings.Instance["MainHeight"] != null) this.Height = Settings.Instance.GetInt32("MainHeight"); if (Settings.Instance["MainWidth"] != null) this.Width = Settings.Instance.GetInt32("MainWidth"); if (Settings.Instance["CMB_rateattitude"] != null) CurrentState.rateattitudebackup = Settings.Instance.GetByte("CMB_rateattitude"); if (Settings.Instance["CMB_rateposition"] != null) CurrentState.ratepositionbackup = Settings.Instance.GetByte("CMB_rateposition"); if (Settings.Instance["CMB_ratestatus"] != null) CurrentState.ratestatusbackup = Settings.Instance.GetByte("CMB_ratestatus"); if (Settings.Instance["CMB_raterc"] != null) CurrentState.ratercbackup = Settings.Instance.GetByte("CMB_raterc"); if (Settings.Instance["CMB_ratesensors"] != null) CurrentState.ratesensorsbackup = Settings.Instance.GetByte("CMB_ratesensors"); // make sure rates propogate MainV2.comPort.MAV.cs.ResetInternals(); if (Settings.Instance["speechenable"] != null) MainV2.speechEnable = Settings.Instance.GetBoolean("speechenable"); if (Settings.Instance["analyticsoptout"] != null) MissionPlanner.Utilities.Tracking.OptOut = Settings.Instance.GetBoolean("analyticsoptout"); try { if (Settings.Instance["TXT_homelat"] != null) MainV2.comPort.MAV.cs.HomeLocation.Lat = Settings.Instance.GetDouble("TXT_homelat"); if (Settings.Instance["TXT_homelng"] != null) MainV2.comPort.MAV.cs.HomeLocation.Lng = Settings.Instance.GetDouble("TXT_homelng"); if (Settings.Instance["TXT_homealt"] != null) MainV2.comPort.MAV.cs.HomeLocation.Alt = Settings.Instance.GetDouble("TXT_homealt"); // remove invalid entrys if (Math.Abs(MainV2.comPort.MAV.cs.HomeLocation.Lat) > 90 || Math.Abs(MainV2.comPort.MAV.cs.HomeLocation.Lng) > 180) MainV2.comPort.MAV.cs.HomeLocation = new PointLatLngAlt(); } catch { } } catch { } if (CurrentState.rateattitudebackup == 0) // initilised to 10, configured above from save { CustomMessageBox.Show( "NOTE: your attitude rate is 0, the hud will not work\nChange in Configuration > Planner > Telemetry Rates"); } // create log dir if it doesnt exist if (!Directory.Exists(Settings.Instance.LogDir)) Directory.CreateDirectory(Settings.Instance.LogDir); //System.Threading.Thread.Sleep(2000); Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; // make sure new enough .net framework is installed if (!MONO) { Microsoft.Win32.RegistryKey installed_versions = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP"); string[] version_names = installed_versions.GetSubKeyNames(); //version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture); int SP = Convert.ToInt32(installed_versions.OpenSubKey(version_names[version_names.Length - 1]) .GetValue("SP", 0)); if (Framework < 4.0) { CustomMessageBox.Show("This program requires .NET Framework 4.0. You currently have " + Framework); } } if (Program.Logo != null) { this.Icon = Icon.FromHandle(((Bitmap) Program.Logo).GetHicon()); } if (Program.Logo != null && Program.vvvvz) { MenuDonate.Click -= this.toolStripMenuItem1_Click; MenuDonate.Text = ""; MenuDonate.Image = Program.Logo; MenuDonate.Click += MenuCustom_Click; MenuFlightData.Visible = false; MenuFlightPlanner.Visible = true; MenuConfigTune.Visible = false; MenuHelp.Visible = false; MenuInitConfig.Visible = false; MenuSimulation.Visible = false; MenuTerminal.Visible = false; } Application.DoEvents(); Comports.Add(comPort); MainV2.comPort.MavChanged += comPort_MavChanged; // save config to test we have write access SaveConfig(); } void comPort_MavChanged(object sender, EventArgs e) { log.Info("Mav Changed " + MainV2.comPort.MAV.sysid); HUD.Custom.src = MainV2.comPort.MAV.cs; CustomWarning.defaultsrc = MainV2.comPort.MAV.cs; MissionPlanner.Controls.PreFlight.CheckListItem.defaultsrc = MainV2.comPort.MAV.cs; // when uploading a firmware we dont want to reload this screen. if (instance.MyView.current.Control != null && instance.MyView.current.Control.GetType() == typeof(GCSViews.InitialSetup)) { var page = ((GCSViews.InitialSetup)instance.MyView.current.Control).backstageView.SelectedPage; if (page != null && page.Text == "Install Firmware") { return; } } if (this.InvokeRequired) { this.Invoke((MethodInvoker) delegate { instance.MyView.Reload(); }); } else { instance.MyView.Reload(); } } void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e) { // try prevent crash on resume if (e.Mode == Microsoft.Win32.PowerModes.Suspend) { doDisconnect(MainV2.comPort); } } private void BGLoadAirports(object nothing) { // read airport list try { Utilities.Airports.ReadOurairports(Application.StartupPath + Path.DirectorySeparatorChar + "airports.csv"); Utilities.Airports.checkdups = true; //Utilities.Airports.ReadOpenflights(Application.StartupPath + Path.DirectorySeparatorChar + "airports.dat"); log.Info("Loaded " + Utilities.Airports.GetAirportCount + " airports"); } catch { } } void switchlight(menuicons icons) { displayicons = icons; MainMenu.BackColor = SystemColors.MenuBar; ThemeManager.ApplyThemeTo(MainMenu); MainMenu.BackgroundImage = displayicons.bg; MenuFlightData.Image = displayicons.fd; MenuFlightPlanner.Image = displayicons.fp; MenuInitConfig.Image = displayicons.config_tuning; MenuSimulation.Image = displayicons.sim; MenuConfigTune.Image = displayicons.config_tuning; MenuTerminal.Image = displayicons.terminal; MenuConnect.Image = displayicons.connect; MenuHelp.Image = displayicons.help; MenuDonate.Image = displayicons.donate; MenuFlightData.ForeColor = ThemeManager.TextColor; MenuFlightPlanner.ForeColor = ThemeManager.TextColor; MenuInitConfig.ForeColor = ThemeManager.TextColor; MenuSimulation.ForeColor = ThemeManager.TextColor; MenuConfigTune.ForeColor = ThemeManager.TextColor; MenuTerminal.ForeColor = ThemeManager.TextColor; MenuConnect.ForeColor = ThemeManager.TextColor; MenuHelp.ForeColor = ThemeManager.TextColor; MenuDonate.ForeColor = ThemeManager.TextColor; } void MenuCustom_Click(object sender, EventArgs e) { if (Settings.Instance.GetBoolean("password_protect") == false) { MenuFlightData.Visible = true; MenuFlightPlanner.Visible = true; MenuConfigTune.Visible = true; MenuHelp.Visible = true; MenuInitConfig.Visible = true; MenuSimulation.Visible = true; MenuTerminal.Visible = true; } else { if (Password.VerifyPassword()) { MenuFlightData.Visible = true; MenuFlightPlanner.Visible = true; MenuConfigTune.Visible = true; MenuHelp.Visible = true; MenuInitConfig.Visible = true; MenuSimulation.Visible = true; MenuTerminal.Visible = true; } } } void adsb_UpdatePlanePosition(object sender, EventArgs e) { lock (adsblock) { adsbPlanes[((MissionPlanner.Utilities.adsb.PointLatLngAltHdg) sender).Tag] = ((MissionPlanner.Utilities.adsb.PointLatLngAltHdg) sender); adsbPlaneAge[((MissionPlanner.Utilities.adsb.PointLatLngAltHdg) sender).Tag] = DateTime.Now; } } private void ResetConnectionStats() { log.Info("Reset connection stats"); // If the form has been closed, or never shown before, we need do nothing, as // connection stats will be reset when shown if (this.connectionStatsForm != null && connectionStatsForm.Visible) { // else the form is already showing. reset the stats this.connectionStatsForm.Controls.Clear(); _connectionStats = new ConnectionStats(comPort); this.connectionStatsForm.Controls.Add(_connectionStats); ThemeManager.ApplyThemeTo(this.connectionStatsForm); } } private void ShowConnectionStatsForm() { if (this.connectionStatsForm == null || this.connectionStatsForm.IsDisposed) { // If the form has been closed, or never shown before, we need all new stuff this.connectionStatsForm = new Form { Width = 430, Height = 180, MaximizeBox = false, MinimizeBox = false, FormBorderStyle = FormBorderStyle.FixedDialog, Text = Strings.LinkStats }; // Change the connection stats control, so that when/if the connection stats form is showing, // there will be something to see this.connectionStatsForm.Controls.Clear(); _connectionStats = new ConnectionStats(comPort); this.connectionStatsForm.Controls.Add(_connectionStats); this.connectionStatsForm.Width = _connectionStats.Width; } this.connectionStatsForm.Show(); ThemeManager.ApplyThemeTo(this.connectionStatsForm); } private void CMB_serialport_Click(object sender, EventArgs e) { string oldport = _connectionControl.CMB_serialport.Text; PopulateSerialportList(); if (_connectionControl.CMB_serialport.Items.Contains(oldport)) _connectionControl.CMB_serialport.Text = oldport; } private void PopulateSerialportList() { _connectionControl.CMB_serialport.Items.Clear(); _connectionControl.CMB_serialport.Items.Add("AUTO"); _connectionControl.CMB_serialport.Items.AddRange(SerialPort.GetPortNames()); _connectionControl.CMB_serialport.Items.Add("TCP"); _connectionControl.CMB_serialport.Items.Add("UDP"); _connectionControl.CMB_serialport.Items.Add("UDPCl"); } private void MenuFlightData_Click(object sender, EventArgs e) { MyView.ShowScreen("FlightData"); } private void MenuFlightPlanner_Click(object sender, EventArgs e) { MyView.ShowScreen("FlightPlanner"); } public void MenuSetup_Click(object sender, EventArgs e) { if (Settings.Instance.GetBoolean("password_protect") == false) { MyView.ShowScreen("HWConfig"); } else { if (Password.VerifyPassword()) { MyView.ShowScreen("HWConfig"); } } } private void MenuSimulation_Click(object sender, EventArgs e) { MyView.ShowScreen("Simulation"); } private void MenuTuning_Click(object sender, EventArgs e) { if (Settings.Instance.GetBoolean("password_protect") == false) { MyView.ShowScreen("SWConfig"); } else { if (Password.VerifyPassword()) { MyView.ShowScreen("SWConfig"); } } } private void MenuTerminal_Click(object sender, EventArgs e) { MyView.ShowScreen("Terminal"); } public void doDisconnect(MAVLinkInterface comPort) { log.Info("We are disconnecting"); try { if (speechEngine != null) // cancel all pending speech speechEngine.SpeakAsyncCancelAll(); comPort.BaseStream.DtrEnable = false; comPort.Close(); } catch (Exception ex) { log.Error(ex); } // now that we have closed the connection, cancel the connection stats // so that the 'time connected' etc does not grow, but the user can still // look at the now frozen stats on the still open form try { // if terminal is used, then closed using this button.... exception if (this.connectionStatsForm != null) ((ConnectionStats) this.connectionStatsForm.Controls[0]).StopUpdates(); } catch { } // refresh config window if needed if (MyView.current != null) { if (MyView.current.Name == "HWConfig") MyView.ShowScreen("HWConfig"); if (MyView.current.Name == "SWConfig") MyView.ShowScreen("SWConfig"); } try { System.Threading.ThreadPool.QueueUserWorkItem((WaitCallback) delegate { try { MissionPlanner.Log.LogSort.SortLogs(Directory.GetFiles(Settings.Instance.LogDir, "*.tlog")); } catch { } } ); } catch { } this.MenuConnect.Image = global::MissionPlanner.Properties.Resources.light_connect_icon; } public void doConnect(MAVLinkInterface comPort, string portname, string baud) { bool skipconnectcheck = false; log.Info("We are connecting"); switch (portname) { case "preset": skipconnectcheck = true; break; case "TCP": comPort.BaseStream = new TcpSerial(); _connectionControl.CMB_serialport.Text = "TCP"; break; case "UDP": comPort.BaseStream = new UdpSerial(); _connectionControl.CMB_serialport.Text = "UDP"; break; case "UDPCl": comPort.BaseStream = new UdpSerialConnect(); _connectionControl.CMB_serialport.Text = "UDPCl"; break; case "AUTO": default: comPort.BaseStream = new SerialPort(); break; } // Tell the connection UI that we are now connected. _connectionControl.IsConnected(true); // Here we want to reset the connection stats counter etc. this.ResetConnectionStats(); comPort.MAV.cs.ResetInternals(); //cleanup any log being played comPort.logreadmode = false; if (comPort.logplaybackfile != null) comPort.logplaybackfile.Close(); comPort.logplaybackfile = null; try { // do autoscan if (portname == "AUTO") { Comms.CommsSerialScan.Scan(false); DateTime deadline = DateTime.Now.AddSeconds(50); while (Comms.CommsSerialScan.foundport == false) { System.Threading.Thread.Sleep(100); if (DateTime.Now > deadline) { CustomMessageBox.Show(Strings.Timeout); _connectionControl.IsConnected(false); return; } } _connectionControl.CMB_serialport.Text = portname = Comms.CommsSerialScan.portinterface.PortName; _connectionControl.CMB_baudrate.Text = baud = Comms.CommsSerialScan.portinterface.BaudRate.ToString(); } log.Info("Set Portname"); // set port, then options comPort.BaseStream.PortName = portname; log.Info("Set Baudrate"); try { comPort.BaseStream.BaudRate = int.Parse(baud); } catch (Exception exp) { log.Error(exp); } // prevent serialreader from doing anything comPort.giveComport = true; log.Info("About to do dtr if needed"); // reset on connect logic. if (Settings.Instance.GetBoolean("CHK_resetapmonconnect") == true) { log.Info("set dtr rts to false"); comPort.BaseStream.DtrEnable = false; comPort.BaseStream.RtsEnable = false; comPort.BaseStream.toggleDTR(); } comPort.giveComport = false; // setup to record new logs try { Directory.CreateDirectory(Settings.Instance.LogDir); comPort.logfile = new BufferedStream( File.Open( Settings.Instance.LogDir + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".tlog", FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)); comPort.rawlogfile = new BufferedStream( File.Open( Settings.Instance.LogDir + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".rlog", FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)); log.Info("creating logfile " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".tlog"); } catch (Exception exp2) { log.Error(exp2); CustomMessageBox.Show(Strings.Failclog); } // soft fail // reset connect time - for timeout functions connecttime = DateTime.Now; // do the connect comPort.Open(false, skipconnectcheck); if (!comPort.BaseStream.IsOpen) { log.Info("comport is closed. existing connect"); try { _connectionControl.IsConnected(false); UpdateConnectIcon(); comPort.Close(); } catch { } return; } // get all mavstates var list = comPort.MAVlist.GetMAVStates(); // get all the params foreach (var mavstate in list) { comPort.sysidcurrent = mavstate.sysid; comPort.compidcurrent = mavstate.compid; comPort.getParamList(); } // set to first seen comPort.sysidcurrent = list[0].sysid; comPort.compidcurrent = list[0].compid; _connectionControl.UpdateSysIDS(); // detect firmware we are conected to. if (comPort.MAV.cs.firmware == Firmwares.ArduCopter2) { _connectionControl.TOOL_APMFirmware.SelectedIndex = _connectionControl.TOOL_APMFirmware.Items.IndexOf(Firmwares.ArduCopter2); } else if (comPort.MAV.cs.firmware == Firmwares.Ateryx) { _connectionControl.TOOL_APMFirmware.SelectedIndex = _connectionControl.TOOL_APMFirmware.Items.IndexOf(Firmwares.Ateryx); } else if (comPort.MAV.cs.firmware == Firmwares.ArduRover) { _connectionControl.TOOL_APMFirmware.SelectedIndex = _connectionControl.TOOL_APMFirmware.Items.IndexOf(Firmwares.ArduRover); } else if (comPort.MAV.cs.firmware == Firmwares.ArduPlane) { _connectionControl.TOOL_APMFirmware.SelectedIndex = _connectionControl.TOOL_APMFirmware.Items.IndexOf(Firmwares.ArduPlane); } // check for newer firmware var softwares = Firmware.LoadSoftwares(); if (softwares.Count > 0) { try { string[] fields1 = comPort.MAV.VersionString.Split(' '); foreach (Firmware.software item in softwares) { string[] fields2 = item.name.Split(' '); // check primare firmware type. ie arudplane, arducopter if (fields1[0] == fields2[0]) { Version ver1 = VersionDetection.GetVersion(comPort.MAV.VersionString); Version ver2 = VersionDetection.GetVersion(item.name); if (ver2 > ver1) { Common.MessageShowAgain(Strings.NewFirmware + "-" + item.name, Strings.NewFirmwareA + item.name + Strings.Pleaseup); break; } // check the first hit only break; } } } catch (Exception ex) { log.Error(ex); } } FlightData.CheckBatteryShow(); MissionPlanner.Utilities.Tracking.AddEvent("Connect", "Connect", comPort.MAV.cs.firmware.ToString(), comPort.MAV.param.Count.ToString()); MissionPlanner.Utilities.Tracking.AddTiming("Connect", "Connect Time", (DateTime.Now - connecttime).TotalMilliseconds, ""); MissionPlanner.Utilities.Tracking.AddEvent("Connect", "Baud", comPort.BaseStream.BaudRate.ToString(), ""); // save the baudrate for this port Settings.Instance[_connectionControl.CMB_serialport.Text + "_BAUD"] = _connectionControl.CMB_baudrate.Text; this.Text = titlebar + " " + comPort.MAV.VersionString; // refresh config window if needed if (MyView.current != null) { if (MyView.current.Name == "HWConfig") MyView.ShowScreen("HWConfig"); if (MyView.current.Name == "SWConfig") MyView.ShowScreen("SWConfig"); } // load wps on connect option. if (Settings.Instance.GetBoolean("loadwpsonconnect") == true) { // only do it if we are connected. if (comPort.BaseStream.IsOpen) { MenuFlightPlanner_Click(null, null); FlightPlanner.BUT_read_Click(null, null); } } // get any rallypoints if (MainV2.comPort.MAV.param.ContainsKey("RALLY_TOTAL") && int.Parse(MainV2.comPort.MAV.param["RALLY_TOTAL"].ToString()) > 0) { FlightPlanner.getRallyPointsToolStripMenuItem_Click(null, null); double maxdist = 0; foreach (var rally in comPort.MAV.rallypoints) { foreach (var rally1 in comPort.MAV.rallypoints) { var pnt1 = new PointLatLngAlt(rally.Value.lat/10000000.0f, rally.Value.lng/10000000.0f); var pnt2 = new PointLatLngAlt(rally1.Value.lat/10000000.0f, rally1.Value.lng/10000000.0f); var dist = pnt1.GetDistance(pnt2); maxdist = Math.Max(maxdist, dist); } } if (comPort.MAV.param.ContainsKey("RALLY_LIMIT_KM") && (maxdist/1000.0) > (float) comPort.MAV.param["RALLY_LIMIT_KM"]) { CustomMessageBox.Show(Strings.Warningrallypointdistance + " " + (maxdist/1000.0).ToString("0.00") + " > " + (float) comPort.MAV.param["RALLY_LIMIT_KM"]); } } // set connected icon this.MenuConnect.Image = displayicons.disconnect; } catch (Exception ex) { log.Warn(ex); try { _connectionControl.IsConnected(false); UpdateConnectIcon(); comPort.Close(); } catch (Exception ex2) { log.Warn(ex2); } CustomMessageBox.Show("Can not establish a connection\n\n" + ex.Message); return; } } private void MenuConnect_Click(object sender, EventArgs e) { comPort.giveComport = false; log.Info("MenuConnect Start"); // sanity check if (comPort.BaseStream.IsOpen && MainV2.comPort.MAV.cs.groundspeed > 4) { if (DialogResult.No == CustomMessageBox.Show(Strings.Stillmoving, Strings.Disconnect, MessageBoxButtons.YesNo)) { return; } } try { log.Info("Cleanup last logfiles"); // cleanup from any previous sessions if (comPort.logfile != null) comPort.logfile.Close(); if (comPort.rawlogfile != null) comPort.rawlogfile.Close(); } catch (Exception ex) { CustomMessageBox.Show(Strings.ErrorClosingLogFile + ex.Message, Strings.ERROR); } comPort.logfile = null; comPort.rawlogfile = null; // decide if this is a connect or disconnect if (comPort.BaseStream.IsOpen) { doDisconnect(comPort); } else { doConnect(comPort, _connectionControl.CMB_serialport.Text, _connectionControl.CMB_baudrate.Text); } MainV2._connectionControl.UpdateSysIDS(); } private void CMB_serialport_SelectedIndexChanged(object sender, EventArgs e) { comPortName = _connectionControl.CMB_serialport.Text; if (comPortName == "UDP" || comPortName == "UDPCl" || comPortName == "TCP" || comPortName == "AUTO") { _connectionControl.CMB_baudrate.Enabled = false; if (comPortName == "TCP") MainV2.comPort.BaseStream = new TcpSerial(); if (comPortName == "UDP") MainV2.comPort.BaseStream = new UdpSerial(); if (comPortName == "UDPCl") MainV2.comPort.BaseStream = new UdpSerialConnect(); if (comPortName == "AUTO") { MainV2.comPort.BaseStream = new SerialPort(); return; } } else { _connectionControl.CMB_baudrate.Enabled = true; MainV2.comPort.BaseStream = new SerialPort(); } try { if (!String.IsNullOrEmpty(_connectionControl.CMB_serialport.Text)) comPort.BaseStream.PortName = _connectionControl.CMB_serialport.Text; MainV2.comPort.BaseStream.BaudRate = int.Parse(_connectionControl.CMB_baudrate.Text); // check for saved baud rate and restore if (Settings.Instance[_connectionControl.CMB_serialport.Text + "_BAUD"] != null) { _connectionControl.CMB_baudrate.Text = Settings.Instance[_connectionControl.CMB_serialport.Text + "_BAUD"]; } } catch { } } /// <summary> /// overriding the OnCLosing is a bit cleaner than handling the event, since it /// is this object. /// /// This happens before FormClosed /// </summary> /// <param name="e"></param> protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); // speed up tile saving on exit GMap.NET.GMaps.Instance.CacheOnIdleRead = false; GMap.NET.GMaps.Instance.BoostCacheEngine = true; log.Info("MainV2_FormClosing"); Settings.Instance["MainHeight"] = this.Height.ToString(); Settings.Instance["MainWidth"] = this.Width.ToString(); Settings.Instance["MainMaximised"] = this.WindowState.ToString(); Settings.Instance["MainLocX"] = this.Location.X.ToString(); Settings.Instance["MainLocY"] = this.Location.Y.ToString(); try { comPort.logreadmode = false; if (comPort.logfile != null) comPort.logfile.Close(); if (comPort.rawlogfile != null) comPort.rawlogfile.Close(); comPort.logfile = null; comPort.rawlogfile = null; } catch { } Utilities.adsb.Stop(); Warnings.WarningEngine.Stop(); log.Info("closing vlcrender"); try { while (vlcrender.store.Count > 0) vlcrender.store[0].Stop(); } catch { } log.Info("closing pluginthread"); pluginthreadrun = false; if (pluginthread != null) pluginthread.Join(); log.Info("closing serialthread"); serialThread = false; if (serialreaderthread != null) serialreaderthread.Join(); log.Info("closing joystickthread"); joystickthreadrun = false; if (joystickthread != null) joystickthread.Join(); log.Info("closing httpthread"); // if we are waiting on a socket we need to force an abort httpserver.Stop(); log.Info("sorting tlogs"); try { System.Threading.ThreadPool.QueueUserWorkItem((WaitCallback) delegate { try { MissionPlanner.Log.LogSort.SortLogs(Directory.GetFiles(Settings.Instance.LogDir, "*.tlog")); } catch { } } ); } catch { } log.Info("closing MyView"); // close all tabs MyView.Dispose(); log.Info("closing fd"); try { FlightData.Dispose(); } catch { } log.Info("closing fp"); try { FlightPlanner.Dispose(); } catch { } log.Info("closing sim"); try { Simulation.Dispose(); } catch { } try { if (comPort.BaseStream.IsOpen) comPort.Close(); } catch { } // i get alot of these errors, the port is still open, but not valid - user has unpluged usb // save config SaveConfig(); Console.WriteLine(httpthread.IsAlive); Console.WriteLine(joystickthread.IsAlive); Console.WriteLine(serialreaderthread.IsAlive); Console.WriteLine(pluginthread.IsAlive); log.Info("MainV2_FormClosing done"); if (MONO) this.Dispose(); } /// <summary> /// this happens after FormClosing... /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override void OnFormClosed(FormClosedEventArgs e) { base.OnFormClosed(e); Console.WriteLine("MainV2_FormClosed"); if (joystick != null) { while (!joysendThreadExited) Thread.Sleep(10); joystick.Dispose(); //proper clean up of joystick. } } private void LoadConfig() { try { log.Info("Loading config"); Settings.Instance.Load(); comPortName = Settings.Instance.ComPort; } catch (Exception ex) { log.Error("Bad Config File", ex); } } private void SaveConfig() { try { log.Info("Saving config"); Settings.Instance.ComPort = comPortName; if (_connectionControl != null) Settings.Instance.BaudRate = _connectionControl.CMB_baudrate.Text; Settings.Instance.APMFirmware = MainV2.comPort.MAV.cs.firmware.ToString(); Settings.Instance.Save(); } catch (Exception ex) { CustomMessageBox.Show(ex.ToString()); } } /// <summary> /// needs to be true by default so that exits properly if no joystick used. /// </summary> volatile private bool joysendThreadExited = true; /// <summary> /// thread used to send joystick packets to the MAV /// </summary> private void joysticksend() { float rate = 50; // 1000 / 50 = 20 hz int count = 0; DateTime lastratechange = DateTime.Now; joystickthreadrun = true; while (joystickthreadrun) { joysendThreadExited = false; //so we know this thread is stil alive. try { if (MONO) { log.Error("Mono: closing joystick thread"); break; } if (!MONO) { //joystick stuff if (joystick != null && joystick.enabled) { MAVLink.mavlink_rc_channels_override_t rc = new MAVLink.mavlink_rc_channels_override_t(); rc.target_component = comPort.MAV.compid; rc.target_system = comPort.MAV.sysid; if (joystick.getJoystickAxis(1) != Joystick.Joystick.joystickaxis.None) rc.chan1_raw = MainV2.comPort.MAV.cs.rcoverridech1; if (joystick.getJoystickAxis(2) != Joystick.Joystick.joystickaxis.None) rc.chan2_raw = MainV2.comPort.MAV.cs.rcoverridech2; if (joystick.getJoystickAxis(3) != Joystick.Joystick.joystickaxis.None) rc.chan3_raw = MainV2.comPort.MAV.cs.rcoverridech3; if (joystick.getJoystickAxis(4) != Joystick.Joystick.joystickaxis.None) rc.chan4_raw = MainV2.comPort.MAV.cs.rcoverridech4; if (joystick.getJoystickAxis(5) != Joystick.Joystick.joystickaxis.None) rc.chan5_raw = MainV2.comPort.MAV.cs.rcoverridech5; if (joystick.getJoystickAxis(6) != Joystick.Joystick.joystickaxis.None) rc.chan6_raw = MainV2.comPort.MAV.cs.rcoverridech6; if (joystick.getJoystickAxis(7) != Joystick.Joystick.joystickaxis.None) rc.chan7_raw = MainV2.comPort.MAV.cs.rcoverridech7; if (joystick.getJoystickAxis(8) != Joystick.Joystick.joystickaxis.None) rc.chan8_raw = MainV2.comPort.MAV.cs.rcoverridech8; if (lastjoystick.AddMilliseconds(rate) < DateTime.Now) { /* if (MainV2.comPort.MAV.cs.rssi > 0 && MainV2.comPort.MAV.cs.remrssi > 0) { if (lastratechange.Second != DateTime.Now.Second) { if (MainV2.comPort.MAV.cs.txbuffer > 90) { if (rate < 20) rate = 21; rate--; if (MainV2.comPort.MAV.cs.linkqualitygcs < 70) rate = 50; } else { if (rate > 100) rate = 100; rate++; } lastratechange = DateTime.Now; } } */ // Console.WriteLine(DateTime.Now.Millisecond + " {0} {1} {2} {3} {4}", rc.chan1_raw, rc.chan2_raw, rc.chan3_raw, rc.chan4_raw,rate); //Console.WriteLine("Joystick btw " + comPort.BaseStream.BytesToWrite); if (!comPort.BaseStream.IsOpen) continue; if (comPort.BaseStream.BytesToWrite < 50) { if (sitl) { MissionPlanner.Controls.SITL.rcinput(); } else { comPort.sendPacket(rc); } count++; lastjoystick = DateTime.Now; } } } } Thread.Sleep(20); } catch { } // cant fall out } joysendThreadExited = true; //so we know this thread exited. } /// <summary> /// Used to fix the icon status for unexpected unplugs etc... /// </summary> private void UpdateConnectIcon() { if ((DateTime.Now - connectButtonUpdate).Milliseconds > 500) { // Console.WriteLine(DateTime.Now.Millisecond); if (comPort.BaseStream.IsOpen) { if ((string) this.MenuConnect.Image.Tag != "Disconnect") { this.BeginInvoke((MethodInvoker) delegate { this.MenuConnect.Image = displayicons.disconnect; this.MenuConnect.Image.Tag = "Disconnect"; this.MenuConnect.Text = Strings.DISCONNECTc; _connectionControl.IsConnected(true); }); } } else { if (this.MenuConnect.Image != null && (string) this.MenuConnect.Image.Tag != "Connect") { this.BeginInvoke((MethodInvoker) delegate { this.MenuConnect.Image = displayicons.connect; this.MenuConnect.Image.Tag = "Connect"; this.MenuConnect.Text = Strings.CONNECTc; _connectionControl.IsConnected(false); if (_connectionStats != null) { _connectionStats.StopUpdates(); } }); } if (comPort.logreadmode) { this.BeginInvoke((MethodInvoker) delegate { _connectionControl.IsConnected(true); }); } } connectButtonUpdate = DateTime.Now; } } ManualResetEvent PluginThreadrunner = new ManualResetEvent(false); private void PluginThread() { Hashtable nextrun = new Hashtable(); pluginthreadrun = true; PluginThreadrunner.Reset(); while (pluginthreadrun) { try { lock (Plugin.PluginLoader.Plugins) { foreach (var plugin in Plugin.PluginLoader.Plugins) { if (!nextrun.ContainsKey(plugin)) nextrun[plugin] = DateTime.MinValue; if (DateTime.Now > plugin.NextRun) { // get ms till next run int msnext = (int) (1000/plugin.loopratehz); // allow the plug to modify this, if needed plugin.NextRun = DateTime.Now.AddMilliseconds(msnext); try { bool ans = plugin.Loop(); } catch (Exception ex) { log.Error(ex); } } } } } catch { } // max rate is 100 hz - prevent massive cpu usage System.Threading.Thread.Sleep(10); } while (Plugin.PluginLoader.Plugins.Count > 0) { var plugin = Plugin.PluginLoader.Plugins[0]; try { plugin.Exit(); } catch (Exception ex) { log.Error(ex); } Plugin.PluginLoader.Plugins.Remove(plugin); } PluginThreadrunner.Set(); return; } ManualResetEvent SerialThreadrunner = new ManualResetEvent(false); /// <summary> /// main serial reader thread /// controls /// serial reading /// link quality stats /// speech voltage - custom - alt warning - data lost /// heartbeat packet sending /// /// and can't fall out /// </summary> private void SerialReader() { if (serialThread == true) return; serialThread = true; SerialThreadrunner.Reset(); int minbytes = 0; int altwarningmax = 0; bool armedstatus = false; string lastmessagehigh = ""; DateTime speechcustomtime = DateTime.Now; DateTime speechlowspeedtime = DateTime.Now; DateTime linkqualitytime = DateTime.Now; while (serialThread) { try { Thread.Sleep(1); // was 5 try { if (GCSViews.Terminal.comPort is MAVLinkSerialPort) { } else { if (GCSViews.Terminal.comPort != null && GCSViews.Terminal.comPort.IsOpen) continue; } } catch (Exception ex) { log.Error(ex); } // update connect/disconnect button and info stats try { UpdateConnectIcon(); } catch (Exception ex) { log.Error(ex); } // 30 seconds interval speech options if (speechEnable && speechEngine != null && (DateTime.Now - speechcustomtime).TotalSeconds > 30 && (MainV2.comPort.logreadmode || comPort.BaseStream.IsOpen)) { if (MainV2.speechEngine.IsReady) { if (Settings.Instance.GetBoolean("speechcustomenabled")) { MainV2.speechEngine.SpeakAsync(Common.speechConversion(""+ Settings.Instance["speechcustom"])); } speechcustomtime = DateTime.Now; } // speech for battery alerts //speechbatteryvolt float warnvolt = Settings.Instance.GetFloat("speechbatteryvolt"); float warnpercent = Settings.Instance.GetFloat("speechbatterypercent"); if (Settings.Instance.GetBoolean("speechbatteryenabled") == true && MainV2.comPort.MAV.cs.battery_voltage <= warnvolt && MainV2.comPort.MAV.cs.battery_voltage >= 5.0) { if (MainV2.speechEngine.IsReady) { MainV2.speechEngine.SpeakAsync(Common.speechConversion(""+ Settings.Instance["speechbattery"])); } } else if (Settings.Instance.GetBoolean("speechbatteryenabled") == true && (MainV2.comPort.MAV.cs.battery_remaining) < warnpercent && MainV2.comPort.MAV.cs.battery_voltage >= 5.0 && MainV2.comPort.MAV.cs.battery_remaining != 0.0) { if (MainV2.speechEngine.IsReady) { MainV2.speechEngine.SpeakAsync( Common.speechConversion("" + Settings.Instance["speechbattery"])); } } } // speech for airspeed alerts if (speechEnable && speechEngine != null && (DateTime.Now - speechlowspeedtime).TotalSeconds > 10 && (MainV2.comPort.logreadmode || comPort.BaseStream.IsOpen)) { if (Settings.Instance.GetBoolean("speechlowspeedenabled") == true && MainV2.comPort.MAV.cs.armed) { float warngroundspeed = Settings.Instance.GetFloat("speechlowgroundspeedtrigger"); float warnairspeed = Settings.Instance.GetFloat("speechlowairspeedtrigger"); if (MainV2.comPort.MAV.cs.airspeed < warnairspeed) { if (MainV2.speechEngine.IsReady) { MainV2.speechEngine.SpeakAsync( Common.speechConversion(""+ Settings.Instance["speechlowairspeed"])); speechlowspeedtime = DateTime.Now; } } else if (MainV2.comPort.MAV.cs.groundspeed < warngroundspeed) { if (MainV2.speechEngine.IsReady) { MainV2.speechEngine.SpeakAsync( Common.speechConversion(""+ Settings.Instance["speechlowgroundspeed"])); speechlowspeedtime = DateTime.Now; } } else { speechlowspeedtime = DateTime.Now; } } } // speech altitude warning - message high warning if (speechEnable && speechEngine != null && (MainV2.comPort.logreadmode || comPort.BaseStream.IsOpen)) { float warnalt = float.MaxValue; if (Settings.Instance.ContainsKey("speechaltheight")) { warnalt = Settings.Instance.GetFloat("speechaltheight"); } try { int todo; // need a reset method altwarningmax = (int) Math.Max(MainV2.comPort.MAV.cs.alt, altwarningmax); if (Settings.Instance.GetBoolean("speechaltenabled") == true && MainV2.comPort.MAV.cs.alt != 0.00 && (MainV2.comPort.MAV.cs.alt <= warnalt) && MainV2.comPort.MAV.cs.armed) { if (altwarningmax > warnalt) { if (MainV2.speechEngine.IsReady) MainV2.speechEngine.SpeakAsync( Common.speechConversion(""+Settings.Instance["speechalt"])); } } } catch { } // silent fail try { // say the latest high priority message if (MainV2.speechEngine.IsReady && lastmessagehigh != MainV2.comPort.MAV.cs.messageHigh && MainV2.comPort.MAV.cs.messageHigh != null) { if (!MainV2.comPort.MAV.cs.messageHigh.StartsWith("PX4v2 ")) { MainV2.speechEngine.SpeakAsync(MainV2.comPort.MAV.cs.messageHigh); lastmessagehigh = MainV2.comPort.MAV.cs.messageHigh; } } } catch { } } // attenuate the link qualty over time if ((DateTime.Now - MainV2.comPort.MAV.lastvalidpacket).TotalSeconds >= 1) { if (linkqualitytime.Second != DateTime.Now.Second) { MainV2.comPort.MAV.cs.linkqualitygcs = (ushort) (MainV2.comPort.MAV.cs.linkqualitygcs*0.8f); linkqualitytime = DateTime.Now; // force redraw is no other packets are being read GCSViews.FlightData.myhud.Invalidate(); } } // data loss warning - wait min of 10 seconds, ignore first 30 seconds of connect, repeat at 5 seconds interval if ((DateTime.Now - MainV2.comPort.MAV.lastvalidpacket).TotalSeconds > 10 && (DateTime.Now - connecttime).TotalSeconds > 30 && (DateTime.Now - nodatawarning).TotalSeconds > 5 && (MainV2.comPort.logreadmode || comPort.BaseStream.IsOpen) && MainV2.comPort.MAV.cs.armed) { if (speechEnable && speechEngine != null) { if (MainV2.speechEngine.IsReady) { MainV2.speechEngine.SpeakAsync("WARNING No Data for " + (int) (DateTime.Now - MainV2.comPort.MAV.lastvalidpacket) .TotalSeconds + " Seconds"); nodatawarning = DateTime.Now; } } } // get home point on armed status change. if (armedstatus != MainV2.comPort.MAV.cs.armed && comPort.BaseStream.IsOpen) { armedstatus = MainV2.comPort.MAV.cs.armed; // status just changed to armed if (MainV2.comPort.MAV.cs.armed == true && MainV2.comPort.MAV.aptype != MAVLink.MAV_TYPE.GIMBAL) { try { MainV2.comPort.MAV.cs.HomeLocation = new PointLatLngAlt(MainV2.comPort.getWP(0)); if (MyView.current != null && MyView.current.Name == "FlightPlanner") { // update home if we are on flight data tab FlightPlanner.updateHome(); } } catch { // dont hang this loop this.BeginInvoke( (MethodInvoker) delegate { CustomMessageBox.Show("Failed to update home location (" + MainV2.comPort.MAV.sysid + ")"); }); } } if (speechEnable && speechEngine != null) { if (Settings.Instance.GetBoolean("speecharmenabled")) { string speech = armedstatus ? Settings.Instance["speecharm"] : Settings.Instance["speechdisarm"]; if (!string.IsNullOrEmpty(speech)) { MainV2.speechEngine.SpeakAsync(Common.speechConversion(speech)); } } } } // send a hb every seconds from gcs to ap if (heatbeatSend.Second != DateTime.Now.Second) { MAVLink.mavlink_heartbeat_t htb = new MAVLink.mavlink_heartbeat_t() { type = (byte) MAVLink.MAV_TYPE.GCS, autopilot = (byte) MAVLink.MAV_AUTOPILOT.INVALID, mavlink_version = 3 // MAVLink.MAVLINK_VERSION }; foreach (var port in Comports) { try { port.sendPacket(htb); } catch (Exception ex) { log.Error(ex); // close the bad port port.Close(); // refresh the screen if needed if (port == MainV2.comPort) { // refresh config window if needed if (MyView.current != null) { this.Invoke((MethodInvoker)delegate() { if (MyView.current.Name == "HWConfig") MyView.ShowScreen("HWConfig"); if (MyView.current.Name == "SWConfig") MyView.ShowScreen("SWConfig"); }); } } } } heatbeatSend = DateTime.Now; } // if not connected or busy, sleep and loop if (!comPort.BaseStream.IsOpen || comPort.giveComport == true) { if (!comPort.BaseStream.IsOpen) { // check if other ports are still open foreach (var port in Comports) { if (port.BaseStream.IsOpen) { Console.WriteLine("Main comport shut, swapping to other mav"); comPort = port; break; } } } System.Threading.Thread.Sleep(100); } // read the interfaces foreach (var port in Comports.ToArray()) { if (!port.BaseStream.IsOpen) { // skip primary interface if (port == comPort) continue; // modify array and drop out Comports.Remove(port); break; } while (port.BaseStream.IsOpen && port.BaseStream.BytesToRead > minbytes && port.giveComport == false) { try { port.readPacket(); } catch (Exception ex) { log.Error(ex); } } // update currentstate of sysids on the port foreach (var MAV in port.MAVlist.GetMAVStates()) { try { MAV.cs.UpdateCurrentSettings(null, false, port, MAV); } catch (Exception ex) { log.Error(ex); } } } } catch (Exception e) { Tracking.AddException(e); log.Error("Serial Reader fail :" + e.ToString()); try { comPort.Close(); } catch (Exception ex) { log.Error(ex); } } } Console.WriteLine("SerialReader Done"); SerialThreadrunner.Set(); } protected override void OnLoad(EventArgs e) { // check if its defined, and force to show it if not known about if (Settings.Instance["menu_autohide"] == null) { Settings.Instance["menu_autohide"] = "false"; } try { AutoHideMenu(Settings.Instance.GetBoolean("menu_autohide")); } catch { } MyView.AddScreen(new MainSwitcher.Screen("FlightData", FlightData, true)); MyView.AddScreen(new MainSwitcher.Screen("FlightPlanner", FlightPlanner, true)); MyView.AddScreen(new MainSwitcher.Screen("HWConfig", typeof (GCSViews.InitialSetup), false)); MyView.AddScreen(new MainSwitcher.Screen("SWConfig", typeof (GCSViews.SoftwareConfig), false)); MyView.AddScreen(new MainSwitcher.Screen("Simulation", Simulation, true)); MyView.AddScreen(new MainSwitcher.Screen("Terminal", typeof (GCSViews.Terminal), false)); MyView.AddScreen(new MainSwitcher.Screen("Help", typeof (GCSViews.Help), false)); try { if (Control.ModifierKeys == Keys.Shift) { } else { log.Info("Load Pluggins"); Plugin.PluginLoader.LoadAll(); log.Info("Load Pluggins Done"); } } catch (Exception ex) { log.Error(ex); } if (Program.Logo != null && Program.vvvvz) { this.PerformLayout(); MenuFlightPlanner_Click(this, e); MainMenu_ItemClicked(this, new ToolStripItemClickedEventArgs(MenuFlightPlanner)); } else { this.PerformLayout(); MenuFlightData_Click(this, e); MainMenu_ItemClicked(this, new ToolStripItemClickedEventArgs(MenuFlightData)); } // for long running tasks using own threads. // for short use threadpool this.SuspendLayout(); // setup http server try { httpthread = new Thread(new httpserver().listernforclients) { Name = "motion jpg stream-network kml", IsBackground = true }; httpthread.Start(); } catch (Exception ex) { log.Error("Error starting TCP listener thread: ", ex); CustomMessageBox.Show(ex.ToString()); } // setup joystick packet sender joystickthread = new Thread(new ThreadStart(joysticksend)) { IsBackground = true, Priority = ThreadPriority.AboveNormal, Name = "Main joystick sender" }; joystickthread.Start(); // setup main serial reader serialreaderthread = new Thread(SerialReader) { IsBackground = true, Name = "Main Serial reader", Priority = ThreadPriority.AboveNormal }; serialreaderthread.Start(); // setup main plugin thread pluginthread = new Thread(PluginThread) { IsBackground = true, Name = "plugin runner thread", Priority = ThreadPriority.BelowNormal }; pluginthread.Start(); ThreadPool.QueueUserWorkItem(BGLoadAirports); ThreadPool.QueueUserWorkItem(BGCreateMaps); //ThreadPool.QueueUserWorkItem(BGGetAlmanac); ThreadPool.QueueUserWorkItem(BGgetTFR); ThreadPool.QueueUserWorkItem(BGNoFly); ThreadPool.QueueUserWorkItem(BGGetKIndex); // update firmware version list - only once per day ThreadPool.QueueUserWorkItem(BGFirmwareCheck); this.ResumeLayout(); Program.Splash.Close(); MissionPlanner.Utilities.Tracking.AddTiming("AppLoad", "Load Time", (DateTime.Now - Program.starttime).TotalMilliseconds, ""); try { // single update check per day - in a seperate thread if (Settings.Instance["update_check"] != DateTime.Now.ToShortDateString()) { System.Threading.ThreadPool.QueueUserWorkItem(checkupdate); Settings.Instance["update_check"] = DateTime.Now.ToShortDateString(); } else if (Settings.Instance.GetBoolean("beta_updates") == true) { MissionPlanner.Utilities.Update.dobeta = true; System.Threading.ThreadPool.QueueUserWorkItem(checkupdate); } } catch (Exception ex) { log.Error("Update check failed", ex); } // play a tlog that was passed to the program/ load a bin log passed if (Program.args.Length > 0) { if (File.Exists(Program.args[0]) && Program.args[0].ToLower().EndsWith(".tlog")) { FlightData.LoadLogFile(Program.args[0]); FlightData.BUT_playlog_Click(null, null); } else if (File.Exists(Program.args[0]) && Program.args[0].ToLower().EndsWith(".bin")) { LogBrowse logbrowse = new LogBrowse(); ThemeManager.ApplyThemeTo(logbrowse); logbrowse.logfilename = Program.args[0]; logbrowse.Show(); logbrowse.TopMost = true; } } } private void BGFirmwareCheck(object state) { try { if (Settings.Instance["fw_check"] != DateTime.Now.ToShortDateString()) { var fw = new Firmware(); var list = fw.getFWList(); if (list.Count > 1) Firmware.SaveSoftwares(list); Settings.Instance["fw_check"] = DateTime.Now.ToShortDateString(); } } catch (Exception ex) { log.Error(ex); } } private void BGGetKIndex(object state) { try { // check the last kindex date if (Settings.Instance["kindexdate"] == DateTime.Now.ToShortDateString()) { KIndex_KIndex(Settings.Instance.GetInt32("kindex"), null); } else { // get a new kindex KIndex.KIndexEvent += KIndex_KIndex; KIndex.GetKIndex(); Settings.Instance["kindexdate"] = DateTime.Now.ToShortDateString(); } } catch (Exception ex) { log.Error(ex); } } private void BGgetTFR(object state) { try { tfr.GetTFRs(); } catch (Exception ex) { log.Error(ex); } } private void BGNoFly(object state) { try { NoFly.NoFly.Scan(); } catch (Exception ex) { log.Error(ex); } } private void BGGetAlmanac(object state) { // prep for future try { if (Settings.Instance["almanac_date"] != DateTime.Now.ToShortDateString()) { Common.getFilefromNet("http://alp.u-blox.com/current_1d.alp", Application.StartupPath + Path.DirectorySeparatorChar + "current_d1.alp"); Settings.Instance["almanac_date"] = DateTime.Now.ToShortDateString(); } } catch { } } void KIndex_KIndex(object sender, EventArgs e) { CurrentState.KIndexstatic = (int) sender; Settings.Instance["kindex"] = CurrentState.KIndexstatic.ToString(); } private void BGCreateMaps(object state) { // sort logs try { MissionPlanner.Log.LogSort.SortLogs(Directory.GetFiles(Settings.Instance.LogDir, "*.tlog")); } catch (Exception ex) { log.Error(ex); } try { // create maps Log.LogMap.MapLogs(Directory.GetFiles(Settings.Instance.LogDir, "*.tlog", SearchOption.AllDirectories)); Log.LogMap.MapLogs(Directory.GetFiles(Settings.Instance.LogDir, "*.bin", SearchOption.AllDirectories)); Log.LogMap.MapLogs(Directory.GetFiles(Settings.Instance.LogDir, "*.log", SearchOption.AllDirectories)); if (File.Exists(tlogThumbnailHandler.tlogThumbnailHandler.queuefile)) { Log.LogMap.MapLogs(File.ReadAllLines(tlogThumbnailHandler.tlogThumbnailHandler.queuefile)); File.Delete(tlogThumbnailHandler.tlogThumbnailHandler.queuefile); } } catch (Exception ex) { log.Error(ex); } try { if (File.Exists(tlogThumbnailHandler.tlogThumbnailHandler.queuefile)) { Log.LogMap.MapLogs(File.ReadAllLines(tlogThumbnailHandler.tlogThumbnailHandler.queuefile)); File.Delete(tlogThumbnailHandler.tlogThumbnailHandler.queuefile); } } catch (Exception ex) { log.Error(ex); } } private void checkupdate(object stuff) { try { MissionPlanner.Utilities.Update.CheckForUpdate(); } catch (Exception ex) { log.Error("Update check failed", ex); } } private void MainV2_Resize(object sender, EventArgs e) { // mono - resize is called before the control is created if (MyView != null) log.Info("myview width " + MyView.Width + " height " + MyView.Height); log.Info("this width " + this.Width + " height " + this.Height); } private void MenuHelp_Click(object sender, EventArgs e) { MyView.ShowScreen("Help"); } /// <summary> /// keyboard shortcuts override /// </summary> /// <param name="msg"></param> /// <param name="keyData"></param> /// <returns></returns> protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.F12) { MenuConnect_Click(null, null); return true; } if (keyData == Keys.F2) { MenuFlightData_Click(null, null); return true; } if (keyData == Keys.F3) { MenuFlightPlanner_Click(null, null); return true; } if (keyData == Keys.F4) { MenuTuning_Click(null, null); return true; } if (keyData == Keys.F5) { comPort.getParamList(); MyView.ShowScreen(MyView.current.Name); return true; } if (keyData == (Keys.Control | Keys.F)) // temp { Form frm = new temp(); ThemeManager.ApplyThemeTo(frm); frm.Show(); return true; } /*if (keyData == (Keys.Control | Keys.S)) // screenshot { ScreenShot(); return true; }*/ if (keyData == (Keys.Control | Keys.G)) // nmea out { Form frm = new SerialOutputNMEA(); ThemeManager.ApplyThemeTo(frm); frm.Show(); return true; } if (keyData == (Keys.Control | Keys.X)) { } if (keyData == (Keys.Control | Keys.L)) // limits { return true; } if (keyData == (Keys.Control | Keys.W)) // test ac config { return true; } if (keyData == (Keys.Control | Keys.Z)) { MissionPlanner.GenOTP otp = new MissionPlanner.GenOTP(); otp.ShowDialog(this); return true; } if (keyData == (Keys.Control | Keys.T)) // for override connect { try { MainV2.comPort.Open(false); } catch (Exception ex) { CustomMessageBox.Show(ex.ToString()); } return true; } if (keyData == (Keys.Control | Keys.Y)) // for ryan beall and ollyw42 { // write try { MainV2.comPort.doCommand(MAVLink.MAV_CMD.PREFLIGHT_STORAGE, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); } catch { CustomMessageBox.Show("Invalid command"); return true; } //read ///////MainV2.comPort.doCommand(MAVLink09.MAV_CMD.PREFLIGHT_STORAGE, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); CustomMessageBox.Show("Done MAV_ACTION_STORAGE_WRITE"); return true; } if (keyData == (Keys.Control | Keys.J)) { /* var test = MainV2.comPort.GetLogList(); foreach (var item in test) { var ms = comPort.GetLog(item.id); using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("test" + item.id + ".bin"))) { bw.Write(ms.ToArray()); } var temp1 = Log.BinaryLog.ReadLog("test" + item.id + ".bin"); File.WriteAllLines("test" + item.id + ".log", temp1); }*/ return true; } return base.ProcessCmdKey(ref msg, keyData); } public void changelanguage(CultureInfo ci) { log.Info("change lang to " + ci.ToString() + " current " + Thread.CurrentThread.CurrentUICulture.ToString()); if (ci != null && !Thread.CurrentThread.CurrentUICulture.Equals(ci)) { Thread.CurrentThread.CurrentUICulture = ci; Settings.Instance["language"] = ci.Name; //System.Threading.Thread.CurrentThread.CurrentCulture = ci; HashSet<Control> views = new HashSet<Control> {this, FlightData, FlightPlanner, Simulation}; foreach (Control view in MyView.Controls) views.Add(view); foreach (Control view in views) { if (view != null) { ComponentResourceManager rm = new ComponentResourceManager(view.GetType()); foreach (Control ctrl in view.Controls) { rm.ApplyResource(ctrl); } rm.ApplyResources(view, "$this"); } } } } public void ChangeUnits() { try { // dist if (Settings.Instance["distunits"] != null) { switch ( (Common.distances) Enum.Parse(typeof (Common.distances), Settings.Instance["distunits"].ToString())) { case Common.distances.Meters: CurrentState.multiplierdist = 1; CurrentState.DistanceUnit = "m"; break; case Common.distances.Feet: CurrentState.multiplierdist = 3.2808399f; CurrentState.DistanceUnit = "ft"; break; } } else { CurrentState.multiplierdist = 1; CurrentState.DistanceUnit = "m"; } // speed if (Settings.Instance["speedunits"] != null) { switch ((Common.speeds) Enum.Parse(typeof (Common.speeds), Settings.Instance["speedunits"].ToString())) { case Common.speeds.meters_per_second: CurrentState.multiplierspeed = 1; CurrentState.SpeedUnit = "m/s"; break; case Common.speeds.fps: CurrentState.multiplierdist = 3.2808399f; CurrentState.SpeedUnit = "fps"; break; case Common.speeds.kph: CurrentState.multiplierspeed = 3.6f; CurrentState.SpeedUnit = "kph"; break; case Common.speeds.mph: CurrentState.multiplierspeed = 2.23693629f; CurrentState.SpeedUnit = "mph"; break; case Common.speeds.knots: CurrentState.multiplierspeed = 1.94384449f; CurrentState.SpeedUnit = "knots"; break; } } else { CurrentState.multiplierspeed = 1; CurrentState.SpeedUnit = "m/s"; } } catch { } } private void CMB_baudrate_TextChanged(object sender, EventArgs e) { var sb = new StringBuilder(); int baud = 0; for (int i = 0; i < _connectionControl.CMB_baudrate.Text.Length; i++) if (char.IsDigit(_connectionControl.CMB_baudrate.Text[i])) { sb.Append(_connectionControl.CMB_baudrate.Text[i]); baud = baud*10 + _connectionControl.CMB_baudrate.Text[i] - '0'; } if (_connectionControl.CMB_baudrate.Text != sb.ToString()) { _connectionControl.CMB_baudrate.Text = sb.ToString(); } try { if (baud > 0 && comPort.BaseStream.BaudRate != baud) comPort.BaseStream.BaudRate = baud; } catch (Exception) { } } private void MainMenu_MouseLeave(object sender, EventArgs e) { if (_connectionControl.PointToClient(Control.MousePosition).Y < MainMenu.Height) return; this.SuspendLayout(); panel1.Visible = false; this.ResumeLayout(); } void menu_MouseEnter(object sender, EventArgs e) { this.SuspendLayout(); panel1.Location = new Point(0, 0); panel1.Width = menu.Width; panel1.BringToFront(); panel1.Visible = true; this.ResumeLayout(); } private void autoHideToolStripMenuItem_Click(object sender, EventArgs e) { AutoHideMenu(autoHideToolStripMenuItem.Checked); Settings.Instance["menu_autohide"] = autoHideToolStripMenuItem.Checked.ToString(); } void AutoHideMenu(bool hide) { autoHideToolStripMenuItem.Checked = hide; if (!hide) { this.SuspendLayout(); panel1.Dock = DockStyle.Top; panel1.SendToBack(); panel1.Visible = true; menu.Visible = false; MainMenu.MouseLeave -= MainMenu_MouseLeave; panel1.MouseLeave -= MainMenu_MouseLeave; toolStripConnectionControl.MouseLeave -= MainMenu_MouseLeave; this.ResumeLayout(false); } else { this.SuspendLayout(); panel1.Dock = DockStyle.None; panel1.Visible = false; MainMenu.MouseLeave += MainMenu_MouseLeave; panel1.MouseLeave += MainMenu_MouseLeave; toolStripConnectionControl.MouseLeave += MainMenu_MouseLeave; menu.Visible = true; menu.SendToBack(); this.ResumeLayout(false); } } private void MainV2_KeyDown(object sender, KeyEventArgs e) { Message temp = new Message(); ProcessCmdKey(ref temp, e.KeyData); Console.WriteLine("MainV2_KeyDown " + e.ToString()); } private void toolStripMenuItem1_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start( "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=mich146%40hotmail%2ecom&lc=AU&item_name=Michael%20Oborne&no_note=0&currency_code=AUD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHostedGuest"); } catch { CustomMessageBox.Show("Link open failed. check your default webpage association"); } } [StructLayout(LayoutKind.Sequential)] internal class DEV_BROADCAST_HDR { internal Int32 dbch_size; internal Int32 dbch_devicetype; internal Int32 dbch_reserved; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal class DEV_BROADCAST_PORT { public int dbcp_size; public int dbcp_devicetype; public int dbcp_reserved; // MSDN say "do not use" [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)] public byte[] dbcp_name; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal class DEV_BROADCAST_DEVICEINTERFACE { public Int32 dbcc_size; public Int32 dbcc_devicetype; public Int32 dbcc_reserved; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U1, SizeConst = 16)] internal Byte[] dbcc_classguid; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)] internal Byte[] dbcc_name; } protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_CREATE: try { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer; IntPtr deviceNotificationHandle = IntPtr.Zero; Int32 size = 0; // frmMy is the form that will receive device-change messages. size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE.ToByteArray(); devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); deviceNotificationHandle = NativeMethods.RegisterDeviceNotification(this.Handle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); } catch { } break; case WM_DEVICECHANGE: // The WParam value identifies what is occurring. WM_DEVICECHANGE_enum n = (WM_DEVICECHANGE_enum) m.WParam; int l = (int) m.LParam; if (n == WM_DEVICECHANGE_enum.DBT_DEVICEREMOVEPENDING) { Console.WriteLine("DBT_DEVICEREMOVEPENDING"); } if (n == WM_DEVICECHANGE_enum.DBT_DEVNODES_CHANGED) { Console.WriteLine("DBT_DEVNODES_CHANGED"); } if (n == WM_DEVICECHANGE_enum.DBT_DEVICEARRIVAL || n == WM_DEVICECHANGE_enum.DBT_DEVICEREMOVECOMPLETE) { Console.WriteLine(((WM_DEVICECHANGE_enum) n).ToString()); DEV_BROADCAST_HDR hdr = new DEV_BROADCAST_HDR(); Marshal.PtrToStructure(m.LParam, hdr); try { switch (hdr.dbch_devicetype) { case DBT_DEVTYP_DEVICEINTERFACE: DEV_BROADCAST_DEVICEINTERFACE inter = new DEV_BROADCAST_DEVICEINTERFACE(); Marshal.PtrToStructure(m.LParam, inter); log.InfoFormat("Interface {0}", ASCIIEncoding.Unicode.GetString(inter.dbcc_name, 0, inter.dbcc_size - (4*3))); break; case DBT_DEVTYP_PORT: DEV_BROADCAST_PORT prt = new DEV_BROADCAST_PORT(); Marshal.PtrToStructure(m.LParam, prt); log.InfoFormat("port {0}", ASCIIEncoding.Unicode.GetString(prt.dbcp_name, 0, prt.dbcp_size - (4*3))); break; } } catch { } //string port = Marshal.PtrToStringAuto((IntPtr)((long)m.LParam + 12)); //Console.WriteLine("Added port {0}",port); } log.InfoFormat("Device Change {0} {1} {2}", m.Msg, (WM_DEVICECHANGE_enum) m.WParam, m.LParam); if (DeviceChanged != null) { try { DeviceChanged((WM_DEVICECHANGE_enum) m.WParam); } catch { } } foreach (Plugin.Plugin item in MissionPlanner.Plugin.PluginLoader.Plugins) { item.Host.ProcessDeviceChanged((WM_DEVICECHANGE_enum) m.WParam); } break; default: break; } base.WndProc(ref m); } const int DBT_DEVTYP_PORT = 0x00000003; const int WM_CREATE = 0x0001; const Int32 DBT_DEVTYP_HANDLE = 6; const Int32 DBT_DEVTYP_DEVICEINTERFACE = 5; const Int32 DEVICE_NOTIFY_WINDOW_HANDLE = 0; const Int32 DIGCF_PRESENT = 2; const Int32 DIGCF_DEVICEINTERFACE = 0X10; const Int32 WM_DEVICECHANGE = 0X219; public static Guid GUID_DEVINTERFACE_USB_DEVICE = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); public enum WM_DEVICECHANGE_enum { DBT_CONFIGCHANGECANCELED = 0x19, DBT_CONFIGCHANGED = 0x18, DBT_CUSTOMEVENT = 0x8006, DBT_DEVICEARRIVAL = 0x8000, DBT_DEVICEQUERYREMOVE = 0x8001, DBT_DEVICEQUERYREMOVEFAILED = 0x8002, DBT_DEVICEREMOVECOMPLETE = 0x8004, DBT_DEVICEREMOVEPENDING = 0x8003, DBT_DEVICETYPESPECIFIC = 0x8005, DBT_DEVNODES_CHANGED = 0x7, DBT_QUERYCHANGECONFIG = 0x17, DBT_USERDEFINED = 0xFFFF, } private void MainMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { foreach (ToolStripItem item in MainMenu.Items) { if (e.ClickedItem == item) { item.BackColor = ThemeManager.ControlBGColor; } else { item.BackColor = Color.Transparent; item.BackgroundImage = displayicons.bg; //.BackColor = Color.Black; } } //MainMenu.BackColor = Color.Black; //MainMenu.BackgroundImage = MissionPlanner.Properties.Resources.bgdark; } private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e) { // full screen if (fullScreenToolStripMenuItem.Checked) { this.TopMost = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.WindowState = FormWindowState.Normal; this.WindowState = FormWindowState.Maximized; } else { this.TopMost = false; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.WindowState = FormWindowState.Maximized; } } private void readonlyToolStripMenuItem_Click(object sender, EventArgs e) { MainV2.comPort.ReadOnly = readonlyToolStripMenuItem.Checked; } private void connectionOptionsToolStripMenuItem_Click(object sender, EventArgs e) { new ConnectionOptions().Show(this); } private void MainV2_Load(object sender, EventArgs e) { } } }
bsmrstu-warriors/Moytri--The-Drone-Aider
MainV2.cs
C#
gpl-3.0
120,530
<?php $domainx=$argv[1]; $cmdx="find /home/vpopmail/domains/".$domainx."/ -maxdepth 1 -type f -name .qmail-*"; $cmdout=`$cmdx`; $linex=array(); $linex=explode("\n",$cmdout); $u=0; for($e=0;$e<sizeof($linex);$e++) { if($linex[$e] !="") { #print "\n $e --> ".$linex[$e]; $filedata=file_get_contents($linex[$e]); #print "$filedata"; $ex=array(); $ex=explode("catchall",$filedata); $esize=sizeof($ex); if($esize>1) { $u++; #print " -->".$esize; #print "$filedata"; $dotqmail=$linex[$e]; $dotqmail=str_replace("/home/vpopmail/domains/".$domainx."/","",$dotqmail); $dotqmail=str_replace(".qmail-","",$dotqmail); $dotqmail=str_replace(":",".",$dotqmail); print $dotqmail; print "\n"; } } } print "\n"; ?>
deependhulla/powermail-debian9
files/rootdir/usr/local/src/mail-export-tools/export-vpopmail-catchall-dot-qmail.php
PHP
gpl-3.0
702
var helpers = require('./../../../helpers'), path = require('path'), os = require('os'), should = require('should'), sinon = require('sinon'), lib_path = helpers.lib_path(), join = require('path').join, custom_dirs = require(join(lib_path, 'agent', 'utils', 'custom-dirs')) wipe_path = join(lib_path, 'agent', 'actions', 'wipe'), wipe2 = require(join(lib_path, 'agent', 'actions', 'wipe', 'wipe')), wipe = require(wipe_path), wipe_win = require(wipe_path + '/windows'), sys_index_path = helpers.lib_path('system'), sys_index = require(sys_index_path), sys_win = require(join(sys_index_path, 'windows')) api_path = join(lib_path, 'agent', 'plugins', 'control-panel', 'api'), keys = require(join(api_path, 'keys')); var outlook_versions = { old: { '2002': '10', '2003': '11', '2007': '12', '2010': '14' }, new: { '2013': '15', '2016': '16', } }; var OUTLOOK_NEW = 15, OUTLOOK_OLD = 10; var registryPath = { outlook_version: join('HKEY_CLASSES_ROOT', 'Outlook.Application', 'CurVEr'), profileRegistry: join('HKEY_CURRENT_USER', 'Software', 'Microsoft'), firefox: join('HKEY_CLASSES_ROOT', 'FirefoxHTML', 'DefaultIcon'), thunderbird: join('HKEY_CLASSES_ROOT', 'ThunderbirdEML', 'DefaultIcon') }; var hash; describe('wipe valid types', function() { before(function() { hash = { wipe_cloud: false, wipe_directories: false, wipe_documents: false, wipe_passwords: false, wipe_cookies: false, wipe_emails: false } }); describe('when one type is selected', function() { describe('and is not directories', function() { before(function() { hash.wipe_documents = true; }); after(function() { hash.wipe_documents = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('documents'); done(); }) }); describe('and is directories', function() { describe('and is only one path', function() { describe('and the path is blank', function() { before(function() { hash.wipe_directories = ''; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should an empty array', function(done){ var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(0); done(); }) }) describe('and the path is invalid', function() { before(function() { hash.wipe_directories = 'not a path'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should an empty array', function(done){ var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(0); done(); }) }) describe('and the path is valid', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return directories', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(1); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); done(); }) }) }) describe('and there are more than one path', function() { describe('and one path is blank', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe, '; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(1); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); done(); }) }) describe('and one path is invalid', function() { describe('and one path is blank', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe, invalidpath, /Users/another/valid/path'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(2); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); wipe.directories[1].should.equal('/Users/another/valid/path'); done(); }) }) }) describe('and all paths are valid', function() { before(function() { hash.wipe_directories = '/Users/one/path/to/wipe,/Users/another/valid/path,/Users/lastvalid'; }); after(function() { hash.wipe_directories = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('directories'); wipe.directories.length.should.equal(3); wipe.directories[0].should.equal('/Users/one/path/to/wipe'); wipe.directories[1].should.equal('/Users/another/valid/path'); wipe.directories[2].should.equal('/Users/lastvalid'); done(); }) }) }) }) }) describe('when more than one type is selected', function() { describe('and no includes directories', function() { before(function() { hash.wipe_documents = true; hash.wipe_passwords = true; hash.wipe_emails = true; }); after(function() { hash.wipe_documents = false; hash.wipe_passwords = false; hash.wipe_emails = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(3); out[0].should.equal('documents'); out[1].should.equal('passwords'); out[2].should.equal('emails'); done(); }) }); describe('and includes directories', function() { describe('and the path is valid', function() { before(function() { hash.wipe_directories = '/Users/valid/path'; hash.wipe_passwords = true; }); after(function() { hash.wipe_directories = false; hash.wipe_passwords = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(2); out[0].should.equal('directories'); out[1].should.equal('passwords'); wipe.directories[0].should.equal('/Users/valid/path'); done(); }) }) describe('and the path is invalid', function() { before(function() { hash.wipe_directories = 'invalidpath'; hash.wipe_passwords = true; }); after(function() { hash.wipe_directories = false; hash.wipe_passwords = false; wipe.directories = []; }); it('should return documents', function(done) { var out = wipe.valid_types(hash); out.should.be.Array; out.length.should.equal(1); out[0].should.equal('passwords'); wipe.directories.length.should.equal(0); done(); }) }) }); }); }); describe('in Windows OS', function() { var platform_stub, outlook_version, spy_fetch_dirs; var opts = { "wipe_directories": "/Users/user/Desktop/file.txt" }; before(() => { wipe.node_bin = '/usr/local/bin/node'; sys_index.os_name = "windows"; sys_index.check_service = sys_win.check_service; sys_index.run_as_admin = sys_win.run_as_admin; platform_stub = sinon.stub(os, 'platform').callsFake(() => { return 'win32'; }); keys_get_stub = sinon.stub(keys, 'get').callsFake(() => { return { api: 'aaaaaaaaaa', device: 'bbbbbb' } }); }) after(() => { platform_stub.restore(); keys_get_stub.restore(); }) describe('on registry commands', function() { wipe_win.registryManager.query.toString().should.containEql('reg query'); wipe_win.registryManager.add.toString().should.containEql('reg add'); wipe_win.registryManager.delete.toString().should.containEql('reg delete'); wipe_win.registryManager.killtask.toString().should.containEql('taskkill'); }) describe('when running in old Outlook version', function() { iterate_versions(outlook_versions.old); }); describe('when running in new Outlook version', function() { iterate_versions(outlook_versions.new); }); describe('when service is available', () => { before(() => { spy_fetch_dirs = sinon.spy(wipe2, 'fetch_dirs'); sys_win.monitoring_service_go = true; }); after(() => { spy_fetch_dirs.restore(); }) it('should wipe through the service', (done) => { wipe.start("123",opts, (err, em) => { em.on('end', (err, out) => { spy_fetch_dirs.calledOnce.should.equal(true); done(); }) }) }) }) describe('when service is not available', () => { before(() => { sys_win.monitoring_service_go = false; }) it('should not wipe through the service', (done) => { wipe.start("1234",opts, (err, em) => { em.on('end', (id,err, out) => { should.exist(err); err.message.should.containEql("Wipe command failed.") done(); }) }) }) }) function iterate_versions(versions) { Object.keys(versions).forEach(function(k) { test_outlook_version(k, versions[k]); }); } function get_outlook_path(version) { if (parseInt(version) >= 15) { return join('HKEY_USERS', 'User1', 'Software', 'Microsoft', 'Office', `${version}.0`, 'Outlook', 'Profiles'); } else if (parseInt(version) < OUTLOOK_NEW && parseInt(version) >= OUTLOOK_OLD) { return join('HKEY_USERS', 'Software', 'Microsoft', 'User1', 'Windows NT', 'CurrentVersion', 'Windows Messaging Subsystem', 'Profiles'); } else { return join('HKEY_USERS', 'Software', 'Microsoft', `User1`, 'Windows Messaging Subsystem', 'Profiles'); } } function test_outlook_version(version_type, version) { var stub_path; var stub_registry; describe(version_type, function() { before(function() { stub_path = sinon.stub(wipe_win, 'getOutlookVersion').callsFake(cb => { cb(null, version); }) stub_registry = sinon.stub(wipe_win.registryManager, 'query').callsFake((query, cb) => { return cb(null, '\r\nUser1\r\n') }) }); after(function() { stub_registry.restore(); stub_path.restore(); }); it('returns path', function(done) { wipe_win.getProfileRegistry(function(err, out) { out[0].should.equal(get_outlook_path(version)); done(); }); }); }); }; });
prey/prey-node-client
test/lib/agent/actions/wipe.js
JavaScript
gpl-3.0
12,290
package com.bekvon.bukkit.residence.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; public enum TimeModifier { s(1), m(60), h(60 * 60), d(60 * 60 * 24), w(60 * 60 * 24 * 7), M(60 * 60 * 24 * 30), Y(60 * 60 * 24 * 365); private int modifier = 0; static Pattern patern = Pattern.compile("(\\d+[a-z])"); TimeModifier(int modifier) { this.modifier = modifier; } public int getModifier() { return modifier; } public void setModifier(int modifier) { this.modifier = modifier; } public static Long getTimeRangeFromString(String time) { try { return Long.parseLong(time); } catch (Exception e) { } Matcher match = patern.matcher(time); Long total = null; while (match.find()) { String t = match.group(1); for (TimeModifier one : TimeModifier.values()) { if (t.endsWith(one.name())) { try { Long amount = Long.parseLong(t.substring(0, t.length() - one.name().length())); if (total == null) total = 0L; total += amount * one.getModifier(); } catch (Exception e) { break; } } } } return total; } }
Zrips/Residence
src/com/bekvon/bukkit/residence/utils/TimeModifier.java
Java
gpl-3.0
1,185
package core import ( "bytes" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "strings" "time" "github.com/eris-ltd/mint-client/Godeps/_workspace/src/github.com/tendermint/tendermint/account" ptypes "github.com/eris-ltd/mint-client/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" rtypes "github.com/eris-ltd/mint-client/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" cclient "github.com/eris-ltd/mint-client/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client" "github.com/eris-ltd/mint-client/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) //------------------------------------------------------------------------------------ // core functions with string args. // validates strings and forms transaction func Output(addr, amtS string) ([]byte, error) { if amtS == "" { return nil, fmt.Errorf("output must specify an amount with the --amt flag") } if addr == "" { return nil, fmt.Errorf("output must specify an addr with the --addr flag") } addrBytes, err := hex.DecodeString(addr) if err != nil { return nil, fmt.Errorf("addr is bad hex: %v", err) } amt, err := strconv.ParseInt(amtS, 10, 64) if err != nil { return nil, fmt.Errorf("amt is misformatted: %v", err) } // TODO: validate amt! txOutput := types.TxOutput{ Address: addrBytes, Amount: amt, } n, errPtr := new(int64), new(error) buf := new(bytes.Buffer) txOutput.WriteSignBytes(buf, n, errPtr) if *errPtr != nil { return nil, *errPtr } return buf.Bytes(), nil } func Input(nodeAddr, pubkey, amtS, nonceS, addr string) ([]byte, error) { pub, addrBytes, amt, nonce, err := checkCommon(nodeAddr, pubkey, addr, amtS, nonceS) if err != nil { return nil, err } txInput := types.TxInput{ Address: addrBytes, Amount: amt, Sequence: int(nonce), PubKey: pub, } n, errPtr := new(int64), new(error) buf := new(bytes.Buffer) txInput.WriteSignBytes(buf, n, errPtr) if *errPtr != nil { return nil, *errPtr } return buf.Bytes(), nil } func Send(nodeAddr, pubkey, addr, toAddr, amtS, nonceS string) (*types.SendTx, error) { pub, addrBytes, amt, nonce, err := checkCommon(nodeAddr, pubkey, addr, amtS, nonceS) if err != nil { return nil, err } if toAddr == "" { return nil, fmt.Errorf("destination address must be given with --to flag") } toAddrBytes, err := hex.DecodeString(toAddr) if err != nil { return nil, fmt.Errorf("toAddr is bad hex: %v", err) } tx := types.NewSendTx() _ = addrBytes // TODO! tx.AddInputWithNonce(pub, amt, int(nonce)) tx.AddOutput(toAddrBytes, amt) return tx, nil } func Call(nodeAddr, pubkey, addr, toAddr, amtS, nonceS, gasS, feeS, data string) (*types.CallTx, error) { pub, _, amt, nonce, err := checkCommon(nodeAddr, pubkey, addr, amtS, nonceS) if err != nil { return nil, err } toAddrBytes, err := hex.DecodeString(toAddr) if err != nil { return nil, fmt.Errorf("toAddr is bad hex: %v", err) } fee, err := strconv.ParseInt(feeS, 10, 64) if err != nil { return nil, fmt.Errorf("fee is misformatted: %v", err) } gas, err := strconv.ParseInt(gasS, 10, 64) if err != nil { return nil, fmt.Errorf("gas is misformatted: %v", err) } dataBytes, err := hex.DecodeString(data) if err != nil { return nil, fmt.Errorf("data is bad hex: %v", err) } tx := types.NewCallTxWithNonce(pub, toAddrBytes, dataBytes, amt, gas, fee, int(nonce)) return tx, nil } func Name(nodeAddr, pubkey, addr, amtS, nonceS, feeS, name, data string) (*types.NameTx, error) { pub, _, amt, nonce, err := checkCommon(nodeAddr, pubkey, addr, amtS, nonceS) if err != nil { return nil, err } fee, err := strconv.ParseInt(feeS, 10, 64) if err != nil { return nil, fmt.Errorf("fee is misformatted: %v", err) } tx := types.NewNameTxWithNonce(pub, name, data, amt, fee, int(nonce)) return tx, nil } func Permissions(nodeAddr, pubkey, addrS, nonceS, permFunc string, argsS []string) (*types.PermissionsTx, error) { pub, _, _, nonce, err := checkCommon(nodeAddr, pubkey, addrS, "0", "0") if err != nil { return nil, err } var args ptypes.PermArgs switch permFunc { case "set_base": addr, pF, err := decodeAddressPermFlag(argsS[0], argsS[1]) if err != nil { return nil, err } if len(argsS) != 3 { return nil, fmt.Errorf("set_base also takes a value (true or false)") } var value bool if argsS[2] == "true" { value = true } else if argsS[2] == "false" { value = false } else { return nil, fmt.Errorf("Unknown value %s", argsS[2]) } args = &ptypes.SetBaseArgs{addr, pF, value} case "unset_base": addr, pF, err := decodeAddressPermFlag(argsS[0], argsS[1]) if err != nil { return nil, err } args = &ptypes.UnsetBaseArgs{addr, pF} case "set_global": pF, err := ptypes.PermStringToFlag(argsS[0]) if err != nil { return nil, err } var value bool if argsS[1] == "true" { value = true } else if argsS[1] == "false" { value = false } else { return nil, fmt.Errorf("Unknown value %s", argsS[1]) } args = &ptypes.SetGlobalArgs{pF, value} case "add_role": addr, err := hex.DecodeString(argsS[0]) if err != nil { return nil, err } args = &ptypes.AddRoleArgs{addr, argsS[1]} case "rm_role": addr, err := hex.DecodeString(argsS[0]) if err != nil { return nil, err } args = &ptypes.RmRoleArgs{addr, argsS[1]} default: return nil, fmt.Errorf("Invalid permission function for use in PermissionsTx: %s", permFunc) } // args := snativeArgs( tx := types.NewPermissionsTxWithNonce(pub, args, int(nonce)) return tx, nil } func decodeAddressPermFlag(addrS, permFlagS string) (addr []byte, pFlag ptypes.PermFlag, err error) { if addr, err = hex.DecodeString(addrS); err != nil { return } if pFlag, err = ptypes.PermStringToFlag(permFlagS); err != nil { return } return } type NameGetter struct { client cclient.Client } func (n NameGetter) GetNameRegEntry(name string) *types.NameRegEntry { entry, err := n.client.GetName(name) if err != nil { panic(err) } return entry.Entry } /* func coreNewAccount(nodeAddr, pubkey, chainID string) (*types.NewAccountTx, error) { pub, _, _, _, err := checkCommon(nodeAddr, pubkey, "", "0", "0") if err != nil { return nil, err } client := cclient.NewClient(nodeAddr, "HTTP") return types.NewNewAccountTx(NameGetter{client}, pub, chainID) } */ func Bond(nodeAddr, pubkey, unbondAddr, amtS, nonceS string) (*types.BondTx, error) { pub, addrBytes, amt, nonce, err := checkCommon(nodeAddr, pubkey, "", amtS, nonceS) if err != nil { return nil, err } var pubKey account.PubKeyEd25519 var unbondAddrBytes []byte if unbondAddr == "" { pkb, _ := hex.DecodeString(pubkey) copy(pubKey[:], pkb) unbondAddrBytes = pubKey.Address() } else { unbondAddrBytes, err = hex.DecodeString(unbondAddr) if err != nil { return nil, fmt.Errorf("unbondAddr is bad hex: %v", err) } } tx, err := types.NewBondTx(pub) if err != nil { return nil, err } _ = addrBytes tx.AddInputWithNonce(pub, amt, int(nonce)) tx.AddOutput(unbondAddrBytes, amt) return tx, nil } func Unbond(addrS, heightS string) (*types.UnbondTx, error) { if addrS == "" { return nil, fmt.Errorf("Validator address must be given with --addr flag") } addrBytes, err := hex.DecodeString(addrS) if err != nil { return nil, fmt.Errorf("addr is bad hex: %v", err) } height, err := strconv.ParseInt(heightS, 10, 32) if err != nil { return nil, fmt.Errorf("height is misformatted: %v", err) } return &types.UnbondTx{ Address: addrBytes, Height: int(height), }, nil } func Rebond(addrS, heightS string) (*types.RebondTx, error) { if addrS == "" { return nil, fmt.Errorf("Validator address must be given with --addr flag") } addrBytes, err := hex.DecodeString(addrS) if err != nil { return nil, fmt.Errorf("addr is bad hex: %v", err) } height, err := strconv.ParseInt(heightS, 10, 32) if err != nil { return nil, fmt.Errorf("height is misformatted: %v", err) } return &types.RebondTx{ Address: addrBytes, Height: int(height), }, nil } //------------------------------------------------------------------------------------ // sign and broadcast func Sign(signBytes, signAddr, signRPC string) (sig [64]byte, err error) { args := map[string]string{ "hash": signBytes, "addr": signAddr, } b, err := json.Marshal(args) if err != nil { return } logger.Debugln("Sending request body:", string(b)) req, err := http.NewRequest("POST", signRPC+"/sign", bytes.NewBuffer(b)) if err != nil { return } req.Header.Add("Content-Type", "application/json") sigS, errS, err := requestResponse(req) if err != nil { return sig, fmt.Errorf("Error calling signing daemon: %s", err.Error()) } if errS != "" { return sig, fmt.Errorf("Error (string) calling signing daemon: %s", errS) } sigBytes, err := hex.DecodeString(sigS) if err != nil { return } copy(sig[:], sigBytes) return } func Broadcast(tx types.Tx, broadcastRPC string) (*rtypes.Receipt, error) { client := cclient.NewClient(broadcastRPC, "JSONRPC") rec, err := client.BroadcastTx(tx) if err != nil { return nil, err } return &rec.Receipt, nil } //------------------------------------------------------------------------------------ // utils for talking to the key server type HTTPResponse struct { Response string Error string } func requestResponse(req *http.Request) (string, string, error) { client := new(http.Client) resp, err := client.Do(req) if err != nil { return "", "", err } if resp.StatusCode >= 400 { return "", "", fmt.Errorf(resp.Status) } return unpackResponse(resp) } func unpackResponse(resp *http.Response) (string, string, error) { b, err := ioutil.ReadAll(resp.Body) if err != nil { return "", "", err } r := new(HTTPResponse) if err := json.Unmarshal(b, r); err != nil { return "", "", err } return r.Response, r.Error, nil } //------------------------------------------------------------------------------------ // sign and broadcast convenience // tx has either one input or we default to the first one (ie for send/bond) // TODO: better support for multisig and bonding func signTx(signAddr, chainID string, tx_ types.Tx) ([]byte, types.Tx, error) { signBytes := fmt.Sprintf("%X", account.SignBytes(chainID, tx_)) var inputAddr []byte var sigED account.SignatureEd25519 switch tx := tx_.(type) { case *types.SendTx: inputAddr = tx.Inputs[0].Address defer func(s *account.SignatureEd25519) { tx.Inputs[0].Signature = *s }(&sigED) case *types.NameTx: inputAddr = tx.Input.Address defer func(s *account.SignatureEd25519) { tx.Input.Signature = *s }(&sigED) case *types.CallTx: inputAddr = tx.Input.Address defer func(s *account.SignatureEd25519) { tx.Input.Signature = *s }(&sigED) case *types.PermissionsTx: inputAddr = tx.Input.Address defer func(s *account.SignatureEd25519) { tx.Input.Signature = *s }(&sigED) case *types.BondTx: inputAddr = tx.Inputs[0].Address defer func(s *account.SignatureEd25519) { tx.Signature = *s tx.Inputs[0].Signature = *s }(&sigED) case *types.UnbondTx: inputAddr = tx.Address defer func(s *account.SignatureEd25519) { tx.Signature = *s }(&sigED) case *types.RebondTx: inputAddr = tx.Address defer func(s *account.SignatureEd25519) { tx.Signature = *s }(&sigED) } addrHex := fmt.Sprintf("%X", inputAddr) sig, err := Sign(signBytes, addrHex, signAddr) if err != nil { return nil, nil, err } sigED = account.SignatureEd25519(sig) logger.Debugf("SIG: %X\n", sig) return inputAddr, tx_, nil } type TxResult struct { BlockHash []byte // all txs get in a block Hash []byte // all txs get a hash // only CallTx Address []byte // only for new contracts Return []byte Exception string //TODO: make Broadcast() errors more responsive so we // can differentiate mempool errors from other } func SignAndBroadcast(chainID, nodeAddr, signAddr string, tx types.Tx, sign, broadcast, wait bool) (txResult *TxResult, err error) { var inputAddr []byte if sign { inputAddr, tx, err = signTx(signAddr, chainID, tx) if err != nil { return nil, err } } if broadcast { if wait { var ch chan Msg ch, err = subscribeAndWait(tx, chainID, nodeAddr, inputAddr) if err != nil { return nil, err } else { defer func() { if err != nil { // if broadcast threw an error, just return return } logger.Debugln("Waiting for tx to be committed ...") msg := <-ch if msg.Error != nil { logger.Infof("Encountered error waiting for event: %v\n", msg.Error) err = msg.Error } else { txResult.BlockHash = msg.BlockHash txResult.Return = msg.Value txResult.Exception = msg.Exception } }() } } var receipt *rtypes.Receipt receipt, err = Broadcast(tx, nodeAddr) if err != nil { return nil, err } txResult = &TxResult{ Hash: receipt.TxHash, } if tx_, ok := tx.(*types.CallTx); ok { if len(tx_.Address) == 0 { txResult.Address = types.NewContractAddress(tx_.Input.Address, tx_.Input.Sequence) } } } return } //------------------------------------------------------------------------------------ // wait for events type Msg struct { BlockHash []byte Value []byte Exception string Error error } func subscribeAndWait(tx types.Tx, chainID, nodeAddr string, inputAddr []byte) (chan Msg, error) { // subscribe to event and wait for tx to be committed wsAddr := strings.TrimPrefix(nodeAddr, "http://") wsAddr = "ws://" + wsAddr + "websocket" logger.Debugln(wsAddr) wsClient := cclient.NewWSClient(wsAddr) wsClient.Start() eid := types.EventStringAccInput(inputAddr) if err := wsClient.Subscribe(eid); err != nil { return nil, fmt.Errorf("Error subscribing to AccInput event: %v", err) } if err := wsClient.Subscribe(types.EventStringNewBlock()); err != nil { return nil, fmt.Errorf("Error subscribing to NewBlock event: %v", err) } resultChan := make(chan Msg, 1) var latestBlockHash []byte // Read message go func() { for { result := <-wsClient.EventsCh // if its a block, remember the block hash blockData, ok := result.Data.(types.EventDataNewBlock) if ok { latestBlockHash = blockData.Block.Hash() continue } // we don't accept events unless they came after a new block (ie. in) if latestBlockHash == nil { continue } if result.Event != eid { logger.Debugf("received unsolicited event! Got %s, expected %s\n", result.Event, eid) continue } data, ok := result.Data.(types.EventDataTx) if !ok { resultChan <- Msg{Error: fmt.Errorf("response error: expected result.Data to be *types.EventDataTx")} return } if !bytes.Equal(types.TxID(chainID, data.Tx), types.TxID(chainID, tx)) { logger.Debugf("Received event for same input from another transaction: %X\n", types.TxID(chainID, data.Tx)) continue } if data.Exception != "" { resultChan <- Msg{BlockHash: latestBlockHash, Value: data.Return, Exception: data.Exception} return } // GOOD! resultChan <- Msg{BlockHash: latestBlockHash, Value: data.Return} return } }() // txs should take no more than 10 seconds timeoutTicker := time.Tick(10 * time.Second) go func() { <-timeoutTicker resultChan <- Msg{Error: fmt.Errorf("timed out waiting for event")} return }() return resultChan, nil } //------------------------------------------------------------------------------------ // convenience function func checkCommon(nodeAddr, pubkey, addr, amtS, nonceS string) (pub account.PubKey, addrBytes []byte, amt int64, nonce int64, err error) { if amtS == "" { err = fmt.Errorf("input must specify an amount with the --amt flag") return } if pubkey == "" && addr == "" { err = fmt.Errorf("at least one of --pubkey or --addr must be given") return } pubKeyBytes, err := hex.DecodeString(pubkey) if err != nil { err = fmt.Errorf("pubkey is bad hex: %v", err) return } addrBytes, err = hex.DecodeString(addr) if err != nil { err = fmt.Errorf("addr is bad hex: %v", err) return } amt, err = strconv.ParseInt(amtS, 10, 64) if err != nil { err = fmt.Errorf("amt is misformatted: %v", err) } if len(pubKeyBytes) > 0 { var pubArray [32]byte copy(pubArray[:], pubKeyBytes) pub = account.PubKeyEd25519(pubArray) addrBytes = pub.Address() } if nonceS == "" { if nodeAddr == "" { err = fmt.Errorf("input must specify a nonce with the --nonce flag or use --node-addr (or MINTX_NODE_ADDR) to fetch the nonce from a node") return } // fetch nonce from node client := cclient.NewClient(nodeAddr, "HTTP") ac, err2 := client.GetAccount(addrBytes) if err2 != nil { err = fmt.Errorf("Error connecting to node (%s) to fetch nonce: %s", nodeAddr, err2.Error()) return } if ac == nil || ac.Account == nil { err = fmt.Errorf("unknown account %X", addrBytes) return } nonce = int64(ac.Account.Sequence) + 1 } else { nonce, err = strconv.ParseInt(nonceS, 10, 64) if err != nil { err = fmt.Errorf("nonce is misformatted: %v", err) return } } return }
alist/mint-client
mintx/core/core.go
GO
gpl-3.0
17,152
#include "matFiles.hpp" #include <iostream> int writeFs (MATFile *pmat, mxArray *pn, double fsHz) { /* fsHZ */ pn = mxCreateDoubleScalar(fsHz); if (pn == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } int status = matPutVariable(pmat, "fsHz", pn); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } return 0; } int matFiles::readMatFile(const char *file, std::vector <std::vector<double> >& earSignals, double *fsHz) { MATFile *pmat; const char **dir; const char *name; int ndir; int i; mxArray *pa; mxArray *var; const size_t *dims; size_t ndims; double *data; /* * Open file to get directory */ pmat = matOpen(file, "r"); if (pmat == NULL) { printf("Error opening file %s\n", file); return(1); } /* * get directory of MAT-file */ dir = (const char **)matGetDir(pmat, &ndir); if (dir == NULL) { printf("Error reading directory of file %s\n", file); return(1); } mxFree(dir); /* In order to use matGetNextXXX correctly, reopen file to read in headers. */ if (matClose(pmat) != 0) { printf("Error closing file %s\n",file); return(1); } pmat = matOpen(file, "r"); if (pmat == NULL) { printf("Error reopening file %s\n", file); return(1); } /* Get headers of all variables */ /* Examining the header for each variable */ for (i=0; i < ndir; i++) { pa = matGetNextVariableInfo(pmat, &name); var = matGetVariable(pmat, name); data = mxGetPr(var); if (pa == NULL) { printf("Error reading in file %s\n", file); return(1); } if ( strcmp(name,"earSignals") == 0 ) { ndims = mxGetNumberOfDimensions(pa); dims = mxGetDimensions(pa); earSignals.resize(ndims); for ( size_t ii = 0 ; ii < ndims ; ++ii ) earSignals[ii].resize(dims[0],0); size_t ii, iii; for ( ii = 0 ; ii < dims[0] ; ++ii ) earSignals[0][ii] = data[ii]; for ( ii = dims[0], iii = 0 ; ii < dims[0] * 2 ; ++ii, ++iii ) earSignals[1][iii] = data[ii]; } else if ( strcmp(name,"fsHz") == 0 ) { ndims = mxGetNumberOfDimensions(pa); dims = mxGetDimensions(pa); assert( ndims == 2 ); assert( dims[0] == 1 ); *fsHz = data[0]; } mxDestroyArray(pa); } if (matClose(pmat) != 0) { printf("Error closing file %s\n",file); return(1); } return(0); } int matFiles::writeTDSMatFile(const char *file, std::shared_ptr<openAFE::twoCTypeBlock<double> > left, std::shared_ptr<openAFE::twoCTypeBlock<double> > right, double fsHz) { MATFile *pmat; /* Variables for mxArrays */ mxArray *pn_l = NULL, *pn2 = NULL; pmat = matOpen(file, "w"); if (pmat == NULL) { printf("Error creating file"); return(EXIT_FAILURE); } int status; /* EAR SIGNAL */ uint32_t leftSize = left->array1.second + left->array2.second; uint32_t rightSize = right->array1.second + right->array2.second; assert ( leftSize == rightSize ); pn_l = mxCreateDoubleMatrix(leftSize,2,mxREAL); if (pn_l == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } /* Left */ memcpy( mxGetPr(pn_l), left->array1.first, left->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + left->array1.second, left->array2.first, left->array2.second * sizeof(double) ); /* Right */ memcpy( mxGetPr(pn_l) + leftSize, right->array1.first, right->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + leftSize + right->array1.second, right->array2.first, right->array2.second * sizeof(double) ); status = matPutVariable(pmat, "outputSignals", pn_l); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } /* fsHZ */ writeFs (pmat, pn2, fsHz); return(0); } int matFiles::writeTFSMatFile(const char *file, std::vector<std::shared_ptr<openAFE::twoCTypeBlock<double> > >& left, std::vector<std::shared_ptr<openAFE::twoCTypeBlock<double> > >& right, double fsHz) { MATFile *pmat; /* Variables for mxArrays */ mxArray *pn_l = NULL, *pn_r = NULL, *pn2 = NULL; pmat = matOpen(file, "w"); if (pmat == NULL) { printf("Error creating file"); return(EXIT_FAILURE); } int status; /* EAR SIGNAL */ std::size_t leftSize = left.size(); std::size_t rightSize = right.size(); uint32_t frameNumber = left[0]->array1.second + left[0]->array2.second; assert ( leftSize == rightSize ); pn_l = mxCreateDoubleMatrix(frameNumber,leftSize,mxREAL); if (pn_l == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } for ( std::size_t ii = 0 ; ii < leftSize ; ++ii ) { memcpy( mxGetPr(pn_l) + frameNumber * ii, left[ii]->array1.first, left[ii]->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + frameNumber * ii + left[ii]->array1.second, left[ii]->array2.first, left[ii]->array2.second * sizeof(double) ); } status = matPutVariable(pmat, "leftOutput", pn_l); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } pn_r = mxCreateDoubleMatrix(frameNumber,rightSize,mxREAL); if ( pn_r == NULL ) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } for ( std::size_t ii = 0 ; ii < rightSize ; ++ii ) { memcpy( mxGetPr(pn_r) + frameNumber * ii, right[ii]->array1.first, right[ii]->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_r) + frameNumber * ii + right[ii]->array1.second, right[ii]->array2.first, right[ii]->array2.second * sizeof(double) ); } status = matPutVariable(pmat, "rightOutput", pn_r); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } /* fsHZ */ writeFs (pmat, pn2, fsHz); return(0); } int matFiles::writeXCORRMatFile(const char *file, std::vector<std::vector<std::shared_ptr<openAFE::twoCTypeBlock<double> > > >& left, double fsHz) { MATFile *pmat; /* Variables for mxArrays */ mxArray *pn_l = NULL, *pn2 = NULL; pmat = matOpen(file, "w"); if (pmat == NULL) { printf("Error creating file"); return(EXIT_FAILURE); } int status; /* EAR SIGNAL */ std::size_t leftChannels = left.size(); std::size_t leftLags = left[0].size(); uint32_t frameNumber = left[0][0]->array1.second + left[0][0]->array2.second; std::size_t ndim = 3, dims[3] = {frameNumber, leftChannels, leftLags }; pn_l = mxCreateNumericArray(ndim, dims, mxDOUBLE_CLASS, mxREAL ); if (pn_l == NULL) { printf("Unable to create mxArray with mxCreateDoubleMatrix\n"); return(1); } for ( std::size_t ii = 0 ; ii < leftChannels ; ++ii ) { for ( std::size_t jj = 0 ; jj < leftLags ; ++jj ) { memcpy( mxGetPr(pn_l) + frameNumber * ii + frameNumber * leftChannels * jj , left[ii][jj]->array1.first, left[ii][jj]->array1.second * sizeof(double) ); memcpy( mxGetPr(pn_l) + frameNumber * ii + frameNumber * leftChannels * jj + left[ii][jj]->array1.second, left[ii][jj]->array2.first, left[ii][jj]->array2.second * sizeof(double) ); } } status = matPutVariable(pmat, "leftOutput", pn_l); if ((status) != 0) { printf("Error writing.\n"); return(EXIT_FAILURE); } writeFs (pmat, pn2, fsHz); return(0); }
TWOEARS/TwoEars
RoboticPlatform/openAFE/examples/matFiles.cpp
C++
gpl-3.0
7,332
# -*- encoding: UTF-8 -*- import datetime from sqlalchemy import MetaData, Table, Column, String, Integer from Interface import AbstractDataObject from utils.String import attributes_repr def define_event_table(meta: MetaData): return Table( 'events', meta, Column('book_id', String, primary_key=True), Column('reader_id', String, primary_key=True), Column('event_date', String, primary_key=True), Column('event_type', String, primary_key=True), Column('times', Integer), ) class Event(AbstractDataObject): __attributes__ = ('book_id', 'reader_id', 'event_date', 'event_type') __repr__ = attributes_repr def __init__(self, book_id: str, reader_id: str, event_date: str, event_type: str): self.book_id = book_id self.reader_id = reader_id self.event_date = event_date self.event_type = event_type self.times = 1 def __eq__(self, other): if type(self) != type(other): return False else: if self.event_date == other.event_date: if self.book_id == other.book_id and self.reader_id == other.reader_id and \ self.event_type == other.event_type: return True else: return False else: return False @property def date(self): return datetime.datetime.strptime(self.event_date, '%Y%m%d').date() def update_from(self, value): if type(value) == type(self): if self == value: self.times += 1 else: pass else: raise NotImplementedError return self def compare_by(self, **kwargs): for tag in kwargs: if tag not in self.__attributes__: raise AttributeError('Event has no attribute {}'.format(tag)) else: if kwargs[tag] != getattr(self, tag): return False return True @classmethod def init_from(cls, value): if isinstance(value, dict): return cls( book_id=value['sysID'], reader_id=value['userID'], event_date=value['event_date'], event_type=value['event_type'], ) else: raise NotImplementedError @property def hashable_key(self): return '|'.join([self.book_id, self.reader_id, self.event_date, self.event_type])
mingotang/libdata
structures/Event.py
Python
gpl-3.0
2,531
<?php /** * Sidebar */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly get_sidebar(); ?>
dunskii/BookingX
templates/global/sidebar.php
PHP
gpl-3.0
108
Ext.define('Onlineshopping.onlineshopping.shared.shop.model.location.TimezoneModel', { "extend": "Ext.data.Model", "fields": [{ "name": "primaryKey", "type": "string", "defaultValue": "" }, { "name": "timeZoneId", "type": "string", "defaultValue": "" }, { "name": "utcdifference", "type": "int", "defaultValue": "" }, { "name": "gmtLabel", "type": "string", "defaultValue": "" }, { "name": "timeZoneLabel", "type": "string", "defaultValue": "" }, { "name": "country", "type": "string", "defaultValue": "" }, { "name": "cities", "type": "string", "defaultValue": "" }, { "name": "versionId", "type": "int", "defaultValue": "" }, { "name": "entityAudit", "reference": "EntityAudit" }, { "name": "primaryDisplay", "type": "string", "defaultValue": "" }] });
applifireAlgo/OnlineShopEx
onlineshopping/src/main/webapp/app/onlineshopping/shared/shop/model/location/TimezoneModel.js
JavaScript
gpl-3.0
1,104
/* * A 2D video game in C++ with SFML where platforms are actually Maths Curves resulting of equations you write * Copyright (C) 2013,2017 Gomez Guillaume, Jarretier Adrien * * 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/>. * * Contact us on Github : https://github.com/guillaume-gomez/MathGame * or https://github.com/AdrienJarretier */ #ifndef BUTTONANIM_H #define BUTTONANIM_H #ifdef DEBUG #include <iostream> #endif // DEBUG #include "AniSprite.hpp" #include "StaticButton.hpp" class ButtonAnim : public StaticButton { public: ButtonAnim(const char* _filename = "", int _widthFrame=0, int _heigtFrame=0); virtual ~ButtonAnim(); void switchTile(); void handle_input(sf::Event& event, sf::RenderTarget& target); void Launch(); private: //to launch animation for instance; bool m_changing; AniSprite m_spriteList; sf::Texture m_texture; }; #endif // BUTTONANIM_H
AdrienJarretier/MathGame
include/ButtonAnim.hpp
C++
gpl-3.0
1,638
/* * This library is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. For the terms of this * license, see licenses/gpl_v3.txt or <http://www.gnu.org/licenses/>. * * You are free to use this library under the terms of the GNU General * Public License, 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. * * Alternatively, you can license this library under a commercial * license, as set out in licenses/commercial.txt. */ package ch.swingfx.twinkle.style.background; import ch.swingfx.color.ColorUtil; import java.awt.*; import java.awt.geom.RoundRectangle2D; /** * Paints a color as background * @author Heinrich Spreiter * */ public class ColorBackground implements IBackground { /** Color of the background */ private Color fColor; /** * Create a new {@link ColorBackground} * @param color color of this background */ public ColorBackground(Color color) { fColor = color; } public void paintBackground(Graphics g, boolean isMouseOver, int cornerRadius) { final Graphics2D copy = (Graphics2D) g.create(); final Shape clip = copy.getClip(); copy.setColor(fColor); copy.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if(cornerRadius == 0) { copy.fill(clip); } else { copy.fill(new RoundRectangle2D.Double(0, 0, clip.getBounds().getWidth(), clip.getBounds().getHeight(), cornerRadius, cornerRadius)); } copy.dispose(); } public void setAlpha(float alpha) { fColor = ColorUtil.withAlpha(fColor, alpha); } }
Bvink/WildTornado
src/ch/swingfx/twinkle/style/background/ColorBackground.java
Java
gpl-3.0
1,751
#include "VisualizerCanvasPoincare.h" #include <QMouseEvent> #include <assert.h> #include "VisualizerContext3D.h" #include <cmath> #include <limits> #include <boost/foreach.hpp> #include <algorithm> #define pi 3.14159256 double log(double,int){ assert(false); return 0; } VisualizerCanvasPoincare::VisualizerCanvasPoincare(QWidget* parent, VisualizerContext3D* context) : VisualizerCanvas(parent, context), m_context(context), m_sphere_model(0), m_data_models(0) { setBackgroundColor(1.f, 1.f, 1.f); m_mode = NAVIGATION; snapViewAroundData(); } VisualizerCanvasPoincare::~VisualizerCanvasPoincare(void) { deleteModels(); } void VisualizerCanvasPoincare::refresh() { deleteModels(); } void VisualizerCanvasPoincare::setXAxisDescription(string desc) { m_xAxisDescription = desc; } void VisualizerCanvasPoincare::setYAxisDescription(string desc) { m_yAxisDescription = desc; } void VisualizerCanvasPoincare::setZAxisDescription(string desc) { m_zAxisDescription = desc; } void VisualizerCanvasPoincare::addData(VisualizerData* data) { makeCurrent(); VisualizerData3D* data_3d = dynamic_cast<VisualizerData3D*>( data ); assert( data_3d ); VisualizerCanvas::addData( data_3d ); } void VisualizerCanvasPoincare::clearData() { deleteModels(); VisualizerCanvas::clearData(); } void VisualizerCanvasPoincare::initializeGL() { glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void VisualizerCanvasPoincare::resizeGL(int width, int height) { makeCurrent(); glViewport(0,0, width, height); setViewport(); } void VisualizerCanvasPoincare::paintGL() { clearCanvas(); setViewport(); paintSphere(); paintData(); paintAxisLabels(); } void VisualizerCanvasPoincare::setViewport() { makeCurrent(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-m_viewport.width / 2.0f , m_viewport.width / 2.0f , -m_viewport.height / 2.0f, m_viewport.height / 2.0f, 0.0, 10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef( m_translation.x, m_translation.y, -1.5f ); glRotatef( m_rotation.x, 1.0f, 0.0f, 0.0f ); glRotatef( m_rotation.y, 0.0f, 1.0f, 0.0f ); // Kippen der gesamten Kugel um 90 Grad um s1, damit die Darstellung derjenigen von MATLAB // gleicht: glRotatef( -90.0f, 1.0f, 0.0f, 0.0f ); } void VisualizerCanvasPoincare::clearCanvas() { makeCurrent(); glClearColor(getBackgroundColor().red, getBackgroundColor().green, getBackgroundColor().blue, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); } void VisualizerCanvasPoincare::paintSphere() { makeCurrent(); if (!m_sphere_model) m_sphere_model = createSphereModel(); glCallList(m_sphere_model); } void VisualizerCanvasPoincare::paintData() { makeCurrent(); if ( m_data_models.empty() ) { BOOST_FOREACH( VisualizerData* data, getData() ) { m_data_models.push_back( createDataModel( data ) ); } } BOOST_FOREACH( GLuint model, m_data_models ) glCallList(model); } void VisualizerCanvasPoincare::paintAxisLabels() { glColor4f(0.0, 0.0, 0.0, 1.0); const double dist = 1.23f; const double off = 0.02 * dist; QFont font; font.setPixelSize( 51.0f / m_viewport.height ); renderText(dist, off, off, "s1", font); renderText( off, dist, off, "s2", font); renderText( off, off, dist, "s3", font); } GLuint VisualizerCanvasPoincare::createSphereModel() { makeCurrent(); const double sphere_radius = 1.0f; // Radius der Kugel beträgt 1. const double delta_phi = pi / 12.0; // Kugel wird in 15-Grad-Schritten unterteilt. GLuint sphere = glGenLists(1); glNewList(sphere, GL_COMPILE); glEnable(GL_BLEND); glColor4f( 1-getBackgroundColor().red+0.6, 1-getBackgroundColor().green+0.6, 1-getBackgroundColor().blue+0.6, 0.8f ); glLineStipple(3, 0xAAAA); glEnable(GL_LINE_STIPPLE); for ( double phi = delta_phi; phi < pi; phi += delta_phi ) { double z_pos = sphere_radius * cos(phi); double radius = sphere_radius * sin(phi); drawCircle( Point(0.0f, 0.0f, z_pos), radius, Point(1.0f, 0.0f, 0.0f), 0.0f ); } glPushMatrix(); glRotatef(90.0, 1.0, 0.0, 0.0); for ( double phi = 0; phi < pi; phi += delta_phi ) { drawCircle( Point(0.0f, 0.0, 0.0f), sphere_radius, Point(0.0f, 1.0f, 0.0f), phi / pi * 180.0 ); } glPopMatrix(); glDisable(GL_LINE_STIPPLE); // Zeichne die Achsen ein: drawAxes(); glDisable(GL_BLEND); glEndList(); return sphere; } void VisualizerCanvasPoincare::drawAxes() { drawAxis( Axis( Angle( 0.0, 0.0), RGBAColor(0.0, 0.0, 0.0, 1.0) ) ); drawAxis( Axis( Angle(-90.0, 0.0), RGBAColor(0.0, 0.0, 0.0, 1.0) ) ); drawAxis( Axis( Angle( 0.0, 90.0), RGBAColor(0.0, 0.0, 0.0, 1.0) ) ); } void VisualizerCanvasPoincare::drawAxis( const Axis& a ) { makeCurrent(); glPushMatrix(); glRotatef(a.direction.theta, 0.0, 1.0, 0.0); glRotatef(a.direction.phi, 0.0, 0.0, 1.0); const double length = 1.18f; glColor4f(a.color.r, a.color.g, a.color.b, a.color.a); glBegin(GL_LINES); glVertex3f( 0.0f, 0.0f, 0.0f); glVertex3f(length, 0.0f, 0.0f); glEnd(); glPushMatrix(); glTranslatef(length, 0.0, 0.0); const double width = 0.03; glBegin(GL_TRIANGLES); glVertex3f(-width * 3, 0.0, -width); glVertex3f(-width * 3, 0.0, width); glVertex3f(0.0, 0.0, 0.0); glEnd(); glRotatef(90, 1.0, 0.0, 0.0); glBegin(GL_TRIANGLES); glVertex3f(-width * 3, 0.0, -width); glVertex3f(-width * 3, 0.0, width); glVertex3f(0.0, 0.0, 0.0); glEnd(); glPopMatrix(); glPopMatrix(); } GLuint VisualizerCanvasPoincare::createDataModel( VisualizerData* raw_data ) { makeCurrent(); VisualizerData3D* data = dynamic_cast<VisualizerData3D*>( raw_data ); assert( data ); GLuint data_model = glGenLists(1); glNewList(data_model, GL_COMPILE); glEnable(GL_BLEND); if ( data->isVisible() ) { switch ( data->getStyle() ) { case VisualizerData::LINE: case VisualizerData::DASHED_LINE: case VisualizerData::DASHED_DOTTED_LINE: drawDataAsLines(data); break; case VisualizerData::CROSS: case VisualizerData::SQUARE: drawDataAsCrosses(data); break; default: assert(false); } } glDisable(GL_BLEND); glEndList(); return data_model; } vector<double> VisualizerCanvasPoincare::getAlphaValues( VisualizerData3D* data ) { vector<double> intensities; intensities.resize( data->getData().size(), 1.0f ); if ( data->hasAnnotation("Intensity") && data->isTransparent() ) { intensities = data->getAnnotation("Intensity"); double highest = -std::numeric_limits<double>::infinity(); double lowest = std::numeric_limits<double>::infinity(); for (uint i = 0; i < intensities.size(); ++i) { if ( intensities[i] > highest ) highest = intensities[i]; if ( intensities[i] < lowest ) lowest = intensities[i]; } lowest = log(lowest + 1.0f , 10); highest = log(highest + 1.0f, 10); if ( (highest - lowest) / highest < 1e-6 ) { // Im Falle, das alle Intensitäten (nahezu) gleich sind... return vector<double>( data->getData().size(), 1.0f ); // Gleichverteilung zurückgeben, denn die Intensitäten sind ja auch gleichverteilt. } for (uint i = 0; i < intensities.size(); ++i) { intensities[i] = ( log( intensities[i] + 1.0f , 10 ) - lowest ) / (highest - lowest); if ( intensities[i] < 0.10 ) { intensities[i] = 0.0; } } } return intensities; } void VisualizerCanvasPoincare::drawDataAsLines( VisualizerData3D* data ) { if (data->getStyle() == VisualizerData::DASHED_LINE) { glLineStipple (1, 0xAAAA); glEnable(GL_LINE_STIPPLE); } if (data->getStyle() == VisualizerData::DASHED_DOTTED_LINE) { glLineStipple (1, 0x1C47); glEnable(GL_LINE_STIPPLE); } vector<double> alpha = getAlphaValues(data); glBegin( GL_LINE_STRIP ); for (uint i = 0; i < data->getData().size(); ++i) { VisualizerData3D::Point p = data->getData()[i]; glColor4f(data->getColorRed(),data->getColorGreen(),data->getColorBlue(),alpha[i]); glVertex3f( p.x, p.y, p.z ); } glEnd(); if ( glIsEnabled( GL_LINE_STIPPLE ) ) glDisable(GL_LINE_STIPPLE); } void VisualizerCanvasPoincare::drawDataAsCrosses( VisualizerData3D* data ) { const double cross = 3.0f / 100.0f; vector<double> alpha = getAlphaValues(data); if ( data->isBold() ) glLineWidth( 5.0f ); for (uint i = 0; i < data->getData().size(); ++i) { VisualizerData3D::Point p = data->getData()[i]; glBegin( GL_LINES ); glColor4f(data->getColorRed(),data->getColorGreen(),data->getColorBlue(),alpha[i]); glVertex3f( p.x - cross / 2.0, p.y, p.z ); glVertex3f( p.x + cross / 2.0, p.y, p.z ); glVertex3f( p.x, p.y - cross / 2.0f, p.z ); glVertex3f( p.x, p.y + cross / 2.0f, p.z ); glVertex3f( p.x, p.y, p.z - cross / 2.0f ); glVertex3f( p.x, p.y, p.z + cross / 2.0f ); glEnd(); } if ( data->isBold() ) glLineWidth( 1.0f ); } void VisualizerCanvasPoincare::drawCircle( Point center, double radius, Point rotationVector, double angle ) { glPushMatrix(); glTranslatef(center.x, center.y, center.z); glRotatef(angle, rotationVector.x, rotationVector.y, rotationVector.z); const double delta_phi = 2*pi / 100; glBegin(GL_LINE_LOOP); for ( double phi = 0; phi < 2*pi; phi += delta_phi ) { glVertex3f( radius * cos(phi), radius * sin(phi), 0.0f ); } glEnd(); glPopMatrix(); } void VisualizerCanvasPoincare::deleteModels() { makeCurrent(); if (m_sphere_model) { glDeleteLists(m_sphere_model, 1); m_sphere_model = 0; } if (!m_data_models.empty()) { BOOST_FOREACH( GLuint model, m_data_models ) { glDeleteLists(model, 1); } m_data_models.clear(); } } void VisualizerCanvasPoincare::mousePressEvent(QMouseEvent *event) { m_last_mouse_pos.first = event->x(); m_last_mouse_pos.second = event->y(); } void VisualizerCanvasPoincare::mouseReleaseEvent(QMouseEvent *) { } void VisualizerCanvasPoincare::mouseMoveEvent(QMouseEvent *event) { pair<int, int> current( event->x(), event->y() ); pair<int, int> last = m_last_mouse_pos; if (m_mode == NAVIGATION) { switch (event->buttons()) { case Qt::LeftButton: rotate( current.first - last.first, current.second - last.second ); break; case Qt::RightButton: translate( current.first - last.first, current.second - last.second ); break; } updateGL(); } m_last_mouse_pos = current; } void VisualizerCanvasPoincare::wheelEvent(QWheelEvent* event) { int numDegrees = event->delta() / 8; int numSteps = numDegrees / 15; if (event->orientation() == Qt::Vertical) { if ( (m_viewport.width > 2 * numSteps / 10.0f) && (m_viewport.height > 2 * numSteps / 10.0f) ) { m_viewport.width -= numSteps / 10.0f; m_viewport.height -= numSteps / 10.0f; } setViewport(); updateGL(); event->accept(); } } void VisualizerCanvasPoincare::snapViewAroundData() { m_rotation.x = m_rotation.y = m_rotation.z = 0.0f; m_translation.x = m_translation.y = m_translation.z = 0.0f; m_viewport.width = m_viewport.height = 3.0f; setViewport(); if ( isVisible() ) { makeCurrent(); updateGL(); } } void VisualizerCanvasPoincare::updateVisualizerData(VisualizerData*) { deleteModels(); updateGL(); } void VisualizerCanvasPoincare::rotate( int x, int y ) { const double px2deg = 0.5 / 3.0 * m_viewport.width; m_rotation.x += y * px2deg; m_rotation.y += x * px2deg; if (m_rotation.x > 90.0f) m_rotation.x = 90.0f; if (m_rotation.x < -90.0f) m_rotation.x = -90.0f; } void VisualizerCanvasPoincare::translate( int x, int y ) { float diminisher = 600.0f / m_viewport.width; m_translation.x += x / diminisher; m_translation.y -= y / diminisher; }
lucksus/neuro_edit
Visualizer/VisualizerCanvasPoincare.cpp
C++
gpl-3.0
11,508
package navalbattle.protocol.messages.common; import java.util.ArrayList; import navalbattle.boats.BoatPosition; import navalbattle.protocol.common.NavalBattleProtocol; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import xmlhelper.XMLHelper; public class NavalBattlePositionMyBoats extends NavalBattleMessage { private ArrayList<BoatPosition> boats = null; public ArrayList<BoatPosition> getBoats() { return boats; } @Override public Document getXMLRepresentation() { Document doc = XMLHelper.createBaseDocument(); Element rootNode = doc.createElement("request"); rootNode.setAttribute("type", "positionMyBoats"); Element boatsNode = doc.createElement("boats"); for (BoatPosition boat : this.boats) { Element boatNode = doc.createElement("boat"); boatNode.setAttribute("x", Integer.toString(boat.getX())); boatNode.setAttribute("y", Integer.toString(boat.getY())); boatNode.setAttribute("size", Integer.toString(boat.getLength())); boatNode.setAttribute("orientation", ((boat.getOrientation() == NavalBattleProtocol.BOAT_ORIENTATION.HORIZONTAL) ? "horizontal" : "vertical")); boatsNode.appendChild(boatNode); } rootNode.appendChild(boatsNode); doc.appendChild(rootNode); return doc; } @Override public NavalBattlePositionMyBoats parse(Document message) throws InvalidMessage { ArrayList<BoatPosition> boatsRead = new ArrayList<>(); Node rootNode = message.getDocumentElement(); Node boatsNode = XMLHelper.getChildren(rootNode).get("boats"); NodeList allBoats = boatsNode.getChildNodes(); final int boatsCount = allBoats.getLength(); for (int i = 0; i < boatsCount; ++i) { int x; int y; int length; NavalBattleProtocol.BOAT_ORIENTATION orientation; Node boatNode = allBoats.item(i); if (boatNode.getNodeType() != Node.ELEMENT_NODE) continue; NamedNodeMap nodeAttributes = boatNode.getAttributes(); x = Integer.parseInt(nodeAttributes.getNamedItem("x").getNodeValue()); y = Integer.parseInt(nodeAttributes.getNamedItem("y").getNodeValue()); length = Integer.parseInt(nodeAttributes.getNamedItem("size").getNodeValue()); if (x < 0 || y < 0 || length <= 0) { throw new InvalidMessage(); } switch (nodeAttributes.getNamedItem("orientation").getTextContent()) { case "horizontal": orientation = NavalBattleProtocol.BOAT_ORIENTATION.HORIZONTAL; break; case "vertical": orientation = NavalBattleProtocol.BOAT_ORIENTATION.VERTICAL; break; default: throw new InvalidMessage(); } boatsRead.add(new BoatPosition(x, y, orientation, length)); } this.setValues(boatsRead); return this; } public void setValues(ArrayList<BoatPosition> boats) { this.boats = boats; } }
ArmandDelessert/WarTanks
NavalBattle/src/navalbattle/protocol/messages/common/NavalBattlePositionMyBoats.java
Java
gpl-3.0
3,356
/******************************************************************* This file is part of iContact. iContact 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. iContact 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 iContact. If not, see <http://www.gnu.org/licenses/>. *******************************************************************/ #include "stdafx.h" #include "GraphicFunctions.h" #include "macros.h" HFONT BuildFont(int iFontSize, BOOL bBold, BOOL bItalic) { LOGFONT lf; memset(&lf, 0, sizeof(LOGFONT)); lf.lfHeight = iFontSize; lf.lfWidth = 0; lf.lfEscapement = 0; lf.lfOrientation = 0; lf.lfWeight = bBold ? 600 : 500; lf.lfItalic = bItalic; lf.lfUnderline = false; lf.lfStrikeOut = false; lf.lfCharSet = EASTEUROPE_CHARSET; lf.lfOutPrecision = OUT_RASTER_PRECIS; lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; lf.lfQuality = CLEARTYPE_QUALITY; lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; _tcsncpy (lf.lfFaceName, TEXT("Tahoma"), LF_FACESIZE); //lf.lfFaceName[LF_FACESIZE-1] = L'\0'; // Ensure null termination return CreateFontIndirect(&lf); } // ************************************************************************** // Function Name: DrawRect // // Purpose: Draws a rectangle with the coordinates and the color passed in // // Arguments: // IN HDC hdc - DC for drawing // IN LPRECT prc - Area to draw the rectangle // IN COLORREF clr - color to draw the rectangle // // Return Values: // NONE // void DrawRect(HDC hdc, LPRECT prc, COLORREF clr) { COLORREF clrSave = SetBkColor(hdc, clr); ExtTextOut(hdc,0,0,ETO_OPAQUE,prc,NULL,0,NULL); SetBkColor(hdc, clrSave); } void DrawGradientGDI(HDC tdc, RECT iRect, COLORREF StartRGB, COLORREF EndRGB) { unsigned int Shift = 8; TRIVERTEX vert[2] ; GRADIENT_RECT gRect; vert [0] .x = iRect.left; vert [0] .y = iRect.top; vert [0] .Red = GetRValue(StartRGB) << Shift; vert [0] .Green = GetGValue(StartRGB) << Shift; vert [0] .Blue = GetBValue(StartRGB) << Shift; vert [0] .Alpha = 0x0000; vert [1] .x = iRect.right; vert [1] .y = iRect.bottom; vert [1] .Red = GetRValue(EndRGB) << Shift; vert [1] .Green = GetGValue(EndRGB) << Shift; vert [1] .Blue = GetBValue(EndRGB) << Shift; vert [1] .Alpha = 0x0000; gRect.UpperLeft = 0; gRect.LowerRight = 1; GradientFill(tdc, vert, 2, &gRect, 1, GRADIENT_FILL_RECT_V); } void BltAlpha(HDC hdcDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, HDC hdcSrc, int nXOriginSrc, int nYoriginSrc, int nWidthSrc, int nHeightSrc, BYTE alpha) { BLENDFUNCTION bf; bf.BlendOp = AC_SRC_OVER; bf.BlendFlags = 0; bf.SourceConstantAlpha = alpha; bf.AlphaFormat = 0; AlphaBlend(hdcDest, nXOriginDest, nYOriginDest, nWidthDest, nHeightDest, hdcSrc, nXOriginSrc, nYoriginSrc, nWidthSrc, nHeightSrc, bf); } void BltAlpha(HDC hdcDest, int nLeft, int nTop, int nWidth, int nHeight, HDC hdcSrc, BYTE alpha) { BltAlpha(hdcDest, nLeft, nTop, nWidth, nHeight, hdcSrc, 0, 0, nWidth, nHeight, alpha); } // ************************************************************************** // Function Name: GetStreamSize // // Purpose: Given an IStream, returns the size of the stream. This is needed // for streams that do not support the Stat method // // Arguments: // IN IStream* pStream - stream to determine size for // OUT ULONG* pulSize - size of stream // // Return Values: // HRESULT - S_OK if success, failure code if not // // Side Effects: // The stream pointer always resets to the beginning // HRESULT GetStreamSize(IStream* pStream, ULONG* pulSize) { HRESULT hr; LARGE_INTEGER li = {0}; ULARGE_INTEGER uliZero = {0}; ULARGE_INTEGER uli; CBR(pStream != NULL && pulSize != NULL); hr = pStream->Seek(li, STREAM_SEEK_END, &uli); CHR(hr); *pulSize = uli.LowPart; hr = S_OK; Error: if (SUCCEEDED(hr)) { // Move the stream back to the beginning of the file hr = pStream->Seek(li, STREAM_SEEK_SET, &uliZero); } return hr; } // ************************************************************************** // Function Name: ScaleProportional // // Purpose: Scale the width and height to fit the given width and height // but maintain the proportion // // Arguments: // IN UINT uFitToWidth - width of source image // IN UINT uFitToHeight - height of source image // IN/OUT UINT* puWidthToScale - width of image to scale to // IN/OUT UINT* puHeightToScale - height of image to scale to // // Return Values: // HRESULT - S_OK if success, failure code if not // void ScaleProportional(UINT uFitToWidth, UINT uFitToHeight, UINT *puWidthToScale, UINT *puHeightToScale) { HRESULT hr; CBR(puWidthToScale != NULL && puHeightToScale != NULL); // Scale (*puWidthToScale, *puHeightToScale) to fit within (uFitToWidth, uFitToHeight), while // maintaining the aspect ratio int nScaledWidth = MulDiv(*puWidthToScale, uFitToHeight, *puHeightToScale); // If we didn't overflow and the scaled width does not exceed bounds if (nScaledWidth >= 0 && nScaledWidth <= (int)uFitToWidth) { *puWidthToScale = nScaledWidth; *puHeightToScale = uFitToHeight; } else { *puHeightToScale = MulDiv(*puHeightToScale, uFitToWidth, *puWidthToScale); // The height *must* be within the bounds [0, uFitToHeight] since we overflowed // while fitting to height ASSERT(*puHeightToScale >= 0 && *puHeightToScale <= uFitToHeight); *puWidthToScale = uFitToWidth; } Error: return; } // ************************************************************************** // Function Name: HBITMAPFromImage // // Purpose: Convert IImage to HBITMAP. If bitmap has transparency, the // background will be filled with the color passed in // // Arguments: // IN IImage* pImage - pointer to the IImage // IN COLORREF crBackColor - color of the background // // Return Values: // HRESULT - S_OK if success, failure code if not // HBITMAP HBITMAPFromImage (IN IImage * pImage, IN COLORREF crBackColor) { HRESULT hr; HBITMAP hbmResult = NULL; ImageInfo ii; HDC hDC = NULL; HBITMAP hbmNew = NULL; void * pv; BITMAPINFO bmi = { 0 }; HBITMAP hbmOld = NULL; RECT rc = { 0 }; CBR(pImage != NULL); // Get image width/height hr = pImage->GetImageInfo(&ii); CHR(hr); // Create HDC hDC = CreateCompatibleDC(NULL); CBR(hDC != NULL); // Create DIB section bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = ii.Width; bmi.bmiHeader.biHeight = ii.Height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 24; bmi.bmiHeader.biCompression = BI_RGB; hbmNew = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, &pv, NULL, 0); CBR(hbmNew != NULL); // Select DIB into DC hbmOld = (HBITMAP)SelectObject(hDC, hbmNew); rc.right = ii.Width; rc.bottom = ii.Height; // Clear the bitmap using the background color DrawRect(hDC, &rc, crBackColor); // Draw into DC/DIB hr = pImage->Draw(hDC, &rc, NULL); CHR(hr); hbmResult = hbmNew; hbmNew = NULL; Error: if (hbmNew) { DeleteObject(hbmNew); } if (hDC) { if (hbmOld) { SelectObject(hDC, hbmOld); } DeleteDC(hDC); } return hbmResult; } // ************************************************************************** // Function Name: GetBitmapFromStream // // Purpose: Convert an IStream to an HBITMAP and return the new dimensions // // Arguments: // IN UINT uFitToWidth - width of source image // IN UINT uFitToHeight - height of source image // OUT UINT* puWidth - width of image to scale to // OUT UINT* puHeight - height of image to scale to // // Return Values: // HRESULT - S_OK if success, failure code if not // HRESULT GetBitmapFromStream(IStream* pStream, HBITMAP* phBitmap, UINT* puWidth, UINT* puHeight) { HRESULT hr; HBITMAP hBitmap = NULL; IImagingFactory* pFactory = NULL; IImage* pImage = NULL; IImage* pThumbnail = NULL; ImageInfo imgInfo = {0}; CBR(pStream != NULL && phBitmap != NULL && puWidth != NULL && puHeight != NULL); // Use a little imaging help hr = CoCreateInstance(CLSID_ImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IImagingFactory, (void**) &pFactory); CHR(hr); hr = pFactory->CreateImageFromStream(pStream, &pImage); CHR(hr); hr = pImage->GetImageInfo(&imgInfo); CHR(hr); CBR(imgInfo.Width > 0 && imgInfo.Height > 0); // Scale to the new size ScaleProportional(*puWidth, *puHeight, &imgInfo.Width, &imgInfo.Height); // Get the new image hr = pImage->GetThumbnail(imgInfo.Width, imgInfo.Height, &pThumbnail); CHR(hr); // Convert this to HBITMAP, our target format hBitmap = HBITMAPFromImage(pThumbnail, RGB(255,255,255)); CBR(hBitmap != NULL); *puWidth = imgInfo.Width; *puHeight = imgInfo.Height; *phBitmap = hBitmap; hBitmap = NULL; Error: RELEASE_OBJ(pFactory); RELEASE_OBJ(pImage); RELEASE_OBJ(pThumbnail); if (hBitmap) { DeleteObject((HGDIOBJ)(HBITMAP)(hBitmap)); } return hr; } // http://www.koders.com/cpp/fid743B2B2FCDBFE91584C329A50766C1155709DA1B.aspx /***************************************************************************** * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *****************************************************************************/ /* Call IImageEncoder::GetEncodeSink to retrieve an IImageSink interface. The IImageSink interface is implemented as follows: a. Call IImageSink::BeginSink to negotiate the values contained in the ImageInfo structure for encoding the current frame. b. Call IImageSink::SetPalette to pass color palette information about the current image frame to the image sink. c. If you need to pass property data to the image sink, you can optionally call IImageSink::GetPropertyBuffer to obtain a buffer that will contain the property data. d. If GetPropertyBuffer is called above, you must next call IImageSink::PushPropertyItems to transfer the property data to the image sink. The buffer that was allocated by GetPropertyBuffer must be deallocated in the implementation for PushPropertyItems. e. Call IImageSink::PushPixelData or IImageSink::GetPixelDataBuffer to begin the data transfer, depending on how the image data is stored in the source: * If the image source has allocated memory for the image, use PushPixelData. * If the image source has not allocated memory for the image, use GetPixelDataBuffer. For each call to GetPixelDataBuffer, IImageSink::ReleasePixelDataBuffer must also be called. f. Call ImageSink::EndSink to complete the encoding process. g. Call ImageSink::Release to free the IImagesink interface. */ HRESULT SavePNG(HDC hDC, HBITMAP hBitmap, const TCHAR* szPath, IImagingFactory * pFactory) { HRESULT hr; // Set the particular encoder to use TCHAR * pszMimeType = TEXT("image/png"); UINT count; ImageCodecInfo* imageCodecInfo = NULL; hr = pFactory->GetInstalledEncoders(&count, &imageCodecInfo); CHR(hr); CBR(count > 0); CLSID encoderClassId; for (int i = 0; i < (int)count; i++) { if (wcscmp(imageCodecInfo[i].MimeType, pszMimeType) == 0) { encoderClassId = imageCodecInfo[i].Clsid; free(imageCodecInfo); break; } else { continue; } } IImageEncoder* imageEncoder = NULL; hr = pFactory->CreateImageEncoderToFile(&encoderClassId, szPath, &imageEncoder); CHR(hr); IImageSink* imageSink = NULL; hr = imageEncoder->GetEncodeSink(&imageSink); CHR(hr); BITMAP bm; GetObject ((HGDIOBJ)hBitmap, sizeof(BITMAP), &bm); ImageInfo* imageInfo = new ImageInfo(); imageInfo->Height = bm.bmHeight; imageInfo->Width = bm.bmWidth; //imageInfo->RawDataFormat = ImageFormatMemoryBMP;// ???? imageInfo->Flags |= SinkFlagsTopDown | SinkFlagsFullWidth; imageInfo->Xdpi = 192; imageInfo->Ydpi = 192; // Get pixel format from hBitmap switch (bm.bmBitsPixel) { case 1: imageInfo->PixelFormat = PixelFormat1bppIndexed; break; case 4: imageInfo->PixelFormat = PixelFormat4bppIndexed; break; case 8: imageInfo->PixelFormat = PixelFormat8bppIndexed; break; case 16: imageInfo->PixelFormat = PixelFormat16bppARGB1555; imageInfo->Flags |= SinkFlagsHasAlpha; break; case 24: imageInfo->PixelFormat = PixelFormat24bppRGB; break; default: imageInfo->PixelFormat = PixelFormat32bppARGB; imageInfo->Flags |= SinkFlagsHasAlpha; break; } hr = imageSink->BeginSink(imageInfo, NULL); CHR(hr); ColorPalette* palette = (ColorPalette*)malloc(sizeof(ColorPalette)); palette->Count = 0; if (imageInfo->Flags & SinkFlagsHasAlpha) palette->Flags = PALFLAG_HASALPHA; hr = imageSink->SetPalette(palette); CHR(hr); BitmapData* bmData = new BitmapData(); bmData->Height = bm.bmHeight; bmData->Width = bm.bmWidth; bmData->Scan0 = bm.bmBits; bmData->PixelFormat = imageInfo->PixelFormat; UINT bitsPerLine = imageInfo->Width * bm.bmBitsPixel; UINT bitAlignment = sizeof(LONG) * 8; // The image buffer is always padded to LONG boundaries UINT bitStride = bitAlignment * (bitsPerLine / bitAlignment); // Add a bit more for the leftover values if ((bitsPerLine % bitAlignment) != 0) bitStride += bitAlignment; bmData->Stride = bitStride / 8; RECT rect; SetRect(&rect, 0, 0, bm.bmWidth, bm.bmHeight); hr = imageSink->PushPixelData(&rect, bmData, TRUE); CHR(hr); hr = imageSink->EndSink(S_OK); CHR(hr); imageSink->Release(); hr = imageEncoder->TerminateEncoder(); CHR(hr); hr = S_OK; Error: RELEASE_OBJ(imageSink); return hr; }
scharada/icontact-wm
iContact/GraphicFunctions.cpp
C++
gpl-3.0
15,422
/* * PT2314PreAmp.cpp * * Created on: 28.12.2017 * Author: wmarkowski */ #include "PT2314PreAmp.h" PT2314PreAmp::PT2314PreAmp(PT2314 *pt2314) { this->pt2314 = pt2314; this->volume = 0; this->inputChannel = 0; } void PT2314PreAmp::setVolume(uint8_t newVolume) { if (getVolume() == newVolume) { return; } this->volume = newVolume; pt2314->volume(newVolume); } uint8_t PT2314PreAmp::getVolume() { return volume; } void PT2314PreAmp::setInputChannel(uint8_t channel) { this->inputChannel = channel; pt2314->channel(channel); } uint8_t PT2314PreAmp::getInputChannel() { return inputChannel; }
wmarkow/arduino-sandbox
diy-audio/src/hardware/PT2314PreAmp.cpp
C++
gpl-3.0
648
#!/usr/bin/env python import logging import os import urllib from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface import cvmfsreplica.pluginsmanagement as pm class Updatedserver(RepositoryPluginAcceptanceInterface): def __init__(self, repository, conf): self.log = logging.getLogger('cvmfsreplica.updatedserver') self.repository = repository self.conf = conf try: self.url = self.repository.cvmfsconf.get('CVMFS_STRATUM0') self.reportplugins = pm.readplugins(self.repository, 'repository', 'report', self.conf.namespace('acceptance.updatedserver.', exclude=True) ) except: raise PluginConfigurationFailure('failed to initialize Updatedserver plugin') self.log.debug('plugin Updatedserver initialized properly') #def verify(self): # ''' # checks if file .cvmfspublished # was updated more recently than variable # repository.last_published # ''' # try: # # FIXME # # maybe we should try a couple of times in case of failures before failing definitely # for line in urllib.urlopen('%s/.cvmfspublished' %self.url).readlines(): # if line.startswith('T'): # time = int(line[1:-1]) # break # out = time > self.repository.last_published # if out == False: # self._notify_failure('No new content at the server for repository %s' \ # %self.repository.repositoryname) # return out # except: # self.log.warning('file %s/.cvmfspublished cannot be read. Returning False' %self.url) # return False def verify(self): ''' checks if the revision number in local copy of .cvmfspublished is different that the revision number of remote .cvmfspublished ''' try: # FIXME # maybe we should try a couple of times in case of failures before failing definitely for line in urllib.urlopen('%s/.cvmfspublished' %self.url).readlines(): if line.startswith('S'): serverrevision = int(line[1:-1]) break # read the local revision number cvmfs_upstream_storage = self.repository._get_cvmfs_upstream_storage() # FIXME, this should not be here localfile = '%s/.cvmfspublished' %cvmfs_upstream_storage if not os.path.isfile(localfile): self.log.warning('local file %s does not exist. Returning True' %localfile) return True else: # FIXME: too much duplicated code for line in open(localfile): if line.startswith('S'): localrevision = int(line[1:-1]) break out = (serverrevision != localrevision) if out == False: self._notify_failure('No new content at the server for repository %s' \ %self.repository.repositoryname) return out except: self.log.warning('file %s/.cvmfspublished cannot be read. Returning False' %self.url) return False def _notify_failure(self, msg): for report in self.reportplugins: report.notifyfailure(msg)
jose-caballero/cvmfsreplica
cvmfsreplica/plugins/repository/acceptance/Updatedserver.py
Python
gpl-3.0
3,761
/** @file MeshBuilder.cpp @maintainer Morgan McGuire, matrix@graphics3d.com @created 2002-02-27 @edited 2005-02-24 */ #include "G3D/MeshBuilder.h" #include "G3D/MeshAlg.h" namespace G3D { void MeshBuilder::setName(const std::string& n) { name = n; } void MeshBuilder::commit(std::string& n, Array<int>& indexArray, Array<Vector3>& outvertexArray) { n = name; // Make the data fit in a unit cube centerTriList(); Array<int> toNew, toOld; if (close == MeshBuilder::AUTO_WELD) { Array<int> index; MeshAlg::createIndexArray(triList.size(), index); double minEdgeLen, maxEdgeLen, meanEdgeLen, medianEdgeLen; double minFaceArea, maxFaceArea, meanFaceArea, medianFaceArea; MeshAlg::computeAreaStatistics(triList, index, minEdgeLen, meanEdgeLen, medianEdgeLen, maxEdgeLen, minFaceArea, meanFaceArea, medianFaceArea, maxFaceArea); close = minEdgeLen * 0.1; } MeshAlg::computeWeld(triList, outvertexArray, toNew, toOld, close); // Construct triangles for (int t = 0; t < triList.size(); t += 3) { int index[3]; for (int i = 0; i < 3; ++i) { index[i] = toNew[t + i]; } // Throw out zero size triangles if ((index[0] != index[1]) && (index[1] != index[2]) && (index[2] != index[0])) { indexArray.append(index[0], index[1], index[2]); } } } void MeshBuilder::centerTriList() { // Compute the range of the vertices Vector3 vmin, vmax; computeBounds(vmin, vmax); Vector3 diagonal = vmax - vmin; double scale = max(max(diagonal.x, diagonal.y), diagonal.z) / 2; debugAssert(scale > 0); Vector3 translation = vmin + diagonal / 2; // Center and scale all vertices in the input list int v; //Matrix3 rot90 = Matrix3::fromAxisAngle(Vector3::UNIT_Y, toRadians(180)) * Matrix3::fromAxisAngle(Vector3::UNIT_X, toRadians(90)); for (v = 0; v < triList.size(); ++v) { triList[v] = (triList[v] - translation) / scale; //triList[v] = rot90 * triList[v]; } } void MeshBuilder::computeBounds(Vector3& min, Vector3& max) { min = Vector3::inf(); max = -min; int v; for (v = 0; v < triList.size(); ++v) { min = min.min(triList[v]); max = max.max(triList[v]); } } void MeshBuilder::addTriangle(const Vector3& a, const Vector3& b, const Vector3& c) { triList.append(a, b, c); if (_twoSided) { triList.append(c, b, a); } } void MeshBuilder::addQuad(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d) { addTriangle(a, b, c); addTriangle(a, c, d); } void MeshBuilder::addTriangle(const Triangle& t) { addTriangle(t.vertex(0), t.vertex(1), t.vertex(2)); } } // namespace
jolan78/MoveMaps
dep/src/G3D/MeshBuilder.cpp
C++
gpl-3.0
2,826
#include <QtGui/QApplication> #include "dialog.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Dialog w; w.show(); return a.exec(); }
urykhy/qcryptdisk
main.cpp
C++
gpl-3.0
170
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AuthService } from './auth.service'; @NgModule({ imports: [ CommonModule ], declarations: [], providers: [AuthService] }) export class CoreModule { }
gonza5569/studyplan
src/app/core/core.module.ts
TypeScript
gpl-3.0
261
package it.unibas.lunatic.gui.node; import it.unibas.lunatic.Scenario; import it.unibas.lunatic.gui.node.chase.mc.ChaseStepNode; import it.unibas.lunatic.model.chase.chasemc.DeltaChaseStep; import speedy.model.database.IDatabase; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; public class DbNode extends AbstractNode implements IChaseNode { private IDatabase db; private DeltaChaseStep chaseStep; private ChaseStepNode chaseStepNode; private Scenario scenario; public DbNode(Scenario scenario, IDatabase db, DeltaChaseStep chaseStep, ChaseStepNode chaseStepNode, boolean showId) { this(scenario, db, chaseStep.getId(), Children.create(new DbChildFactory(db, chaseStepNode, chaseStep, scenario), true), showId); this.chaseStep = chaseStep; this.chaseStepNode = chaseStepNode; } public DbNode(Scenario scenario, IDatabase db, String qualifier, boolean showId) { this(scenario, db, qualifier, Children.create(new DbChildFactory(db, scenario), true), showId); } public DbNode(Scenario scenario, IDatabase db, String qualifier) { this(scenario, db, qualifier, true); } protected DbNode(Scenario scenario, IDatabase db, String qualifier, Children c, boolean showId) { super(c); this.db = db; this.scenario = scenario; if (!qualifier.equals("")) { qualifier = qualifier.concat(":"); } String name = getTargetDbName(scenario, db); setName(qualifier.concat(name)); if (!showId) { setDisplayName(name); } this.setIconBaseWithExtension("it/unibas/lunatic/icons/database.gif"); } @Override public DeltaChaseStep getChaseStep() { assert chaseStep != null; return chaseStep; } @Override public boolean isMcResultNode() { return chaseStep != null; } public boolean hasChaseStepNode() { return chaseStepNode != null; } public ChaseStepNode getChaseStepNode() { return chaseStepNode; } public IDatabase getDb() { assert db != null; return db; } public Scenario getScenario() { return scenario; } public static String getTargetDbName(Scenario scenario, IDatabase db) { if (db.getName().equalsIgnoreCase("virtualtarget")) { return scenario.getTarget().getName(); } return db.getName(); } }
donatellosantoro/Llunatic
LunaticGUI/gui/src/it/unibas/lunatic/gui/node/DbNode.java
Java
gpl-3.0
2,551
<?php namespace Ivoz\Provider\Domain\Model\BrandUrl; use Ivoz\Core\Domain\Service\FileContainerInterface; use Ivoz\Core\Domain\Model\LoggableEntityInterface; interface BrandUrlInterface extends FileContainerInterface, LoggableEntityInterface { /** * @codeCoverageIgnore * @return array */ public function getChangeSet(); /** * @return array */ public function getFileObjects(); /** * {@inheritDoc} */ public function setUrl($url); /** * Get url * * @return string */ public function getUrl(); /** * @deprecated * Set klearTheme * * @param string $klearTheme * * @return self */ public function setKlearTheme($klearTheme = null); /** * Get klearTheme * * @return string */ public function getKlearTheme(); /** * @deprecated * Set urlType * * @param string $urlType * * @return self */ public function setUrlType($urlType); /** * Get urlType * * @return string */ public function getUrlType(); /** * @deprecated * Set name * * @param string $name * * @return self */ public function setName($name = null); /** * Get name * * @return string */ public function getName(); /** * @deprecated * Set userTheme * * @param string $userTheme * * @return self */ public function setUserTheme($userTheme = null); /** * Get userTheme * * @return string */ public function getUserTheme(); /** * Set brand * * @param \Ivoz\Provider\Domain\Model\Brand\BrandInterface $brand * * @return self */ public function setBrand(\Ivoz\Provider\Domain\Model\Brand\BrandInterface $brand = null); /** * Get brand * * @return \Ivoz\Provider\Domain\Model\Brand\BrandInterface */ public function getBrand(); /** * Set logo * * @param \Ivoz\Provider\Domain\Model\BrandUrl\Logo $logo * * @return self */ public function setLogo(\Ivoz\Provider\Domain\Model\BrandUrl\Logo $logo); /** * Get logo * * @return \Ivoz\Provider\Domain\Model\BrandUrl\Logo */ public function getLogo(); /** * @param $fldName * @param TempFile $file */ public function addTmpFile($fldName, \Ivoz\Core\Domain\Service\TempFile $file); /** * @param TempFile $file * @throws \Exception */ public function removeTmpFile(\Ivoz\Core\Domain\Service\TempFile $file); /** * @return TempFile[] */ public function getTempFiles(); /** * @var string $fldName * @return null | TempFile */ public function getTempFileByFieldName($fldName); }
manfer/ivozprovider
library/Ivoz/Provider/Domain/Model/BrandUrl/BrandUrlInterface.php
PHP
gpl-3.0
2,876
/* Kiduino.cpp - Kiduino library Copyright (c) 2014 Adithya Selvaprithiviraj. All right 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 2.1 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; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /****************************************************************************** * Includes ******************************************************************************/ #include "Kiduino.h" #include "Arduino.h" /** LED class begins**/ /****************************************************************************** * Definitions ******************************************************************************/ /****************************************************************************** * Constructors ******************************************************************************/ Led::Led(int pin) { pinMode(pin,OUTPUT); _pin = pin; ledstate=0; long int current; long int previous=0; brightness = 0; fadeAmount = 5; } /****************************************************************************** * User API ******************************************************************************/ void Led::blink(int a) { current=millis(); if(current-previous>=a) { ledstate=!ledstate; previous=current; } digitalWrite(_pin,ledstate); } void Led::on() { digitalWrite(_pin,HIGH); } void Led::off() { digitalWrite(_pin,LOW); } void Led::fade() { analogWrite(_pin, brightness); brightness = brightness + fadeAmount; if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } delay(30); } /**LED class ends**/ /**Ping class function starts**/ /****************************************************************************** * Definitions ******************************************************************************/ /****************************************************************************** * Constructors ******************************************************************************/ Ping::Ping(int pin) { int _pin = pin; } /****************************************************************************** * User API ******************************************************************************/ long int Ping::getcm() { pinMode(_pin,OUTPUT); digitalWrite(_pin,1); delayMicroseconds(10); pinMode(_pin,INPUT); long int x=pulseIn(_pin,HIGH);//microseconds long int dist=(330*x/20000); return (dist); } long int Ping::getin() { pinMode(_pin,OUTPUT); digitalWrite(_pin,1); delayMicroseconds(10); pinMode(_pin,INPUT); long int x=pulseIn(_pin,HIGH);//microseconds long int dist=(330*x/20000); return (dist*0.393701); } /**Ping class ends**/ /**Sled class begins**/ /****************************************************************************** * Definitions ******************************************************************************/ /****************************************************************************** * Constructors ******************************************************************************/ SLed::SLed() { boolean number[10]={B111111,B000110,B01011011,B01001111,B01100110,B01101101,B01111101,B111,B1111111,B1101111}; DDRD=255; } /****************************************************************************** * User API ******************************************************************************/ void SLed::display(int a) { PORTD=number[a]; } /**SLed class ends**/ /**RGB class begins**/ /****************************************************************************** * Definitions ******************************************************************************/ /****************************************************************************** * Constructors ******************************************************************************/ RGB::RGB(int pin1,int pin2,int pin3) { _pin1=pin1; _pin2=pin2; _pin3=pin3; int x; int y; int z; } /****************************************************************************** * User API ******************************************************************************/ void RGB::write(int a,int b,int c) { analogWrite(_pin1,a); analogWrite(_pin2,b); analogWrite(_pin3,c); } void RGB::rand() { x=random(0,255); y=random(0,255); z=random(0,255); analogWrite(_pin1,x); analogWrite(_pin2,y); analogWrite(_pin3,z); } /**RGB class ends**/ /**SIRC class begins**/ /****************************************************************************** * Definitions ******************************************************************************/ /****************************************************************************** * Constructors ******************************************************************************/ SIRC::SIRC(int pin,int mode) { if(mode==1) { pinMode(pin,OUTPUT); } if(mode==2) { pinMode(pin,INPUT); } int _pin=pin; } /****************************************************************************** * User API ******************************************************************************/ int SIRC::read() { if(pulseIn(_pin,LOW)>2000) { val=0; for(int i=0;i<12;i++) { if(pulseIn(_pin,LOW)>1000) data[i]=1; else data[i]=0; } for(int i=0;i<12;i++) { if(data[i]==1) val=val+(1<<i); } return (val); } } void SIRC::write(int value) { sendCode(96); for(int i=0;i<12;i++) { int val=value%2; value = value/2; if(val==1) sendCode(48); else sendCode(24); } } void SIRC::sendCode(int number) { for(int i=0;i<number;i++) { digitalWrite(14,HIGH); delayMicroseconds(8); digitalWrite(14,LOW); delayMicroseconds(7); } delayMicroseconds(600); } /**SIRC class ends **/ /**PIN class begins**/ /****************************************************************************** * Definitions ******************************************************************************/ /****************************************************************************** * Constructors ******************************************************************************/ PIN::PIN(int pin,int mode) { if(mode==1) { pinMode(pin,INPUT); } if(mode==2) { pinMode(pin,OUTPUT); } int _pin=pin; int analog; } /****************************************************************************** * User API ******************************************************************************/ void PIN::on() { digitalWrite(_pin,HIGH); } void PIN::off() { digitalWrite(_pin,LOW); } void PIN::awrite(int a) { analogWrite(_pin,a); } int PIN::aread() { analog=analogRead(_pin); return analog; } /**PIN class ends**/ /**GP120 class begins**/ /****************************************************************************** * Definitions ******************************************************************************/ /****************************************************************************** * Constructors ******************************************************************************/ GP120::GP120(int pin) { int volts; int range; int _pin=pin; } /****************************************************************************** * User API ******************************************************************************/ int GP120::read() { int volts=analogRead(_pin); int range=(2914/(volts+5))-1; return range; }
adithyaselv/Kiduino
Kiduino.cpp
C++
gpl-3.0
8,128
(function () { var modern = (function () { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.ThemeManager'); var global$1 = tinymce.util.Tools.resolve('tinymce.EditorManager'); var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools'); var isBrandingEnabled = function (editor) { return editor.getParam('branding', true, 'boolean'); }; var hasMenubar = function (editor) { return getMenubar(editor) !== false; }; var getMenubar = function (editor) { return editor.getParam('menubar'); }; var hasStatusbar = function (editor) { return editor.getParam('statusbar', true, 'boolean'); }; var getToolbarSize = function (editor) { return editor.getParam('toolbar_items_size'); }; var isReadOnly = function (editor) { return editor.getParam('readonly', false, 'boolean'); }; var getFixedToolbarContainer = function (editor) { return editor.getParam('fixed_toolbar_container'); }; var getInlineToolbarPositionHandler = function (editor) { return editor.getParam('inline_toolbar_position_handler'); }; var getMenu = function (editor) { return editor.getParam('menu'); }; var getRemovedMenuItems = function (editor) { return editor.getParam('removed_menuitems', ''); }; var getMinWidth = function (editor) { return editor.getParam('min_width', 100, 'number'); }; var getMinHeight = function (editor) { return editor.getParam('min_height', 100, 'number'); }; var getMaxWidth = function (editor) { return editor.getParam('max_width', 65535, 'number'); }; var getMaxHeight = function (editor) { return editor.getParam('max_height', 65535, 'number'); }; var isSkinDisabled = function (editor) { return editor.settings.skin === false; }; var isInline = function (editor) { return editor.getParam('inline', false, 'boolean'); }; var getResize = function (editor) { var resize = editor.getParam('resize', 'vertical'); if (resize === false) { return 'none'; } else if (resize === 'both') { return 'both'; } else { return 'vertical'; } }; var getSkinUrl = function (editor) { var settings = editor.settings; var skin = settings.skin; var skinUrl = settings.skin_url; if (skin !== false) { var skinName = skin ? skin : 'lightgray'; if (skinUrl) { skinUrl = editor.documentBaseURI.toAbsolute(skinUrl); } else { skinUrl = global$1.baseURL + '/skins/' + skinName; } } return skinUrl; }; var getIndexedToolbars = function (settings, defaultToolbar) { var toolbars = []; for (var i = 1; i < 10; i++) { var toolbar_1 = settings['toolbar' + i]; if (!toolbar_1) { break; } toolbars.push(toolbar_1); } var mainToolbar = settings.toolbar ? [settings.toolbar] : [defaultToolbar]; return toolbars.length > 0 ? toolbars : mainToolbar; }; var getToolbars = function (editor) { var toolbar = editor.getParam('toolbar'); var defaultToolbar = 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image'; if (toolbar === false) { return []; } else if (global$2.isArray(toolbar)) { return global$2.grep(toolbar, function (toolbar) { return toolbar.length > 0; }); } else { return getIndexedToolbars(editor.settings, defaultToolbar); } }; var global$3 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); var global$4 = tinymce.util.Tools.resolve('tinymce.ui.Factory'); var global$5 = tinymce.util.Tools.resolve('tinymce.util.I18n'); var fireSkinLoaded = function (editor) { return editor.fire('SkinLoaded'); }; var fireResizeEditor = function (editor) { return editor.fire('ResizeEditor'); }; var fireBeforeRenderUI = function (editor) { return editor.fire('BeforeRenderUI'); }; var $_aycuj2t7jh8lz3jp = { fireSkinLoaded: fireSkinLoaded, fireResizeEditor: fireResizeEditor, fireBeforeRenderUI: fireBeforeRenderUI }; var focus = function (panel, type) { return function () { var item = panel.find(type)[0]; if (item) { item.focus(true); } }; }; var addKeys = function (editor, panel) { editor.shortcuts.add('Alt+F9', '', focus(panel, 'menubar')); editor.shortcuts.add('Alt+F10,F10', '', focus(panel, 'toolbar')); editor.shortcuts.add('Alt+F11', '', focus(panel, 'elementpath')); panel.on('cancel', function () { editor.focus(); }); }; var $_47hpztt8jh8lz3jq = { addKeys: addKeys }; var global$6 = tinymce.util.Tools.resolve('tinymce.geom.Rect'); var global$7 = tinymce.util.Tools.resolve('tinymce.util.Delay'); var noop = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } }; var noarg = function (f) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return f(); }; }; var compose = function (fa, fb) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return fa(fb.apply(null, arguments)); }; }; var constant = function (value) { return function () { return value; }; }; var identity = function (x) { return x; }; var tripleEquals = function (a, b) { return a === b; }; var curry = function (f) { var x = []; for (var _i = 1; _i < arguments.length; _i++) { x[_i - 1] = arguments[_i]; } var args = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } var newArgs = new Array(arguments.length); for (var j = 0; j < newArgs.length; j++) newArgs[j] = arguments[j]; var all = args.concat(newArgs); return f.apply(null, all); }; }; var not = function (f) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return !f.apply(null, arguments); }; }; var die = function (msg) { return function () { throw new Error(msg); }; }; var apply = function (f) { return f(); }; var call = function (f) { f(); }; var never = constant(false); var always = constant(true); var $_3pjweotejh8lz3k4 = { noop: noop, noarg: noarg, compose: compose, constant: constant, identity: identity, tripleEquals: tripleEquals, curry: curry, not: not, die: die, apply: apply, call: call, never: never, always: always }; var never$1 = $_3pjweotejh8lz3k4.never; var always$1 = $_3pjweotejh8lz3k4.always; var none = function () { return NONE; }; var NONE = function () { var eq = function (o) { return o.isNone(); }; var call = function (thunk) { return thunk(); }; var id = function (n) { return n; }; var noop = function () { }; var me = { fold: function (n, s) { return n(); }, is: never$1, isSome: never$1, isNone: always$1, getOr: id, getOrThunk: call, getOrDie: function (msg) { throw new Error(msg || 'error: getOrDie called on none.'); }, or: id, orThunk: call, map: none, ap: none, each: noop, bind: none, flatten: none, exists: never$1, forall: always$1, filter: none, equals: eq, equals_: eq, toArray: function () { return []; }, toString: $_3pjweotejh8lz3k4.constant('none()') }; if (Object.freeze) Object.freeze(me); return me; }(); var some = function (a) { var constant_a = function () { return a; }; var self = function () { return me; }; var map = function (f) { return some(f(a)); }; var bind = function (f) { return f(a); }; var me = { fold: function (n, s) { return s(a); }, is: function (v) { return a === v; }, isSome: always$1, isNone: never$1, getOr: constant_a, getOrThunk: constant_a, getOrDie: constant_a, or: self, orThunk: self, map: map, ap: function (optfab) { return optfab.fold(none, function (fab) { return some(fab(a)); }); }, each: function (f) { f(a); }, bind: bind, flatten: constant_a, exists: bind, forall: bind, filter: function (f) { return f(a) ? me : NONE; }, equals: function (o) { return o.is(a); }, equals_: function (o, elementEq) { return o.fold(never$1, function (b) { return elementEq(a, b); }); }, toArray: function () { return [a]; }, toString: function () { return 'some(' + a + ')'; } }; return me; }; var from = function (value) { return value === null || value === undefined ? NONE : some(value); }; var Option = { some: some, none: none, from: from }; var getUiContainerDelta = function (ctrl) { var uiContainer = getUiContainer(ctrl); if (uiContainer && global$3.DOM.getStyle(uiContainer, 'position', true) !== 'static') { var containerPos = global$3.DOM.getPos(uiContainer); var dx = uiContainer.scrollLeft - containerPos.x; var dy = uiContainer.scrollTop - containerPos.y; return Option.some({ x: dx, y: dy }); } else { return Option.none(); } }; var setUiContainer = function (editor, ctrl) { var uiContainer = global$3.DOM.select(editor.settings.ui_container)[0]; ctrl.getRoot().uiContainer = uiContainer; }; var getUiContainer = function (ctrl) { return ctrl ? ctrl.getRoot().uiContainer : null; }; var inheritUiContainer = function (fromCtrl, toCtrl) { return toCtrl.uiContainer = getUiContainer(fromCtrl); }; var $_1jk3jvtcjh8lz3jy = { getUiContainerDelta: getUiContainerDelta, setUiContainer: setUiContainer, getUiContainer: getUiContainer, inheritUiContainer: inheritUiContainer }; var createToolbar = function (editor, items, size) { var toolbarItems = []; var buttonGroup; if (!items) { return; } global$2.each(items.split(/[ ,]/), function (item) { var itemName; var bindSelectorChanged = function () { var selection = editor.selection; if (item.settings.stateSelector) { selection.selectorChanged(item.settings.stateSelector, function (state) { item.active(state); }, true); } if (item.settings.disabledStateSelector) { selection.selectorChanged(item.settings.disabledStateSelector, function (state) { item.disabled(state); }); } }; if (item === '|') { buttonGroup = null; } else { if (!buttonGroup) { buttonGroup = { type: 'buttongroup', items: [] }; toolbarItems.push(buttonGroup); } if (editor.buttons[item]) { itemName = item; item = editor.buttons[itemName]; if (typeof item === 'function') { item = item(); } item.type = item.type || 'button'; item.size = size; item = global$4.create(item); buttonGroup.items.push(item); if (editor.initialized) { bindSelectorChanged(); } else { editor.on('init', bindSelectorChanged); } } } }); return { type: 'toolbar', layout: 'flow', items: toolbarItems }; }; var createToolbars = function (editor, size) { var toolbars = []; var addToolbar = function (items) { if (items) { toolbars.push(createToolbar(editor, items, size)); } }; global$2.each(getToolbars(editor), function (toolbar) { addToolbar(toolbar); }); if (toolbars.length) { return { type: 'panel', layout: 'stack', classes: 'toolbar-grp', ariaRoot: true, ariaRemember: true, items: toolbars }; } }; var $_fudqhrtfjh8lz3k7 = { createToolbar: createToolbar, createToolbars: createToolbars }; var DOM = global$3.DOM; var toClientRect = function (geomRect) { return { left: geomRect.x, top: geomRect.y, width: geomRect.w, height: geomRect.h, right: geomRect.x + geomRect.w, bottom: geomRect.y + geomRect.h }; }; var hideAllFloatingPanels = function (editor) { global$2.each(editor.contextToolbars, function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var movePanelTo = function (panel, pos) { panel.moveTo(pos.left, pos.top); }; var togglePositionClass = function (panel, relPos, predicate) { relPos = relPos ? relPos.substr(0, 2) : ''; global$2.each({ t: 'down', b: 'up' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(0, 1))); }); global$2.each({ l: 'left', r: 'right' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(1, 1))); }); }; var userConstrain = function (handler, x, y, elementRect, contentAreaRect, panelRect) { panelRect = toClientRect({ x: x, y: y, w: panelRect.w, h: panelRect.h }); if (handler) { panelRect = handler({ elementRect: toClientRect(elementRect), contentAreaRect: toClientRect(contentAreaRect), panelRect: panelRect }); } return panelRect; }; var addContextualToolbars = function (editor) { var scrollContainer; var getContextToolbars = function () { return editor.contextToolbars || []; }; var getElementRect = function (elm) { var pos, targetRect, root; pos = DOM.getPos(editor.getContentAreaContainer()); targetRect = editor.dom.getRect(elm); root = editor.dom.getRoot(); if (root.nodeName === 'BODY') { targetRect.x -= root.ownerDocument.documentElement.scrollLeft || root.scrollLeft; targetRect.y -= root.ownerDocument.documentElement.scrollTop || root.scrollTop; } targetRect.x += pos.x; targetRect.y += pos.y; return targetRect; }; var reposition = function (match, shouldShow) { var relPos, panelRect, elementRect, contentAreaRect, panel, relRect, testPositions, smallElementWidthThreshold; var handler = getInlineToolbarPositionHandler(editor); if (editor.removed) { return; } if (!match || !match.toolbar.panel) { hideAllFloatingPanels(editor); return; } testPositions = [ 'bc-tc', 'tc-bc', 'tl-bl', 'bl-tl', 'tr-br', 'br-tr' ]; panel = match.toolbar.panel; if (shouldShow) { panel.show(); } elementRect = getElementRect(match.element); panelRect = DOM.getRect(panel.getEl()); contentAreaRect = DOM.getRect(editor.getContentAreaContainer() || editor.getBody()); var delta = $_1jk3jvtcjh8lz3jy.getUiContainerDelta(panel).getOr({ x: 0, y: 0 }); elementRect.x += delta.x; elementRect.y += delta.y; panelRect.x += delta.x; panelRect.y += delta.y; contentAreaRect.x += delta.x; contentAreaRect.y += delta.y; smallElementWidthThreshold = 25; if (DOM.getStyle(match.element, 'display', true) !== 'inline') { var clientRect = match.element.getBoundingClientRect(); elementRect.w = clientRect.width; elementRect.h = clientRect.height; } if (!editor.inline) { contentAreaRect.w = editor.getDoc().documentElement.offsetWidth; } if (editor.selection.controlSelection.isResizable(match.element) && elementRect.w < smallElementWidthThreshold) { elementRect = global$6.inflate(elementRect, 0, 8); } relPos = global$6.findBestRelativePosition(panelRect, elementRect, contentAreaRect, testPositions); elementRect = global$6.clamp(elementRect, contentAreaRect); if (relPos) { relRect = global$6.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { contentAreaRect.h += panelRect.h; elementRect = global$6.intersect(contentAreaRect, elementRect); if (elementRect) { relPos = global$6.findBestRelativePosition(panelRect, elementRect, contentAreaRect, [ 'bc-tc', 'bl-tl', 'br-tr' ]); if (relPos) { relRect = global$6.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { movePanelTo(panel, userConstrain(handler, elementRect.x, elementRect.y, elementRect, contentAreaRect, panelRect)); } } else { panel.hide(); } } togglePositionClass(panel, relPos, function (pos1, pos2) { return pos1 === pos2; }); }; var repositionHandler = function (show) { return function () { var execute = function () { if (editor.selection) { reposition(findFrontMostMatch(editor.selection.getNode()), show); } }; global$7.requestAnimationFrame(execute); }; }; var bindScrollEvent = function (panel) { if (!scrollContainer) { var reposition_1 = repositionHandler(true); var uiContainer_1 = $_1jk3jvtcjh8lz3jy.getUiContainer(panel); scrollContainer = editor.selection.getScrollContainer() || editor.getWin(); DOM.bind(scrollContainer, 'scroll', reposition_1); DOM.bind(uiContainer_1, 'scroll', reposition_1); editor.on('remove', function () { DOM.unbind(scrollContainer, 'scroll', reposition_1); DOM.unbind(uiContainer_1, 'scroll', reposition_1); }); } }; var showContextToolbar = function (match) { var panel; if (match.toolbar.panel) { match.toolbar.panel.show(); reposition(match); return; } panel = global$4.create({ type: 'floatpanel', role: 'dialog', classes: 'tinymce tinymce-inline arrow', ariaLabel: 'Inline toolbar', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: true, fixed: true, border: 1, items: $_fudqhrtfjh8lz3k7.createToolbar(editor, match.toolbar.items), oncancel: function () { editor.focus(); } }); $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel); bindScrollEvent(panel); match.toolbar.panel = panel; panel.renderTo().reflow(); reposition(match); }; var hideAllContextToolbars = function () { global$2.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var findFrontMostMatch = function (targetElm) { var i, y, parentsAndSelf; var toolbars = getContextToolbars(); parentsAndSelf = editor.$(targetElm).parents().add(targetElm); for (i = parentsAndSelf.length - 1; i >= 0; i--) { for (y = toolbars.length - 1; y >= 0; y--) { if (toolbars[y].predicate(parentsAndSelf[i])) { return { toolbar: toolbars[y], element: parentsAndSelf[i] }; } } } return null; }; editor.on('click keyup setContent ObjectResized', function (e) { if (e.type === 'setcontent' && !e.selection) { return; } global$7.setEditorTimeout(editor, function () { var match; match = findFrontMostMatch(editor.selection.getNode()); if (match) { hideAllContextToolbars(); showContextToolbar(match); } else { hideAllContextToolbars(); } }); }); editor.on('blur hide contextmenu', hideAllContextToolbars); editor.on('ObjectResizeStart', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.hide(); } }); editor.on('ResizeEditor ResizeWindow', repositionHandler(true)); editor.on('nodeChange', repositionHandler(false)); editor.on('remove', function () { global$2.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.remove(); } }); editor.contextToolbars = {}; }); editor.shortcuts.add('ctrl+shift+e > ctrl+shift+p', '', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.items()[0].focus(); } }); }; var $_5kodmdt9jh8lz3js = { addContextualToolbars: addContextualToolbars }; var typeOf = function (x) { if (x === null) return 'null'; var t = typeof x; if (t === 'object' && Array.prototype.isPrototypeOf(x)) return 'array'; if (t === 'object' && String.prototype.isPrototypeOf(x)) return 'string'; return t; }; var isType = function (type) { return function (value) { return typeOf(value) === type; }; }; var $_d8bie3tijh8lz3kn = { isString: isType('string'), isObject: isType('object'), isArray: isType('array'), isNull: isType('null'), isBoolean: isType('boolean'), isUndefined: isType('undefined'), isFunction: isType('function'), isNumber: isType('number') }; var rawIndexOf = function () { var pIndexOf = Array.prototype.indexOf; var fastIndex = function (xs, x) { return pIndexOf.call(xs, x); }; var slowIndex = function (xs, x) { return slowIndexOf(xs, x); }; return pIndexOf === undefined ? slowIndex : fastIndex; }(); var indexOf = function (xs, x) { var r = rawIndexOf(xs, x); return r === -1 ? Option.none() : Option.some(r); }; var contains = function (xs, x) { return rawIndexOf(xs, x) > -1; }; var exists = function (xs, pred) { return findIndex(xs, pred).isSome(); }; var range = function (num, f) { var r = []; for (var i = 0; i < num; i++) { r.push(f(i)); } return r; }; var chunk = function (array, size) { var r = []; for (var i = 0; i < array.length; i += size) { var s = array.slice(i, i + size); r.push(s); } return r; }; var map = function (xs, f) { var len = xs.length; var r = new Array(len); for (var i = 0; i < len; i++) { var x = xs[i]; r[i] = f(x, i, xs); } return r; }; var each = function (xs, f) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; f(x, i, xs); } }; var eachr = function (xs, f) { for (var i = xs.length - 1; i >= 0; i--) { var x = xs[i]; f(x, i, xs); } }; var partition = function (xs, pred) { var pass = []; var fail = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; var arr = pred(x, i, xs) ? pass : fail; arr.push(x); } return { pass: pass, fail: fail }; }; var filter = function (xs, pred) { var r = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i, xs)) { r.push(x); } } return r; }; var groupBy = function (xs, f) { if (xs.length === 0) { return []; } else { var wasType = f(xs[0]); var r = []; var group = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; var type = f(x); if (type !== wasType) { r.push(group); group = []; } wasType = type; group.push(x); } if (group.length !== 0) { r.push(group); } return r; } }; var foldr = function (xs, f, acc) { eachr(xs, function (x) { acc = f(acc, x); }); return acc; }; var foldl = function (xs, f, acc) { each(xs, function (x) { acc = f(acc, x); }); return acc; }; var find = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i, xs)) { return Option.some(x); } } return Option.none(); }; var findIndex = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i, xs)) { return Option.some(i); } } return Option.none(); }; var slowIndexOf = function (xs, x) { for (var i = 0, len = xs.length; i < len; ++i) { if (xs[i] === x) { return i; } } return -1; }; var push = Array.prototype.push; var flatten = function (xs) { var r = []; for (var i = 0, len = xs.length; i < len; ++i) { if (!Array.prototype.isPrototypeOf(xs[i])) throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); push.apply(r, xs[i]); } return r; }; var bind = function (xs, f) { var output = map(xs, f); return flatten(output); }; var forall = function (xs, pred) { for (var i = 0, len = xs.length; i < len; ++i) { var x = xs[i]; if (pred(x, i, xs) !== true) { return false; } } return true; }; var equal = function (a1, a2) { return a1.length === a2.length && forall(a1, function (x, i) { return x === a2[i]; }); }; var slice = Array.prototype.slice; var reverse = function (xs) { var r = slice.call(xs, 0); r.reverse(); return r; }; var difference = function (a1, a2) { return filter(a1, function (x) { return !contains(a2, x); }); }; var mapToObject = function (xs, f) { var r = {}; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; r[String(x)] = f(x, i); } return r; }; var pure = function (x) { return [x]; }; var sort = function (xs, comparator) { var copy = slice.call(xs, 0); copy.sort(comparator); return copy; }; var head = function (xs) { return xs.length === 0 ? Option.none() : Option.some(xs[0]); }; var last = function (xs) { return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]); }; var from$1 = $_d8bie3tijh8lz3kn.isFunction(Array.from) ? Array.from : function (x) { return slice.call(x); }; var $_f3qxhzthjh8lz3kg = { map: map, each: each, eachr: eachr, partition: partition, filter: filter, groupBy: groupBy, indexOf: indexOf, foldr: foldr, foldl: foldl, find: find, findIndex: findIndex, flatten: flatten, bind: bind, forall: forall, exists: exists, contains: contains, equal: equal, reverse: reverse, chunk: chunk, difference: difference, mapToObject: mapToObject, pure: pure, sort: sort, range: range, head: head, last: last, from: from$1 }; var defaultMenus = { file: { title: 'File', items: 'newdocument restoredraft | preview | print' }, edit: { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall' }, view: { title: 'View', items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen' }, insert: { title: 'Insert', items: 'image link media template codesample inserttable | charmap hr | pagebreak nonbreaking anchor toc | insertdatetime' }, format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | blockformats align | removeformat' }, tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | a11ycheck code' }, table: { title: 'Table' }, help: { title: 'Help' } }; var delimiterMenuNamePair = function () { return { name: '|', item: { text: '|' } }; }; var createMenuNameItemPair = function (name, item) { var menuItem = item ? { name: name, item: item } : null; return name === '|' ? delimiterMenuNamePair() : menuItem; }; var hasItemName = function (namedMenuItems, name) { return $_f3qxhzthjh8lz3kg.findIndex(namedMenuItems, function (namedMenuItem) { return namedMenuItem.name === name; }).isSome(); }; var isSeparator = function (namedMenuItem) { return namedMenuItem && namedMenuItem.item.text === '|'; }; var cleanupMenu = function (namedMenuItems, removedMenuItems) { var menuItemsPass1 = $_f3qxhzthjh8lz3kg.filter(namedMenuItems, function (namedMenuItem) { return removedMenuItems.hasOwnProperty(namedMenuItem.name) === false; }); var menuItemsPass2 = $_f3qxhzthjh8lz3kg.filter(menuItemsPass1, function (namedMenuItem, i, namedMenuItems) { return !isSeparator(namedMenuItem) || !isSeparator(namedMenuItems[i - 1]); }); return $_f3qxhzthjh8lz3kg.filter(menuItemsPass2, function (namedMenuItem, i, namedMenuItems) { return !isSeparator(namedMenuItem) || i > 0 && i < namedMenuItems.length - 1; }); }; var createMenu = function (editorMenuItems, menus, removedMenuItems, context) { var menuButton, menu, namedMenuItems, isUserDefined; if (menus) { menu = menus[context]; isUserDefined = true; } else { menu = defaultMenus[context]; } if (menu) { menuButton = { text: menu.title }; namedMenuItems = []; global$2.each((menu.items || '').split(/[ ,]/), function (name) { var namedMenuItem = createMenuNameItemPair(name, editorMenuItems[name]); if (namedMenuItem) { namedMenuItems.push(namedMenuItem); } }); if (!isUserDefined) { global$2.each(editorMenuItems, function (item, name) { if (item.context === context && !hasItemName(namedMenuItems, name)) { if (item.separator === 'before') { namedMenuItems.push(delimiterMenuNamePair()); } if (item.prependToContext) { namedMenuItems.unshift(createMenuNameItemPair(name, item)); } else { namedMenuItems.push(createMenuNameItemPair(name, item)); } if (item.separator === 'after') { namedMenuItems.push(delimiterMenuNamePair()); } } }); } menuButton.menu = $_f3qxhzthjh8lz3kg.map(cleanupMenu(namedMenuItems, removedMenuItems), function (menuItem) { return menuItem.item; }); if (!menuButton.menu.length) { return null; } } return menuButton; }; var getDefaultMenubar = function (editor) { var name; var defaultMenuBar = []; var menu = getMenu(editor); if (menu) { for (name in menu) { defaultMenuBar.push(name); } } else { for (name in defaultMenus) { defaultMenuBar.push(name); } } return defaultMenuBar; }; var createMenuButtons = function (editor) { var menuButtons = []; var defaultMenuBar = getDefaultMenubar(editor); var removedMenuItems = global$2.makeMap(getRemovedMenuItems(editor).split(/[ ,]/)); var menubar = getMenubar(editor); var enabledMenuNames = typeof menubar === 'string' ? menubar.split(/[ ,]/) : defaultMenuBar; for (var i = 0; i < enabledMenuNames.length; i++) { var menuItems = enabledMenuNames[i]; var menu = createMenu(editor.menuItems, getMenu(editor), removedMenuItems, menuItems); if (menu) { menuButtons.push(menu); } } return menuButtons; }; var $_8i78rftgjh8lz3ka = { createMenuButtons: createMenuButtons }; var DOM$1 = global$3.DOM; var getSize = function (elm) { return { width: elm.clientWidth, height: elm.clientHeight }; }; var resizeTo = function (editor, width, height) { var containerElm, iframeElm, containerSize, iframeSize; containerElm = editor.getContainer(); iframeElm = editor.getContentAreaContainer().firstChild; containerSize = getSize(containerElm); iframeSize = getSize(iframeElm); if (width !== null) { width = Math.max(getMinWidth(editor), width); width = Math.min(getMaxWidth(editor), width); DOM$1.setStyle(containerElm, 'width', width + (containerSize.width - iframeSize.width)); DOM$1.setStyle(iframeElm, 'width', width); } height = Math.max(getMinHeight(editor), height); height = Math.min(getMaxHeight(editor), height); DOM$1.setStyle(iframeElm, 'height', height); $_aycuj2t7jh8lz3jp.fireResizeEditor(editor); }; var resizeBy = function (editor, dw, dh) { var elm = editor.getContentAreaContainer(); resizeTo(editor, elm.clientWidth + dw, elm.clientHeight + dh); }; var $_5toavetjjh8lz3ko = { resizeTo: resizeTo, resizeBy: resizeBy }; var global$8 = tinymce.util.Tools.resolve('tinymce.Env'); var api = function (elm) { return { element: function () { return elm; } }; }; var trigger = function (sidebar, panel, callbackName) { var callback = sidebar.settings[callbackName]; if (callback) { callback(api(panel.getEl('body'))); } }; var hidePanels = function (name, container, sidebars) { global$2.each(sidebars, function (sidebar) { var panel = container.items().filter('#' + sidebar.name)[0]; if (panel && panel.visible() && sidebar.name !== name) { trigger(sidebar, panel, 'onhide'); panel.visible(false); } }); }; var deactivateButtons = function (toolbar) { toolbar.items().each(function (ctrl) { ctrl.active(false); }); }; var findSidebar = function (sidebars, name) { return global$2.grep(sidebars, function (sidebar) { return sidebar.name === name; })[0]; }; var showPanel = function (editor, name, sidebars) { return function (e) { var btnCtrl = e.control; var container = btnCtrl.parents().filter('panel')[0]; var panel = container.find('#' + name)[0]; var sidebar = findSidebar(sidebars, name); hidePanels(name, container, sidebars); deactivateButtons(btnCtrl.parent()); if (panel && panel.visible()) { trigger(sidebar, panel, 'onhide'); panel.hide(); btnCtrl.active(false); } else { if (panel) { panel.show(); trigger(sidebar, panel, 'onshow'); } else { panel = global$4.create({ type: 'container', name: name, layout: 'stack', classes: 'sidebar-panel', html: '' }); container.prepend(panel); trigger(sidebar, panel, 'onrender'); trigger(sidebar, panel, 'onshow'); } btnCtrl.active(true); } $_aycuj2t7jh8lz3jp.fireResizeEditor(editor); }; }; var isModernBrowser = function () { return !global$8.ie || global$8.ie >= 11; }; var hasSidebar = function (editor) { return isModernBrowser() && editor.sidebars ? editor.sidebars.length > 0 : false; }; var createSidebar = function (editor) { var buttons = global$2.map(editor.sidebars, function (sidebar) { var settings = sidebar.settings; return { type: 'button', icon: settings.icon, image: settings.image, tooltip: settings.tooltip, onclick: showPanel(editor, sidebar.name, editor.sidebars) }; }); return { type: 'panel', name: 'sidebar', layout: 'stack', classes: 'sidebar', items: [{ type: 'toolbar', layout: 'stack', classes: 'sidebar-toolbar', items: buttons }] }; }; var $_5buua9tkjh8lz3kq = { hasSidebar: hasSidebar, createSidebar: createSidebar }; var fireSkinLoaded$1 = function (editor) { var done = function () { editor._skinLoaded = true; $_aycuj2t7jh8lz3jp.fireSkinLoaded(editor); }; return function () { if (editor.initialized) { done(); } else { editor.on('init', done); } }; }; var $_231e94tmjh8lz3ku = { fireSkinLoaded: fireSkinLoaded$1 }; var DOM$2 = global$3.DOM; var switchMode = function (panel) { return function (e) { panel.find('*').disabled(e.mode === 'readonly'); }; }; var editArea = function (border) { return { type: 'panel', name: 'iframe', layout: 'stack', classes: 'edit-area', border: border, html: '' }; }; var editAreaContainer = function (editor) { return { type: 'panel', layout: 'stack', classes: 'edit-aria-container', border: '1 0 0 0', items: [ editArea('0'), $_5buua9tkjh8lz3kq.createSidebar(editor) ] }; }; var render = function (editor, theme, args) { var panel, resizeHandleCtrl, startSize; if (isSkinDisabled(editor) === false && args.skinUiCss) { DOM$2.styleSheetLoader.load(args.skinUiCss, $_231e94tmjh8lz3ku.fireSkinLoaded(editor)); } else { $_231e94tmjh8lz3ku.fireSkinLoaded(editor)(); } panel = theme.panel = global$4.create({ type: 'panel', role: 'application', classes: 'tinymce', style: 'visibility: hidden', layout: 'stack', border: 1, items: [ { type: 'container', classes: 'top-part', items: [ hasMenubar(editor) === false ? null : { type: 'menubar', border: '0 0 1 0', items: $_8i78rftgjh8lz3ka.createMenuButtons(editor) }, $_fudqhrtfjh8lz3k7.createToolbars(editor, getToolbarSize(editor)) ] }, $_5buua9tkjh8lz3kq.hasSidebar(editor) ? editAreaContainer(editor) : editArea('1 0 0 0') ] }); $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel); if (getResize(editor) !== 'none') { resizeHandleCtrl = { type: 'resizehandle', direction: getResize(editor), onResizeStart: function () { var elm = editor.getContentAreaContainer().firstChild; startSize = { width: elm.clientWidth, height: elm.clientHeight }; }, onResize: function (e) { if (getResize(editor) === 'both') { $_5toavetjjh8lz3ko.resizeTo(editor, startSize.width + e.deltaX, startSize.height + e.deltaY); } else { $_5toavetjjh8lz3ko.resizeTo(editor, null, startSize.height + e.deltaY); } } }; } if (hasStatusbar(editor)) { var linkHtml = '<a href="https://www.tinymce.com/?utm_campaign=editor_referral&amp;utm_medium=poweredby&amp;utm_source=tinymce" rel="noopener" target="_blank" role="presentation" tabindex="-1">tinymce</a>'; var html = global$5.translate([ 'Powered by {0}', linkHtml ]); var brandingLabel = isBrandingEnabled(editor) ? { type: 'label', classes: 'branding', html: ' ' + html } : null; panel.add({ type: 'panel', name: 'statusbar', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', ariaRoot: true, items: [ { type: 'elementpath', editor: editor }, resizeHandleCtrl, brandingLabel ] }); } $_aycuj2t7jh8lz3jp.fireBeforeRenderUI(editor); editor.on('SwitchMode', switchMode(panel)); panel.renderBefore(args.targetNode).reflow(); if (isReadOnly(editor)) { editor.setMode('readonly'); } if (args.width) { DOM$2.setStyle(panel.getEl(), 'width', args.width); } editor.on('remove', function () { panel.remove(); panel = null; }); $_47hpztt8jh8lz3jq.addKeys(editor, panel); $_5kodmdt9jh8lz3js.addContextualToolbars(editor); return { iframeContainer: panel.find('#iframe')[0].getEl(), editorContainer: panel.getEl() }; }; var $_4cj0a3t3jh8lz3jk = { render: render }; var global$9 = tinymce.util.Tools.resolve('tinymce.dom.DomQuery'); var count = 0; var funcs = { id: function () { return 'mceu_' + count++; }, create: function (name, attrs, children) { var elm = document.createElement(name); global$3.DOM.setAttribs(elm, attrs); if (typeof children === 'string') { elm.innerHTML = children; } else { global$2.each(children, function (child) { if (child.nodeType) { elm.appendChild(child); } }); } return elm; }, createFragment: function (html) { return global$3.DOM.createFragment(html); }, getWindowSize: function () { return global$3.DOM.getViewPort(); }, getSize: function (elm) { var width, height; if (elm.getBoundingClientRect) { var rect = elm.getBoundingClientRect(); width = Math.max(rect.width || rect.right - rect.left, elm.offsetWidth); height = Math.max(rect.height || rect.bottom - rect.bottom, elm.offsetHeight); } else { width = elm.offsetWidth; height = elm.offsetHeight; } return { width: width, height: height }; }, getPos: function (elm, root) { return global$3.DOM.getPos(elm, root || funcs.getContainer()); }, getContainer: function () { return global$8.container ? global$8.container : document.body; }, getViewPort: function (win) { return global$3.DOM.getViewPort(win); }, get: function (id) { return document.getElementById(id); }, addClass: function (elm, cls) { return global$3.DOM.addClass(elm, cls); }, removeClass: function (elm, cls) { return global$3.DOM.removeClass(elm, cls); }, hasClass: function (elm, cls) { return global$3.DOM.hasClass(elm, cls); }, toggleClass: function (elm, cls, state) { return global$3.DOM.toggleClass(elm, cls, state); }, css: function (elm, name, value) { return global$3.DOM.setStyle(elm, name, value); }, getRuntimeStyle: function (elm, name) { return global$3.DOM.getStyle(elm, name, true); }, on: function (target, name, callback, scope) { return global$3.DOM.bind(target, name, callback, scope); }, off: function (target, name, callback) { return global$3.DOM.unbind(target, name, callback); }, fire: function (target, name, args) { return global$3.DOM.fire(target, name, args); }, innerHtml: function (elm, html) { global$3.DOM.setHTML(elm, html); } }; var isStatic = function (elm) { return funcs.getRuntimeStyle(elm, 'position') === 'static'; }; var isFixed = function (ctrl) { return ctrl.state.get('fixed'); }; function calculateRelativePosition(ctrl, targetElm, rel) { var ctrlElm, pos, x, y, selfW, selfH, targetW, targetH, viewport, size; viewport = getWindowViewPort(); pos = funcs.getPos(targetElm, $_1jk3jvtcjh8lz3jy.getUiContainer(ctrl)); x = pos.x; y = pos.y; if (isFixed(ctrl) && isStatic(document.body)) { x -= viewport.x; y -= viewport.y; } ctrlElm = ctrl.getEl(); size = funcs.getSize(ctrlElm); selfW = size.width; selfH = size.height; size = funcs.getSize(targetElm); targetW = size.width; targetH = size.height; rel = (rel || '').split(''); if (rel[0] === 'b') { y += targetH; } if (rel[1] === 'r') { x += targetW; } if (rel[0] === 'c') { y += Math.round(targetH / 2); } if (rel[1] === 'c') { x += Math.round(targetW / 2); } if (rel[3] === 'b') { y -= selfH; } if (rel[4] === 'r') { x -= selfW; } if (rel[3] === 'c') { y -= Math.round(selfH / 2); } if (rel[4] === 'c') { x -= Math.round(selfW / 2); } return { x: x, y: y, w: selfW, h: selfH }; } var getUiContainerViewPort = function (customUiContainer) { return { x: 0, y: 0, w: customUiContainer.scrollWidth - 1, h: customUiContainer.scrollHeight - 1 }; }; var getWindowViewPort = function () { var win = window; var x = Math.max(win.pageXOffset, document.body.scrollLeft, document.documentElement.scrollLeft); var y = Math.max(win.pageYOffset, document.body.scrollTop, document.documentElement.scrollTop); var w = win.innerWidth || document.documentElement.clientWidth; var h = win.innerHeight || document.documentElement.clientHeight; return { x: x, y: y, w: x + w, h: y + h }; }; var getViewPortRect = function (ctrl) { var customUiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(ctrl); return customUiContainer && !isFixed(ctrl) ? getUiContainerViewPort(customUiContainer) : getWindowViewPort(); }; var $_d97gfctrjh8lz3lm = { testMoveRel: function (elm, rels) { var viewPortRect = getViewPortRect(this); for (var i = 0; i < rels.length; i++) { var pos = calculateRelativePosition(this, elm, rels[i]); if (isFixed(this)) { if (pos.x > 0 && pos.x + pos.w < viewPortRect.w && pos.y > 0 && pos.y + pos.h < viewPortRect.h) { return rels[i]; } } else { if (pos.x > viewPortRect.x && pos.x + pos.w < viewPortRect.w && pos.y > viewPortRect.y && pos.y + pos.h < viewPortRect.h) { return rels[i]; } } } return rels[0]; }, moveRel: function (elm, rel) { if (typeof rel !== 'string') { rel = this.testMoveRel(elm, rel); } var pos = calculateRelativePosition(this, elm, rel); return this.moveTo(pos.x, pos.y); }, moveBy: function (dx, dy) { var self = this, rect = self.layoutRect(); self.moveTo(rect.x + dx, rect.y + dy); return self; }, moveTo: function (x, y) { var self = this; function constrain(value, max, size) { if (value < 0) { return 0; } if (value + size > max) { value = max - size; return value < 0 ? 0 : value; } return value; } if (self.settings.constrainToViewport) { var viewPortRect = getViewPortRect(this); var layoutRect = self.layoutRect(); x = constrain(x, viewPortRect.w, layoutRect.w); y = constrain(y, viewPortRect.h, layoutRect.h); } var uiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(self); if (uiContainer && isStatic(uiContainer) && !isFixed(self)) { x -= uiContainer.scrollLeft; y -= uiContainer.scrollTop; } if (uiContainer) { x += 1; y += 1; } if (self.state.get('rendered')) { self.layoutRect({ x: x, y: y }).repaint(); } else { self.settings.x = x; self.settings.y = y; } self.fire('move', { x: x, y: y }); return self; } }; var global$10 = tinymce.util.Tools.resolve('tinymce.util.Class'); var global$11 = tinymce.util.Tools.resolve('tinymce.util.EventDispatcher'); var $_focdcktxjh8lz3mn = { parseBox: function (value) { var len; var radix = 10; if (!value) { return; } if (typeof value === 'number') { value = value || 0; return { top: value, left: value, bottom: value, right: value }; } value = value.split(' '); len = value.length; if (len === 1) { value[1] = value[2] = value[3] = value[0]; } else if (len === 2) { value[2] = value[0]; value[3] = value[1]; } else if (len === 3) { value[3] = value[1]; } return { top: parseInt(value[0], radix) || 0, right: parseInt(value[1], radix) || 0, bottom: parseInt(value[2], radix) || 0, left: parseInt(value[3], radix) || 0 }; }, measureBox: function (elm, prefix) { function getStyle(name) { var defaultView = elm.ownerDocument.defaultView; if (defaultView) { var computedStyle = defaultView.getComputedStyle(elm, null); if (computedStyle) { name = name.replace(/[A-Z]/g, function (a) { return '-' + a; }); return computedStyle.getPropertyValue(name); } else { return null; } } return elm.currentStyle[name]; } function getSide(name) { var val = parseFloat(getStyle(name)); return isNaN(val) ? 0 : val; } return { top: getSide(prefix + 'TopWidth'), right: getSide(prefix + 'RightWidth'), bottom: getSide(prefix + 'BottomWidth'), left: getSide(prefix + 'LeftWidth') }; } }; function noop$1() { } function ClassList(onchange) { this.cls = []; this.cls._map = {}; this.onchange = onchange || noop$1; this.prefix = ''; } global$2.extend(ClassList.prototype, { add: function (cls) { if (cls && !this.contains(cls)) { this.cls._map[cls] = true; this.cls.push(cls); this._change(); } return this; }, remove: function (cls) { if (this.contains(cls)) { var i = void 0; for (i = 0; i < this.cls.length; i++) { if (this.cls[i] === cls) { break; } } this.cls.splice(i, 1); delete this.cls._map[cls]; this._change(); } return this; }, toggle: function (cls, state) { var curState = this.contains(cls); if (curState !== state) { if (curState) { this.remove(cls); } else { this.add(cls); } this._change(); } return this; }, contains: function (cls) { return !!this.cls._map[cls]; }, _change: function () { delete this.clsValue; this.onchange.call(this); } }); ClassList.prototype.toString = function () { var value; if (this.clsValue) { return this.clsValue; } value = ''; for (var i = 0; i < this.cls.length; i++) { if (i > 0) { value += ' '; } value += this.prefix + this.cls[i]; } return value; }; function unique(array) { var uniqueItems = []; var i = array.length, item; while (i--) { item = array[i]; if (!item.__checked) { uniqueItems.push(item); item.__checked = 1; } } i = uniqueItems.length; while (i--) { delete uniqueItems[i].__checked; } return uniqueItems; } var expression = /^([\w\\*]+)?(?:#([\w\-\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i; var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g; var whiteSpace = /^\s*|\s*$/g; var Collection; var Selector = global$10.extend({ init: function (selector) { var match = this.match; function compileNameFilter(name) { if (name) { name = name.toLowerCase(); return function (item) { return name === '*' || item.type === name; }; } } function compileIdFilter(id) { if (id) { return function (item) { return item._name === id; }; } } function compileClassesFilter(classes) { if (classes) { classes = classes.split('.'); return function (item) { var i = classes.length; while (i--) { if (!item.classes.contains(classes[i])) { return false; } } return true; }; } } function compileAttrFilter(name, cmp, check) { if (name) { return function (item) { var value = item[name] ? item[name]() : ''; return !cmp ? !!check : cmp === '=' ? value === check : cmp === '*=' ? value.indexOf(check) >= 0 : cmp === '~=' ? (' ' + value + ' ').indexOf(' ' + check + ' ') >= 0 : cmp === '!=' ? value !== check : cmp === '^=' ? value.indexOf(check) === 0 : cmp === '$=' ? value.substr(value.length - check.length) === check : false; }; } } function compilePsuedoFilter(name) { var notSelectors; if (name) { name = /(?:not\((.+)\))|(.+)/i.exec(name); if (!name[1]) { name = name[2]; return function (item, index, length) { return name === 'first' ? index === 0 : name === 'last' ? index === length - 1 : name === 'even' ? index % 2 === 0 : name === 'odd' ? index % 2 === 1 : item[name] ? item[name]() : false; }; } notSelectors = parseChunks(name[1], []); return function (item) { return !match(item, notSelectors); }; } } function compile(selector, filters, direct) { var parts; function add(filter) { if (filter) { filters.push(filter); } } parts = expression.exec(selector.replace(whiteSpace, '')); add(compileNameFilter(parts[1])); add(compileIdFilter(parts[2])); add(compileClassesFilter(parts[3])); add(compileAttrFilter(parts[4], parts[5], parts[6])); add(compilePsuedoFilter(parts[7])); filters.pseudo = !!parts[7]; filters.direct = direct; return filters; } function parseChunks(selector, selectors) { var parts = []; var extra, matches, i; do { chunker.exec(''); matches = chunker.exec(selector); if (matches) { selector = matches[3]; parts.push(matches[1]); if (matches[2]) { extra = matches[3]; break; } } } while (matches); if (extra) { parseChunks(extra, selectors); } selector = []; for (i = 0; i < parts.length; i++) { if (parts[i] !== '>') { selector.push(compile(parts[i], [], parts[i - 1] === '>')); } } selectors.push(selector); return selectors; } this._selectors = parseChunks(selector, []); }, match: function (control, selectors) { var i, l, si, sl, selector, fi, fl, filters, index, length, siblings, count, item; selectors = selectors || this._selectors; for (i = 0, l = selectors.length; i < l; i++) { selector = selectors[i]; sl = selector.length; item = control; count = 0; for (si = sl - 1; si >= 0; si--) { filters = selector[si]; while (item) { if (filters.pseudo) { siblings = item.parent().items(); index = length = siblings.length; while (index--) { if (siblings[index] === item) { break; } } } for (fi = 0, fl = filters.length; fi < fl; fi++) { if (!filters[fi](item, index, length)) { fi = fl + 1; break; } } if (fi === fl) { count++; break; } else { if (si === sl - 1) { break; } } item = item.parent(); } } if (count === sl) { return true; } } return false; }, find: function (container) { var matches = [], i, l; var selectors = this._selectors; function collect(items, selector, index) { var i, l, fi, fl, item; var filters = selector[index]; for (i = 0, l = items.length; i < l; i++) { item = items[i]; for (fi = 0, fl = filters.length; fi < fl; fi++) { if (!filters[fi](item, i, l)) { fi = fl + 1; break; } } if (fi === fl) { if (index === selector.length - 1) { matches.push(item); } else { if (item.items) { collect(item.items(), selector, index + 1); } } } else if (filters.direct) { return; } if (item.items) { collect(item.items(), selector, index); } } } if (container.items) { for (i = 0, l = selectors.length; i < l; i++) { collect(container.items(), selectors[i], 0); } if (l > 1) { matches = unique(matches); } } if (!Collection) { Collection = Selector.Collection; } return new Collection(matches); } }); var Collection$1; var proto; var push$1 = Array.prototype.push; var slice$1 = Array.prototype.slice; proto = { length: 0, init: function (items) { if (items) { this.add(items); } }, add: function (items) { var self = this; if (!global$2.isArray(items)) { if (items instanceof Collection$1) { self.add(items.toArray()); } else { push$1.call(self, items); } } else { push$1.apply(self, items); } return self; }, set: function (items) { var self = this; var len = self.length; var i; self.length = 0; self.add(items); for (i = self.length; i < len; i++) { delete self[i]; } return self; }, filter: function (selector) { var self = this; var i, l; var matches = []; var item, match; if (typeof selector === 'string') { selector = new Selector(selector); match = function (item) { return selector.match(item); }; } else { match = selector; } for (i = 0, l = self.length; i < l; i++) { item = self[i]; if (match(item)) { matches.push(item); } } return new Collection$1(matches); }, slice: function () { return new Collection$1(slice$1.apply(this, arguments)); }, eq: function (index) { return index === -1 ? this.slice(index) : this.slice(index, +index + 1); }, each: function (callback) { global$2.each(this, callback); return this; }, toArray: function () { return global$2.toArray(this); }, indexOf: function (ctrl) { var self = this; var i = self.length; while (i--) { if (self[i] === ctrl) { break; } } return i; }, reverse: function () { return new Collection$1(global$2.toArray(this).reverse()); }, hasClass: function (cls) { return this[0] ? this[0].classes.contains(cls) : false; }, prop: function (name, value) { var self = this; var item; if (value !== undefined) { self.each(function (item) { if (item[name]) { item[name](value); } }); return self; } item = self[0]; if (item && item[name]) { return item[name](); } }, exec: function (name) { var self = this, args = global$2.toArray(arguments).slice(1); self.each(function (item) { if (item[name]) { item[name].apply(item, args); } }); return self; }, remove: function () { var i = this.length; while (i--) { this[i].remove(); } return this; }, addClass: function (cls) { return this.each(function (item) { item.classes.add(cls); }); }, removeClass: function (cls) { return this.each(function (item) { item.classes.remove(cls); }); } }; global$2.each('fire on off show hide append prepend before after reflow'.split(' '), function (name) { proto[name] = function () { var args = global$2.toArray(arguments); this.each(function (ctrl) { if (name in ctrl) { ctrl[name].apply(ctrl, args); } }); return this; }; }); global$2.each('text name disabled active selected checked visible parent value data'.split(' '), function (name) { proto[name] = function (value) { return this.prop(name, value); }; }); Collection$1 = global$10.extend(proto); Selector.Collection = Collection$1; var Collection$2 = Collection$1; var Binding = function (settings) { this.create = settings.create; }; Binding.create = function (model, name) { return new Binding({ create: function (otherModel, otherName) { var bindings; var fromSelfToOther = function (e) { otherModel.set(otherName, e.value); }; var fromOtherToSelf = function (e) { model.set(name, e.value); }; otherModel.on('change:' + otherName, fromOtherToSelf); model.on('change:' + name, fromSelfToOther); bindings = otherModel._bindings; if (!bindings) { bindings = otherModel._bindings = []; otherModel.on('destroy', function () { var i = bindings.length; while (i--) { bindings[i](); } }); } bindings.push(function () { model.off('change:' + name, fromSelfToOther); }); return model.get(name); } }); }; var global$12 = tinymce.util.Tools.resolve('tinymce.util.Observable'); function isNode(node) { return node.nodeType > 0; } function isEqual(a, b) { var k, checked; if (a === b) { return true; } if (a === null || b === null) { return a === b; } if (typeof a !== 'object' || typeof b !== 'object') { return a === b; } if (global$2.isArray(b)) { if (a.length !== b.length) { return false; } k = a.length; while (k--) { if (!isEqual(a[k], b[k])) { return false; } } } if (isNode(a) || isNode(b)) { return a === b; } checked = {}; for (k in b) { if (!isEqual(a[k], b[k])) { return false; } checked[k] = true; } for (k in a) { if (!checked[k] && !isEqual(a[k], b[k])) { return false; } } return true; } var ObservableObject = global$10.extend({ Mixins: [global$12], init: function (data) { var name, value; data = data || {}; for (name in data) { value = data[name]; if (value instanceof Binding) { data[name] = value.create(this, name); } } this.data = data; }, set: function (name, value) { var key, args; var oldValue = this.data[name]; if (value instanceof Binding) { value = value.create(this, name); } if (typeof name === 'object') { for (key in name) { this.set(key, name[key]); } return this; } if (!isEqual(oldValue, value)) { this.data[name] = value; args = { target: this, name: name, value: value, oldValue: oldValue }; this.fire('change:' + name, args); this.fire('change', args); } return this; }, get: function (name) { return this.data[name]; }, has: function (name) { return name in this.data; }, bind: function (name) { return Binding.create(this, name); }, destroy: function () { this.fire('destroy'); } }); var dirtyCtrls = {}; var animationFrameRequested; var $_ef12j5u4jh8lz3nl = { add: function (ctrl) { var parent = ctrl.parent(); if (parent) { if (!parent._layout || parent._layout.isNative()) { return; } if (!dirtyCtrls[parent._id]) { dirtyCtrls[parent._id] = parent; } if (!animationFrameRequested) { animationFrameRequested = true; global$7.requestAnimationFrame(function () { var id, ctrl; animationFrameRequested = false; for (id in dirtyCtrls) { ctrl = dirtyCtrls[id]; if (ctrl.state.get('rendered')) { ctrl.reflow(); } } dirtyCtrls = {}; }, document.body); } } }, remove: function (ctrl) { if (dirtyCtrls[ctrl._id]) { delete dirtyCtrls[ctrl._id]; } } }; var hasMouseWheelEventSupport = 'onmousewheel' in document; var hasWheelEventSupport = false; var classPrefix = 'mce-'; var Control; var idCounter = 0; var proto$1 = { Statics: { classPrefix: classPrefix }, isRtl: function () { return Control.rtl; }, classPrefix: classPrefix, init: function (settings) { var self = this; var classes, defaultClasses; function applyClasses(classes) { var i; classes = classes.split(' '); for (i = 0; i < classes.length; i++) { self.classes.add(classes[i]); } } self.settings = settings = global$2.extend({}, self.Defaults, settings); self._id = settings.id || 'mceu_' + idCounter++; self._aria = { role: settings.role }; self._elmCache = {}; self.$ = global$9; self.state = new ObservableObject({ visible: true, active: false, disabled: false, value: '' }); self.data = new ObservableObject(settings.data); self.classes = new ClassList(function () { if (self.state.get('rendered')) { self.getEl().className = this.toString(); } }); self.classes.prefix = self.classPrefix; classes = settings.classes; if (classes) { if (self.Defaults) { defaultClasses = self.Defaults.classes; if (defaultClasses && classes !== defaultClasses) { applyClasses(defaultClasses); } } applyClasses(classes); } global$2.each('title text name visible disabled active value'.split(' '), function (name) { if (name in settings) { self[name](settings[name]); } }); self.on('click', function () { if (self.disabled()) { return false; } }); self.settings = settings; self.borderBox = $_focdcktxjh8lz3mn.parseBox(settings.border); self.paddingBox = $_focdcktxjh8lz3mn.parseBox(settings.padding); self.marginBox = $_focdcktxjh8lz3mn.parseBox(settings.margin); if (settings.hidden) { self.hide(); } }, Properties: 'parent,name', getContainerElm: function () { var uiContainer = $_1jk3jvtcjh8lz3jy.getUiContainer(this); return uiContainer ? uiContainer : funcs.getContainer(); }, getParentCtrl: function (elm) { var ctrl; var lookup = this.getRoot().controlIdLookup; while (elm && lookup) { ctrl = lookup[elm.id]; if (ctrl) { break; } elm = elm.parentNode; } return ctrl; }, initLayoutRect: function () { var self = this; var settings = self.settings; var borderBox, layoutRect; var elm = self.getEl(); var width, height, minWidth, minHeight, autoResize; var startMinWidth, startMinHeight, initialSize; borderBox = self.borderBox = self.borderBox || $_focdcktxjh8lz3mn.measureBox(elm, 'border'); self.paddingBox = self.paddingBox || $_focdcktxjh8lz3mn.measureBox(elm, 'padding'); self.marginBox = self.marginBox || $_focdcktxjh8lz3mn.measureBox(elm, 'margin'); initialSize = funcs.getSize(elm); startMinWidth = settings.minWidth; startMinHeight = settings.minHeight; minWidth = startMinWidth || initialSize.width; minHeight = startMinHeight || initialSize.height; width = settings.width; height = settings.height; autoResize = settings.autoResize; autoResize = typeof autoResize !== 'undefined' ? autoResize : !width && !height; width = width || minWidth; height = height || minHeight; var deltaW = borderBox.left + borderBox.right; var deltaH = borderBox.top + borderBox.bottom; var maxW = settings.maxWidth || 65535; var maxH = settings.maxHeight || 65535; self._layoutRect = layoutRect = { x: settings.x || 0, y: settings.y || 0, w: width, h: height, deltaW: deltaW, deltaH: deltaH, contentW: width - deltaW, contentH: height - deltaH, innerW: width - deltaW, innerH: height - deltaH, startMinWidth: startMinWidth || 0, startMinHeight: startMinHeight || 0, minW: Math.min(minWidth, maxW), minH: Math.min(minHeight, maxH), maxW: maxW, maxH: maxH, autoResize: autoResize, scrollW: 0 }; self._lastLayoutRect = {}; return layoutRect; }, layoutRect: function (newRect) { var self = this; var curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, repaintControls; if (!curRect) { curRect = self.initLayoutRect(); } if (newRect) { deltaWidth = curRect.deltaW; deltaHeight = curRect.deltaH; if (newRect.x !== undefined) { curRect.x = newRect.x; } if (newRect.y !== undefined) { curRect.y = newRect.y; } if (newRect.minW !== undefined) { curRect.minW = newRect.minW; } if (newRect.minH !== undefined) { curRect.minH = newRect.minH; } size = newRect.w; if (size !== undefined) { size = size < curRect.minW ? curRect.minW : size; size = size > curRect.maxW ? curRect.maxW : size; curRect.w = size; curRect.innerW = size - deltaWidth; } size = newRect.h; if (size !== undefined) { size = size < curRect.minH ? curRect.minH : size; size = size > curRect.maxH ? curRect.maxH : size; curRect.h = size; curRect.innerH = size - deltaHeight; } size = newRect.innerW; if (size !== undefined) { size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size; size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size; curRect.innerW = size; curRect.w = size + deltaWidth; } size = newRect.innerH; if (size !== undefined) { size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size; size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size; curRect.innerH = size; curRect.h = size + deltaHeight; } if (newRect.contentW !== undefined) { curRect.contentW = newRect.contentW; } if (newRect.contentH !== undefined) { curRect.contentH = newRect.contentH; } lastLayoutRect = self._lastLayoutRect; if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y || lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) { repaintControls = Control.repaintControls; if (repaintControls) { if (repaintControls.map && !repaintControls.map[self._id]) { repaintControls.push(self); repaintControls.map[self._id] = true; } } lastLayoutRect.x = curRect.x; lastLayoutRect.y = curRect.y; lastLayoutRect.w = curRect.w; lastLayoutRect.h = curRect.h; } return self; } return curRect; }, repaint: function () { var self = this; var style, bodyStyle, bodyElm, rect, borderBox; var borderW, borderH, lastRepaintRect, round, value; round = !document.createRange ? Math.round : function (value) { return value; }; style = self.getEl().style; rect = self._layoutRect; lastRepaintRect = self._lastRepaintRect || {}; borderBox = self.borderBox; borderW = borderBox.left + borderBox.right; borderH = borderBox.top + borderBox.bottom; if (rect.x !== lastRepaintRect.x) { style.left = round(rect.x) + 'px'; lastRepaintRect.x = rect.x; } if (rect.y !== lastRepaintRect.y) { style.top = round(rect.y) + 'px'; lastRepaintRect.y = rect.y; } if (rect.w !== lastRepaintRect.w) { value = round(rect.w - borderW); style.width = (value >= 0 ? value : 0) + 'px'; lastRepaintRect.w = rect.w; } if (rect.h !== lastRepaintRect.h) { value = round(rect.h - borderH); style.height = (value >= 0 ? value : 0) + 'px'; lastRepaintRect.h = rect.h; } if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) { value = round(rect.innerW); bodyElm = self.getEl('body'); if (bodyElm) { bodyStyle = bodyElm.style; bodyStyle.width = (value >= 0 ? value : 0) + 'px'; } lastRepaintRect.innerW = rect.innerW; } if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) { value = round(rect.innerH); bodyElm = bodyElm || self.getEl('body'); if (bodyElm) { bodyStyle = bodyStyle || bodyElm.style; bodyStyle.height = (value >= 0 ? value : 0) + 'px'; } lastRepaintRect.innerH = rect.innerH; } self._lastRepaintRect = lastRepaintRect; self.fire('repaint', {}, false); }, updateLayoutRect: function () { var self = this; self.parent()._lastRect = null; funcs.css(self.getEl(), { width: '', height: '' }); self._layoutRect = self._lastRepaintRect = self._lastLayoutRect = null; self.initLayoutRect(); }, on: function (name, callback) { var self = this; function resolveCallbackName(name) { var callback, scope; if (typeof name !== 'string') { return name; } return function (e) { if (!callback) { self.parentsAndSelf().each(function (ctrl) { var callbacks = ctrl.settings.callbacks; if (callbacks && (callback = callbacks[name])) { scope = ctrl; return false; } }); } if (!callback) { e.action = name; this.fire('execute', e); return; } return callback.call(scope, e); }; } getEventDispatcher(self).on(name, resolveCallbackName(callback)); return self; }, off: function (name, callback) { getEventDispatcher(this).off(name, callback); return this; }, fire: function (name, args, bubble) { var self = this; args = args || {}; if (!args.control) { args.control = self; } args = getEventDispatcher(self).fire(name, args); if (bubble !== false && self.parent) { var parent_1 = self.parent(); while (parent_1 && !args.isPropagationStopped()) { parent_1.fire(name, args, false); parent_1 = parent_1.parent(); } } return args; }, hasEventListeners: function (name) { return getEventDispatcher(this).has(name); }, parents: function (selector) { var self = this; var ctrl, parents = new Collection$2(); for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) { parents.add(ctrl); } if (selector) { parents = parents.filter(selector); } return parents; }, parentsAndSelf: function (selector) { return new Collection$2(this).add(this.parents(selector)); }, next: function () { var parentControls = this.parent().items(); return parentControls[parentControls.indexOf(this) + 1]; }, prev: function () { var parentControls = this.parent().items(); return parentControls[parentControls.indexOf(this) - 1]; }, innerHtml: function (html) { this.$el.html(html); return this; }, getEl: function (suffix) { var id = suffix ? this._id + '-' + suffix : this._id; if (!this._elmCache[id]) { this._elmCache[id] = global$9('#' + id)[0]; } return this._elmCache[id]; }, show: function () { return this.visible(true); }, hide: function () { return this.visible(false); }, focus: function () { try { this.getEl().focus(); } catch (ex) { } return this; }, blur: function () { this.getEl().blur(); return this; }, aria: function (name, value) { var self = this, elm = self.getEl(self.ariaTarget); if (typeof value === 'undefined') { return self._aria[name]; } self._aria[name] = value; if (self.state.get('rendered')) { elm.setAttribute(name === 'role' ? name : 'aria-' + name, value); } return self; }, encode: function (text, translate) { if (translate !== false) { text = this.translate(text); } return (text || '').replace(/[&<>"]/g, function (match) { return '&#' + match.charCodeAt(0) + ';'; }); }, translate: function (text) { return Control.translate ? Control.translate(text) : text; }, before: function (items) { var self = this, parent = self.parent(); if (parent) { parent.insert(items, parent.items().indexOf(self), true); } return self; }, after: function (items) { var self = this, parent = self.parent(); if (parent) { parent.insert(items, parent.items().indexOf(self)); } return self; }, remove: function () { var self = this; var elm = self.getEl(); var parent = self.parent(); var newItems, i; if (self.items) { var controls = self.items().toArray(); i = controls.length; while (i--) { controls[i].remove(); } } if (parent && parent.items) { newItems = []; parent.items().each(function (item) { if (item !== self) { newItems.push(item); } }); parent.items().set(newItems); parent._lastRect = null; } if (self._eventsRoot && self._eventsRoot === self) { global$9(elm).off(); } var lookup = self.getRoot().controlIdLookup; if (lookup) { delete lookup[self._id]; } if (elm && elm.parentNode) { elm.parentNode.removeChild(elm); } self.state.set('rendered', false); self.state.destroy(); self.fire('remove'); return self; }, renderBefore: function (elm) { global$9(elm).before(this.renderHtml()); this.postRender(); return this; }, renderTo: function (elm) { global$9(elm || this.getContainerElm()).append(this.renderHtml()); this.postRender(); return this; }, preRender: function () { }, render: function () { }, renderHtml: function () { return '<div id="' + this._id + '" class="' + this.classes + '"></div>'; }, postRender: function () { var self = this; var settings = self.settings; var elm, box, parent, name, parentEventsRoot; self.$el = global$9(self.getEl()); self.state.set('rendered', true); for (name in settings) { if (name.indexOf('on') === 0) { self.on(name.substr(2), settings[name]); } } if (self._eventsRoot) { for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) { parentEventsRoot = parent._eventsRoot; } if (parentEventsRoot) { for (name in parentEventsRoot._nativeEvents) { self._nativeEvents[name] = true; } } } bindPendingEvents(self); if (settings.style) { elm = self.getEl(); if (elm) { elm.setAttribute('style', settings.style); elm.style.cssText = settings.style; } } if (self.settings.border) { box = self.borderBox; self.$el.css({ 'border-top-width': box.top, 'border-right-width': box.right, 'border-bottom-width': box.bottom, 'border-left-width': box.left }); } var root = self.getRoot(); if (!root.controlIdLookup) { root.controlIdLookup = {}; } root.controlIdLookup[self._id] = self; for (var key in self._aria) { self.aria(key, self._aria[key]); } if (self.state.get('visible') === false) { self.getEl().style.display = 'none'; } self.bindStates(); self.state.on('change:visible', function (e) { var state = e.value; var parentCtrl; if (self.state.get('rendered')) { self.getEl().style.display = state === false ? 'none' : ''; self.getEl().getBoundingClientRect(); } parentCtrl = self.parent(); if (parentCtrl) { parentCtrl._lastRect = null; } self.fire(state ? 'show' : 'hide'); $_ef12j5u4jh8lz3nl.add(self); }); self.fire('postrender', {}, false); }, bindStates: function () { }, scrollIntoView: function (align) { function getOffset(elm, rootElm) { var x, y, parent = elm; x = y = 0; while (parent && parent !== rootElm && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } return { x: x, y: y }; } var elm = this.getEl(), parentElm = elm.parentNode; var x, y, width, height, parentWidth, parentHeight; var pos = getOffset(elm, parentElm); x = pos.x; y = pos.y; width = elm.offsetWidth; height = elm.offsetHeight; parentWidth = parentElm.clientWidth; parentHeight = parentElm.clientHeight; if (align === 'end') { x -= parentWidth - width; y -= parentHeight - height; } else if (align === 'center') { x -= parentWidth / 2 - width / 2; y -= parentHeight / 2 - height / 2; } parentElm.scrollLeft = x; parentElm.scrollTop = y; return this; }, getRoot: function () { var ctrl = this, rootControl; var parents = []; while (ctrl) { if (ctrl.rootControl) { rootControl = ctrl.rootControl; break; } parents.push(ctrl); rootControl = ctrl; ctrl = ctrl.parent(); } if (!rootControl) { rootControl = this; } var i = parents.length; while (i--) { parents[i].rootControl = rootControl; } return rootControl; }, reflow: function () { $_ef12j5u4jh8lz3nl.remove(this); var parent = this.parent(); if (parent && parent._layout && !parent._layout.isNative()) { parent.reflow(); } return this; } }; global$2.each('text title visible disabled active value'.split(' '), function (name) { proto$1[name] = function (value) { if (arguments.length === 0) { return this.state.get(name); } if (typeof value !== 'undefined') { this.state.set(name, value); } return this; }; }); Control = global$10.extend(proto$1); function getEventDispatcher(obj) { if (!obj._eventDispatcher) { obj._eventDispatcher = new global$11({ scope: obj, toggleEvent: function (name, state) { if (state && global$11.isNative(name)) { if (!obj._nativeEvents) { obj._nativeEvents = {}; } obj._nativeEvents[name] = true; if (obj.state.get('rendered')) { bindPendingEvents(obj); } } } }); } return obj._eventDispatcher; } function bindPendingEvents(eventCtrl) { var i, l, parents, eventRootCtrl, nativeEvents, name; function delegate(e) { var control = eventCtrl.getParentCtrl(e.target); if (control) { control.fire(e.type, e); } } function mouseLeaveHandler() { var ctrl = eventRootCtrl._lastHoverCtrl; if (ctrl) { ctrl.fire('mouseleave', { target: ctrl.getEl() }); ctrl.parents().each(function (ctrl) { ctrl.fire('mouseleave', { target: ctrl.getEl() }); }); eventRootCtrl._lastHoverCtrl = null; } } function mouseEnterHandler(e) { var ctrl = eventCtrl.getParentCtrl(e.target), lastCtrl = eventRootCtrl._lastHoverCtrl, idx = 0, i, parents, lastParents; if (ctrl !== lastCtrl) { eventRootCtrl._lastHoverCtrl = ctrl; parents = ctrl.parents().toArray().reverse(); parents.push(ctrl); if (lastCtrl) { lastParents = lastCtrl.parents().toArray().reverse(); lastParents.push(lastCtrl); for (idx = 0; idx < lastParents.length; idx++) { if (parents[idx] !== lastParents[idx]) { break; } } for (i = lastParents.length - 1; i >= idx; i--) { lastCtrl = lastParents[i]; lastCtrl.fire('mouseleave', { target: lastCtrl.getEl() }); } } for (i = idx; i < parents.length; i++) { ctrl = parents[i]; ctrl.fire('mouseenter', { target: ctrl.getEl() }); } } } function fixWheelEvent(e) { e.preventDefault(); if (e.type === 'mousewheel') { e.deltaY = -1 / 40 * e.wheelDelta; if (e.wheelDeltaX) { e.deltaX = -1 / 40 * e.wheelDeltaX; } } else { e.deltaX = 0; e.deltaY = e.detail; } e = eventCtrl.fire('wheel', e); } nativeEvents = eventCtrl._nativeEvents; if (nativeEvents) { parents = eventCtrl.parents().toArray(); parents.unshift(eventCtrl); for (i = 0, l = parents.length; !eventRootCtrl && i < l; i++) { eventRootCtrl = parents[i]._eventsRoot; } if (!eventRootCtrl) { eventRootCtrl = parents[parents.length - 1] || eventCtrl; } eventCtrl._eventsRoot = eventRootCtrl; for (l = i, i = 0; i < l; i++) { parents[i]._eventsRoot = eventRootCtrl; } var eventRootDelegates = eventRootCtrl._delegates; if (!eventRootDelegates) { eventRootDelegates = eventRootCtrl._delegates = {}; } for (name in nativeEvents) { if (!nativeEvents) { return false; } if (name === 'wheel' && !hasWheelEventSupport) { if (hasMouseWheelEventSupport) { global$9(eventCtrl.getEl()).on('mousewheel', fixWheelEvent); } else { global$9(eventCtrl.getEl()).on('DOMMouseScroll', fixWheelEvent); } continue; } if (name === 'mouseenter' || name === 'mouseleave') { if (!eventRootCtrl._hasMouseEnter) { global$9(eventRootCtrl.getEl()).on('mouseleave', mouseLeaveHandler).on('mouseover', mouseEnterHandler); eventRootCtrl._hasMouseEnter = 1; } } else if (!eventRootDelegates[name]) { global$9(eventRootCtrl.getEl()).on(name, delegate); eventRootDelegates[name] = true; } nativeEvents[name] = false; } } } var Control$1 = Control; var hasTabstopData = function (elm) { return elm.getAttribute('data-mce-tabstop') ? true : false; }; function KeyboardNavigation (settings) { var root = settings.root; var focusedElement, focusedControl; function isElement(node) { return node && node.nodeType === 1; } try { focusedElement = document.activeElement; } catch (ex) { focusedElement = document.body; } focusedControl = root.getParentCtrl(focusedElement); function getRole(elm) { elm = elm || focusedElement; if (isElement(elm)) { return elm.getAttribute('role'); } return null; } function getParentRole(elm) { var role, parent = elm || focusedElement; while (parent = parent.parentNode) { if (role = getRole(parent)) { return role; } } } function getAriaProp(name) { var elm = focusedElement; if (isElement(elm)) { return elm.getAttribute('aria-' + name); } } function isTextInputElement(elm) { var tagName = elm.tagName.toUpperCase(); return tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT'; } function canFocus(elm) { if (isTextInputElement(elm) && !elm.hidden) { return true; } if (hasTabstopData(elm)) { return true; } if (/^(button|menuitem|checkbox|tab|menuitemcheckbox|option|gridcell|slider)$/.test(getRole(elm))) { return true; } return false; } function getFocusElements(elm) { var elements = []; function collect(elm) { if (elm.nodeType !== 1 || elm.style.display === 'none' || elm.disabled) { return; } if (canFocus(elm)) { elements.push(elm); } for (var i = 0; i < elm.childNodes.length; i++) { collect(elm.childNodes[i]); } } collect(elm || root.getEl()); return elements; } function getNavigationRoot(targetControl) { var navigationRoot, controls; targetControl = targetControl || focusedControl; controls = targetControl.parents().toArray(); controls.unshift(targetControl); for (var i = 0; i < controls.length; i++) { navigationRoot = controls[i]; if (navigationRoot.settings.ariaRoot) { break; } } return navigationRoot; } function focusFirst(targetControl) { var navigationRoot = getNavigationRoot(targetControl); var focusElements = getFocusElements(navigationRoot.getEl()); if (navigationRoot.settings.ariaRemember && 'lastAriaIndex' in navigationRoot) { moveFocusToIndex(navigationRoot.lastAriaIndex, focusElements); } else { moveFocusToIndex(0, focusElements); } } function moveFocusToIndex(idx, elements) { if (idx < 0) { idx = elements.length - 1; } else if (idx >= elements.length) { idx = 0; } if (elements[idx]) { elements[idx].focus(); } return idx; } function moveFocus(dir, elements) { var idx = -1; var navigationRoot = getNavigationRoot(); elements = elements || getFocusElements(navigationRoot.getEl()); for (var i = 0; i < elements.length; i++) { if (elements[i] === focusedElement) { idx = i; } } idx += dir; navigationRoot.lastAriaIndex = moveFocusToIndex(idx, elements); } function left() { var parentRole = getParentRole(); if (parentRole === 'tablist') { moveFocus(-1, getFocusElements(focusedElement.parentNode)); } else if (focusedControl.parent().submenu) { cancel(); } else { moveFocus(-1); } } function right() { var role = getRole(), parentRole = getParentRole(); if (parentRole === 'tablist') { moveFocus(1, getFocusElements(focusedElement.parentNode)); } else if (role === 'menuitem' && parentRole === 'menu' && getAriaProp('haspopup')) { enter(); } else { moveFocus(1); } } function up() { moveFocus(-1); } function down() { var role = getRole(), parentRole = getParentRole(); if (role === 'menuitem' && parentRole === 'menubar') { enter(); } else if (role === 'button' && getAriaProp('haspopup')) { enter({ key: 'down' }); } else { moveFocus(1); } } function tab(e) { var parentRole = getParentRole(); if (parentRole === 'tablist') { var elm = getFocusElements(focusedControl.getEl('body'))[0]; if (elm) { elm.focus(); } } else { moveFocus(e.shiftKey ? -1 : 1); } } function cancel() { focusedControl.fire('cancel'); } function enter(aria) { aria = aria || {}; focusedControl.fire('click', { target: focusedElement, aria: aria }); } root.on('keydown', function (e) { function handleNonTabOrEscEvent(e, handler) { if (isTextInputElement(focusedElement) || hasTabstopData(focusedElement)) { return; } if (getRole(focusedElement) === 'slider') { return; } if (handler(e) !== false) { e.preventDefault(); } } if (e.isDefaultPrevented()) { return; } switch (e.keyCode) { case 37: handleNonTabOrEscEvent(e, left); break; case 39: handleNonTabOrEscEvent(e, right); break; case 38: handleNonTabOrEscEvent(e, up); break; case 40: handleNonTabOrEscEvent(e, down); break; case 27: cancel(); break; case 14: case 13: case 32: handleNonTabOrEscEvent(e, enter); break; case 9: tab(e); e.preventDefault(); break; } }); root.on('focusin', function (e) { focusedElement = e.target; focusedControl = e.control; }); return { focusFirst: focusFirst }; } var selectorCache = {}; var Container = Control$1.extend({ init: function (settings) { var self = this; self._super(settings); settings = self.settings; if (settings.fixed) { self.state.set('fixed', true); } self._items = new Collection$2(); if (self.isRtl()) { self.classes.add('rtl'); } self.bodyClasses = new ClassList(function () { if (self.state.get('rendered')) { self.getEl('body').className = this.toString(); } }); self.bodyClasses.prefix = self.classPrefix; self.classes.add('container'); self.bodyClasses.add('container-body'); if (settings.containerCls) { self.classes.add(settings.containerCls); } self._layout = global$4.create((settings.layout || '') + 'layout'); if (self.settings.items) { self.add(self.settings.items); } else { self.add(self.render()); } self._hasBody = true; }, items: function () { return this._items; }, find: function (selector) { selector = selectorCache[selector] = selectorCache[selector] || new Selector(selector); return selector.find(this); }, add: function (items) { var self = this; self.items().add(self.create(items)).parent(self); return self; }, focus: function (keyboard) { var self = this; var focusCtrl, keyboardNav, items; if (keyboard) { keyboardNav = self.keyboardNav || self.parents().eq(-1)[0].keyboardNav; if (keyboardNav) { keyboardNav.focusFirst(self); return; } } items = self.find('*'); if (self.statusbar) { items.add(self.statusbar.items()); } items.each(function (ctrl) { if (ctrl.settings.autofocus) { focusCtrl = null; return false; } if (ctrl.canFocus) { focusCtrl = focusCtrl || ctrl; } }); if (focusCtrl) { focusCtrl.focus(); } return self; }, replace: function (oldItem, newItem) { var ctrlElm; var items = this.items(); var i = items.length; while (i--) { if (items[i] === oldItem) { items[i] = newItem; break; } } if (i >= 0) { ctrlElm = newItem.getEl(); if (ctrlElm) { ctrlElm.parentNode.removeChild(ctrlElm); } ctrlElm = oldItem.getEl(); if (ctrlElm) { ctrlElm.parentNode.removeChild(ctrlElm); } } newItem.parent(this); }, create: function (items) { var self = this; var settings; var ctrlItems = []; if (!global$2.isArray(items)) { items = [items]; } global$2.each(items, function (item) { if (item) { if (!(item instanceof Control$1)) { if (typeof item === 'string') { item = { type: item }; } settings = global$2.extend({}, self.settings.defaults, item); item.type = settings.type = settings.type || item.type || self.settings.defaultType || (settings.defaults ? settings.defaults.type : null); item = global$4.create(settings); } ctrlItems.push(item); } }); return ctrlItems; }, renderNew: function () { var self = this; self.items().each(function (ctrl, index) { var containerElm; ctrl.parent(self); if (!ctrl.state.get('rendered')) { containerElm = self.getEl('body'); if (containerElm.hasChildNodes() && index <= containerElm.childNodes.length - 1) { global$9(containerElm.childNodes[index]).before(ctrl.renderHtml()); } else { global$9(containerElm).append(ctrl.renderHtml()); } ctrl.postRender(); $_ef12j5u4jh8lz3nl.add(ctrl); } }); self._layout.applyClasses(self.items().filter(':visible')); self._lastRect = null; return self; }, append: function (items) { return this.add(items).renderNew(); }, prepend: function (items) { var self = this; self.items().set(self.create(items).concat(self.items().toArray())); return self.renderNew(); }, insert: function (items, index, before) { var self = this; var curItems, beforeItems, afterItems; items = self.create(items); curItems = self.items(); if (!before && index < curItems.length - 1) { index += 1; } if (index >= 0 && index < curItems.length) { beforeItems = curItems.slice(0, index).toArray(); afterItems = curItems.slice(index).toArray(); curItems.set(beforeItems.concat(items, afterItems)); } return self.renderNew(); }, fromJSON: function (data) { var self = this; for (var name_1 in data) { self.find('#' + name_1).value(data[name_1]); } return self; }, toJSON: function () { var self = this, data = {}; self.find('*').each(function (ctrl) { var name = ctrl.name(), value = ctrl.value(); if (name && typeof value !== 'undefined') { data[name] = value; } }); return data; }, renderHtml: function () { var self = this, layout = self._layout, role = this.settings.role; self.preRender(); layout.preRender(self); return '<div id="' + self._id + '" class="' + self.classes + '"' + (role ? ' role="' + this.settings.role + '"' : '') + '>' + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>'; }, postRender: function () { var self = this; var box; self.items().exec('postRender'); self._super(); self._layout.postRender(self); self.state.set('rendered', true); if (self.settings.style) { self.$el.css(self.settings.style); } if (self.settings.border) { box = self.borderBox; self.$el.css({ 'border-top-width': box.top, 'border-right-width': box.right, 'border-bottom-width': box.bottom, 'border-left-width': box.left }); } if (!self.parent()) { self.keyboardNav = KeyboardNavigation({ root: self }); } return self; }, initLayoutRect: function () { var self = this, layoutRect = self._super(); self._layout.recalc(self); return layoutRect; }, recalc: function () { var self = this; var rect = self._layoutRect; var lastRect = self._lastRect; if (!lastRect || lastRect.w !== rect.w || lastRect.h !== rect.h) { self._layout.recalc(self); rect = self.layoutRect(); self._lastRect = { x: rect.x, y: rect.y, w: rect.w, h: rect.h }; return true; } }, reflow: function () { var i; $_ef12j5u4jh8lz3nl.remove(this); if (this.visible()) { Control$1.repaintControls = []; Control$1.repaintControls.map = {}; this.recalc(); i = Control$1.repaintControls.length; while (i--) { Control$1.repaintControls[i].repaint(); } if (this.settings.layout !== 'flow' && this.settings.layout !== 'stack') { this.repaint(); } Control$1.repaintControls = []; } return this; } }); function getDocumentSize(doc) { var documentElement, body, scrollWidth, clientWidth; var offsetWidth, scrollHeight, clientHeight, offsetHeight; var max = Math.max; documentElement = doc.documentElement; body = doc.body; scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); clientWidth = max(documentElement.clientWidth, body.clientWidth); offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); clientHeight = max(documentElement.clientHeight, body.clientHeight); offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); return { width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, height: scrollHeight < offsetHeight ? clientHeight : scrollHeight }; } function updateWithTouchData(e) { var keys, i; if (e.changedTouches) { keys = 'screenX screenY pageX pageY clientX clientY'.split(' '); for (i = 0; i < keys.length; i++) { e[keys[i]] = e.changedTouches[0][keys[i]]; } } } function DragHelper (id, settings) { var $eventOverlay; var doc = settings.document || document; var downButton; var start, stop, drag, startX, startY; settings = settings || {}; var handleElement = doc.getElementById(settings.handle || id); start = function (e) { var docSize = getDocumentSize(doc); var handleElm, cursor; updateWithTouchData(e); e.preventDefault(); downButton = e.button; handleElm = handleElement; startX = e.screenX; startY = e.screenY; if (window.getComputedStyle) { cursor = window.getComputedStyle(handleElm, null).getPropertyValue('cursor'); } else { cursor = handleElm.runtimeStyle.cursor; } $eventOverlay = global$9('<div></div>').css({ position: 'absolute', top: 0, left: 0, width: docSize.width, height: docSize.height, zIndex: 2147483647, opacity: 0.0001, cursor: cursor }).appendTo(doc.body); global$9(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop); settings.start(e); }; drag = function (e) { updateWithTouchData(e); if (e.button !== downButton) { return stop(e); } e.deltaX = e.screenX - startX; e.deltaY = e.screenY - startY; e.preventDefault(); settings.drag(e); }; stop = function (e) { updateWithTouchData(e); global$9(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop); $eventOverlay.remove(); if (settings.stop) { settings.stop(e); } }; this.destroy = function () { global$9(handleElement).off(); }; global$9(handleElement).on('mousedown touchstart', start); } var $_4acv48u6jh8lz3ns = { init: function () { var self = this; self.on('repaint', self.renderScroll); }, renderScroll: function () { var self = this, margin = 2; function repaintScroll() { var hasScrollH, hasScrollV, bodyElm; function repaintAxis(axisName, posName, sizeName, contentSizeName, hasScroll, ax) { var containerElm, scrollBarElm, scrollThumbElm; var containerSize, scrollSize, ratio, rect; var posNameLower, sizeNameLower; scrollBarElm = self.getEl('scroll' + axisName); if (scrollBarElm) { posNameLower = posName.toLowerCase(); sizeNameLower = sizeName.toLowerCase(); global$9(self.getEl('absend')).css(posNameLower, self.layoutRect()[contentSizeName] - 1); if (!hasScroll) { global$9(scrollBarElm).css('display', 'none'); return; } global$9(scrollBarElm).css('display', 'block'); containerElm = self.getEl('body'); scrollThumbElm = self.getEl('scroll' + axisName + 't'); containerSize = containerElm['client' + sizeName] - margin * 2; containerSize -= hasScrollH && hasScrollV ? scrollBarElm['client' + ax] : 0; scrollSize = containerElm['scroll' + sizeName]; ratio = containerSize / scrollSize; rect = {}; rect[posNameLower] = containerElm['offset' + posName] + margin; rect[sizeNameLower] = containerSize; global$9(scrollBarElm).css(rect); rect = {}; rect[posNameLower] = containerElm['scroll' + posName] * ratio; rect[sizeNameLower] = containerSize * ratio; global$9(scrollThumbElm).css(rect); } } bodyElm = self.getEl('body'); hasScrollH = bodyElm.scrollWidth > bodyElm.clientWidth; hasScrollV = bodyElm.scrollHeight > bodyElm.clientHeight; repaintAxis('h', 'Left', 'Width', 'contentW', hasScrollH, 'Height'); repaintAxis('v', 'Top', 'Height', 'contentH', hasScrollV, 'Width'); } function addScroll() { function addScrollAxis(axisName, posName, sizeName, deltaPosName, ax) { var scrollStart; var axisId = self._id + '-scroll' + axisName, prefix = self.classPrefix; global$9(self.getEl()).append('<div id="' + axisId + '" class="' + prefix + 'scrollbar ' + prefix + 'scrollbar-' + axisName + '">' + '<div id="' + axisId + 't" class="' + prefix + 'scrollbar-thumb"></div>' + '</div>'); self.draghelper = new DragHelper(axisId + 't', { start: function () { scrollStart = self.getEl('body')['scroll' + posName]; global$9('#' + axisId).addClass(prefix + 'active'); }, drag: function (e) { var ratio, hasScrollH, hasScrollV, containerSize; var layoutRect = self.layoutRect(); hasScrollH = layoutRect.contentW > layoutRect.innerW; hasScrollV = layoutRect.contentH > layoutRect.innerH; containerSize = self.getEl('body')['client' + sizeName] - margin * 2; containerSize -= hasScrollH && hasScrollV ? self.getEl('scroll' + axisName)['client' + ax] : 0; ratio = containerSize / self.getEl('body')['scroll' + sizeName]; self.getEl('body')['scroll' + posName] = scrollStart + e['delta' + deltaPosName] / ratio; }, stop: function () { global$9('#' + axisId).removeClass(prefix + 'active'); } }); } self.classes.add('scroll'); addScrollAxis('v', 'Top', 'Height', 'Y', 'Width'); addScrollAxis('h', 'Left', 'Width', 'X', 'Height'); } if (self.settings.autoScroll) { if (!self._hasScroll) { self._hasScroll = true; addScroll(); self.on('wheel', function (e) { var bodyEl = self.getEl('body'); bodyEl.scrollLeft += (e.deltaX || 0) * 10; bodyEl.scrollTop += e.deltaY * 10; repaintScroll(); }); global$9(self.getEl('body')).on('scroll', repaintScroll); } repaintScroll(); } } }; var Panel = Container.extend({ Defaults: { layout: 'fit', containerCls: 'panel' }, Mixins: [$_4acv48u6jh8lz3ns], renderHtml: function () { var self = this; var layout = self._layout; var innerHtml = self.settings.html; self.preRender(); layout.preRender(self); if (typeof innerHtml === 'undefined') { innerHtml = '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + layout.renderHtml(self) + '</div>'; } else { if (typeof innerHtml === 'function') { innerHtml = innerHtml.call(self); } self._hasBody = false; } return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1" role="group">' + (self._preBodyHtml || '') + innerHtml + '</div>'; } }); var $_8a2gtru8jh8lz3ny = { resizeToContent: function () { this._layoutRect.autoResize = true; this._lastRect = null; this.reflow(); }, resizeTo: function (w, h) { if (w <= 1 || h <= 1) { var rect = funcs.getWindowSize(); w = w <= 1 ? w * rect.w : w; h = h <= 1 ? h * rect.h : h; } this._layoutRect.autoResize = false; return this.layoutRect({ minW: w, minH: h, w: w, h: h }).reflow(); }, resizeBy: function (dw, dh) { var self = this, rect = self.layoutRect(); return self.resizeTo(rect.w + dw, rect.h + dh); } }; var documentClickHandler; var documentScrollHandler; var windowResizeHandler; var visiblePanels = []; var zOrder = []; var hasModal; function isChildOf(ctrl, parent) { while (ctrl) { if (ctrl === parent) { return true; } ctrl = ctrl.parent(); } } function skipOrHidePanels(e) { var i = visiblePanels.length; while (i--) { var panel = visiblePanels[i], clickCtrl = panel.getParentCtrl(e.target); if (panel.settings.autohide) { if (clickCtrl) { if (isChildOf(clickCtrl, panel) || panel.parent() === clickCtrl) { continue; } } e = panel.fire('autohide', { target: e.target }); if (!e.isDefaultPrevented()) { panel.hide(); } } } } function bindDocumentClickHandler() { if (!documentClickHandler) { documentClickHandler = function (e) { if (e.button === 2) { return; } skipOrHidePanels(e); }; global$9(document).on('click touchstart', documentClickHandler); } } function bindDocumentScrollHandler() { if (!documentScrollHandler) { documentScrollHandler = function () { var i; i = visiblePanels.length; while (i--) { repositionPanel(visiblePanels[i]); } }; global$9(window).on('scroll', documentScrollHandler); } } function bindWindowResizeHandler() { if (!windowResizeHandler) { var docElm_1 = document.documentElement; var clientWidth_1 = docElm_1.clientWidth, clientHeight_1 = docElm_1.clientHeight; windowResizeHandler = function () { if (!document.all || clientWidth_1 !== docElm_1.clientWidth || clientHeight_1 !== docElm_1.clientHeight) { clientWidth_1 = docElm_1.clientWidth; clientHeight_1 = docElm_1.clientHeight; FloatPanel.hideAll(); } }; global$9(window).on('resize', windowResizeHandler); } } function repositionPanel(panel) { var scrollY = funcs.getViewPort().y; function toggleFixedChildPanels(fixed, deltaY) { var parent; for (var i = 0; i < visiblePanels.length; i++) { if (visiblePanels[i] !== panel) { parent = visiblePanels[i].parent(); while (parent && (parent = parent.parent())) { if (parent === panel) { visiblePanels[i].fixed(fixed).moveBy(0, deltaY).repaint(); } } } } } if (panel.settings.autofix) { if (!panel.state.get('fixed')) { panel._autoFixY = panel.layoutRect().y; if (panel._autoFixY < scrollY) { panel.fixed(true).layoutRect({ y: 0 }).repaint(); toggleFixedChildPanels(true, scrollY - panel._autoFixY); } } else { if (panel._autoFixY > scrollY) { panel.fixed(false).layoutRect({ y: panel._autoFixY }).repaint(); toggleFixedChildPanels(false, panel._autoFixY - scrollY); } } } } function addRemove(add, ctrl) { var i, zIndex = FloatPanel.zIndex || 65535, topModal; if (add) { zOrder.push(ctrl); } else { i = zOrder.length; while (i--) { if (zOrder[i] === ctrl) { zOrder.splice(i, 1); } } } if (zOrder.length) { for (i = 0; i < zOrder.length; i++) { if (zOrder[i].modal) { zIndex++; topModal = zOrder[i]; } zOrder[i].getEl().style.zIndex = zIndex; zOrder[i].zIndex = zIndex; zIndex++; } } var modalBlockEl = global$9('#' + ctrl.classPrefix + 'modal-block', ctrl.getContainerElm())[0]; if (topModal) { global$9(modalBlockEl).css('z-index', topModal.zIndex - 1); } else if (modalBlockEl) { modalBlockEl.parentNode.removeChild(modalBlockEl); hasModal = false; } FloatPanel.currentZIndex = zIndex; } var FloatPanel = Panel.extend({ Mixins: [ $_d97gfctrjh8lz3lm, $_8a2gtru8jh8lz3ny ], init: function (settings) { var self = this; self._super(settings); self._eventsRoot = self; self.classes.add('floatpanel'); if (settings.autohide) { bindDocumentClickHandler(); bindWindowResizeHandler(); visiblePanels.push(self); } if (settings.autofix) { bindDocumentScrollHandler(); self.on('move', function () { repositionPanel(this); }); } self.on('postrender show', function (e) { if (e.control === self) { var $modalBlockEl_1; var prefix_1 = self.classPrefix; if (self.modal && !hasModal) { $modalBlockEl_1 = global$9('#' + prefix_1 + 'modal-block', self.getContainerElm()); if (!$modalBlockEl_1[0]) { $modalBlockEl_1 = global$9('<div id="' + prefix_1 + 'modal-block" class="' + prefix_1 + 'reset ' + prefix_1 + 'fade"></div>').appendTo(self.getContainerElm()); } global$7.setTimeout(function () { $modalBlockEl_1.addClass(prefix_1 + 'in'); global$9(self.getEl()).addClass(prefix_1 + 'in'); }); hasModal = true; } addRemove(true, self); } }); self.on('show', function () { self.parents().each(function (ctrl) { if (ctrl.state.get('fixed')) { self.fixed(true); return false; } }); }); if (settings.popover) { self._preBodyHtml = '<div class="' + self.classPrefix + 'arrow"></div>'; self.classes.add('popover').add('bottom').add(self.isRtl() ? 'end' : 'start'); } self.aria('label', settings.ariaLabel); self.aria('labelledby', self._id); self.aria('describedby', self.describedBy || self._id + '-none'); }, fixed: function (state) { var self = this; if (self.state.get('fixed') !== state) { if (self.state.get('rendered')) { var viewport = funcs.getViewPort(); if (state) { self.layoutRect().y -= viewport.y; } else { self.layoutRect().y += viewport.y; } } self.classes.toggle('fixed', state); self.state.set('fixed', state); } return self; }, show: function () { var self = this; var i; var state = self._super(); i = visiblePanels.length; while (i--) { if (visiblePanels[i] === self) { break; } } if (i === -1) { visiblePanels.push(self); } return state; }, hide: function () { removeVisiblePanel(this); addRemove(false, this); return this._super(); }, hideAll: function () { FloatPanel.hideAll(); }, close: function () { var self = this; if (!self.fire('close').isDefaultPrevented()) { self.remove(); addRemove(false, self); } return self; }, remove: function () { removeVisiblePanel(this); this._super(); }, postRender: function () { var self = this; if (self.settings.bodyRole) { this.getEl('body').setAttribute('role', self.settings.bodyRole); } return self._super(); } }); FloatPanel.hideAll = function () { var i = visiblePanels.length; while (i--) { var panel = visiblePanels[i]; if (panel && panel.settings.autohide) { panel.hide(); visiblePanels.splice(i, 1); } } }; function removeVisiblePanel(panel) { var i; i = visiblePanels.length; while (i--) { if (visiblePanels[i] === panel) { visiblePanels.splice(i, 1); } } i = zOrder.length; while (i--) { if (zOrder[i] === panel) { zOrder.splice(i, 1); } } } var isFixed$1 = function (inlineToolbarContainer, editor) { return !!(inlineToolbarContainer && !editor.settings.ui_container); }; var render$1 = function (editor, theme, args) { var panel, inlineToolbarContainer; var DOM = global$3.DOM; var fixedToolbarContainer = getFixedToolbarContainer(editor); if (fixedToolbarContainer) { inlineToolbarContainer = DOM.select(fixedToolbarContainer)[0]; } var reposition = function () { if (panel && panel.moveRel && panel.visible() && !panel._fixed) { var scrollContainer = editor.selection.getScrollContainer(), body = editor.getBody(); var deltaX = 0, deltaY = 0; if (scrollContainer) { var bodyPos = DOM.getPos(body), scrollContainerPos = DOM.getPos(scrollContainer); deltaX = Math.max(0, scrollContainerPos.x - bodyPos.x); deltaY = Math.max(0, scrollContainerPos.y - bodyPos.y); } panel.fixed(false).moveRel(body, editor.rtl ? [ 'tr-br', 'br-tr' ] : [ 'tl-bl', 'bl-tl', 'tr-br' ]).moveBy(deltaX, deltaY); } }; var show = function () { if (panel) { panel.show(); reposition(); DOM.addClass(editor.getBody(), 'mce-edit-focus'); } }; var hide = function () { if (panel) { panel.hide(); FloatPanel.hideAll(); DOM.removeClass(editor.getBody(), 'mce-edit-focus'); } }; var render = function () { if (panel) { if (!panel.visible()) { show(); } return; } panel = theme.panel = global$4.create({ type: inlineToolbarContainer ? 'panel' : 'floatpanel', role: 'application', classes: 'tinymce tinymce-inline', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: isFixed$1(inlineToolbarContainer, editor), fixed: isFixed$1(inlineToolbarContainer, editor), border: 1, items: [ hasMenubar(editor) === false ? null : { type: 'menubar', border: '0 0 1 0', items: $_8i78rftgjh8lz3ka.createMenuButtons(editor) }, $_fudqhrtfjh8lz3k7.createToolbars(editor, getToolbarSize(editor)) ] }); $_1jk3jvtcjh8lz3jy.setUiContainer(editor, panel); $_aycuj2t7jh8lz3jp.fireBeforeRenderUI(editor); if (inlineToolbarContainer) { panel.renderTo(inlineToolbarContainer).reflow(); } else { panel.renderTo().reflow(); } $_47hpztt8jh8lz3jq.addKeys(editor, panel); show(); $_5kodmdt9jh8lz3js.addContextualToolbars(editor); editor.on('nodeChange', reposition); editor.on('ResizeWindow', reposition); editor.on('activate', show); editor.on('deactivate', hide); editor.nodeChanged(); }; editor.settings.content_editable = true; editor.on('focus', function () { if (isSkinDisabled(editor) === false && args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, render, render); } else { render(); } }); editor.on('blur hide', hide); editor.on('remove', function () { if (panel) { panel.remove(); panel = null; } }); if (isSkinDisabled(editor) === false && args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, $_231e94tmjh8lz3ku.fireSkinLoaded(editor)); } else { $_231e94tmjh8lz3ku.fireSkinLoaded(editor)(); } return {}; }; var $_7wdylstnjh8lz3kv = { render: render$1 }; function Throbber (elm, inline) { var self = this; var state; var classPrefix = Control$1.classPrefix; var timer; self.show = function (time, callback) { function render() { if (state) { global$9(elm).append('<div class="' + classPrefix + 'throbber' + (inline ? ' ' + classPrefix + 'throbber-inline' : '') + '"></div>'); if (callback) { callback(); } } } self.hide(); state = true; if (time) { timer = global$7.setTimeout(render, time); } else { render(); } return self; }; self.hide = function () { var child = elm.lastChild; global$7.clearTimeout(timer); if (child && child.className.indexOf('throbber') !== -1) { child.parentNode.removeChild(child); } state = false; return self; }; } var setup = function (editor, theme) { var throbber; editor.on('ProgressState', function (e) { throbber = throbber || new Throbber(theme.panel.getEl('body')); if (e.state) { throbber.show(e.time); } else { throbber.hide(); } }); }; var $_e9w0qfu9jh8lz3nz = { setup: setup }; var renderUI = function (editor, theme, args) { var skinUrl = getSkinUrl(editor); if (skinUrl) { args.skinUiCss = skinUrl + '/skin.min.css'; editor.contentCSS.push(skinUrl + '/content' + (editor.inline ? '.inline' : '') + '.min.css'); } $_e9w0qfu9jh8lz3nz.setup(editor, theme); return isInline(editor) ? $_7wdylstnjh8lz3kv.render(editor, theme, args) : $_4cj0a3t3jh8lz3jk.render(editor, theme, args); }; var $_5ent4szjh8lz3ja = { renderUI: renderUI }; var Tooltip = Control$1.extend({ Mixins: [$_d97gfctrjh8lz3lm], Defaults: { classes: 'widget tooltip tooltip-n' }, renderHtml: function () { var self = this, prefix = self.classPrefix; return '<div id="' + self._id + '" class="' + self.classes + '" role="presentation">' + '<div class="' + prefix + 'tooltip-arrow"></div>' + '<div class="' + prefix + 'tooltip-inner">' + self.encode(self.state.get('text')) + '</div>' + '</div>'; }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.getEl().lastChild.innerHTML = self.encode(e.value); }); return self._super(); }, repaint: function () { var self = this; var style, rect; style = self.getEl().style; rect = self._layoutRect; style.left = rect.x + 'px'; style.top = rect.y + 'px'; style.zIndex = 65535 + 65535; } }); var Widget = Control$1.extend({ init: function (settings) { var self = this; self._super(settings); settings = self.settings; self.canFocus = true; if (settings.tooltip && Widget.tooltips !== false) { self.on('mouseenter', function (e) { var tooltip = self.tooltip().moveTo(-65535); if (e.control === self) { var rel = tooltip.text(settings.tooltip).show().testMoveRel(self.getEl(), [ 'bc-tc', 'bc-tl', 'bc-tr' ]); tooltip.classes.toggle('tooltip-n', rel === 'bc-tc'); tooltip.classes.toggle('tooltip-nw', rel === 'bc-tl'); tooltip.classes.toggle('tooltip-ne', rel === 'bc-tr'); tooltip.moveRel(self.getEl(), rel); } else { tooltip.hide(); } }); self.on('mouseleave mousedown click', function () { self.tooltip().remove(); self._tooltip = null; }); } self.aria('label', settings.ariaLabel || settings.tooltip); }, tooltip: function () { if (!this._tooltip) { this._tooltip = new Tooltip({ type: 'tooltip' }); $_1jk3jvtcjh8lz3jy.inheritUiContainer(this, this._tooltip); this._tooltip.renderTo(); } return this._tooltip; }, postRender: function () { var self = this, settings = self.settings; self._super(); if (!self.parent() && (settings.width || settings.height)) { self.initLayoutRect(); self.repaint(); } if (settings.autofocus) { self.focus(); } }, bindStates: function () { var self = this; function disable(state) { self.aria('disabled', state); self.classes.toggle('disabled', state); } function active(state) { self.aria('pressed', state); self.classes.toggle('active', state); } self.state.on('change:disabled', function (e) { disable(e.value); }); self.state.on('change:active', function (e) { active(e.value); }); if (self.state.get('disabled')) { disable(true); } if (self.state.get('active')) { active(true); } return self._super(); }, remove: function () { this._super(); if (this._tooltip) { this._tooltip.remove(); this._tooltip = null; } } }); var Progress = Widget.extend({ Defaults: { value: 0 }, init: function (settings) { var self = this; self._super(settings); self.classes.add('progress'); if (!self.settings.filter) { self.settings.filter = function (value) { return Math.round(value); }; } }, renderHtml: function () { var self = this, id = self._id, prefix = this.classPrefix; return '<div id="' + id + '" class="' + self.classes + '">' + '<div class="' + prefix + 'bar-container">' + '<div class="' + prefix + 'bar"></div>' + '</div>' + '<div class="' + prefix + 'text">0%</div>' + '</div>'; }, postRender: function () { var self = this; self._super(); self.value(self.settings.value); return self; }, bindStates: function () { var self = this; function setValue(value) { value = self.settings.filter(value); self.getEl().lastChild.innerHTML = value + '%'; self.getEl().firstChild.firstChild.style.width = value + '%'; } self.state.on('change:value', function (e) { setValue(e.value); }); setValue(self.state.get('value')); return self._super(); } }); var updateLiveRegion = function (ctx, text) { ctx.getEl().lastChild.textContent = text + (ctx.progressBar ? ' ' + ctx.progressBar.value() + '%' : ''); }; var Notification = Control$1.extend({ Mixins: [$_d97gfctrjh8lz3lm], Defaults: { classes: 'widget notification' }, init: function (settings) { var self = this; self._super(settings); self.maxWidth = settings.maxWidth; if (settings.text) { self.text(settings.text); } if (settings.icon) { self.icon = settings.icon; } if (settings.color) { self.color = settings.color; } if (settings.type) { self.classes.add('notification-' + settings.type); } if (settings.timeout && (settings.timeout < 0 || settings.timeout > 0) && !settings.closeButton) { self.closeButton = false; } else { self.classes.add('has-close'); self.closeButton = true; } if (settings.progressBar) { self.progressBar = new Progress(); } self.on('click', function (e) { if (e.target.className.indexOf(self.classPrefix + 'close') !== -1) { self.close(); } }); }, renderHtml: function () { var self = this; var prefix = self.classPrefix; var icon = '', closeButton = '', progressBar = '', notificationStyle = ''; if (self.icon) { icon = '<i class="' + prefix + 'ico' + ' ' + prefix + 'i-' + self.icon + '"></i>'; } notificationStyle = ' style="max-width: ' + self.maxWidth + 'px;' + (self.color ? 'background-color: ' + self.color + ';"' : '"'); if (self.closeButton) { closeButton = '<button type="button" class="' + prefix + 'close" aria-hidden="true">\xD7</button>'; } if (self.progressBar) { progressBar = self.progressBar.renderHtml(); } return '<div id="' + self._id + '" class="' + self.classes + '"' + notificationStyle + ' role="presentation">' + icon + '<div class="' + prefix + 'notification-inner">' + self.state.get('text') + '</div>' + progressBar + closeButton + '<div style="clip: rect(1px, 1px, 1px, 1px);height: 1px;overflow: hidden;position: absolute;width: 1px;"' + ' aria-live="assertive" aria-relevant="additions" aria-atomic="true"></div>' + '</div>'; }, postRender: function () { var self = this; global$7.setTimeout(function () { self.$el.addClass(self.classPrefix + 'in'); updateLiveRegion(self, self.state.get('text')); }, 100); return self._super(); }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.getEl().firstChild.innerHTML = e.value; updateLiveRegion(self, e.value); }); if (self.progressBar) { self.progressBar.bindStates(); self.progressBar.state.on('change:value', function (e) { updateLiveRegion(self, self.state.get('text')); }); } return self._super(); }, close: function () { var self = this; if (!self.fire('close').isDefaultPrevented()) { self.remove(); } return self; }, repaint: function () { var self = this; var style, rect; style = self.getEl().style; rect = self._layoutRect; style.left = rect.x + 'px'; style.top = rect.y + 'px'; style.zIndex = 65535 - 1; } }); function NotificationManagerImpl (editor) { var getEditorContainer = function (editor) { return editor.inline ? editor.getElement() : editor.getContentAreaContainer(); }; var getContainerWidth = function () { var container = getEditorContainer(editor); return funcs.getSize(container).width; }; var prePositionNotifications = function (notifications) { $_f3qxhzthjh8lz3kg.each(notifications, function (notification) { notification.moveTo(0, 0); }); }; var positionNotifications = function (notifications) { if (notifications.length > 0) { var firstItem = notifications.slice(0, 1)[0]; var container = getEditorContainer(editor); firstItem.moveRel(container, 'tc-tc'); $_f3qxhzthjh8lz3kg.each(notifications, function (notification, index) { if (index > 0) { notification.moveRel(notifications[index - 1].getEl(), 'bc-tc'); } }); } }; var reposition = function (notifications) { prePositionNotifications(notifications); positionNotifications(notifications); }; var open = function (args, closeCallback) { var extendedArgs = global$2.extend(args, { maxWidth: getContainerWidth() }); var notif = new Notification(extendedArgs); notif.args = extendedArgs; if (extendedArgs.timeout > 0) { notif.timer = setTimeout(function () { notif.close(); closeCallback(); }, extendedArgs.timeout); } notif.on('close', function () { closeCallback(); }); notif.renderTo(); return notif; }; var close = function (notification) { notification.close(); }; var getArgs = function (notification) { return notification.args; }; return { open: open, close: close, reposition: reposition, getArgs: getArgs }; } var windows = []; var oldMetaValue = ''; function toggleFullScreenState(state) { var noScaleMetaValue = 'width=device-width,initial-scale=1.0,user-scalable=0,minimum-scale=1.0,maximum-scale=1.0'; var viewport = global$9('meta[name=viewport]')[0], contentValue; if (global$8.overrideViewPort === false) { return; } if (!viewport) { viewport = document.createElement('meta'); viewport.setAttribute('name', 'viewport'); document.getElementsByTagName('head')[0].appendChild(viewport); } contentValue = viewport.getAttribute('content'); if (contentValue && typeof oldMetaValue !== 'undefined') { oldMetaValue = contentValue; } viewport.setAttribute('content', state ? noScaleMetaValue : oldMetaValue); } function toggleBodyFullScreenClasses(classPrefix, state) { if (checkFullscreenWindows() && state === false) { global$9([ document.documentElement, document.body ]).removeClass(classPrefix + 'fullscreen'); } } function checkFullscreenWindows() { for (var i = 0; i < windows.length; i++) { if (windows[i]._fullscreen) { return true; } } return false; } function handleWindowResize() { if (!global$8.desktop) { var lastSize_1 = { w: window.innerWidth, h: window.innerHeight }; global$7.setInterval(function () { var w = window.innerWidth, h = window.innerHeight; if (lastSize_1.w !== w || lastSize_1.h !== h) { lastSize_1 = { w: w, h: h }; global$9(window).trigger('resize'); } }, 100); } function reposition() { var i; var rect = funcs.getWindowSize(); var layoutRect; for (i = 0; i < windows.length; i++) { layoutRect = windows[i].layoutRect(); windows[i].moveTo(windows[i].settings.x || Math.max(0, rect.w / 2 - layoutRect.w / 2), windows[i].settings.y || Math.max(0, rect.h / 2 - layoutRect.h / 2)); } } global$9(window).on('resize', reposition); } var Window = FloatPanel.extend({ modal: true, Defaults: { border: 1, layout: 'flex', containerCls: 'panel', role: 'dialog', callbacks: { submit: function () { this.fire('submit', { data: this.toJSON() }); }, close: function () { this.close(); } } }, init: function (settings) { var self = this; self._super(settings); if (self.isRtl()) { self.classes.add('rtl'); } self.classes.add('window'); self.bodyClasses.add('window-body'); self.state.set('fixed', true); if (settings.buttons) { self.statusbar = new Panel({ layout: 'flex', border: '1 0 0 0', spacing: 3, padding: 10, align: 'center', pack: self.isRtl() ? 'start' : 'end', defaults: { type: 'button' }, items: settings.buttons }); self.statusbar.classes.add('foot'); self.statusbar.parent(self); } self.on('click', function (e) { var closeClass = self.classPrefix + 'close'; if (funcs.hasClass(e.target, closeClass) || funcs.hasClass(e.target.parentNode, closeClass)) { self.close(); } }); self.on('cancel', function () { self.close(); }); self.on('move', function (e) { if (e.control === self) { FloatPanel.hideAll(); } }); self.aria('describedby', self.describedBy || self._id + '-none'); self.aria('label', settings.title); self._fullscreen = false; }, recalc: function () { var self = this; var statusbar = self.statusbar; var layoutRect, width, x, needsRecalc; if (self._fullscreen) { self.layoutRect(funcs.getWindowSize()); self.layoutRect().contentH = self.layoutRect().innerH; } self._super(); layoutRect = self.layoutRect(); if (self.settings.title && !self._fullscreen) { width = layoutRect.headerW; if (width > layoutRect.w) { x = layoutRect.x - Math.max(0, width / 2); self.layoutRect({ w: width, x: x }); needsRecalc = true; } } if (statusbar) { statusbar.layoutRect({ w: self.layoutRect().innerW }).recalc(); width = statusbar.layoutRect().minW + layoutRect.deltaW; if (width > layoutRect.w) { x = layoutRect.x - Math.max(0, width - layoutRect.w); self.layoutRect({ w: width, x: x }); needsRecalc = true; } } if (needsRecalc) { self.recalc(); } }, initLayoutRect: function () { var self = this; var layoutRect = self._super(); var deltaH = 0, headEl; if (self.settings.title && !self._fullscreen) { headEl = self.getEl('head'); var size = funcs.getSize(headEl); layoutRect.headerW = size.width; layoutRect.headerH = size.height; deltaH += layoutRect.headerH; } if (self.statusbar) { deltaH += self.statusbar.layoutRect().h; } layoutRect.deltaH += deltaH; layoutRect.minH += deltaH; layoutRect.h += deltaH; var rect = funcs.getWindowSize(); layoutRect.x = self.settings.x || Math.max(0, rect.w / 2 - layoutRect.w / 2); layoutRect.y = self.settings.y || Math.max(0, rect.h / 2 - layoutRect.h / 2); return layoutRect; }, renderHtml: function () { var self = this, layout = self._layout, id = self._id, prefix = self.classPrefix; var settings = self.settings; var headerHtml = '', footerHtml = '', html = settings.html; self.preRender(); layout.preRender(self); if (settings.title) { headerHtml = '<div id="' + id + '-head" class="' + prefix + 'window-head">' + '<div id="' + id + '-title" class="' + prefix + 'title">' + self.encode(settings.title) + '</div>' + '<div id="' + id + '-dragh" class="' + prefix + 'dragh"></div>' + '<button type="button" class="' + prefix + 'close" aria-hidden="true">' + '<i class="mce-ico mce-i-remove"></i>' + '</button>' + '</div>'; } if (settings.url) { html = '<iframe src="' + settings.url + '" tabindex="-1"></iframe>'; } if (typeof html === 'undefined') { html = layout.renderHtml(self); } if (self.statusbar) { footerHtml = self.statusbar.renderHtml(); } return '<div id="' + id + '" class="' + self.classes + '" hidefocus="1">' + '<div class="' + self.classPrefix + 'reset" role="application">' + headerHtml + '<div id="' + id + '-body" class="' + self.bodyClasses + '">' + html + '</div>' + footerHtml + '</div>' + '</div>'; }, fullscreen: function (state) { var self = this; var documentElement = document.documentElement; var slowRendering; var prefix = self.classPrefix; var layoutRect; if (state !== self._fullscreen) { global$9(window).on('resize', function () { var time; if (self._fullscreen) { if (!slowRendering) { time = new Date().getTime(); var rect = funcs.getWindowSize(); self.moveTo(0, 0).resizeTo(rect.w, rect.h); if (new Date().getTime() - time > 50) { slowRendering = true; } } else { if (!self._timer) { self._timer = global$7.setTimeout(function () { var rect = funcs.getWindowSize(); self.moveTo(0, 0).resizeTo(rect.w, rect.h); self._timer = 0; }, 50); } } } }); layoutRect = self.layoutRect(); self._fullscreen = state; if (!state) { self.borderBox = $_focdcktxjh8lz3mn.parseBox(self.settings.border); self.getEl('head').style.display = ''; layoutRect.deltaH += layoutRect.headerH; global$9([ documentElement, document.body ]).removeClass(prefix + 'fullscreen'); self.classes.remove('fullscreen'); self.moveTo(self._initial.x, self._initial.y).resizeTo(self._initial.w, self._initial.h); } else { self._initial = { x: layoutRect.x, y: layoutRect.y, w: layoutRect.w, h: layoutRect.h }; self.borderBox = $_focdcktxjh8lz3mn.parseBox('0'); self.getEl('head').style.display = 'none'; layoutRect.deltaH -= layoutRect.headerH + 2; global$9([ documentElement, document.body ]).addClass(prefix + 'fullscreen'); self.classes.add('fullscreen'); var rect = funcs.getWindowSize(); self.moveTo(0, 0).resizeTo(rect.w, rect.h); } } return self.reflow(); }, postRender: function () { var self = this; var startPos; setTimeout(function () { self.classes.add('in'); self.fire('open'); }, 0); self._super(); if (self.statusbar) { self.statusbar.postRender(); } self.focus(); this.dragHelper = new DragHelper(self._id + '-dragh', { start: function () { startPos = { x: self.layoutRect().x, y: self.layoutRect().y }; }, drag: function (e) { self.moveTo(startPos.x + e.deltaX, startPos.y + e.deltaY); } }); self.on('submit', function (e) { if (!e.isDefaultPrevented()) { self.close(); } }); windows.push(self); toggleFullScreenState(true); }, submit: function () { return this.fire('submit', { data: this.toJSON() }); }, remove: function () { var self = this; var i; self.dragHelper.destroy(); self._super(); if (self.statusbar) { this.statusbar.remove(); } toggleBodyFullScreenClasses(self.classPrefix, false); i = windows.length; while (i--) { if (windows[i] === self) { windows.splice(i, 1); } } toggleFullScreenState(windows.length > 0); }, getContentWindow: function () { var ifr = this.getEl().getElementsByTagName('iframe')[0]; return ifr ? ifr.contentWindow : null; } }); handleWindowResize(); var MessageBox = Window.extend({ init: function (settings) { settings = { border: 1, padding: 20, layout: 'flex', pack: 'center', align: 'center', containerCls: 'panel', autoScroll: true, buttons: { type: 'button', text: 'Ok', action: 'ok' }, items: { type: 'label', multiline: true, maxWidth: 500, maxHeight: 200 } }; this._super(settings); }, Statics: { OK: 1, OK_CANCEL: 2, YES_NO: 3, YES_NO_CANCEL: 4, msgBox: function (settings) { var buttons; var callback = settings.callback || function () { }; function createButton(text, status, primary) { return { type: 'button', text: text, subtype: primary ? 'primary' : '', onClick: function (e) { e.control.parents()[1].close(); callback(status); } }; } switch (settings.buttons) { case MessageBox.OK_CANCEL: buttons = [ createButton('Ok', true, true), createButton('Cancel', false) ]; break; case MessageBox.YES_NO: case MessageBox.YES_NO_CANCEL: buttons = [ createButton('Yes', 1, true), createButton('No', 0) ]; if (settings.buttons === MessageBox.YES_NO_CANCEL) { buttons.push(createButton('Cancel', -1)); } break; default: buttons = [createButton('Ok', true, true)]; break; } return new Window({ padding: 20, x: settings.x, y: settings.y, minWidth: 300, minHeight: 100, layout: 'flex', pack: 'center', align: 'center', buttons: buttons, title: settings.title, role: 'alertdialog', items: { type: 'label', multiline: true, maxWidth: 500, maxHeight: 200, text: settings.text }, onPostRender: function () { this.aria('describedby', this.items()[0]._id); }, onClose: settings.onClose, onCancel: function () { callback(false); } }).renderTo(document.body).reflow(); }, alert: function (settings, callback) { if (typeof settings === 'string') { settings = { text: settings }; } settings.callback = callback; return MessageBox.msgBox(settings); }, confirm: function (settings, callback) { if (typeof settings === 'string') { settings = { text: settings }; } settings.callback = callback; settings.buttons = MessageBox.OK_CANCEL; return MessageBox.msgBox(settings); } } }); function WindowManagerImpl (editor) { var open = function (args, params, closeCallback) { var win; args.title = args.title || ' '; args.url = args.url || args.file; if (args.url) { args.width = parseInt(args.width || 320, 10); args.height = parseInt(args.height || 240, 10); } if (args.body) { args.items = { defaults: args.defaults, type: args.bodyType || 'form', items: args.body, data: args.data, callbacks: args.commands }; } if (!args.url && !args.buttons) { args.buttons = [ { text: 'Ok', subtype: 'primary', onclick: function () { win.find('form')[0].submit(); } }, { text: 'Cancel', onclick: function () { win.close(); } } ]; } win = new Window(args); win.on('close', function () { closeCallback(win); }); if (args.data) { win.on('postRender', function () { this.find('*').each(function (ctrl) { var name = ctrl.name(); if (name in args.data) { ctrl.value(args.data[name]); } }); }); } win.features = args || {}; win.params = params || {}; win = win.renderTo(document.body).reflow(); return win; }; var alert = function (message, choiceCallback, closeCallback) { var win; win = MessageBox.alert(message, function () { choiceCallback(); }); win.on('close', function () { closeCallback(win); }); return win; }; var confirm = function (message, choiceCallback, closeCallback) { var win; win = MessageBox.confirm(message, function (state) { choiceCallback(state); }); win.on('close', function () { closeCallback(win); }); return win; }; var close = function (window) { window.close(); }; var getParams = function (window) { return window.params; }; var setParams = function (window, params) { window.params = params; }; return { open: open, alert: alert, confirm: confirm, close: close, getParams: getParams, setParams: setParams }; } var get = function (editor) { var renderUI = function (args) { return $_5ent4szjh8lz3ja.renderUI(editor, this, args); }; var resizeTo = function (w, h) { return $_5toavetjjh8lz3ko.resizeTo(editor, w, h); }; var resizeBy = function (dw, dh) { return $_5toavetjjh8lz3ko.resizeBy(editor, dw, dh); }; var getNotificationManagerImpl = function () { return NotificationManagerImpl(editor); }; var getWindowManagerImpl = function () { return WindowManagerImpl(editor); }; return { renderUI: renderUI, resizeTo: resizeTo, resizeBy: resizeBy, getNotificationManagerImpl: getNotificationManagerImpl, getWindowManagerImpl: getWindowManagerImpl }; }; var $_1os0v5syjh8lz3j9 = { get: get }; var Layout = global$10.extend({ Defaults: { firstControlClass: 'first', lastControlClass: 'last' }, init: function (settings) { this.settings = global$2.extend({}, this.Defaults, settings); }, preRender: function (container) { container.bodyClasses.add(this.settings.containerClass); }, applyClasses: function (items) { var self = this; var settings = self.settings; var firstClass, lastClass, firstItem, lastItem; firstClass = settings.firstControlClass; lastClass = settings.lastControlClass; items.each(function (item) { item.classes.remove(firstClass).remove(lastClass).add(settings.controlClass); if (item.visible()) { if (!firstItem) { firstItem = item; } lastItem = item; } }); if (firstItem) { firstItem.classes.add(firstClass); } if (lastItem) { lastItem.classes.add(lastClass); } }, renderHtml: function (container) { var self = this; var html = ''; self.applyClasses(container.items()); container.items().each(function (item) { html += item.renderHtml(); }); return html; }, recalc: function () { }, postRender: function () { }, isNative: function () { return false; } }); var AbsoluteLayout = Layout.extend({ Defaults: { containerClass: 'abs-layout', controlClass: 'abs-layout-item' }, recalc: function (container) { container.items().filter(':visible').each(function (ctrl) { var settings = ctrl.settings; ctrl.layoutRect({ x: settings.x, y: settings.y, w: settings.w, h: settings.h }); if (ctrl.recalc) { ctrl.recalc(); } }); }, renderHtml: function (container) { return '<div id="' + container._id + '-absend" class="' + container.classPrefix + 'abs-end"></div>' + this._super(container); } }); var Button = Widget.extend({ Defaults: { classes: 'widget btn', role: 'button' }, init: function (settings) { var self = this; var size; self._super(settings); settings = self.settings; size = self.settings.size; self.on('click mousedown', function (e) { e.preventDefault(); }); self.on('touchstart', function (e) { self.fire('click', e); e.preventDefault(); }); if (settings.subtype) { self.classes.add(settings.subtype); } if (size) { self.classes.add('btn-' + size); } if (settings.icon) { self.icon(settings.icon); } }, icon: function (icon) { if (!arguments.length) { return this.state.get('icon'); } this.state.set('icon', icon); return this; }, repaint: function () { var btnElm = this.getEl().firstChild; var btnStyle; if (btnElm) { btnStyle = btnElm.style; btnStyle.width = btnStyle.height = '100%'; } this._super(); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; var icon = self.state.get('icon'), image; var text = self.state.get('text'); var textHtml = ''; var ariaPressed; var settings = self.settings; image = settings.image; if (image) { icon = 'none'; if (typeof image !== 'string') { image = window.getSelection ? image[0] : image[1]; } image = ' style="background-image: url(\'' + image + '\')"'; } else { image = ''; } if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } icon = icon ? prefix + 'ico ' + prefix + 'i-' + icon : ''; ariaPressed = typeof settings.active === 'boolean' ? ' aria-pressed="' + settings.active + '"' : ''; return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1"' + ariaPressed + '>' + '<button id="' + id + '-button" role="presentation" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + '</button>' + '</div>'; }, bindStates: function () { var self = this, $ = self.$, textCls = self.classPrefix + 'txt'; function setButtonText(text) { var $span = $('span.' + textCls, self.getEl()); if (text) { if (!$span[0]) { $('button:first', self.getEl()).append('<span class="' + textCls + '"></span>'); $span = $('span.' + textCls, self.getEl()); } $span.html(self.encode(text)); } else { $span.remove(); } self.classes.toggle('btn-has-text', !!text); } self.state.on('change:text', function (e) { setButtonText(e.value); }); self.state.on('change:icon', function (e) { var icon = e.value; var prefix = self.classPrefix; self.settings.icon = icon; icon = icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; var btnElm = self.getEl().firstChild; var iconElm = btnElm.getElementsByTagName('i')[0]; if (icon) { if (!iconElm || iconElm !== btnElm.firstChild) { iconElm = document.createElement('i'); btnElm.insertBefore(iconElm, btnElm.firstChild); } iconElm.className = icon; } else if (iconElm) { btnElm.removeChild(iconElm); } setButtonText(self.state.get('text')); }); return self._super(); } }); var BrowseButton = Button.extend({ init: function (settings) { var self = this; settings = global$2.extend({ text: 'Browse...', multiple: false, accept: null }, settings); self._super(settings); self.classes.add('browsebutton'); if (settings.multiple) { self.classes.add('multiple'); } }, postRender: function () { var self = this; var input = funcs.create('input', { type: 'file', id: self._id + '-browse', accept: self.settings.accept }); self._super(); global$9(input).on('change', function (e) { var files = e.target.files; self.value = function () { if (!files.length) { return null; } else if (self.settings.multiple) { return files; } else { return files[0]; } }; e.preventDefault(); if (files.length) { self.fire('change', e); } }); global$9(input).on('click', function (e) { e.stopPropagation(); }); global$9(self.getEl('button')).on('click', function (e) { e.stopPropagation(); input.click(); }); self.getEl().appendChild(input); }, remove: function () { global$9(this.getEl('button')).off(); global$9(this.getEl('input')).off(); this._super(); } }); var ButtonGroup = Container.extend({ Defaults: { defaultType: 'button', role: 'group' }, renderHtml: function () { var self = this, layout = self._layout; self.classes.add('btn-group'); self.preRender(); layout.preRender(self); return '<div id="' + self._id + '" class="' + self.classes + '">' + '<div id="' + self._id + '-body">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>'; } }); var Checkbox = Widget.extend({ Defaults: { classes: 'checkbox', role: 'checkbox', checked: false }, init: function (settings) { var self = this; self._super(settings); self.on('click mousedown', function (e) { e.preventDefault(); }); self.on('click', function (e) { e.preventDefault(); if (!self.disabled()) { self.checked(!self.checked()); } }); self.checked(self.settings.checked); }, checked: function (state) { if (!arguments.length) { return this.state.get('checked'); } this.state.set('checked', state); return this; }, value: function (state) { if (!arguments.length) { return this.checked(); } return this.checked(state); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; return '<div id="' + id + '" class="' + self.classes + '" unselectable="on" aria-labelledby="' + id + '-al" tabindex="-1">' + '<i class="' + prefix + 'ico ' + prefix + 'i-checkbox"></i>' + '<span id="' + id + '-al" class="' + prefix + 'label">' + self.encode(self.state.get('text')) + '</span>' + '</div>'; }, bindStates: function () { var self = this; function checked(state) { self.classes.toggle('checked', state); self.aria('checked', state); } self.state.on('change:text', function (e) { self.getEl('al').firstChild.data = self.translate(e.value); }); self.state.on('change:checked change:value', function (e) { self.fire('change'); checked(e.value); }); self.state.on('change:icon', function (e) { var icon = e.value; var prefix = self.classPrefix; if (typeof icon === 'undefined') { return self.settings.icon; } self.settings.icon = icon; icon = icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; var btnElm = self.getEl().firstChild; var iconElm = btnElm.getElementsByTagName('i')[0]; if (icon) { if (!iconElm || iconElm !== btnElm.firstChild) { iconElm = document.createElement('i'); btnElm.insertBefore(iconElm, btnElm.firstChild); } iconElm.className = icon; } else if (iconElm) { btnElm.removeChild(iconElm); } }); if (self.state.get('checked')) { checked(true); } return self._super(); } }); var global$13 = tinymce.util.Tools.resolve('tinymce.util.VK'); var ComboBox = Widget.extend({ init: function (settings) { var self = this; self._super(settings); settings = self.settings; self.classes.add('combobox'); self.subinput = true; self.ariaTarget = 'inp'; settings.menu = settings.menu || settings.values; if (settings.menu) { settings.icon = 'caret'; } self.on('click', function (e) { var elm = e.target; var root = self.getEl(); if (!global$9.contains(root, elm) && elm !== root) { return; } while (elm && elm !== root) { if (elm.id && elm.id.indexOf('-open') !== -1) { self.fire('action'); if (settings.menu) { self.showMenu(); if (e.aria) { self.menu.items()[0].focus(); } } } elm = elm.parentNode; } }); self.on('keydown', function (e) { var rootControl; if (e.keyCode === 13 && e.target.nodeName === 'INPUT') { e.preventDefault(); self.parents().reverse().each(function (ctrl) { if (ctrl.toJSON) { rootControl = ctrl; return false; } }); self.fire('submit', { data: rootControl.toJSON() }); } }); self.on('keyup', function (e) { if (e.target.nodeName === 'INPUT') { var oldValue = self.state.get('value'); var newValue = e.target.value; if (newValue !== oldValue) { self.state.set('value', newValue); self.fire('autocomplete', e); } } }); self.on('mouseover', function (e) { var tooltip = self.tooltip().moveTo(-65535); if (self.statusLevel() && e.target.className.indexOf(self.classPrefix + 'status') !== -1) { var statusMessage = self.statusMessage() || 'Ok'; var rel = tooltip.text(statusMessage).show().testMoveRel(e.target, [ 'bc-tc', 'bc-tl', 'bc-tr' ]); tooltip.classes.toggle('tooltip-n', rel === 'bc-tc'); tooltip.classes.toggle('tooltip-nw', rel === 'bc-tl'); tooltip.classes.toggle('tooltip-ne', rel === 'bc-tr'); tooltip.moveRel(e.target, rel); } }); }, statusLevel: function (value) { if (arguments.length > 0) { this.state.set('statusLevel', value); } return this.state.get('statusLevel'); }, statusMessage: function (value) { if (arguments.length > 0) { this.state.set('statusMessage', value); } return this.state.get('statusMessage'); }, showMenu: function () { var self = this; var settings = self.settings; var menu; if (!self.menu) { menu = settings.menu || []; if (menu.length) { menu = { type: 'menu', items: menu }; } else { menu.type = menu.type || 'menu'; } self.menu = global$4.create(menu).parent(self).renderTo(self.getContainerElm()); self.fire('createmenu'); self.menu.reflow(); self.menu.on('cancel', function (e) { if (e.control === self.menu) { self.focus(); } }); self.menu.on('show hide', function (e) { e.control.items().each(function (ctrl) { ctrl.active(ctrl.value() === self.value()); }); }).fire('show'); self.menu.on('select', function (e) { self.value(e.control.value()); }); self.on('focusin', function (e) { if (e.target.tagName.toUpperCase() === 'INPUT') { self.menu.hide(); } }); self.aria('expanded', true); } self.menu.show(); self.menu.layoutRect({ w: self.layoutRect().w }); self.menu.moveRel(self.getEl(), self.isRtl() ? [ 'br-tr', 'tr-br' ] : [ 'bl-tl', 'tl-bl' ]); }, focus: function () { this.getEl('inp').focus(); }, repaint: function () { var self = this, elm = self.getEl(), openElm = self.getEl('open'), rect = self.layoutRect(); var width, lineHeight, innerPadding = 0; var inputElm = elm.firstChild; if (self.statusLevel() && self.statusLevel() !== 'none') { innerPadding = parseInt(funcs.getRuntimeStyle(inputElm, 'padding-right'), 10) - parseInt(funcs.getRuntimeStyle(inputElm, 'padding-left'), 10); } if (openElm) { width = rect.w - funcs.getSize(openElm).width - 10; } else { width = rect.w - 10; } var doc = document; if (doc.all && (!doc.documentMode || doc.documentMode <= 8)) { lineHeight = self.layoutRect().h - 2 + 'px'; } global$9(inputElm).css({ width: width - innerPadding, lineHeight: lineHeight }); self._super(); return self; }, postRender: function () { var self = this; global$9(this.getEl('inp')).on('change', function (e) { self.state.set('value', e.target.value); self.fire('change', e); }); return self._super(); }, renderHtml: function () { var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix; var value = self.state.get('value') || ''; var icon, text, openBtnHtml = '', extraAttrs = '', statusHtml = ''; if ('spellcheck' in settings) { extraAttrs += ' spellcheck="' + settings.spellcheck + '"'; } if (settings.maxLength) { extraAttrs += ' maxlength="' + settings.maxLength + '"'; } if (settings.size) { extraAttrs += ' size="' + settings.size + '"'; } if (settings.subtype) { extraAttrs += ' type="' + settings.subtype + '"'; } statusHtml = '<i id="' + id + '-status" class="mce-status mce-ico" style="display: none"></i>'; if (self.disabled()) { extraAttrs += ' disabled="disabled"'; } icon = settings.icon; if (icon && icon !== 'caret') { icon = prefix + 'ico ' + prefix + 'i-' + settings.icon; } text = self.state.get('text'); if (icon || text) { openBtnHtml = '<div id="' + id + '-open" class="' + prefix + 'btn ' + prefix + 'open" tabIndex="-1" role="button">' + '<button id="' + id + '-action" type="button" hidefocus="1" tabindex="-1">' + (icon !== 'caret' ? '<i class="' + icon + '"></i>' : '<i class="' + prefix + 'caret"></i>') + (text ? (icon ? ' ' : '') + text : '') + '</button>' + '</div>'; self.classes.add('has-open'); } return '<div id="' + id + '" class="' + self.classes + '">' + '<input id="' + id + '-inp" class="' + prefix + 'textbox" value="' + self.encode(value, false) + '" hidefocus="1"' + extraAttrs + ' placeholder="' + self.encode(settings.placeholder) + '" />' + statusHtml + openBtnHtml + '</div>'; }, value: function (value) { if (arguments.length) { this.state.set('value', value); return this; } if (this.state.get('rendered')) { this.state.set('value', this.getEl('inp').value); } return this.state.get('value'); }, showAutoComplete: function (items, term) { var self = this; if (items.length === 0) { self.hideMenu(); return; } var insert = function (value, title) { return function () { self.fire('selectitem', { title: title, value: value }); }; }; if (self.menu) { self.menu.items().remove(); } else { self.menu = global$4.create({ type: 'menu', classes: 'combobox-menu', layout: 'flow' }).parent(self).renderTo(); } global$2.each(items, function (item) { self.menu.add({ text: item.title, url: item.previewUrl, match: term, classes: 'menu-item-ellipsis', onclick: insert(item.value, item.title) }); }); self.menu.renderNew(); self.hideMenu(); self.menu.on('cancel', function (e) { if (e.control.parent() === self.menu) { e.stopPropagation(); self.focus(); self.hideMenu(); } }); self.menu.on('select', function () { self.focus(); }); var maxW = self.layoutRect().w; self.menu.layoutRect({ w: maxW, minW: 0, maxW: maxW }); self.menu.repaint(); self.menu.reflow(); self.menu.show(); self.menu.moveRel(self.getEl(), self.isRtl() ? [ 'br-tr', 'tr-br' ] : [ 'bl-tl', 'tl-bl' ]); }, hideMenu: function () { if (this.menu) { this.menu.hide(); } }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { if (self.getEl('inp').value !== e.value) { self.getEl('inp').value = e.value; } }); self.state.on('change:disabled', function (e) { self.getEl('inp').disabled = e.value; }); self.state.on('change:statusLevel', function (e) { var statusIconElm = self.getEl('status'); var prefix = self.classPrefix, value = e.value; funcs.css(statusIconElm, 'display', value === 'none' ? 'none' : ''); funcs.toggleClass(statusIconElm, prefix + 'i-checkmark', value === 'ok'); funcs.toggleClass(statusIconElm, prefix + 'i-warning', value === 'warn'); funcs.toggleClass(statusIconElm, prefix + 'i-error', value === 'error'); self.classes.toggle('has-status', value !== 'none'); self.repaint(); }); funcs.on(self.getEl('status'), 'mouseleave', function () { self.tooltip().hide(); }); self.on('cancel', function (e) { if (self.menu && self.menu.visible()) { e.stopPropagation(); self.hideMenu(); } }); var focusIdx = function (idx, menu) { if (menu && menu.items().length > 0) { menu.items().eq(idx)[0].focus(); } }; self.on('keydown', function (e) { var keyCode = e.keyCode; if (e.target.nodeName === 'INPUT') { if (keyCode === global$13.DOWN) { e.preventDefault(); self.fire('autocomplete'); focusIdx(0, self.menu); } else if (keyCode === global$13.UP) { e.preventDefault(); focusIdx(-1, self.menu); } } }); return self._super(); }, remove: function () { global$9(this.getEl('inp')).off(); if (this.menu) { this.menu.remove(); } this._super(); } }); var ColorBox = ComboBox.extend({ init: function (settings) { var self = this; settings.spellcheck = false; if (settings.onaction) { settings.icon = 'none'; } self._super(settings); self.classes.add('colorbox'); self.on('change keyup postrender', function () { self.repaintColor(self.value()); }); }, repaintColor: function (value) { var openElm = this.getEl('open'); var elm = openElm ? openElm.getElementsByTagName('i')[0] : null; if (elm) { try { elm.style.background = value; } catch (ex) { } } }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { if (self.state.get('rendered')) { self.repaintColor(e.value); } }); return self._super(); } }); var PanelButton = Button.extend({ showPanel: function () { var self = this, settings = self.settings; self.classes.add('opened'); if (!self.panel) { var panelSettings = settings.panel; if (panelSettings.type) { panelSettings = { layout: 'grid', items: panelSettings }; } panelSettings.role = panelSettings.role || 'dialog'; panelSettings.popover = true; panelSettings.autohide = true; panelSettings.ariaRoot = true; self.panel = new FloatPanel(panelSettings).on('hide', function () { self.classes.remove('opened'); }).on('cancel', function (e) { e.stopPropagation(); self.focus(); self.hidePanel(); }).parent(self).renderTo(self.getContainerElm()); self.panel.fire('show'); self.panel.reflow(); } else { self.panel.show(); } var rtlRels = [ 'bc-tc', 'bc-tl', 'bc-tr' ]; var ltrRels = [ 'bc-tc', 'bc-tr', 'bc-tl', 'tc-bc', 'tc-br', 'tc-bl' ]; var rel = self.panel.testMoveRel(self.getEl(), settings.popoverAlign || (self.isRtl() ? rtlRels : ltrRels)); self.panel.classes.toggle('start', rel.substr(-1) === 'l'); self.panel.classes.toggle('end', rel.substr(-1) === 'r'); var isTop = rel.substr(0, 1) === 't'; self.panel.classes.toggle('bottom', !isTop); self.panel.classes.toggle('top', isTop); self.panel.moveRel(self.getEl(), rel); }, hidePanel: function () { var self = this; if (self.panel) { self.panel.hide(); } }, postRender: function () { var self = this; self.aria('haspopup', true); self.on('click', function (e) { if (e.control === self) { if (self.panel && self.panel.visible()) { self.hidePanel(); } else { self.showPanel(); self.panel.focus(!!e.aria); } } }); return self._super(); }, remove: function () { if (this.panel) { this.panel.remove(); this.panel = null; } return this._super(); } }); var DOM$3 = global$3.DOM; var ColorButton = PanelButton.extend({ init: function (settings) { this._super(settings); this.classes.add('splitbtn'); this.classes.add('colorbutton'); }, color: function (color) { if (color) { this._color = color; this.getEl('preview').style.backgroundColor = color; return this; } return this._color; }, resetColor: function () { this._color = null; this.getEl('preview').style.backgroundColor = null; return this; }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix, text = self.state.get('text'); var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; var textHtml = ''; if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } return '<div id="' + id + '" class="' + self.classes + '" role="button" tabindex="-1" aria-haspopup="true">' + '<button role="presentation" hidefocus="1" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + '<span id="' + id + '-preview" class="' + prefix + 'preview"></span>' + textHtml + '</button>' + '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>'; }, postRender: function () { var self = this, onClickHandler = self.settings.onclick; self.on('click', function (e) { if (e.aria && e.aria.key === 'down') { return; } if (e.control === self && !DOM$3.getParent(e.target, '.' + self.classPrefix + 'open')) { e.stopImmediatePropagation(); onClickHandler.call(self, e); } }); delete self.settings.onclick; return self._super(); } }); var global$14 = tinymce.util.Tools.resolve('tinymce.util.Color'); var ColorPicker = Widget.extend({ Defaults: { classes: 'widget colorpicker' }, init: function (settings) { this._super(settings); }, postRender: function () { var self = this; var color = self.color(); var hsv, hueRootElm, huePointElm, svRootElm, svPointElm; hueRootElm = self.getEl('h'); huePointElm = self.getEl('hp'); svRootElm = self.getEl('sv'); svPointElm = self.getEl('svp'); function getPos(elm, event) { var pos = funcs.getPos(elm); var x, y; x = event.pageX - pos.x; y = event.pageY - pos.y; x = Math.max(0, Math.min(x / elm.clientWidth, 1)); y = Math.max(0, Math.min(y / elm.clientHeight, 1)); return { x: x, y: y }; } function updateColor(hsv, hueUpdate) { var hue = (360 - hsv.h) / 360; funcs.css(huePointElm, { top: hue * 100 + '%' }); if (!hueUpdate) { funcs.css(svPointElm, { left: hsv.s + '%', top: 100 - hsv.v + '%' }); } svRootElm.style.background = global$14({ s: 100, v: 100, h: hsv.h }).toHex(); self.color().parse({ s: hsv.s, v: hsv.v, h: hsv.h }); } function updateSaturationAndValue(e) { var pos; pos = getPos(svRootElm, e); hsv.s = pos.x * 100; hsv.v = (1 - pos.y) * 100; updateColor(hsv); self.fire('change'); } function updateHue(e) { var pos; pos = getPos(hueRootElm, e); hsv = color.toHsv(); hsv.h = (1 - pos.y) * 360; updateColor(hsv, true); self.fire('change'); } self._repaint = function () { hsv = color.toHsv(); updateColor(hsv); }; self._super(); self._svdraghelper = new DragHelper(self._id + '-sv', { start: updateSaturationAndValue, drag: updateSaturationAndValue }); self._hdraghelper = new DragHelper(self._id + '-h', { start: updateHue, drag: updateHue }); self._repaint(); }, rgb: function () { return this.color().toRgb(); }, value: function (value) { var self = this; if (arguments.length) { self.color().parse(value); if (self._rendered) { self._repaint(); } } else { return self.color().toHex(); } }, color: function () { if (!this._color) { this._color = global$14(); } return this._color; }, renderHtml: function () { var self = this; var id = self._id; var prefix = self.classPrefix; var hueHtml; var stops = '#ff0000,#ff0080,#ff00ff,#8000ff,#0000ff,#0080ff,#00ffff,#00ff80,#00ff00,#80ff00,#ffff00,#ff8000,#ff0000'; function getOldIeFallbackHtml() { var i, l, html = '', gradientPrefix, stopsList; gradientPrefix = 'filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='; stopsList = stops.split(','); for (i = 0, l = stopsList.length - 1; i < l; i++) { html += '<div class="' + prefix + 'colorpicker-h-chunk" style="' + 'height:' + 100 / l + '%;' + gradientPrefix + stopsList[i] + ',endColorstr=' + stopsList[i + 1] + ');' + '-ms-' + gradientPrefix + stopsList[i] + ',endColorstr=' + stopsList[i + 1] + ')' + '"></div>'; } return html; } var gradientCssText = 'background: -ms-linear-gradient(top,' + stops + ');' + 'background: linear-gradient(to bottom,' + stops + ');'; hueHtml = '<div id="' + id + '-h" class="' + prefix + 'colorpicker-h" style="' + gradientCssText + '">' + getOldIeFallbackHtml() + '<div id="' + id + '-hp" class="' + prefix + 'colorpicker-h-marker"></div>' + '</div>'; return '<div id="' + id + '" class="' + self.classes + '">' + '<div id="' + id + '-sv" class="' + prefix + 'colorpicker-sv">' + '<div class="' + prefix + 'colorpicker-overlay1">' + '<div class="' + prefix + 'colorpicker-overlay2">' + '<div id="' + id + '-svp" class="' + prefix + 'colorpicker-selector1">' + '<div class="' + prefix + 'colorpicker-selector2"></div>' + '</div>' + '</div>' + '</div>' + '</div>' + hueHtml + '</div>'; } }); var DropZone = Widget.extend({ init: function (settings) { var self = this; settings = global$2.extend({ height: 100, text: 'Drop an image here', multiple: false, accept: null }, settings); self._super(settings); self.classes.add('dropzone'); if (settings.multiple) { self.classes.add('multiple'); } }, renderHtml: function () { var self = this; var attrs, elm; var cfg = self.settings; attrs = { id: self._id, hidefocus: '1' }; elm = funcs.create('div', attrs, '<span>' + this.translate(cfg.text) + '</span>'); if (cfg.height) { funcs.css(elm, 'height', cfg.height + 'px'); } if (cfg.width) { funcs.css(elm, 'width', cfg.width + 'px'); } elm.className = self.classes; return elm.outerHTML; }, postRender: function () { var self = this; var toggleDragClass = function (e) { e.preventDefault(); self.classes.toggle('dragenter'); self.getEl().className = self.classes; }; var filter = function (files) { var accept = self.settings.accept; if (typeof accept !== 'string') { return files; } var re = new RegExp('(' + accept.split(/\s*,\s*/).join('|') + ')$', 'i'); return global$2.grep(files, function (file) { return re.test(file.name); }); }; self._super(); self.$el.on('dragover', function (e) { e.preventDefault(); }); self.$el.on('dragenter', toggleDragClass); self.$el.on('dragleave', toggleDragClass); self.$el.on('drop', function (e) { e.preventDefault(); if (self.state.get('disabled')) { return; } var files = filter(e.dataTransfer.files); self.value = function () { if (!files.length) { return null; } else if (self.settings.multiple) { return files; } else { return files[0]; } }; if (files.length) { self.fire('change', e); } }); }, remove: function () { this.$el.off(); this._super(); } }); var Path = Widget.extend({ init: function (settings) { var self = this; if (!settings.delimiter) { settings.delimiter = '\xBB'; } self._super(settings); self.classes.add('path'); self.canFocus = true; self.on('click', function (e) { var index; var target = e.target; if (index = target.getAttribute('data-index')) { self.fire('select', { value: self.row()[index], index: index }); } }); self.row(self.settings.row); }, focus: function () { var self = this; self.getEl().firstChild.focus(); return self; }, row: function (row) { if (!arguments.length) { return this.state.get('row'); } this.state.set('row', row); return this; }, renderHtml: function () { var self = this; return '<div id="' + self._id + '" class="' + self.classes + '">' + self._getDataPathHtml(self.state.get('row')) + '</div>'; }, bindStates: function () { var self = this; self.state.on('change:row', function (e) { self.innerHtml(self._getDataPathHtml(e.value)); }); return self._super(); }, _getDataPathHtml: function (data) { var self = this; var parts = data || []; var i, l, html = ''; var prefix = self.classPrefix; for (i = 0, l = parts.length; i < l; i++) { html += (i > 0 ? '<div class="' + prefix + 'divider" aria-hidden="true"> ' + self.settings.delimiter + ' </div>' : '') + '<div role="button" class="' + prefix + 'path-item' + (i === l - 1 ? ' ' + prefix + 'last' : '') + '" data-index="' + i + '" tabindex="-1" id="' + self._id + '-' + i + '" aria-level="' + (i + 1) + '">' + parts[i].name + '</div>'; } if (!html) { html = '<div class="' + prefix + 'path-item">\xA0</div>'; } return html; } }); var ElementPath = Path.extend({ postRender: function () { var self = this, editor = self.settings.editor; function isHidden(elm) { if (elm.nodeType === 1) { if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) { return true; } if (elm.getAttribute('data-mce-type') === 'bookmark') { return true; } } return false; } if (editor.settings.elementpath !== false) { self.on('select', function (e) { editor.focus(); editor.selection.select(this.row()[e.index].element); editor.nodeChanged(); }); editor.on('nodeChange', function (e) { var outParents = []; var parents = e.parents; var i = parents.length; while (i--) { if (parents[i].nodeType === 1 && !isHidden(parents[i])) { var args = editor.fire('ResolveName', { name: parents[i].nodeName.toLowerCase(), target: parents[i] }); if (!args.isDefaultPrevented()) { outParents.push({ name: args.name, element: parents[i] }); } if (args.isPropagationStopped()) { break; } } } self.row(outParents); }); } return self._super(); } }); var FormItem = Container.extend({ Defaults: { layout: 'flex', align: 'center', defaults: { flex: 1 } }, renderHtml: function () { var self = this, layout = self._layout, prefix = self.classPrefix; self.classes.add('formitem'); layout.preRender(self); return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + (self.settings.title ? '<div id="' + self._id + '-title" class="' + prefix + 'title">' + self.settings.title + '</div>' : '') + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</div>'; } }); var Form = Container.extend({ Defaults: { containerCls: 'form', layout: 'flex', direction: 'column', align: 'stretch', flex: 1, padding: 15, labelGap: 30, spacing: 10, callbacks: { submit: function () { this.submit(); } } }, preRender: function () { var self = this, items = self.items(); if (!self.settings.formItemDefaults) { self.settings.formItemDefaults = { layout: 'flex', autoResize: 'overflow', defaults: { flex: 1 } }; } items.each(function (ctrl) { var formItem; var label = ctrl.settings.label; if (label) { formItem = new FormItem(global$2.extend({ items: { type: 'label', id: ctrl._id + '-l', text: label, flex: 0, forId: ctrl._id, disabled: ctrl.disabled() } }, self.settings.formItemDefaults)); formItem.type = 'formitem'; ctrl.aria('labelledby', ctrl._id + '-l'); if (typeof ctrl.settings.flex === 'undefined') { ctrl.settings.flex = 1; } self.replace(ctrl, formItem); formItem.add(ctrl); } }); }, submit: function () { return this.fire('submit', { data: this.toJSON() }); }, postRender: function () { var self = this; self._super(); self.fromJSON(self.settings.data); }, bindStates: function () { var self = this; self._super(); function recalcLabels() { var maxLabelWidth = 0; var labels = []; var i, labelGap, items; if (self.settings.labelGapCalc === false) { return; } if (self.settings.labelGapCalc === 'children') { items = self.find('formitem'); } else { items = self.items(); } items.filter('formitem').each(function (item) { var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth; maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth; labels.push(labelCtrl); }); labelGap = self.settings.labelGap || 0; i = labels.length; while (i--) { labels[i].settings.minWidth = maxLabelWidth + labelGap; } } self.on('show', recalcLabels); recalcLabels(); } }); var FieldSet = Form.extend({ Defaults: { containerCls: 'fieldset', layout: 'flex', direction: 'column', align: 'stretch', flex: 1, padding: '25 15 5 15', labelGap: 30, spacing: 10, border: 1 }, renderHtml: function () { var self = this, layout = self._layout, prefix = self.classPrefix; self.preRender(); layout.preRender(self); return '<fieldset id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + (self.settings.title ? '<legend id="' + self._id + '-title" class="' + prefix + 'fieldset-title">' + self.settings.title + '</legend>' : '') + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + (self.settings.html || '') + layout.renderHtml(self) + '</div>' + '</fieldset>'; } }); var unique$1 = 0; var generate = function (prefix) { var date = new Date(); var time = date.getTime(); var random = Math.floor(Math.random() * 1000000000); unique$1++; return prefix + '_' + random + unique$1 + String(time); }; var $_gdeezvv5jh8lz3rl = { generate: generate }; var fromHtml = function (html, scope) { var doc = scope || document; var div = doc.createElement('div'); div.innerHTML = html; if (!div.hasChildNodes() || div.childNodes.length > 1) { console.error('HTML does not have a single root node', html); throw 'HTML must have a single root node'; } return fromDom(div.childNodes[0]); }; var fromTag = function (tag, scope) { var doc = scope || document; var node = doc.createElement(tag); return fromDom(node); }; var fromText = function (text, scope) { var doc = scope || document; var node = doc.createTextNode(text); return fromDom(node); }; var fromDom = function (node) { if (node === null || node === undefined) throw new Error('Node cannot be null or undefined'); return { dom: $_3pjweotejh8lz3k4.constant(node) }; }; var fromPoint = function (doc, x, y) { return Option.from(doc.dom().elementFromPoint(x, y)).map(fromDom); }; var $_3bkrfxv6jh8lz3rm = { fromHtml: fromHtml, fromTag: fromTag, fromText: fromText, fromDom: fromDom, fromPoint: fromPoint }; var cached = function (f) { var called = false; var r; return function () { if (!called) { called = true; r = f.apply(null, arguments); } return r; }; }; var $_8me1xevajh8lz3s0 = { cached: cached }; var $_8xkvw6vcjh8lz3s2 = { ATTRIBUTE: 2, CDATA_SECTION: 4, COMMENT: 8, DOCUMENT: 9, DOCUMENT_TYPE: 10, DOCUMENT_FRAGMENT: 11, ELEMENT: 1, TEXT: 3, PROCESSING_INSTRUCTION: 7, ENTITY_REFERENCE: 5, ENTITY: 6, NOTATION: 12 }; var name = function (element) { var r = element.dom().nodeName; return r.toLowerCase(); }; var type = function (element) { return element.dom().nodeType; }; var value = function (element) { return element.dom().nodeValue; }; var isType$1 = function (t) { return function (element) { return type(element) === t; }; }; var isComment = function (element) { return type(element) === $_8xkvw6vcjh8lz3s2.COMMENT || name(element) === '#comment'; }; var isElement = isType$1($_8xkvw6vcjh8lz3s2.ELEMENT); var isText = isType$1($_8xkvw6vcjh8lz3s2.TEXT); var isDocument = isType$1($_8xkvw6vcjh8lz3s2.DOCUMENT); var $_11h2nlvbjh8lz3s1 = { name: name, type: type, value: value, isElement: isElement, isText: isText, isDocument: isDocument, isComment: isComment }; var inBody = function (element) { var dom = $_11h2nlvbjh8lz3s1.isText(element) ? element.dom().parentNode : element.dom(); return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom); }; var body = $_8me1xevajh8lz3s0.cached(function () { return getBody($_3bkrfxv6jh8lz3rm.fromDom(document)); }); var getBody = function (doc) { var body = doc.dom().body; if (body === null || body === undefined) throw 'Body is not available yet'; return $_3bkrfxv6jh8lz3rm.fromDom(body); }; var $_35bizev9jh8lz3rx = { body: body, getBody: getBody, inBody: inBody }; function Immutable () { var fields = []; for (var _i = 0; _i < arguments.length; _i++) { fields[_i] = arguments[_i]; } return function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } if (fields.length !== values.length) { throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments'); } var struct = {}; $_f3qxhzthjh8lz3kg.each(fields, function (name, i) { struct[name] = $_3pjweotejh8lz3k4.constant(values[i]); }); return struct; }; } var keys = function () { var fastKeys = Object.keys; var slowKeys = function (o) { var r = []; for (var i in o) { if (o.hasOwnProperty(i)) { r.push(i); } } return r; }; return fastKeys === undefined ? slowKeys : fastKeys; }(); var each$1 = function (obj, f) { var props = keys(obj); for (var k = 0, len = props.length; k < len; k++) { var i = props[k]; var x = obj[i]; f(x, i, obj); } }; var objectMap = function (obj, f) { return tupleMap(obj, function (x, i, obj) { return { k: i, v: f(x, i, obj) }; }); }; var tupleMap = function (obj, f) { var r = {}; each$1(obj, function (x, i) { var tuple = f(x, i, obj); r[tuple.k] = tuple.v; }); return r; }; var bifilter = function (obj, pred) { var t = {}; var f = {}; each$1(obj, function (x, i) { var branch = pred(x, i) ? t : f; branch[i] = x; }); return { t: t, f: f }; }; var mapToArray = function (obj, f) { var r = []; each$1(obj, function (value, name) { r.push(f(value, name)); }); return r; }; var find$1 = function (obj, pred) { var props = keys(obj); for (var k = 0, len = props.length; k < len; k++) { var i = props[k]; var x = obj[i]; if (pred(x, i, obj)) { return Option.some(x); } } return Option.none(); }; var values = function (obj) { return mapToArray(obj, function (v) { return v; }); }; var size = function (obj) { return values(obj).length; }; var $_el35e0vhjh8lz3sl = { bifilter: bifilter, each: each$1, map: objectMap, mapToArray: mapToArray, tupleMap: tupleMap, find: find$1, keys: keys, values: values, size: size }; var sort$1 = function (arr) { return arr.slice(0).sort(); }; var reqMessage = function (required, keys) { throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.'); }; var unsuppMessage = function (unsupported) { throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', ')); }; var validateStrArr = function (label, array) { if (!$_d8bie3tijh8lz3kn.isArray(array)) throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.'); $_f3qxhzthjh8lz3kg.each(array, function (a) { if (!$_d8bie3tijh8lz3kn.isString(a)) throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.'); }); }; var invalidTypeMessage = function (incorrect, type) { throw new Error('All values need to be of type: ' + type + '. Keys (' + sort$1(incorrect).join(', ') + ') were not.'); }; var checkDupes = function (everything) { var sorted = sort$1(everything); var dupe = $_f3qxhzthjh8lz3kg.find(sorted, function (s, i) { return i < sorted.length - 1 && s === sorted[i + 1]; }); dupe.each(function (d) { throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].'); }); }; var $_6xoomwvijh8lz3sn = { sort: sort$1, reqMessage: reqMessage, unsuppMessage: unsuppMessage, validateStrArr: validateStrArr, invalidTypeMessage: invalidTypeMessage, checkDupes: checkDupes }; function MixedBag (required, optional) { var everything = required.concat(optional); if (everything.length === 0) throw new Error('You must specify at least one required or optional field.'); $_6xoomwvijh8lz3sn.validateStrArr('required', required); $_6xoomwvijh8lz3sn.validateStrArr('optional', optional); $_6xoomwvijh8lz3sn.checkDupes(everything); return function (obj) { var keys = $_el35e0vhjh8lz3sl.keys(obj); var allReqd = $_f3qxhzthjh8lz3kg.forall(required, function (req) { return $_f3qxhzthjh8lz3kg.contains(keys, req); }); if (!allReqd) $_6xoomwvijh8lz3sn.reqMessage(required, keys); var unsupported = $_f3qxhzthjh8lz3kg.filter(keys, function (key) { return !$_f3qxhzthjh8lz3kg.contains(everything, key); }); if (unsupported.length > 0) $_6xoomwvijh8lz3sn.unsuppMessage(unsupported); var r = {}; $_f3qxhzthjh8lz3kg.each(required, function (req) { r[req] = $_3pjweotejh8lz3k4.constant(obj[req]); }); $_f3qxhzthjh8lz3kg.each(optional, function (opt) { r[opt] = $_3pjweotejh8lz3k4.constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none()); }); return r; }; } var $_57mdu6vejh8lz3sg = { immutable: Immutable, immutableBag: MixedBag }; var toArray = function (target, f) { var r = []; var recurse = function (e) { r.push(e); return f(e); }; var cur = f(target); do { cur = cur.bind(recurse); } while (cur.isSome()); return r; }; var $_861s8bvjjh8lz3sp = { toArray: toArray }; var global$15 = typeof window !== 'undefined' ? window : Function('return this;')(); var path = function (parts, scope) { var o = scope !== undefined && scope !== null ? scope : global$15; for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i) o = o[parts[i]]; return o; }; var resolve = function (p, scope) { var parts = p.split('.'); return path(parts, scope); }; var step = function (o, part) { if (o[part] === undefined || o[part] === null) o[part] = {}; return o[part]; }; var forge = function (parts, target) { var o = target !== undefined ? target : global$15; for (var i = 0; i < parts.length; ++i) o = step(o, parts[i]); return o; }; var namespace = function (name, target) { var parts = name.split('.'); return forge(parts, target); }; var $_1cxe7nvnjh8lz3td = { path: path, resolve: resolve, forge: forge, namespace: namespace }; var unsafe = function (name, scope) { return $_1cxe7nvnjh8lz3td.resolve(name, scope); }; var getOrDie = function (name, scope) { var actual = unsafe(name, scope); if (actual === undefined || actual === null) throw name + ' not available on this browser'; return actual; }; var $_eol4qgvmjh8lz3t9 = { getOrDie: getOrDie }; var node = function () { var f = $_eol4qgvmjh8lz3t9.getOrDie('Node'); return f; }; var compareDocumentPosition = function (a, b, match) { return (a.compareDocumentPosition(b) & match) !== 0; }; var documentPositionPreceding = function (a, b) { return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_PRECEDING); }; var documentPositionContainedBy = function (a, b) { return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_CONTAINED_BY); }; var $_7n27kvvljh8lz3t8 = { documentPositionPreceding: documentPositionPreceding, documentPositionContainedBy: documentPositionContainedBy }; var firstMatch = function (regexes, s) { for (var i = 0; i < regexes.length; i++) { var x = regexes[i]; if (x.test(s)) return x; } return undefined; }; var find$2 = function (regexes, agent) { var r = firstMatch(regexes, agent); if (!r) return { major: 0, minor: 0 }; var group = function (i) { return Number(agent.replace(r, '$' + i)); }; return nu(group(1), group(2)); }; var detect = function (versionRegexes, agent) { var cleanedAgent = String(agent).toLowerCase(); if (versionRegexes.length === 0) return unknown(); return find$2(versionRegexes, cleanedAgent); }; var unknown = function () { return nu(0, 0); }; var nu = function (major, minor) { return { major: major, minor: minor }; }; var $_afos0kvsjh8lz3tm = { nu: nu, detect: detect, unknown: unknown }; var edge = 'Edge'; var chrome = 'Chrome'; var ie = 'IE'; var opera = 'Opera'; var firefox = 'Firefox'; var safari = 'Safari'; var isBrowser = function (name, current) { return function () { return current === name; }; }; var unknown$1 = function () { return nu$1({ current: undefined, version: $_afos0kvsjh8lz3tm.unknown() }); }; var nu$1 = function (info) { var current = info.current; var version = info.version; return { current: current, version: version, isEdge: isBrowser(edge, current), isChrome: isBrowser(chrome, current), isIE: isBrowser(ie, current), isOpera: isBrowser(opera, current), isFirefox: isBrowser(firefox, current), isSafari: isBrowser(safari, current) }; }; var $_fidpetvrjh8lz3tj = { unknown: unknown$1, nu: nu$1, edge: $_3pjweotejh8lz3k4.constant(edge), chrome: $_3pjweotejh8lz3k4.constant(chrome), ie: $_3pjweotejh8lz3k4.constant(ie), opera: $_3pjweotejh8lz3k4.constant(opera), firefox: $_3pjweotejh8lz3k4.constant(firefox), safari: $_3pjweotejh8lz3k4.constant(safari) }; var windows$1 = 'Windows'; var ios = 'iOS'; var android = 'Android'; var linux = 'Linux'; var osx = 'OSX'; var solaris = 'Solaris'; var freebsd = 'FreeBSD'; var isOS = function (name, current) { return function () { return current === name; }; }; var unknown$2 = function () { return nu$2({ current: undefined, version: $_afos0kvsjh8lz3tm.unknown() }); }; var nu$2 = function (info) { var current = info.current; var version = info.version; return { current: current, version: version, isWindows: isOS(windows$1, current), isiOS: isOS(ios, current), isAndroid: isOS(android, current), isOSX: isOS(osx, current), isLinux: isOS(linux, current), isSolaris: isOS(solaris, current), isFreeBSD: isOS(freebsd, current) }; }; var $_1z8n9kvtjh8lz3to = { unknown: unknown$2, nu: nu$2, windows: $_3pjweotejh8lz3k4.constant(windows$1), ios: $_3pjweotejh8lz3k4.constant(ios), android: $_3pjweotejh8lz3k4.constant(android), linux: $_3pjweotejh8lz3k4.constant(linux), osx: $_3pjweotejh8lz3k4.constant(osx), solaris: $_3pjweotejh8lz3k4.constant(solaris), freebsd: $_3pjweotejh8lz3k4.constant(freebsd) }; function DeviceType (os, browser, userAgent) { var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true; var isiPhone = os.isiOS() && !isiPad; var isAndroid3 = os.isAndroid() && os.version.major === 3; var isAndroid4 = os.isAndroid() && os.version.major === 4; var isTablet = isiPad || isAndroid3 || isAndroid4 && /mobile/i.test(userAgent) === true; var isTouch = os.isiOS() || os.isAndroid(); var isPhone = isTouch && !isTablet; var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false; return { isiPad: $_3pjweotejh8lz3k4.constant(isiPad), isiPhone: $_3pjweotejh8lz3k4.constant(isiPhone), isTablet: $_3pjweotejh8lz3k4.constant(isTablet), isPhone: $_3pjweotejh8lz3k4.constant(isPhone), isTouch: $_3pjweotejh8lz3k4.constant(isTouch), isAndroid: os.isAndroid, isiOS: os.isiOS, isWebView: $_3pjweotejh8lz3k4.constant(iOSwebview) }; } var detect$1 = function (candidates, userAgent) { var agent = String(userAgent).toLowerCase(); return $_f3qxhzthjh8lz3kg.find(candidates, function (candidate) { return candidate.search(agent); }); }; var detectBrowser = function (browsers, userAgent) { return detect$1(browsers, userAgent).map(function (browser) { var version = $_afos0kvsjh8lz3tm.detect(browser.versionRegexes, userAgent); return { current: browser.name, version: version }; }); }; var detectOs = function (oses, userAgent) { return detect$1(oses, userAgent).map(function (os) { var version = $_afos0kvsjh8lz3tm.detect(os.versionRegexes, userAgent); return { current: os.name, version: version }; }); }; var $_bvrih8vvjh8lz3tv = { detectBrowser: detectBrowser, detectOs: detectOs }; var addToStart = function (str, prefix) { return prefix + str; }; var addToEnd = function (str, suffix) { return str + suffix; }; var removeFromStart = function (str, numChars) { return str.substring(numChars); }; var removeFromEnd = function (str, numChars) { return str.substring(0, str.length - numChars); }; var $_enj27ovyjh8lz3u7 = { addToStart: addToStart, addToEnd: addToEnd, removeFromStart: removeFromStart, removeFromEnd: removeFromEnd }; var first = function (str, count) { return str.substr(0, count); }; var last$1 = function (str, count) { return str.substr(str.length - count, str.length); }; var head$1 = function (str) { return str === '' ? Option.none() : Option.some(str.substr(0, 1)); }; var tail = function (str) { return str === '' ? Option.none() : Option.some(str.substring(1)); }; var $_49etxbvzjh8lz3u8 = { first: first, last: last$1, head: head$1, tail: tail }; var checkRange = function (str, substr, start) { if (substr === '') return true; if (str.length < substr.length) return false; var x = str.substr(start, start + substr.length); return x === substr; }; var supplant = function (str, obj) { var isStringOrNumber = function (a) { var t = typeof a; return t === 'string' || t === 'number'; }; return str.replace(/\${([^{}]*)}/g, function (a, b) { var value = obj[b]; return isStringOrNumber(value) ? value : a; }); }; var removeLeading = function (str, prefix) { return startsWith(str, prefix) ? $_enj27ovyjh8lz3u7.removeFromStart(str, prefix.length) : str; }; var removeTrailing = function (str, prefix) { return endsWith(str, prefix) ? $_enj27ovyjh8lz3u7.removeFromEnd(str, prefix.length) : str; }; var ensureLeading = function (str, prefix) { return startsWith(str, prefix) ? str : $_enj27ovyjh8lz3u7.addToStart(str, prefix); }; var ensureTrailing = function (str, prefix) { return endsWith(str, prefix) ? str : $_enj27ovyjh8lz3u7.addToEnd(str, prefix); }; var contains$1 = function (str, substr) { return str.indexOf(substr) !== -1; }; var capitalize = function (str) { return $_49etxbvzjh8lz3u8.head(str).bind(function (head) { return $_49etxbvzjh8lz3u8.tail(str).map(function (tail) { return head.toUpperCase() + tail; }); }).getOr(str); }; var startsWith = function (str, prefix) { return checkRange(str, prefix, 0); }; var endsWith = function (str, suffix) { return checkRange(str, suffix, str.length - suffix.length); }; var trim = function (str) { return str.replace(/^\s+|\s+$/g, ''); }; var lTrim = function (str) { return str.replace(/^\s+/g, ''); }; var rTrim = function (str) { return str.replace(/\s+$/g, ''); }; var $_2absfgvxjh8lz3u4 = { supplant: supplant, startsWith: startsWith, removeLeading: removeLeading, removeTrailing: removeTrailing, ensureLeading: ensureLeading, ensureTrailing: ensureTrailing, endsWith: endsWith, contains: contains$1, trim: trim, lTrim: lTrim, rTrim: rTrim, capitalize: capitalize }; var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/; var checkContains = function (target) { return function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, target); }; }; var browsers = [ { name: 'Edge', versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/], search: function (uastring) { var monstrosity = $_2absfgvxjh8lz3u4.contains(uastring, 'edge/') && $_2absfgvxjh8lz3u4.contains(uastring, 'chrome') && $_2absfgvxjh8lz3u4.contains(uastring, 'safari') && $_2absfgvxjh8lz3u4.contains(uastring, 'applewebkit'); return monstrosity; } }, { name: 'Chrome', versionRegexes: [ /.*?chrome\/([0-9]+)\.([0-9]+).*/, normalVersionRegex ], search: function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, 'chrome') && !$_2absfgvxjh8lz3u4.contains(uastring, 'chromeframe'); } }, { name: 'IE', versionRegexes: [ /.*?msie\ ?([0-9]+)\.([0-9]+).*/, /.*?rv:([0-9]+)\.([0-9]+).*/ ], search: function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, 'msie') || $_2absfgvxjh8lz3u4.contains(uastring, 'trident'); } }, { name: 'Opera', versionRegexes: [ normalVersionRegex, /.*?opera\/([0-9]+)\.([0-9]+).*/ ], search: checkContains('opera') }, { name: 'Firefox', versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/], search: checkContains('firefox') }, { name: 'Safari', versionRegexes: [ normalVersionRegex, /.*?cpu os ([0-9]+)_([0-9]+).*/ ], search: function (uastring) { return ($_2absfgvxjh8lz3u4.contains(uastring, 'safari') || $_2absfgvxjh8lz3u4.contains(uastring, 'mobile/')) && $_2absfgvxjh8lz3u4.contains(uastring, 'applewebkit'); } } ]; var oses = [ { name: 'Windows', search: checkContains('win'), versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/] }, { name: 'iOS', search: function (uastring) { return $_2absfgvxjh8lz3u4.contains(uastring, 'iphone') || $_2absfgvxjh8lz3u4.contains(uastring, 'ipad'); }, versionRegexes: [ /.*?version\/\ ?([0-9]+)\.([0-9]+).*/, /.*cpu os ([0-9]+)_([0-9]+).*/, /.*cpu iphone os ([0-9]+)_([0-9]+).*/ ] }, { name: 'Android', search: checkContains('android'), versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/] }, { name: 'OSX', search: checkContains('os x'), versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/] }, { name: 'Linux', search: checkContains('linux'), versionRegexes: [] }, { name: 'Solaris', search: checkContains('sunos'), versionRegexes: [] }, { name: 'FreeBSD', search: checkContains('freebsd'), versionRegexes: [] } ]; var $_dne06dvwjh8lz3ty = { browsers: $_3pjweotejh8lz3k4.constant(browsers), oses: $_3pjweotejh8lz3k4.constant(oses) }; var detect$2 = function (userAgent) { var browsers = $_dne06dvwjh8lz3ty.browsers(); var oses = $_dne06dvwjh8lz3ty.oses(); var browser = $_bvrih8vvjh8lz3tv.detectBrowser(browsers, userAgent).fold($_fidpetvrjh8lz3tj.unknown, $_fidpetvrjh8lz3tj.nu); var os = $_bvrih8vvjh8lz3tv.detectOs(oses, userAgent).fold($_1z8n9kvtjh8lz3to.unknown, $_1z8n9kvtjh8lz3to.nu); var deviceType = DeviceType(os, browser, userAgent); return { browser: browser, os: os, deviceType: deviceType }; }; var $_8gsy8vqjh8lz3ti = { detect: detect$2 }; var detect$3 = $_8me1xevajh8lz3s0.cached(function () { var userAgent = navigator.userAgent; return $_8gsy8vqjh8lz3ti.detect(userAgent); }); var $_2rbkegvpjh8lz3tf = { detect: detect$3 }; var ELEMENT = $_8xkvw6vcjh8lz3s2.ELEMENT; var DOCUMENT = $_8xkvw6vcjh8lz3s2.DOCUMENT; var is = function (element, selector) { var elem = element.dom(); if (elem.nodeType !== ELEMENT) return false; else if (elem.matches !== undefined) return elem.matches(selector); else if (elem.msMatchesSelector !== undefined) return elem.msMatchesSelector(selector); else if (elem.webkitMatchesSelector !== undefined) return elem.webkitMatchesSelector(selector); else if (elem.mozMatchesSelector !== undefined) return elem.mozMatchesSelector(selector); else throw new Error('Browser lacks native selectors'); }; var bypassSelector = function (dom) { return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT || dom.childElementCount === 0; }; var all = function (selector, scope) { var base = scope === undefined ? document : scope.dom(); return bypassSelector(base) ? [] : $_f3qxhzthjh8lz3kg.map(base.querySelectorAll(selector), $_3bkrfxv6jh8lz3rm.fromDom); }; var one = function (selector, scope) { var base = scope === undefined ? document : scope.dom(); return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map($_3bkrfxv6jh8lz3rm.fromDom); }; var $_2nczsvw0jh8lz3ua = { all: all, is: is, one: one }; var eq = function (e1, e2) { return e1.dom() === e2.dom(); }; var isEqualNode = function (e1, e2) { return e1.dom().isEqualNode(e2.dom()); }; var member = function (element, elements) { return $_f3qxhzthjh8lz3kg.exists(elements, $_3pjweotejh8lz3k4.curry(eq, element)); }; var regularContains = function (e1, e2) { var d1 = e1.dom(), d2 = e2.dom(); return d1 === d2 ? false : d1.contains(d2); }; var ieContains = function (e1, e2) { return $_7n27kvvljh8lz3t8.documentPositionContainedBy(e1.dom(), e2.dom()); }; var browser = $_2rbkegvpjh8lz3tf.detect().browser; var contains$2 = browser.isIE() ? ieContains : regularContains; var $_9ypjy6vkjh8lz3sq = { eq: eq, isEqualNode: isEqualNode, member: member, contains: contains$2, is: $_2nczsvw0jh8lz3ua.is }; var owner = function (element) { return $_3bkrfxv6jh8lz3rm.fromDom(element.dom().ownerDocument); }; var documentElement = function (element) { var doc = owner(element); return $_3bkrfxv6jh8lz3rm.fromDom(doc.dom().documentElement); }; var defaultView = function (element) { var el = element.dom(); var defaultView = el.ownerDocument.defaultView; return $_3bkrfxv6jh8lz3rm.fromDom(defaultView); }; var parent = function (element) { var dom = element.dom(); return Option.from(dom.parentNode).map($_3bkrfxv6jh8lz3rm.fromDom); }; var findIndex$1 = function (element) { return parent(element).bind(function (p) { var kin = children(p); return $_f3qxhzthjh8lz3kg.findIndex(kin, function (elem) { return $_9ypjy6vkjh8lz3sq.eq(element, elem); }); }); }; var parents = function (element, isRoot) { var stop = $_d8bie3tijh8lz3kn.isFunction(isRoot) ? isRoot : $_3pjweotejh8lz3k4.constant(false); var dom = element.dom(); var ret = []; while (dom.parentNode !== null && dom.parentNode !== undefined) { var rawParent = dom.parentNode; var parent = $_3bkrfxv6jh8lz3rm.fromDom(rawParent); ret.push(parent); if (stop(parent) === true) break; else dom = rawParent; } return ret; }; var siblings = function (element) { var filterSelf = function (elements) { return $_f3qxhzthjh8lz3kg.filter(elements, function (x) { return !$_9ypjy6vkjh8lz3sq.eq(element, x); }); }; return parent(element).map(children).map(filterSelf).getOr([]); }; var offsetParent = function (element) { var dom = element.dom(); return Option.from(dom.offsetParent).map($_3bkrfxv6jh8lz3rm.fromDom); }; var prevSibling = function (element) { var dom = element.dom(); return Option.from(dom.previousSibling).map($_3bkrfxv6jh8lz3rm.fromDom); }; var nextSibling = function (element) { var dom = element.dom(); return Option.from(dom.nextSibling).map($_3bkrfxv6jh8lz3rm.fromDom); }; var prevSiblings = function (element) { return $_f3qxhzthjh8lz3kg.reverse($_861s8bvjjh8lz3sp.toArray(element, prevSibling)); }; var nextSiblings = function (element) { return $_861s8bvjjh8lz3sp.toArray(element, nextSibling); }; var children = function (element) { var dom = element.dom(); return $_f3qxhzthjh8lz3kg.map(dom.childNodes, $_3bkrfxv6jh8lz3rm.fromDom); }; var child = function (element, index) { var children = element.dom().childNodes; return Option.from(children[index]).map($_3bkrfxv6jh8lz3rm.fromDom); }; var firstChild = function (element) { return child(element, 0); }; var lastChild = function (element) { return child(element, element.dom().childNodes.length - 1); }; var childNodesCount = function (element) { return element.dom().childNodes.length; }; var hasChildNodes = function (element) { return element.dom().hasChildNodes(); }; var spot = $_57mdu6vejh8lz3sg.immutable('element', 'offset'); var leaf = function (element, offset) { var cs = children(element); return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset); }; var $_3jmbxmvdjh8lz3s4 = { owner: owner, defaultView: defaultView, documentElement: documentElement, parent: parent, findIndex: findIndex$1, parents: parents, siblings: siblings, prevSibling: prevSibling, offsetParent: offsetParent, prevSiblings: prevSiblings, nextSibling: nextSibling, nextSiblings: nextSiblings, children: children, child: child, firstChild: firstChild, lastChild: lastChild, childNodesCount: childNodesCount, hasChildNodes: hasChildNodes, leaf: leaf }; var all$1 = function (predicate) { return descendants($_35bizev9jh8lz3rx.body(), predicate); }; var ancestors = function (scope, predicate, isRoot) { return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.parents(scope, isRoot), predicate); }; var siblings$1 = function (scope, predicate) { return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.siblings(scope), predicate); }; var children$1 = function (scope, predicate) { return $_f3qxhzthjh8lz3kg.filter($_3jmbxmvdjh8lz3s4.children(scope), predicate); }; var descendants = function (scope, predicate) { var result = []; $_f3qxhzthjh8lz3kg.each($_3jmbxmvdjh8lz3s4.children(scope), function (x) { if (predicate(x)) { result = result.concat([x]); } result = result.concat(descendants(x, predicate)); }); return result; }; var $_dz5cwuv8jh8lz3rt = { all: all$1, ancestors: ancestors, siblings: siblings$1, children: children$1, descendants: descendants }; var all$2 = function (selector) { return $_2nczsvw0jh8lz3ua.all(selector); }; var ancestors$1 = function (scope, selector, isRoot) { return $_dz5cwuv8jh8lz3rt.ancestors(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }, isRoot); }; var siblings$2 = function (scope, selector) { return $_dz5cwuv8jh8lz3rt.siblings(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var children$2 = function (scope, selector) { return $_dz5cwuv8jh8lz3rt.children(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var descendants$1 = function (scope, selector) { return $_2nczsvw0jh8lz3ua.all(selector, scope); }; var $_am3j0fv7jh8lz3rs = { all: all$2, ancestors: ancestors$1, siblings: siblings$2, children: children$2, descendants: descendants$1 }; var trim$1 = global$2.trim; var hasContentEditableState = function (value) { return function (node) { if (node && node.nodeType === 1) { if (node.contentEditable === value) { return true; } if (node.getAttribute('data-mce-contenteditable') === value) { return true; } } return false; }; }; var isContentEditableTrue = hasContentEditableState('true'); var isContentEditableFalse = hasContentEditableState('false'); var create = function (type, title, url, level, attach) { return { type: type, title: title, url: url, level: level, attach: attach }; }; var isChildOfContentEditableTrue = function (node) { while (node = node.parentNode) { var value = node.contentEditable; if (value && value !== 'inherit') { return isContentEditableTrue(node); } } return false; }; var select = function (selector, root) { return $_f3qxhzthjh8lz3kg.map($_am3j0fv7jh8lz3rs.descendants($_3bkrfxv6jh8lz3rm.fromDom(root), selector), function (element) { return element.dom(); }); }; var getElementText = function (elm) { return elm.innerText || elm.textContent; }; var getOrGenerateId = function (elm) { return elm.id ? elm.id : $_gdeezvv5jh8lz3rl.generate('h'); }; var isAnchor = function (elm) { return elm && elm.nodeName === 'A' && (elm.id || elm.name); }; var isValidAnchor = function (elm) { return isAnchor(elm) && isEditable(elm); }; var isHeader = function (elm) { return elm && /^(H[1-6])$/.test(elm.nodeName); }; var isEditable = function (elm) { return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm); }; var isValidHeader = function (elm) { return isHeader(elm) && isEditable(elm); }; var getLevel = function (elm) { return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0; }; var headerTarget = function (elm) { var headerId = getOrGenerateId(elm); var attach = function () { elm.id = headerId; }; return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach); }; var anchorTarget = function (elm) { var anchorId = elm.id || elm.name; var anchorText = getElementText(elm); return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, $_3pjweotejh8lz3k4.noop); }; var getHeaderTargets = function (elms) { return $_f3qxhzthjh8lz3kg.map($_f3qxhzthjh8lz3kg.filter(elms, isValidHeader), headerTarget); }; var getAnchorTargets = function (elms) { return $_f3qxhzthjh8lz3kg.map($_f3qxhzthjh8lz3kg.filter(elms, isValidAnchor), anchorTarget); }; var getTargetElements = function (elm) { var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm); return elms; }; var hasTitle = function (target) { return trim$1(target.title).length > 0; }; var find$3 = function (elm) { var elms = getTargetElements(elm); return $_f3qxhzthjh8lz3kg.filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle); }; var $_p3wpev4jh8lz3ra = { find: find$3 }; var getActiveEditor = function () { return window.tinymce ? window.tinymce.activeEditor : global$1.activeEditor; }; var history = {}; var HISTORY_LENGTH = 5; var clearHistory = function () { history = {}; }; var toMenuItem = function (target) { return { title: target.title, value: { title: { raw: target.title }, url: target.url, attach: target.attach } }; }; var toMenuItems = function (targets) { return global$2.map(targets, toMenuItem); }; var staticMenuItem = function (title, url) { return { title: title, value: { title: title, url: url, attach: $_3pjweotejh8lz3k4.noop } }; }; var isUniqueUrl = function (url, targets) { var foundTarget = $_f3qxhzthjh8lz3kg.exists(targets, function (target) { return target.url === url; }); return !foundTarget; }; var getSetting = function (editorSettings, name, defaultValue) { var value = name in editorSettings ? editorSettings[name] : defaultValue; return value === false ? null : value; }; var createMenuItems = function (term, targets, fileType, editorSettings) { var separator = { title: '-' }; var fromHistoryMenuItems = function (history) { var historyItems = history.hasOwnProperty(fileType) ? history[fileType] : []; var uniqueHistory = $_f3qxhzthjh8lz3kg.filter(historyItems, function (url) { return isUniqueUrl(url, targets); }); return global$2.map(uniqueHistory, function (url) { return { title: url, value: { title: url, url: url, attach: $_3pjweotejh8lz3k4.noop } }; }); }; var fromMenuItems = function (type) { var filteredTargets = $_f3qxhzthjh8lz3kg.filter(targets, function (target) { return target.type === type; }); return toMenuItems(filteredTargets); }; var anchorMenuItems = function () { var anchorMenuItems = fromMenuItems('anchor'); var topAnchor = getSetting(editorSettings, 'anchor_top', '#top'); var bottomAchor = getSetting(editorSettings, 'anchor_bottom', '#bottom'); if (topAnchor !== null) { anchorMenuItems.unshift(staticMenuItem('<top>', topAnchor)); } if (bottomAchor !== null) { anchorMenuItems.push(staticMenuItem('<bottom>', bottomAchor)); } return anchorMenuItems; }; var join = function (items) { return $_f3qxhzthjh8lz3kg.foldl(items, function (a, b) { var bothEmpty = a.length === 0 || b.length === 0; return bothEmpty ? a.concat(b) : a.concat(separator, b); }, []); }; if (editorSettings.typeahead_urls === false) { return []; } return fileType === 'file' ? join([ filterByQuery(term, fromHistoryMenuItems(history)), filterByQuery(term, fromMenuItems('header')), filterByQuery(term, anchorMenuItems()) ]) : filterByQuery(term, fromHistoryMenuItems(history)); }; var addToHistory = function (url, fileType) { var items = history[fileType]; if (!/^https?/.test(url)) { return; } if (items) { if ($_f3qxhzthjh8lz3kg.indexOf(items, url).isNone()) { history[fileType] = items.slice(0, HISTORY_LENGTH).concat(url); } } else { history[fileType] = [url]; } }; var filterByQuery = function (term, menuItems) { var lowerCaseTerm = term.toLowerCase(); var result = global$2.grep(menuItems, function (item) { return item.title.toLowerCase().indexOf(lowerCaseTerm) !== -1; }); return result.length === 1 && result[0].title === term ? [] : result; }; var getTitle = function (linkDetails) { var title = linkDetails.title; return title.raw ? title.raw : title; }; var setupAutoCompleteHandler = function (ctrl, editorSettings, bodyElm, fileType) { var autocomplete = function (term) { var linkTargets = $_p3wpev4jh8lz3ra.find(bodyElm); var menuItems = createMenuItems(term, linkTargets, fileType, editorSettings); ctrl.showAutoComplete(menuItems, term); }; ctrl.on('autocomplete', function () { autocomplete(ctrl.value()); }); ctrl.on('selectitem', function (e) { var linkDetails = e.value; ctrl.value(linkDetails.url); var title = getTitle(linkDetails); if (fileType === 'image') { ctrl.fire('change', { meta: { alt: title, attach: linkDetails.attach } }); } else { ctrl.fire('change', { meta: { text: title, attach: linkDetails.attach } }); } ctrl.focus(); }); ctrl.on('click', function (e) { if (ctrl.value().length === 0 && e.target.nodeName === 'INPUT') { autocomplete(''); } }); ctrl.on('PostRender', function () { ctrl.getRoot().on('submit', function (e) { if (!e.isDefaultPrevented()) { addToHistory(ctrl.value(), fileType); } }); }); }; var statusToUiState = function (result) { var status = result.status, message = result.message; if (status === 'valid') { return { status: 'ok', message: message }; } else if (status === 'unknown') { return { status: 'warn', message: message }; } else if (status === 'invalid') { return { status: 'warn', message: message }; } else { return { status: 'none', message: '' }; } }; var setupLinkValidatorHandler = function (ctrl, editorSettings, fileType) { var validatorHandler = editorSettings.filepicker_validator_handler; if (validatorHandler) { var validateUrl_1 = function (url) { if (url.length === 0) { ctrl.statusLevel('none'); return; } validatorHandler({ url: url, type: fileType }, function (result) { var uiState = statusToUiState(result); ctrl.statusMessage(uiState.message); ctrl.statusLevel(uiState.status); }); }; ctrl.state.on('change:value', function (e) { validateUrl_1(e.value); }); } }; var FilePicker = ComboBox.extend({ Statics: { clearHistory: clearHistory }, init: function (settings) { var self = this, editor = getActiveEditor(), editorSettings = editor.settings; var actionCallback, fileBrowserCallback, fileBrowserCallbackTypes; var fileType = settings.filetype; settings.spellcheck = false; fileBrowserCallbackTypes = editorSettings.file_picker_types || editorSettings.file_browser_callback_types; if (fileBrowserCallbackTypes) { fileBrowserCallbackTypes = global$2.makeMap(fileBrowserCallbackTypes, /[, ]/); } if (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType]) { fileBrowserCallback = editorSettings.file_picker_callback; if (fileBrowserCallback && (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType])) { actionCallback = function () { var meta = self.fire('beforecall').meta; meta = global$2.extend({ filetype: fileType }, meta); fileBrowserCallback.call(editor, function (value, meta) { self.value(value).fire('change', { meta: meta }); }, self.value(), meta); }; } else { fileBrowserCallback = editorSettings.file_browser_callback; if (fileBrowserCallback && (!fileBrowserCallbackTypes || fileBrowserCallbackTypes[fileType])) { actionCallback = function () { fileBrowserCallback(self.getEl('inp').id, self.value(), fileType, window); }; } } } if (actionCallback) { settings.icon = 'browse'; settings.onaction = actionCallback; } self._super(settings); self.classes.add('filepicker'); setupAutoCompleteHandler(self, editorSettings, editor.getBody(), fileType); setupLinkValidatorHandler(self, editorSettings, fileType); } }); var FitLayout = AbsoluteLayout.extend({ recalc: function (container) { var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox; container.items().filter(':visible').each(function (ctrl) { ctrl.layoutRect({ x: paddingBox.left, y: paddingBox.top, w: contLayoutRect.innerW - paddingBox.right - paddingBox.left, h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom }); if (ctrl.recalc) { ctrl.recalc(); } }); } }); var FlexLayout = AbsoluteLayout.extend({ recalc: function (container) { var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction; var ctrl, ctrlLayoutRect, ctrlSettings, flex; var maxSizeItems = []; var size, maxSize, ratio, rect, pos, maxAlignEndPos; var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, deltaSizeName, contentSizeName; var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignBeforeName, alignAfterName; var alignDeltaSizeName, alignContentSizeName; var max = Math.max, min = Math.min; items = container.items().filter(':visible'); contLayoutRect = container.layoutRect(); contPaddingBox = container.paddingBox; contSettings = container.settings; direction = container.isRtl() ? contSettings.direction || 'row-reversed' : contSettings.direction; align = contSettings.align; pack = container.isRtl() ? contSettings.pack || 'end' : contSettings.pack; spacing = contSettings.spacing || 0; if (direction === 'row-reversed' || direction === 'column-reverse') { items = items.set(items.toArray().reverse()); direction = direction.split('-')[0]; } if (direction === 'column') { posName = 'y'; sizeName = 'h'; minSizeName = 'minH'; maxSizeName = 'maxH'; innerSizeName = 'innerH'; beforeName = 'top'; deltaSizeName = 'deltaH'; contentSizeName = 'contentH'; alignBeforeName = 'left'; alignSizeName = 'w'; alignAxisName = 'x'; alignInnerSizeName = 'innerW'; alignMinSizeName = 'minW'; alignAfterName = 'right'; alignDeltaSizeName = 'deltaW'; alignContentSizeName = 'contentW'; } else { posName = 'x'; sizeName = 'w'; minSizeName = 'minW'; maxSizeName = 'maxW'; innerSizeName = 'innerW'; beforeName = 'left'; deltaSizeName = 'deltaW'; contentSizeName = 'contentW'; alignBeforeName = 'top'; alignSizeName = 'h'; alignAxisName = 'y'; alignInnerSizeName = 'innerH'; alignMinSizeName = 'minH'; alignAfterName = 'bottom'; alignDeltaSizeName = 'deltaH'; alignContentSizeName = 'contentH'; } availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName]; maxAlignEndPos = totalFlex = 0; for (i = 0, l = items.length; i < l; i++) { ctrl = items[i]; ctrlLayoutRect = ctrl.layoutRect(); ctrlSettings = ctrl.settings; flex = ctrlSettings.flex; availableSpace -= i < l - 1 ? spacing : 0; if (flex > 0) { totalFlex += flex; if (ctrlLayoutRect[maxSizeName]) { maxSizeItems.push(ctrl); } ctrlLayoutRect.flex = flex; } availableSpace -= ctrlLayoutRect[minSizeName]; size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName]; if (size > maxAlignEndPos) { maxAlignEndPos = size; } } rect = {}; if (availableSpace < 0) { rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName]; } else { rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName]; } rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName]; rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace; rect[alignContentSizeName] = maxAlignEndPos; rect.minW = min(rect.minW, contLayoutRect.maxW); rect.minH = min(rect.minH, contLayoutRect.maxH); rect.minW = max(rect.minW, contLayoutRect.startMinWidth); rect.minH = max(rect.minH, contLayoutRect.startMinHeight); if (contLayoutRect.autoResize && (rect.minW !== contLayoutRect.minW || rect.minH !== contLayoutRect.minH)) { rect.w = rect.minW; rect.h = rect.minH; container.layoutRect(rect); this.recalc(container); if (container._lastRect === null) { var parentCtrl = container.parent(); if (parentCtrl) { parentCtrl._lastRect = null; parentCtrl.recalc(); } } return; } ratio = availableSpace / totalFlex; for (i = 0, l = maxSizeItems.length; i < l; i++) { ctrl = maxSizeItems[i]; ctrlLayoutRect = ctrl.layoutRect(); maxSize = ctrlLayoutRect[maxSizeName]; size = ctrlLayoutRect[minSizeName] + ctrlLayoutRect.flex * ratio; if (size > maxSize) { availableSpace -= ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName]; totalFlex -= ctrlLayoutRect.flex; ctrlLayoutRect.flex = 0; ctrlLayoutRect.maxFlexSize = maxSize; } else { ctrlLayoutRect.maxFlexSize = 0; } } ratio = availableSpace / totalFlex; pos = contPaddingBox[beforeName]; rect = {}; if (totalFlex === 0) { if (pack === 'end') { pos = availableSpace + contPaddingBox[beforeName]; } else if (pack === 'center') { pos = Math.round(contLayoutRect[innerSizeName] / 2 - (contLayoutRect[innerSizeName] - availableSpace) / 2) + contPaddingBox[beforeName]; if (pos < 0) { pos = contPaddingBox[beforeName]; } } else if (pack === 'justify') { pos = contPaddingBox[beforeName]; spacing = Math.floor(availableSpace / (items.length - 1)); } } rect[alignAxisName] = contPaddingBox[alignBeforeName]; for (i = 0, l = items.length; i < l; i++) { ctrl = items[i]; ctrlLayoutRect = ctrl.layoutRect(); size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName]; if (align === 'center') { rect[alignAxisName] = Math.round(contLayoutRect[alignInnerSizeName] / 2 - ctrlLayoutRect[alignSizeName] / 2); } else if (align === 'stretch') { rect[alignSizeName] = max(ctrlLayoutRect[alignMinSizeName] || 0, contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName]); rect[alignAxisName] = contPaddingBox[alignBeforeName]; } else if (align === 'end') { rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top; } if (ctrlLayoutRect.flex > 0) { size += ctrlLayoutRect.flex * ratio; } rect[sizeName] = size; rect[posName] = pos; ctrl.layoutRect(rect); if (ctrl.recalc) { ctrl.recalc(); } pos += size + spacing; } } }); var FlowLayout = Layout.extend({ Defaults: { containerClass: 'flow-layout', controlClass: 'flow-layout-item', endClass: 'break' }, recalc: function (container) { container.items().filter(':visible').each(function (ctrl) { if (ctrl.recalc) { ctrl.recalc(); } }); }, isNative: function () { return true; } }); function ClosestOrAncestor (is, ancestor, scope, a, isRoot) { return is(scope, a) ? Option.some(scope) : $_d8bie3tijh8lz3kn.isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot); } var first$1 = function (predicate) { return descendant($_35bizev9jh8lz3rx.body(), predicate); }; var ancestor = function (scope, predicate, isRoot) { var element = scope.dom(); var stop = $_d8bie3tijh8lz3kn.isFunction(isRoot) ? isRoot : $_3pjweotejh8lz3k4.constant(false); while (element.parentNode) { element = element.parentNode; var el = $_3bkrfxv6jh8lz3rm.fromDom(element); if (predicate(el)) return Option.some(el); else if (stop(el)) break; } return Option.none(); }; var closest = function (scope, predicate, isRoot) { var is = function (scope) { return predicate(scope); }; return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot); }; var sibling = function (scope, predicate) { var element = scope.dom(); if (!element.parentNode) return Option.none(); return child$1($_3bkrfxv6jh8lz3rm.fromDom(element.parentNode), function (x) { return !$_9ypjy6vkjh8lz3sq.eq(scope, x) && predicate(x); }); }; var child$1 = function (scope, predicate) { var result = $_f3qxhzthjh8lz3kg.find(scope.dom().childNodes, $_3pjweotejh8lz3k4.compose(predicate, $_3bkrfxv6jh8lz3rm.fromDom)); return result.map($_3bkrfxv6jh8lz3rm.fromDom); }; var descendant = function (scope, predicate) { var descend = function (element) { for (var i = 0; i < element.childNodes.length; i++) { if (predicate($_3bkrfxv6jh8lz3rm.fromDom(element.childNodes[i]))) return Option.some($_3bkrfxv6jh8lz3rm.fromDom(element.childNodes[i])); var res = descend(element.childNodes[i]); if (res.isSome()) return res; } return Option.none(); }; return descend(scope.dom()); }; var $_5a72sw6jh8lz3uv = { first: first$1, ancestor: ancestor, closest: closest, sibling: sibling, child: child$1, descendant: descendant }; var first$2 = function (selector) { return $_2nczsvw0jh8lz3ua.one(selector); }; var ancestor$1 = function (scope, selector, isRoot) { return $_5a72sw6jh8lz3uv.ancestor(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }, isRoot); }; var sibling$1 = function (scope, selector) { return $_5a72sw6jh8lz3uv.sibling(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var child$2 = function (scope, selector) { return $_5a72sw6jh8lz3uv.child(scope, function (e) { return $_2nczsvw0jh8lz3ua.is(e, selector); }); }; var descendant$1 = function (scope, selector) { return $_2nczsvw0jh8lz3ua.one(selector, scope); }; var closest$1 = function (scope, selector, isRoot) { return ClosestOrAncestor($_2nczsvw0jh8lz3ua.is, ancestor$1, scope, selector, isRoot); }; var $_9rr9rgw5jh8lz3uu = { first: first$2, ancestor: ancestor$1, sibling: sibling$1, child: child$2, descendant: descendant$1, closest: closest$1 }; var toggleFormat = function (editor, fmt) { return function () { editor.execCommand('mceToggleFormat', false, fmt); }; }; var addFormatChangedListener = function (editor, name, changed) { var handler = function (state) { changed(state, name); }; if (editor.formatter) { editor.formatter.formatChanged(name, handler); } else { editor.on('init', function () { editor.formatter.formatChanged(name, handler); }); } }; var postRenderFormatToggle = function (editor, name) { return function (e) { addFormatChangedListener(editor, name, function (state) { e.control.active(state); }); }; }; var register = function (editor) { var alignFormats = [ 'alignleft', 'aligncenter', 'alignright', 'alignjustify' ]; var defaultAlign = 'alignleft'; var alignMenuItems = [ { text: 'Left', icon: 'alignleft', onclick: toggleFormat(editor, 'alignleft') }, { text: 'Center', icon: 'aligncenter', onclick: toggleFormat(editor, 'aligncenter') }, { text: 'Right', icon: 'alignright', onclick: toggleFormat(editor, 'alignright') }, { text: 'Justify', icon: 'alignjustify', onclick: toggleFormat(editor, 'alignjustify') } ]; editor.addMenuItem('align', { text: 'Align', menu: alignMenuItems }); editor.addButton('align', { type: 'menubutton', icon: defaultAlign, menu: alignMenuItems, onShowMenu: function (e) { var menu = e.control.menu; global$2.each(alignFormats, function (formatName, idx) { menu.items().eq(idx).each(function (item) { return item.active(editor.formatter.match(formatName)); }); }); }, onPostRender: function (e) { var ctrl = e.control; global$2.each(alignFormats, function (formatName, idx) { addFormatChangedListener(editor, formatName, function (state) { ctrl.icon(defaultAlign); if (state) { ctrl.icon(formatName); } }); }); } }); global$2.each({ alignleft: [ 'Align left', 'JustifyLeft' ], aligncenter: [ 'Align center', 'JustifyCenter' ], alignright: [ 'Align right', 'JustifyRight' ], alignjustify: [ 'Justify', 'JustifyFull' ], alignnone: [ 'No alignment', 'JustifyNone' ] }, function (item, name) { editor.addButton(name, { active: false, tooltip: item[0], cmd: item[1], onPostRender: postRenderFormatToggle(editor, name) }); }); }; var $_a6x5k4w8jh8lz3vh = { register: register }; var getFirstFont = function (fontFamily) { return fontFamily ? fontFamily.split(',')[0] : ''; }; var findMatchingValue = function (items, fontFamily) { var font = fontFamily ? fontFamily.toLowerCase() : ''; var value; global$2.each(items, function (item) { if (item.value.toLowerCase() === font) { value = item.value; } }); global$2.each(items, function (item) { if (!value && getFirstFont(item.value).toLowerCase() === getFirstFont(font).toLowerCase()) { value = item.value; } }); return value; }; var createFontNameListBoxChangeHandler = function (editor, items) { return function () { var self = this; editor.on('init nodeChange', function (e) { var fontFamily = editor.queryCommandValue('FontName'); var match = findMatchingValue(items, fontFamily); self.value(match ? match : null); if (!match && fontFamily) { self.text(getFirstFont(fontFamily)); } }); }; }; var createFormats = function (formats) { formats = formats.replace(/;$/, '').split(';'); var i = formats.length; while (i--) { formats[i] = formats[i].split('='); } return formats; }; var getFontItems = function (editor) { var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats'; var fonts = createFormats(editor.settings.font_formats || defaultFontsFormats); return global$2.map(fonts, function (font) { return { text: { raw: font[0] }, value: font[1], textStyle: font[1].indexOf('dings') === -1 ? 'font-family:' + font[1] : '' }; }); }; var registerButtons = function (editor) { editor.addButton('fontselect', function () { var items = getFontItems(editor); return { type: 'listbox', text: 'Font Family', tooltip: 'Font Family', values: items, fixedWidth: true, onPostRender: createFontNameListBoxChangeHandler(editor, items), onselect: function (e) { if (e.control.settings.value) { editor.execCommand('FontName', false, e.control.settings.value); } } }; }); }; var register$1 = function (editor) { registerButtons(editor); }; var $_4hdsyewajh8lz3vk = { register: register$1 }; var round = function (number, precision) { var factor = Math.pow(10, precision); return Math.round(number * factor) / factor; }; var toPt = function (fontSize, precision) { if (/[0-9.]+px$/.test(fontSize)) { return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt'; } return fontSize; }; var findMatchingValue$1 = function (items, pt, px) { var value; global$2.each(items, function (item) { if (item.value === px) { value = px; } else if (item.value === pt) { value = pt; } }); return value; }; var createFontSizeListBoxChangeHandler = function (editor, items) { return function () { var self = this; editor.on('init nodeChange', function (e) { var px, pt, precision, match; px = editor.queryCommandValue('FontSize'); if (px) { for (precision = 3; !match && precision >= 0; precision--) { pt = toPt(px, precision); match = findMatchingValue$1(items, pt, px); } } self.value(match ? match : null); if (!match) { self.text(pt); } }); }; }; var getFontSizeItems = function (editor) { var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt'; var fontsizeFormats = editor.settings.fontsize_formats || defaultFontsizeFormats; return global$2.map(fontsizeFormats.split(' '), function (item) { var text = item, value = item; var values = item.split('='); if (values.length > 1) { text = values[0]; value = values[1]; } return { text: text, value: value }; }); }; var registerButtons$1 = function (editor) { editor.addButton('fontsizeselect', function () { var items = getFontSizeItems(editor); return { type: 'listbox', text: 'Font Sizes', tooltip: 'Font Sizes', values: items, fixedWidth: true, onPostRender: createFontSizeListBoxChangeHandler(editor, items), onclick: function (e) { if (e.control.settings.value) { editor.execCommand('FontSize', false, e.control.settings.value); } } }; }); }; var register$2 = function (editor) { registerButtons$1(editor); }; var $_du9atdwbjh8lz3vn = { register: register$2 }; var hideMenuObjects = function (editor, menu) { var count = menu.length; global$2.each(menu, function (item) { if (item.menu) { item.hidden = hideMenuObjects(editor, item.menu) === 0; } var formatName = item.format; if (formatName) { item.hidden = !editor.formatter.canApply(formatName); } if (item.hidden) { count--; } }); return count; }; var hideFormatMenuItems = function (editor, menu) { var count = menu.items().length; menu.items().each(function (item) { if (item.menu) { item.visible(hideFormatMenuItems(editor, item.menu) > 0); } if (!item.menu && item.settings.menu) { item.visible(hideMenuObjects(editor, item.settings.menu) > 0); } var formatName = item.settings.format; if (formatName) { item.visible(editor.formatter.canApply(formatName)); } if (!item.visible()) { count--; } }); return count; }; var createFormatMenu = function (editor) { var count = 0; var newFormats = []; var defaultStyleFormats = [ { title: 'Headings', items: [ { title: 'Heading 1', format: 'h1' }, { title: 'Heading 2', format: 'h2' }, { title: 'Heading 3', format: 'h3' }, { title: 'Heading 4', format: 'h4' }, { title: 'Heading 5', format: 'h5' }, { title: 'Heading 6', format: 'h6' } ] }, { title: 'Inline', items: [ { title: 'Bold', icon: 'bold', format: 'bold' }, { title: 'Italic', icon: 'italic', format: 'italic' }, { title: 'Underline', icon: 'underline', format: 'underline' }, { title: 'Strikethrough', icon: 'strikethrough', format: 'strikethrough' }, { title: 'Superscript', icon: 'superscript', format: 'superscript' }, { title: 'Subscript', icon: 'subscript', format: 'subscript' }, { title: 'Code', icon: 'code', format: 'code' } ] }, { title: 'Blocks', items: [ { title: 'Paragraph', format: 'p' }, { title: 'Blockquote', format: 'blockquote' }, { title: 'Div', format: 'div' }, { title: 'Pre', format: 'pre' } ] }, { title: 'Alignment', items: [ { title: 'Left', icon: 'alignleft', format: 'alignleft' }, { title: 'Center', icon: 'aligncenter', format: 'aligncenter' }, { title: 'Right', icon: 'alignright', format: 'alignright' }, { title: 'Justify', icon: 'alignjustify', format: 'alignjustify' } ] } ]; var createMenu = function (formats) { var menu = []; if (!formats) { return; } global$2.each(formats, function (format) { var menuItem = { text: format.title, icon: format.icon }; if (format.items) { menuItem.menu = createMenu(format.items); } else { var formatName = format.format || 'custom' + count++; if (!format.format) { format.name = formatName; newFormats.push(format); } menuItem.format = formatName; menuItem.cmd = format.cmd; } menu.push(menuItem); }); return menu; }; var createStylesMenu = function () { var menu; if (editor.settings.style_formats_merge) { if (editor.settings.style_formats) { menu = createMenu(defaultStyleFormats.concat(editor.settings.style_formats)); } else { menu = createMenu(defaultStyleFormats); } } else { menu = createMenu(editor.settings.style_formats || defaultStyleFormats); } return menu; }; editor.on('init', function () { global$2.each(newFormats, function (format) { editor.formatter.register(format.name, format); }); }); return { type: 'menu', items: createStylesMenu(), onPostRender: function (e) { editor.fire('renderFormatsMenu', { control: e.control }); }, itemDefaults: { preview: true, textStyle: function () { if (this.settings.format) { return editor.formatter.getCssText(this.settings.format); } }, onPostRender: function () { var self = this; self.parent().on('show', function () { var formatName, command; formatName = self.settings.format; if (formatName) { self.disabled(!editor.formatter.canApply(formatName)); self.active(editor.formatter.match(formatName)); } command = self.settings.cmd; if (command) { self.active(editor.queryCommandState(command)); } }); }, onclick: function () { if (this.settings.format) { toggleFormat(editor, this.settings.format)(); } if (this.settings.cmd) { editor.execCommand(this.settings.cmd); } } } }; }; var registerMenuItems = function (editor, formatMenu) { editor.addMenuItem('formats', { text: 'Formats', menu: formatMenu }); }; var registerButtons$2 = function (editor, formatMenu) { editor.addButton('styleselect', { type: 'menubutton', text: 'Formats', menu: formatMenu, onShowMenu: function () { if (editor.settings.style_formats_autohide) { hideFormatMenuItems(editor, this.menu); } } }); }; var register$3 = function (editor) { var formatMenu = createFormatMenu(editor); registerMenuItems(editor, formatMenu); registerButtons$2(editor, formatMenu); }; var $_5xlhbcwcjh8lz3vr = { register: register$3 }; var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre'; var createFormats$1 = function (formats) { formats = formats.replace(/;$/, '').split(';'); var i = formats.length; while (i--) { formats[i] = formats[i].split('='); } return formats; }; var createListBoxChangeHandler = function (editor, items, formatName) { return function () { var self = this; editor.on('nodeChange', function (e) { var formatter = editor.formatter; var value = null; global$2.each(e.parents, function (node) { global$2.each(items, function (item) { if (formatName) { if (formatter.matchNode(node, formatName, { value: item.value })) { value = item.value; } } else { if (formatter.matchNode(node, item.value)) { value = item.value; } } if (value) { return false; } }); if (value) { return false; } }); self.value(value); }); }; }; var lazyFormatSelectBoxItems = function (editor, blocks) { return function () { var items = []; global$2.each(blocks, function (block) { items.push({ text: block[0], value: block[1], textStyle: function () { return editor.formatter.getCssText(block[1]); } }); }); return { type: 'listbox', text: blocks[0][0], values: items, fixedWidth: true, onselect: function (e) { if (e.control) { var fmt = e.control.value(); toggleFormat(editor, fmt)(); } }, onPostRender: createListBoxChangeHandler(editor, items) }; }; }; var buildMenuItems = function (editor, blocks) { return global$2.map(blocks, function (block) { return { text: block[0], onclick: toggleFormat(editor, block[1]), textStyle: function () { return editor.formatter.getCssText(block[1]); } }; }); }; var register$4 = function (editor) { var blocks = createFormats$1(editor.settings.block_formats || defaultBlocks); editor.addMenuItem('blockformats', { text: 'Blocks', menu: buildMenuItems(editor, blocks) }); editor.addButton('formatselect', lazyFormatSelectBoxItems(editor, blocks)); }; var $_bj8nxmwdjh8lz3vw = { register: register$4 }; var createCustomMenuItems = function (editor, names) { var items, nameList; if (typeof names === 'string') { nameList = names.split(' '); } else if (global$2.isArray(names)) { return $_f3qxhzthjh8lz3kg.flatten(global$2.map(names, function (names) { return createCustomMenuItems(editor, names); })); } items = global$2.grep(nameList, function (name) { return name === '|' || name in editor.menuItems; }); return global$2.map(items, function (name) { return name === '|' ? { text: '-' } : editor.menuItems[name]; }); }; var isSeparator$1 = function (menuItem) { return menuItem && menuItem.text === '-'; }; var trimMenuItems = function (menuItems) { var menuItems2 = $_f3qxhzthjh8lz3kg.filter(menuItems, function (menuItem, i, menuItems) { return !isSeparator$1(menuItem) || !isSeparator$1(menuItems[i - 1]); }); return $_f3qxhzthjh8lz3kg.filter(menuItems2, function (menuItem, i, menuItems) { return !isSeparator$1(menuItem) || i > 0 && i < menuItems.length - 1; }); }; var createContextMenuItems = function (editor, context) { var outputMenuItems = [{ text: '-' }]; var menuItems = global$2.grep(editor.menuItems, function (menuItem) { return menuItem.context === context; }); global$2.each(menuItems, function (menuItem) { if (menuItem.separator === 'before') { outputMenuItems.push({ text: '|' }); } if (menuItem.prependToContext) { outputMenuItems.unshift(menuItem); } else { outputMenuItems.push(menuItem); } if (menuItem.separator === 'after') { outputMenuItems.push({ text: '|' }); } }); return outputMenuItems; }; var createInsertMenu = function (editor) { var insertButtonItems = editor.settings.insert_button_items; if (insertButtonItems) { return trimMenuItems(createCustomMenuItems(editor, insertButtonItems)); } else { return trimMenuItems(createContextMenuItems(editor, 'insert')); } }; var registerButtons$3 = function (editor) { editor.addButton('insert', { type: 'menubutton', icon: 'insert', menu: [], oncreatemenu: function () { this.menu.add(createInsertMenu(editor)); this.menu.renderNew(); } }); }; var register$5 = function (editor) { registerButtons$3(editor); }; var $_drvzmkwejh8lz3vz = { register: register$5 }; var registerFormatButtons = function (editor) { global$2.each({ bold: 'Bold', italic: 'Italic', underline: 'Underline', strikethrough: 'Strikethrough', subscript: 'Subscript', superscript: 'Superscript' }, function (text, name) { editor.addButton(name, { active: false, tooltip: text, onPostRender: postRenderFormatToggle(editor, name), onclick: toggleFormat(editor, name) }); }); }; var registerCommandButtons = function (editor) { global$2.each({ outdent: [ 'Decrease indent', 'Outdent' ], indent: [ 'Increase indent', 'Indent' ], cut: [ 'Cut', 'Cut' ], copy: [ 'Copy', 'Copy' ], paste: [ 'Paste', 'Paste' ], help: [ 'Help', 'mceHelp' ], selectall: [ 'Select all', 'SelectAll' ], visualaid: [ 'Visual aids', 'mceToggleVisualAid' ], newdocument: [ 'New document', 'mceNewDocument' ], removeformat: [ 'Clear formatting', 'RemoveFormat' ], remove: [ 'Remove', 'Delete' ] }, function (item, name) { editor.addButton(name, { tooltip: item[0], cmd: item[1] }); }); }; var registerCommandToggleButtons = function (editor) { global$2.each({ blockquote: [ 'Blockquote', 'mceBlockQuote' ], subscript: [ 'Subscript', 'Subscript' ], superscript: [ 'Superscript', 'Superscript' ] }, function (item, name) { editor.addButton(name, { active: false, tooltip: item[0], cmd: item[1], onPostRender: postRenderFormatToggle(editor, name) }); }); }; var registerButtons$4 = function (editor) { registerFormatButtons(editor); registerCommandButtons(editor); registerCommandToggleButtons(editor); }; var registerMenuItems$1 = function (editor) { global$2.each({ bold: [ 'Bold', 'Bold', 'Meta+B' ], italic: [ 'Italic', 'Italic', 'Meta+I' ], underline: [ 'Underline', 'Underline', 'Meta+U' ], strikethrough: [ 'Strikethrough', 'Strikethrough' ], subscript: [ 'Subscript', 'Subscript' ], superscript: [ 'Superscript', 'Superscript' ], removeformat: [ 'Clear formatting', 'RemoveFormat' ], newdocument: [ 'New document', 'mceNewDocument' ], cut: [ 'Cut', 'Cut', 'Meta+X' ], copy: [ 'Copy', 'Copy', 'Meta+C' ], paste: [ 'Paste', 'Paste', 'Meta+V' ], selectall: [ 'Select all', 'SelectAll', 'Meta+A' ] }, function (item, name) { editor.addMenuItem(name, { text: item[0], icon: name, shortcut: item[2], cmd: item[1] }); }); editor.addMenuItem('codeformat', { text: 'Code', icon: 'code', onclick: toggleFormat(editor, 'code') }); }; var register$6 = function (editor) { registerButtons$4(editor); registerMenuItems$1(editor); }; var $_2d67dwfjh8lz3w2 = { register: register$6 }; var toggleUndoRedoState = function (editor, type) { return function () { var self = this; var checkState = function () { var typeFn = type === 'redo' ? 'hasRedo' : 'hasUndo'; return editor.undoManager ? editor.undoManager[typeFn]() : false; }; self.disabled(!checkState()); editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', function () { self.disabled(editor.readonly || !checkState()); }); }; }; var registerMenuItems$2 = function (editor) { editor.addMenuItem('undo', { text: 'Undo', icon: 'undo', shortcut: 'Meta+Z', onPostRender: toggleUndoRedoState(editor, 'undo'), cmd: 'undo' }); editor.addMenuItem('redo', { text: 'Redo', icon: 'redo', shortcut: 'Meta+Y', onPostRender: toggleUndoRedoState(editor, 'redo'), cmd: 'redo' }); }; var registerButtons$5 = function (editor) { editor.addButton('undo', { tooltip: 'Undo', onPostRender: toggleUndoRedoState(editor, 'undo'), cmd: 'undo' }); editor.addButton('redo', { tooltip: 'Redo', onPostRender: toggleUndoRedoState(editor, 'redo'), cmd: 'redo' }); }; var register$7 = function (editor) { registerMenuItems$2(editor); registerButtons$5(editor); }; var $_cd5m9xwgjh8lz3w5 = { register: register$7 }; var toggleVisualAidState = function (editor) { return function () { var self = this; editor.on('VisualAid', function (e) { self.active(e.hasVisual); }); self.active(editor.hasVisual); }; }; var registerMenuItems$3 = function (editor) { editor.addMenuItem('visualaid', { text: 'Visual aids', selectable: true, onPostRender: toggleVisualAidState(editor), cmd: 'mceToggleVisualAid' }); }; var register$8 = function (editor) { registerMenuItems$3(editor); }; var $_1ojpofwhjh8lz3w6 = { register: register$8 }; var setupEnvironment = function () { Widget.tooltips = !global$8.iOS; Control$1.translate = function (text) { return global$1.translate(text); }; }; var setupUiContainer = function (editor) { if (editor.settings.ui_container) { global$8.container = $_9rr9rgw5jh8lz3uu.descendant($_3bkrfxv6jh8lz3rm.fromDom(document.body), editor.settings.ui_container).fold($_3pjweotejh8lz3k4.constant(null), function (elm) { return elm.dom(); }); } }; var setupRtlMode = function (editor) { if (editor.rtl) { Control$1.rtl = true; } }; var setupHideFloatPanels = function (editor) { editor.on('mousedown', function () { FloatPanel.hideAll(); }); }; var setup$1 = function (editor) { setupRtlMode(editor); setupHideFloatPanels(editor); setupUiContainer(editor); setupEnvironment(); $_bj8nxmwdjh8lz3vw.register(editor); $_a6x5k4w8jh8lz3vh.register(editor); $_2d67dwfjh8lz3w2.register(editor); $_cd5m9xwgjh8lz3w5.register(editor); $_du9atdwbjh8lz3vn.register(editor); $_4hdsyewajh8lz3vk.register(editor); $_5xlhbcwcjh8lz3vr.register(editor); $_1ojpofwhjh8lz3w6.register(editor); $_drvzmkwejh8lz3vz.register(editor); }; var $_4qdht3w4jh8lz3uo = { setup: setup$1 }; var GridLayout = AbsoluteLayout.extend({ recalc: function (container) { var settings, rows, cols, items, contLayoutRect, width, height, rect, ctrlLayoutRect, ctrl, x, y, posX, posY, ctrlSettings, contPaddingBox, align, spacingH, spacingV, alignH, alignV, maxX, maxY; var colWidths = []; var rowHeights = []; var ctrlMinWidth, ctrlMinHeight, availableWidth, availableHeight, reverseRows, idx; settings = container.settings; items = container.items().filter(':visible'); contLayoutRect = container.layoutRect(); cols = settings.columns || Math.ceil(Math.sqrt(items.length)); rows = Math.ceil(items.length / cols); spacingH = settings.spacingH || settings.spacing || 0; spacingV = settings.spacingV || settings.spacing || 0; alignH = settings.alignH || settings.align; alignV = settings.alignV || settings.align; contPaddingBox = container.paddingBox; reverseRows = 'reverseRows' in settings ? settings.reverseRows : container.isRtl(); if (alignH && typeof alignH === 'string') { alignH = [alignH]; } if (alignV && typeof alignV === 'string') { alignV = [alignV]; } for (x = 0; x < cols; x++) { colWidths.push(0); } for (y = 0; y < rows; y++) { rowHeights.push(0); } for (y = 0; y < rows; y++) { for (x = 0; x < cols; x++) { ctrl = items[y * cols + x]; if (!ctrl) { break; } ctrlLayoutRect = ctrl.layoutRect(); ctrlMinWidth = ctrlLayoutRect.minW; ctrlMinHeight = ctrlLayoutRect.minH; colWidths[x] = ctrlMinWidth > colWidths[x] ? ctrlMinWidth : colWidths[x]; rowHeights[y] = ctrlMinHeight > rowHeights[y] ? ctrlMinHeight : rowHeights[y]; } } availableWidth = contLayoutRect.innerW - contPaddingBox.left - contPaddingBox.right; for (maxX = 0, x = 0; x < cols; x++) { maxX += colWidths[x] + (x > 0 ? spacingH : 0); availableWidth -= (x > 0 ? spacingH : 0) + colWidths[x]; } availableHeight = contLayoutRect.innerH - contPaddingBox.top - contPaddingBox.bottom; for (maxY = 0, y = 0; y < rows; y++) { maxY += rowHeights[y] + (y > 0 ? spacingV : 0); availableHeight -= (y > 0 ? spacingV : 0) + rowHeights[y]; } maxX += contPaddingBox.left + contPaddingBox.right; maxY += contPaddingBox.top + contPaddingBox.bottom; rect = {}; rect.minW = maxX + (contLayoutRect.w - contLayoutRect.innerW); rect.minH = maxY + (contLayoutRect.h - contLayoutRect.innerH); rect.contentW = rect.minW - contLayoutRect.deltaW; rect.contentH = rect.minH - contLayoutRect.deltaH; rect.minW = Math.min(rect.minW, contLayoutRect.maxW); rect.minH = Math.min(rect.minH, contLayoutRect.maxH); rect.minW = Math.max(rect.minW, contLayoutRect.startMinWidth); rect.minH = Math.max(rect.minH, contLayoutRect.startMinHeight); if (contLayoutRect.autoResize && (rect.minW !== contLayoutRect.minW || rect.minH !== contLayoutRect.minH)) { rect.w = rect.minW; rect.h = rect.minH; container.layoutRect(rect); this.recalc(container); if (container._lastRect === null) { var parentCtrl = container.parent(); if (parentCtrl) { parentCtrl._lastRect = null; parentCtrl.recalc(); } } return; } if (contLayoutRect.autoResize) { rect = container.layoutRect(rect); rect.contentW = rect.minW - contLayoutRect.deltaW; rect.contentH = rect.minH - contLayoutRect.deltaH; } var flexV; if (settings.packV === 'start') { flexV = 0; } else { flexV = availableHeight > 0 ? Math.floor(availableHeight / rows) : 0; } var totalFlex = 0; var flexWidths = settings.flexWidths; if (flexWidths) { for (x = 0; x < flexWidths.length; x++) { totalFlex += flexWidths[x]; } } else { totalFlex = cols; } var ratio = availableWidth / totalFlex; for (x = 0; x < cols; x++) { colWidths[x] += flexWidths ? flexWidths[x] * ratio : ratio; } posY = contPaddingBox.top; for (y = 0; y < rows; y++) { posX = contPaddingBox.left; height = rowHeights[y] + flexV; for (x = 0; x < cols; x++) { if (reverseRows) { idx = y * cols + cols - 1 - x; } else { idx = y * cols + x; } ctrl = items[idx]; if (!ctrl) { break; } ctrlSettings = ctrl.settings; ctrlLayoutRect = ctrl.layoutRect(); width = Math.max(colWidths[x], ctrlLayoutRect.startMinWidth); ctrlLayoutRect.x = posX; ctrlLayoutRect.y = posY; align = ctrlSettings.alignH || (alignH ? alignH[x] || alignH[0] : null); if (align === 'center') { ctrlLayoutRect.x = posX + width / 2 - ctrlLayoutRect.w / 2; } else if (align === 'right') { ctrlLayoutRect.x = posX + width - ctrlLayoutRect.w; } else if (align === 'stretch') { ctrlLayoutRect.w = width; } align = ctrlSettings.alignV || (alignV ? alignV[x] || alignV[0] : null); if (align === 'center') { ctrlLayoutRect.y = posY + height / 2 - ctrlLayoutRect.h / 2; } else if (align === 'bottom') { ctrlLayoutRect.y = posY + height - ctrlLayoutRect.h; } else if (align === 'stretch') { ctrlLayoutRect.h = height; } ctrl.layoutRect(ctrlLayoutRect); posX += width + spacingH; if (ctrl.recalc) { ctrl.recalc(); } } posY += height + spacingV; } } }); var Iframe$1 = Widget.extend({ renderHtml: function () { var self = this; self.classes.add('iframe'); self.canFocus = false; return '<iframe id="' + self._id + '" class="' + self.classes + '" tabindex="-1" src="' + (self.settings.url || 'javascript:\'\'') + '" frameborder="0"></iframe>'; }, src: function (src) { this.getEl().src = src; }, html: function (html, callback) { var self = this, body = this.getEl().contentWindow.document.body; if (!body) { global$7.setTimeout(function () { self.html(html); }); } else { body.innerHTML = html; if (callback) { callback(); } } return this; } }); var InfoBox = Widget.extend({ init: function (settings) { var self = this; self._super(settings); self.classes.add('widget').add('infobox'); self.canFocus = false; }, severity: function (level) { this.classes.remove('error'); this.classes.remove('warning'); this.classes.remove('success'); this.classes.add(level); }, help: function (state) { this.state.set('help', state); }, renderHtml: function () { var self = this, prefix = self.classPrefix; return '<div id="' + self._id + '" class="' + self.classes + '">' + '<div id="' + self._id + '-body">' + self.encode(self.state.get('text')) + '<button role="button" tabindex="-1">' + '<i class="' + prefix + 'ico ' + prefix + 'i-help"></i>' + '</button>' + '</div>' + '</div>'; }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.getEl('body').firstChild.data = self.encode(e.value); if (self.state.get('rendered')) { self.updateLayoutRect(); } }); self.state.on('change:help', function (e) { self.classes.toggle('has-help', e.value); if (self.state.get('rendered')) { self.updateLayoutRect(); } }); return self._super(); } }); var Label = Widget.extend({ init: function (settings) { var self = this; self._super(settings); self.classes.add('widget').add('label'); self.canFocus = false; if (settings.multiline) { self.classes.add('autoscroll'); } if (settings.strong) { self.classes.add('strong'); } }, initLayoutRect: function () { var self = this, layoutRect = self._super(); if (self.settings.multiline) { var size = funcs.getSize(self.getEl()); if (size.width > layoutRect.maxW) { layoutRect.minW = layoutRect.maxW; self.classes.add('multiline'); } self.getEl().style.width = layoutRect.minW + 'px'; layoutRect.startMinH = layoutRect.h = layoutRect.minH = Math.min(layoutRect.maxH, funcs.getSize(self.getEl()).height); } return layoutRect; }, repaint: function () { var self = this; if (!self.settings.multiline) { self.getEl().style.lineHeight = self.layoutRect().h + 'px'; } return self._super(); }, severity: function (level) { this.classes.remove('error'); this.classes.remove('warning'); this.classes.remove('success'); this.classes.add(level); }, renderHtml: function () { var self = this; var targetCtrl, forName, forId = self.settings.forId; var text = self.settings.html ? self.settings.html : self.encode(self.state.get('text')); if (!forId && (forName = self.settings.forName)) { targetCtrl = self.getRoot().find('#' + forName)[0]; if (targetCtrl) { forId = targetCtrl._id; } } if (forId) { return '<label id="' + self._id + '" class="' + self.classes + '"' + (forId ? ' for="' + forId + '"' : '') + '>' + text + '</label>'; } return '<span id="' + self._id + '" class="' + self.classes + '">' + text + '</span>'; }, bindStates: function () { var self = this; self.state.on('change:text', function (e) { self.innerHtml(self.encode(e.value)); if (self.state.get('rendered')) { self.updateLayoutRect(); } }); return self._super(); } }); var Toolbar$1 = Container.extend({ Defaults: { role: 'toolbar', layout: 'flow' }, init: function (settings) { var self = this; self._super(settings); self.classes.add('toolbar'); }, postRender: function () { var self = this; self.items().each(function (ctrl) { ctrl.classes.add('toolbar-item'); }); return self._super(); } }); var MenuBar = Toolbar$1.extend({ Defaults: { role: 'menubar', containerCls: 'menubar', ariaRoot: true, defaults: { type: 'menubutton' } } }); function isChildOf$1(node, parent) { while (node) { if (parent === node) { return true; } node = node.parentNode; } return false; } var MenuButton = Button.extend({ init: function (settings) { var self = this; self._renderOpen = true; self._super(settings); settings = self.settings; self.classes.add('menubtn'); if (settings.fixedWidth) { self.classes.add('fixed-width'); } self.aria('haspopup', true); self.state.set('menu', settings.menu || self.render()); }, showMenu: function (toggle) { var self = this; var menu; if (self.menu && self.menu.visible() && toggle !== false) { return self.hideMenu(); } if (!self.menu) { menu = self.state.get('menu') || []; self.classes.add('opened'); if (menu.length) { menu = { type: 'menu', animate: true, items: menu }; } else { menu.type = menu.type || 'menu'; menu.animate = true; } if (!menu.renderTo) { self.menu = global$4.create(menu).parent(self).renderTo(); } else { self.menu = menu.parent(self).show().renderTo(); } self.fire('createmenu'); self.menu.reflow(); self.menu.on('cancel', function (e) { if (e.control.parent() === self.menu) { e.stopPropagation(); self.focus(); self.hideMenu(); } }); self.menu.on('select', function () { self.focus(); }); self.menu.on('show hide', function (e) { if (e.control === self.menu) { self.activeMenu(e.type === 'show'); self.classes.toggle('opened', e.type === 'show'); } self.aria('expanded', e.type === 'show'); }).fire('show'); } self.menu.show(); self.menu.layoutRect({ w: self.layoutRect().w }); self.menu.repaint(); self.menu.moveRel(self.getEl(), self.isRtl() ? [ 'br-tr', 'tr-br' ] : [ 'bl-tl', 'tl-bl' ]); self.fire('showmenu'); }, hideMenu: function () { var self = this; if (self.menu) { self.menu.items().each(function (item) { if (item.hideMenu) { item.hideMenu(); } }); self.menu.hide(); } }, activeMenu: function (state) { this.classes.toggle('active', state); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; var icon = self.settings.icon, image; var text = self.state.get('text'); var textHtml = ''; image = self.settings.image; if (image) { icon = 'none'; if (typeof image !== 'string') { image = window.getSelection ? image[0] : image[1]; } image = ' style="background-image: url(\'' + image + '\')"'; } else { image = ''; } if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + icon : ''; self.aria('role', self.parent() instanceof MenuBar ? 'menuitem' : 'button'); return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1" aria-labelledby="' + id + '">' + '<button id="' + id + '-open" role="presentation" type="button" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>'; }, postRender: function () { var self = this; self.on('click', function (e) { if (e.control === self && isChildOf$1(e.target, self.getEl())) { self.focus(); self.showMenu(!e.aria); if (e.aria) { self.menu.items().filter(':visible')[0].focus(); } } }); self.on('mouseenter', function (e) { var overCtrl = e.control; var parent = self.parent(); var hasVisibleSiblingMenu; if (overCtrl && parent && overCtrl instanceof MenuButton && overCtrl.parent() === parent) { parent.items().filter('MenuButton').each(function (ctrl) { if (ctrl.hideMenu && ctrl !== overCtrl) { if (ctrl.menu && ctrl.menu.visible()) { hasVisibleSiblingMenu = true; } ctrl.hideMenu(); } }); if (hasVisibleSiblingMenu) { overCtrl.focus(); overCtrl.showMenu(); } } }); return self._super(); }, bindStates: function () { var self = this; self.state.on('change:menu', function () { if (self.menu) { self.menu.remove(); } self.menu = null; }); return self._super(); }, remove: function () { this._super(); if (this.menu) { this.menu.remove(); } } }); var Menu = FloatPanel.extend({ Defaults: { defaultType: 'menuitem', border: 1, layout: 'stack', role: 'application', bodyRole: 'menu', ariaRoot: true }, init: function (settings) { var self = this; settings.autohide = true; settings.constrainToViewport = true; if (typeof settings.items === 'function') { settings.itemsFactory = settings.items; settings.items = []; } if (settings.itemDefaults) { var items = settings.items; var i = items.length; while (i--) { items[i] = global$2.extend({}, settings.itemDefaults, items[i]); } } self._super(settings); self.classes.add('menu'); if (settings.animate && global$8.ie !== 11) { self.classes.add('animate'); } }, repaint: function () { this.classes.toggle('menu-align', true); this._super(); this.getEl().style.height = ''; this.getEl('body').style.height = ''; return this; }, cancel: function () { var self = this; self.hideAll(); self.fire('select'); }, load: function () { var self = this; var time, factory; function hideThrobber() { if (self.throbber) { self.throbber.hide(); self.throbber = null; } } factory = self.settings.itemsFactory; if (!factory) { return; } if (!self.throbber) { self.throbber = new Throbber(self.getEl('body'), true); if (self.items().length === 0) { self.throbber.show(); self.fire('loading'); } else { self.throbber.show(100, function () { self.items().remove(); self.fire('loading'); }); } self.on('hide close', hideThrobber); } self.requestTime = time = new Date().getTime(); self.settings.itemsFactory(function (items) { if (items.length === 0) { self.hide(); return; } if (self.requestTime !== time) { return; } self.getEl().style.width = ''; self.getEl('body').style.width = ''; hideThrobber(); self.items().remove(); self.getEl('body').innerHTML = ''; self.add(items); self.renderNew(); self.fire('loaded'); }); }, hideAll: function () { var self = this; this.find('menuitem').exec('hideMenu'); return self._super(); }, preRender: function () { var self = this; self.items().each(function (ctrl) { var settings = ctrl.settings; if (settings.icon || settings.image || settings.selectable) { self._hasIcons = true; return false; } }); if (self.settings.itemsFactory) { self.on('postrender', function () { if (self.settings.itemsFactory) { self.load(); } }); } self.on('show hide', function (e) { if (e.control === self) { if (e.type === 'show') { global$7.setTimeout(function () { self.classes.add('in'); }, 0); } else { self.classes.remove('in'); } } }); return self._super(); } }); var ListBox = MenuButton.extend({ init: function (settings) { var self = this; var values, selected, selectedText, lastItemCtrl; function setSelected(menuValues) { for (var i = 0; i < menuValues.length; i++) { selected = menuValues[i].selected || settings.value === menuValues[i].value; if (selected) { selectedText = selectedText || menuValues[i].text; self.state.set('value', menuValues[i].value); return true; } if (menuValues[i].menu) { if (setSelected(menuValues[i].menu)) { return true; } } } } self._super(settings); settings = self.settings; self._values = values = settings.values; if (values) { if (typeof settings.value !== 'undefined') { setSelected(values); } if (!selected && values.length > 0) { selectedText = values[0].text; self.state.set('value', values[0].value); } self.state.set('menu', values); } self.state.set('text', settings.text || selectedText); self.classes.add('listbox'); self.on('select', function (e) { var ctrl = e.control; if (lastItemCtrl) { e.lastControl = lastItemCtrl; } if (settings.multiple) { ctrl.active(!ctrl.active()); } else { self.value(e.control.value()); } lastItemCtrl = ctrl; }); }, value: function (value) { if (arguments.length === 0) { return this.state.get('value'); } if (typeof value === 'undefined') { return this; } if (this.settings.values) { var matchingValues = global$2.grep(this.settings.values, function (a) { return a.value === value; }); if (matchingValues.length > 0) { this.state.set('value', value); } else if (value === null) { this.state.set('value', null); } } else { this.state.set('value', value); } return this; }, bindStates: function () { var self = this; function activateMenuItemsByValue(menu, value) { if (menu instanceof Menu) { menu.items().each(function (ctrl) { if (!ctrl.hasMenus()) { ctrl.active(ctrl.value() === value); } }); } } function getSelectedItem(menuValues, value) { var selectedItem; if (!menuValues) { return; } for (var i = 0; i < menuValues.length; i++) { if (menuValues[i].value === value) { return menuValues[i]; } if (menuValues[i].menu) { selectedItem = getSelectedItem(menuValues[i].menu, value); if (selectedItem) { return selectedItem; } } } } self.on('show', function (e) { activateMenuItemsByValue(e.control, self.value()); }); self.state.on('change:value', function (e) { var selectedItem = getSelectedItem(self.state.get('menu'), e.value); if (selectedItem) { self.text(selectedItem.text); } else { self.text(self.settings.text); } }); return self._super(); } }); var toggleTextStyle = function (ctrl, state) { var textStyle = ctrl._textStyle; if (textStyle) { var textElm = ctrl.getEl('text'); textElm.setAttribute('style', textStyle); if (state) { textElm.style.color = ''; textElm.style.backgroundColor = ''; } } }; var MenuItem = Widget.extend({ Defaults: { border: 0, role: 'menuitem' }, init: function (settings) { var self = this; var text; self._super(settings); settings = self.settings; self.classes.add('menu-item'); if (settings.menu) { self.classes.add('menu-item-expand'); } if (settings.preview) { self.classes.add('menu-item-preview'); } text = self.state.get('text'); if (text === '-' || text === '|') { self.classes.add('menu-item-sep'); self.aria('role', 'separator'); self.state.set('text', '-'); } if (settings.selectable) { self.aria('role', 'menuitemcheckbox'); self.classes.add('menu-item-checkbox'); settings.icon = 'selected'; } if (!settings.preview && !settings.selectable) { self.classes.add('menu-item-normal'); } self.on('mousedown', function (e) { e.preventDefault(); }); if (settings.menu && !settings.ariaHideMenu) { self.aria('haspopup', true); } }, hasMenus: function () { return !!this.settings.menu; }, showMenu: function () { var self = this; var settings = self.settings; var menu; var parent = self.parent(); parent.items().each(function (ctrl) { if (ctrl !== self) { ctrl.hideMenu(); } }); if (settings.menu) { menu = self.menu; if (!menu) { menu = settings.menu; if (menu.length) { menu = { type: 'menu', items: menu }; } else { menu.type = menu.type || 'menu'; } if (parent.settings.itemDefaults) { menu.itemDefaults = parent.settings.itemDefaults; } menu = self.menu = global$4.create(menu).parent(self).renderTo(); menu.reflow(); menu.on('cancel', function (e) { e.stopPropagation(); self.focus(); menu.hide(); }); menu.on('show hide', function (e) { if (e.control.items) { e.control.items().each(function (ctrl) { ctrl.active(ctrl.settings.selected); }); } }).fire('show'); menu.on('hide', function (e) { if (e.control === menu) { self.classes.remove('selected'); } }); menu.submenu = true; } else { menu.show(); } menu._parentMenu = parent; menu.classes.add('menu-sub'); var rel = menu.testMoveRel(self.getEl(), self.isRtl() ? [ 'tl-tr', 'bl-br', 'tr-tl', 'br-bl' ] : [ 'tr-tl', 'br-bl', 'tl-tr', 'bl-br' ]); menu.moveRel(self.getEl(), rel); menu.rel = rel; rel = 'menu-sub-' + rel; menu.classes.remove(menu._lastRel).add(rel); menu._lastRel = rel; self.classes.add('selected'); self.aria('expanded', true); } }, hideMenu: function () { var self = this; if (self.menu) { self.menu.items().each(function (item) { if (item.hideMenu) { item.hideMenu(); } }); self.menu.hide(); self.aria('expanded', false); } return self; }, renderHtml: function () { var self = this; var id = self._id; var settings = self.settings; var prefix = self.classPrefix; var text = self.state.get('text'); var icon = self.settings.icon, image = '', shortcut = settings.shortcut; var url = self.encode(settings.url), iconHtml = ''; function convertShortcut(shortcut) { var i, value, replace = {}; if (global$8.mac) { replace = { alt: '&#x2325;', ctrl: '&#x2318;', shift: '&#x21E7;', meta: '&#x2318;' }; } else { replace = { meta: 'Ctrl' }; } shortcut = shortcut.split('+'); for (i = 0; i < shortcut.length; i++) { value = replace[shortcut[i].toLowerCase()]; if (value) { shortcut[i] = value; } } return shortcut.join('+'); } function escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function markMatches(text) { var match = settings.match || ''; return match ? text.replace(new RegExp(escapeRegExp(match), 'gi'), function (match) { return '!mce~match[' + match + ']mce~match!'; }) : text; } function boldMatches(text) { return text.replace(new RegExp(escapeRegExp('!mce~match['), 'g'), '<b>').replace(new RegExp(escapeRegExp(']mce~match!'), 'g'), '</b>'); } if (icon) { self.parent().classes.add('menu-has-icons'); } if (settings.image) { image = ' style="background-image: url(\'' + settings.image + '\')"'; } if (shortcut) { shortcut = convertShortcut(shortcut); } icon = prefix + 'ico ' + prefix + 'i-' + (self.settings.icon || 'none'); iconHtml = text !== '-' ? '<i class="' + icon + '"' + image + '></i>\xA0' : ''; text = boldMatches(self.encode(markMatches(text))); url = boldMatches(self.encode(markMatches(url))); return '<div id="' + id + '" class="' + self.classes + '" tabindex="-1">' + iconHtml + (text !== '-' ? '<span id="' + id + '-text" class="' + prefix + 'text">' + text + '</span>' : '') + (shortcut ? '<div id="' + id + '-shortcut" class="' + prefix + 'menu-shortcut">' + shortcut + '</div>' : '') + (settings.menu ? '<div class="' + prefix + 'caret"></div>' : '') + (url ? '<div class="' + prefix + 'menu-item-link">' + url + '</div>' : '') + '</div>'; }, postRender: function () { var self = this, settings = self.settings; var textStyle = settings.textStyle; if (typeof textStyle === 'function') { textStyle = textStyle.call(this); } if (textStyle) { var textElm = self.getEl('text'); if (textElm) { textElm.setAttribute('style', textStyle); self._textStyle = textStyle; } } self.on('mouseenter click', function (e) { if (e.control === self) { if (!settings.menu && e.type === 'click') { self.fire('select'); global$7.requestAnimationFrame(function () { self.parent().hideAll(); }); } else { self.showMenu(); if (e.aria) { self.menu.focus(true); } } } }); self._super(); return self; }, hover: function () { var self = this; self.parent().items().each(function (ctrl) { ctrl.classes.remove('selected'); }); self.classes.toggle('selected', true); return self; }, active: function (state) { toggleTextStyle(this, state); if (typeof state !== 'undefined') { this.aria('checked', state); } return this._super(state); }, remove: function () { this._super(); if (this.menu) { this.menu.remove(); } } }); var Radio = Checkbox.extend({ Defaults: { classes: 'radio', role: 'radio' } }); var ResizeHandle = Widget.extend({ renderHtml: function () { var self = this, prefix = self.classPrefix; self.classes.add('resizehandle'); if (self.settings.direction === 'both') { self.classes.add('resizehandle-both'); } self.canFocus = false; return '<div id="' + self._id + '" class="' + self.classes + '">' + '<i class="' + prefix + 'ico ' + prefix + 'i-resize"></i>' + '</div>'; }, postRender: function () { var self = this; self._super(); self.resizeDragHelper = new DragHelper(this._id, { start: function () { self.fire('ResizeStart'); }, drag: function (e) { if (self.settings.direction !== 'both') { e.deltaX = 0; } self.fire('Resize', e); }, stop: function () { self.fire('ResizeEnd'); } }); }, remove: function () { if (this.resizeDragHelper) { this.resizeDragHelper.destroy(); } return this._super(); } }); function createOptions(options) { var strOptions = ''; if (options) { for (var i = 0; i < options.length; i++) { strOptions += '<option value="' + options[i] + '">' + options[i] + '</option>'; } } return strOptions; } var SelectBox = Widget.extend({ Defaults: { classes: 'selectbox', role: 'selectbox', options: [] }, init: function (settings) { var self = this; self._super(settings); if (self.settings.size) { self.size = self.settings.size; } if (self.settings.options) { self._options = self.settings.options; } self.on('keydown', function (e) { var rootControl; if (e.keyCode === 13) { e.preventDefault(); self.parents().reverse().each(function (ctrl) { if (ctrl.toJSON) { rootControl = ctrl; return false; } }); self.fire('submit', { data: rootControl.toJSON() }); } }); }, options: function (state) { if (!arguments.length) { return this.state.get('options'); } this.state.set('options', state); return this; }, renderHtml: function () { var self = this; var options, size = ''; options = createOptions(self._options); if (self.size) { size = ' size = "' + self.size + '"'; } return '<select id="' + self._id + '" class="' + self.classes + '"' + size + '>' + options + '</select>'; }, bindStates: function () { var self = this; self.state.on('change:options', function (e) { self.getEl().innerHTML = createOptions(e.value); }); return self._super(); } }); function constrain(value, minVal, maxVal) { if (value < minVal) { value = minVal; } if (value > maxVal) { value = maxVal; } return value; } function setAriaProp(el, name, value) { el.setAttribute('aria-' + name, value); } function updateSliderHandle(ctrl, value) { var maxHandlePos, shortSizeName, sizeName, stylePosName, styleValue, handleEl; if (ctrl.settings.orientation === 'v') { stylePosName = 'top'; sizeName = 'height'; shortSizeName = 'h'; } else { stylePosName = 'left'; sizeName = 'width'; shortSizeName = 'w'; } handleEl = ctrl.getEl('handle'); maxHandlePos = (ctrl.layoutRect()[shortSizeName] || 100) - funcs.getSize(handleEl)[sizeName]; styleValue = maxHandlePos * ((value - ctrl._minValue) / (ctrl._maxValue - ctrl._minValue)) + 'px'; handleEl.style[stylePosName] = styleValue; handleEl.style.height = ctrl.layoutRect().h + 'px'; setAriaProp(handleEl, 'valuenow', value); setAriaProp(handleEl, 'valuetext', '' + ctrl.settings.previewFilter(value)); setAriaProp(handleEl, 'valuemin', ctrl._minValue); setAriaProp(handleEl, 'valuemax', ctrl._maxValue); } var Slider = Widget.extend({ init: function (settings) { var self = this; if (!settings.previewFilter) { settings.previewFilter = function (value) { return Math.round(value * 100) / 100; }; } self._super(settings); self.classes.add('slider'); if (settings.orientation === 'v') { self.classes.add('vertical'); } self._minValue = $_d8bie3tijh8lz3kn.isNumber(settings.minValue) ? settings.minValue : 0; self._maxValue = $_d8bie3tijh8lz3kn.isNumber(settings.maxValue) ? settings.maxValue : 100; self._initValue = self.state.get('value'); }, renderHtml: function () { var self = this, id = self._id, prefix = self.classPrefix; return '<div id="' + id + '" class="' + self.classes + '">' + '<div id="' + id + '-handle" class="' + prefix + 'slider-handle" role="slider" tabindex="-1"></div>' + '</div>'; }, reset: function () { this.value(this._initValue).repaint(); }, postRender: function () { var self = this; var minValue, maxValue, screenCordName, stylePosName, sizeName, shortSizeName; function toFraction(min, max, val) { return (val + min) / (max - min); } function fromFraction(min, max, val) { return val * (max - min) - min; } function handleKeyboard(minValue, maxValue) { function alter(delta) { var value; value = self.value(); value = fromFraction(minValue, maxValue, toFraction(minValue, maxValue, value) + delta * 0.05); value = constrain(value, minValue, maxValue); self.value(value); self.fire('dragstart', { value: value }); self.fire('drag', { value: value }); self.fire('dragend', { value: value }); } self.on('keydown', function (e) { switch (e.keyCode) { case 37: case 38: alter(-1); break; case 39: case 40: alter(1); break; } }); } function handleDrag(minValue, maxValue, handleEl) { var startPos, startHandlePos, maxHandlePos, handlePos, value; self._dragHelper = new DragHelper(self._id, { handle: self._id + '-handle', start: function (e) { startPos = e[screenCordName]; startHandlePos = parseInt(self.getEl('handle').style[stylePosName], 10); maxHandlePos = (self.layoutRect()[shortSizeName] || 100) - funcs.getSize(handleEl)[sizeName]; self.fire('dragstart', { value: value }); }, drag: function (e) { var delta = e[screenCordName] - startPos; handlePos = constrain(startHandlePos + delta, 0, maxHandlePos); handleEl.style[stylePosName] = handlePos + 'px'; value = minValue + handlePos / maxHandlePos * (maxValue - minValue); self.value(value); self.tooltip().text('' + self.settings.previewFilter(value)).show().moveRel(handleEl, 'bc tc'); self.fire('drag', { value: value }); }, stop: function () { self.tooltip().hide(); self.fire('dragend', { value: value }); } }); } minValue = self._minValue; maxValue = self._maxValue; if (self.settings.orientation === 'v') { screenCordName = 'screenY'; stylePosName = 'top'; sizeName = 'height'; shortSizeName = 'h'; } else { screenCordName = 'screenX'; stylePosName = 'left'; sizeName = 'width'; shortSizeName = 'w'; } self._super(); handleKeyboard(minValue, maxValue); handleDrag(minValue, maxValue, self.getEl('handle')); }, repaint: function () { this._super(); updateSliderHandle(this, this.value()); }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { updateSliderHandle(self, e.value); }); return self._super(); } }); var Spacer = Widget.extend({ renderHtml: function () { var self = this; self.classes.add('spacer'); self.canFocus = false; return '<div id="' + self._id + '" class="' + self.classes + '"></div>'; } }); var SplitButton = MenuButton.extend({ Defaults: { classes: 'widget btn splitbtn', role: 'button' }, repaint: function () { var self = this; var elm = self.getEl(); var rect = self.layoutRect(); var mainButtonElm, menuButtonElm; self._super(); mainButtonElm = elm.firstChild; menuButtonElm = elm.lastChild; global$9(mainButtonElm).css({ width: rect.w - funcs.getSize(menuButtonElm).width, height: rect.h - 2 }); global$9(menuButtonElm).css({ height: rect.h - 2 }); return self; }, activeMenu: function (state) { var self = this; global$9(self.getEl().lastChild).toggleClass(self.classPrefix + 'active', state); }, renderHtml: function () { var self = this; var id = self._id; var prefix = self.classPrefix; var image; var icon = self.state.get('icon'); var text = self.state.get('text'); var settings = self.settings; var textHtml = '', ariaPressed; image = settings.image; if (image) { icon = 'none'; if (typeof image !== 'string') { image = window.getSelection ? image[0] : image[1]; } image = ' style="background-image: url(\'' + image + '\')"'; } else { image = ''; } icon = settings.icon ? prefix + 'ico ' + prefix + 'i-' + icon : ''; if (text) { self.classes.add('btn-has-text'); textHtml = '<span class="' + prefix + 'txt">' + self.encode(text) + '</span>'; } ariaPressed = typeof settings.active === 'boolean' ? ' aria-pressed="' + settings.active + '"' : ''; return '<div id="' + id + '" class="' + self.classes + '" role="button"' + ariaPressed + ' tabindex="-1">' + '<button type="button" hidefocus="1" tabindex="-1">' + (icon ? '<i class="' + icon + '"' + image + '></i>' : '') + textHtml + '</button>' + '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' + (self._menuBtnText ? (icon ? '\xA0' : '') + self._menuBtnText : '') + ' <i class="' + prefix + 'caret"></i>' + '</button>' + '</div>'; }, postRender: function () { var self = this, onClickHandler = self.settings.onclick; self.on('click', function (e) { var node = e.target; if (e.control === this) { while (node) { if (e.aria && e.aria.key !== 'down' || node.nodeName === 'BUTTON' && node.className.indexOf('open') === -1) { e.stopImmediatePropagation(); if (onClickHandler) { onClickHandler.call(this, e); } return; } node = node.parentNode; } } }); delete self.settings.onclick; return self._super(); } }); var StackLayout = FlowLayout.extend({ Defaults: { containerClass: 'stack-layout', controlClass: 'stack-layout-item', endClass: 'break' }, isNative: function () { return true; } }); var TabPanel = Panel.extend({ Defaults: { layout: 'absolute', defaults: { type: 'panel' } }, activateTab: function (idx) { var activeTabElm; if (this.activeTabId) { activeTabElm = this.getEl(this.activeTabId); global$9(activeTabElm).removeClass(this.classPrefix + 'active'); activeTabElm.setAttribute('aria-selected', 'false'); } this.activeTabId = 't' + idx; activeTabElm = this.getEl('t' + idx); activeTabElm.setAttribute('aria-selected', 'true'); global$9(activeTabElm).addClass(this.classPrefix + 'active'); this.items()[idx].show().fire('showtab'); this.reflow(); this.items().each(function (item, i) { if (idx !== i) { item.hide(); } }); }, renderHtml: function () { var self = this; var layout = self._layout; var tabsHtml = ''; var prefix = self.classPrefix; self.preRender(); layout.preRender(self); self.items().each(function (ctrl, i) { var id = self._id + '-t' + i; ctrl.aria('role', 'tabpanel'); ctrl.aria('labelledby', id); tabsHtml += '<div id="' + id + '" class="' + prefix + 'tab" ' + 'unselectable="on" role="tab" aria-controls="' + ctrl._id + '" aria-selected="false" tabIndex="-1">' + self.encode(ctrl.settings.title) + '</div>'; }); return '<div id="' + self._id + '" class="' + self.classes + '" hidefocus="1" tabindex="-1">' + '<div id="' + self._id + '-head" class="' + prefix + 'tabs" role="tablist">' + tabsHtml + '</div>' + '<div id="' + self._id + '-body" class="' + self.bodyClasses + '">' + layout.renderHtml(self) + '</div>' + '</div>'; }, postRender: function () { var self = this; self._super(); self.settings.activeTab = self.settings.activeTab || 0; self.activateTab(self.settings.activeTab); this.on('click', function (e) { var targetParent = e.target.parentNode; if (targetParent && targetParent.id === self._id + '-head') { var i = targetParent.childNodes.length; while (i--) { if (targetParent.childNodes[i] === e.target) { self.activateTab(i); } } } }); }, initLayoutRect: function () { var self = this; var rect, minW, minH; minW = funcs.getSize(self.getEl('head')).width; minW = minW < 0 ? 0 : minW; minH = 0; self.items().each(function (item) { minW = Math.max(minW, item.layoutRect().minW); minH = Math.max(minH, item.layoutRect().minH); }); self.items().each(function (ctrl) { ctrl.settings.x = 0; ctrl.settings.y = 0; ctrl.settings.w = minW; ctrl.settings.h = minH; ctrl.layoutRect({ x: 0, y: 0, w: minW, h: minH }); }); var headH = funcs.getSize(self.getEl('head')).height; self.settings.minWidth = minW; self.settings.minHeight = minH + headH; rect = self._super(); rect.deltaH += headH; rect.innerH = rect.h - rect.deltaH; return rect; } }); var TextBox = Widget.extend({ init: function (settings) { var self = this; self._super(settings); self.classes.add('textbox'); if (settings.multiline) { self.classes.add('multiline'); } else { self.on('keydown', function (e) { var rootControl; if (e.keyCode === 13) { e.preventDefault(); self.parents().reverse().each(function (ctrl) { if (ctrl.toJSON) { rootControl = ctrl; return false; } }); self.fire('submit', { data: rootControl.toJSON() }); } }); self.on('keyup', function (e) { self.state.set('value', e.target.value); }); } }, repaint: function () { var self = this; var style, rect, borderBox, borderW, borderH = 0, lastRepaintRect; style = self.getEl().style; rect = self._layoutRect; lastRepaintRect = self._lastRepaintRect || {}; var doc = document; if (!self.settings.multiline && doc.all && (!doc.documentMode || doc.documentMode <= 8)) { style.lineHeight = rect.h - borderH + 'px'; } borderBox = self.borderBox; borderW = borderBox.left + borderBox.right + 8; borderH = borderBox.top + borderBox.bottom + (self.settings.multiline ? 8 : 0); if (rect.x !== lastRepaintRect.x) { style.left = rect.x + 'px'; lastRepaintRect.x = rect.x; } if (rect.y !== lastRepaintRect.y) { style.top = rect.y + 'px'; lastRepaintRect.y = rect.y; } if (rect.w !== lastRepaintRect.w) { style.width = rect.w - borderW + 'px'; lastRepaintRect.w = rect.w; } if (rect.h !== lastRepaintRect.h) { style.height = rect.h - borderH + 'px'; lastRepaintRect.h = rect.h; } self._lastRepaintRect = lastRepaintRect; self.fire('repaint', {}, false); return self; }, renderHtml: function () { var self = this; var settings = self.settings; var attrs, elm; attrs = { id: self._id, hidefocus: '1' }; global$2.each([ 'rows', 'spellcheck', 'maxLength', 'size', 'readonly', 'min', 'max', 'step', 'list', 'pattern', 'placeholder', 'required', 'multiple' ], function (name) { attrs[name] = settings[name]; }); if (self.disabled()) { attrs.disabled = 'disabled'; } if (settings.subtype) { attrs.type = settings.subtype; } elm = funcs.create(settings.multiline ? 'textarea' : 'input', attrs); elm.value = self.state.get('value'); elm.className = self.classes.toString(); return elm.outerHTML; }, value: function (value) { if (arguments.length) { this.state.set('value', value); return this; } if (this.state.get('rendered')) { this.state.set('value', this.getEl().value); } return this.state.get('value'); }, postRender: function () { var self = this; self.getEl().value = self.state.get('value'); self._super(); self.$el.on('change', function (e) { self.state.set('value', e.target.value); self.fire('change', e); }); }, bindStates: function () { var self = this; self.state.on('change:value', function (e) { if (self.getEl().value !== e.value) { self.getEl().value = e.value; } }); self.state.on('change:disabled', function (e) { self.getEl().disabled = e.value; }); return self._super(); }, remove: function () { this.$el.off(); this._super(); } }); var getApi = function () { return { Selector: Selector, Collection: Collection$2, ReflowQueue: $_ef12j5u4jh8lz3nl, Control: Control$1, Factory: global$4, KeyboardNavigation: KeyboardNavigation, Container: Container, DragHelper: DragHelper, Scrollable: $_4acv48u6jh8lz3ns, Panel: Panel, Movable: $_d97gfctrjh8lz3lm, Resizable: $_8a2gtru8jh8lz3ny, FloatPanel: FloatPanel, Window: Window, MessageBox: MessageBox, Tooltip: Tooltip, Widget: Widget, Progress: Progress, Notification: Notification, Layout: Layout, AbsoluteLayout: AbsoluteLayout, Button: Button, ButtonGroup: ButtonGroup, Checkbox: Checkbox, ComboBox: ComboBox, ColorBox: ColorBox, PanelButton: PanelButton, ColorButton: ColorButton, ColorPicker: ColorPicker, Path: Path, ElementPath: ElementPath, FormItem: FormItem, Form: Form, FieldSet: FieldSet, FilePicker: FilePicker, FitLayout: FitLayout, FlexLayout: FlexLayout, FlowLayout: FlowLayout, FormatControls: $_4qdht3w4jh8lz3uo, GridLayout: GridLayout, Iframe: Iframe$1, InfoBox: InfoBox, Label: Label, Toolbar: Toolbar$1, MenuBar: MenuBar, MenuButton: MenuButton, MenuItem: MenuItem, Throbber: Throbber, Menu: Menu, ListBox: ListBox, Radio: Radio, ResizeHandle: ResizeHandle, SelectBox: SelectBox, Slider: Slider, Spacer: Spacer, SplitButton: SplitButton, StackLayout: StackLayout, TabPanel: TabPanel, TextBox: TextBox, DropZone: DropZone, BrowseButton: BrowseButton }; }; var appendTo = function (target) { if (target.ui) { global$2.each(getApi(), function (ref, key) { target.ui[key] = ref; }); } else { target.ui = getApi(); } }; var registerToFactory = function () { global$2.each(getApi(), function (ref, key) { global$4.add(key, ref); }); }; var Api = { appendTo: appendTo, registerToFactory: registerToFactory }; Api.registerToFactory(); Api.appendTo(window.tinymce ? window.tinymce : {}); global.add('modern', function (editor) { $_4qdht3w4jh8lz3uo.setup(editor); return $_1os0v5syjh8lz3j9.get(editor); }); function Theme () { } return Theme; }()); })();
nemiah/poolPi
public_html/backend/libraries/tinymce/themes/modern/theme.js
JavaScript
gpl-3.0
323,313
#include "fizzbuzz.h" #include <iostream> int main(int /*argc*/, char* /*argv*/[]) { playFizzBuzz(); return 0; }
pauldreik/cppsandbox
fizzbuzz/main.cpp
C++
gpl-3.0
119
(function(){ 'use strict'; Ns.views.map.Layout = Marionette.LayoutView.extend({ id: 'map-container', template: '#map-layout-template', regions: { content: '#map-js', legend: '#legend-js', panels: '#map-panels', toolbar: '#map-toolbar', add: '#map-add-node-js', details: '#map-details-js' }, /** * show regions */ onShow: function () { this.content.show(new Ns.views.map.Content({ parent: this })); }, /** * loads map data */ loadMap: function () { var options = { parent: this }; this.toolbar.show(new Ns.views.map.Toolbar(options)); this.panels.show(new Ns.views.map.Panels(options)); this.legend.show(new Ns.views.map.Legend(options)); this.content.currentView.initMapData(); }, /* * show add node view */ addNode: function () { this.reset(); // if not authenticated if (Ns.db.user.isAuthenticated() === false) { // show sign-in modal $('#signin-modal').modal('show'); // listen to loggedin event and come back here this.listenToOnce(Ns.db.user, 'loggedin', this.addNode); return; } this.add.show(new Ns.views.map.Add({ parent: this })); }, showNode: function(node) { this.details.show(new Ns.views.node.Detail({ model: node, parent: this })); }, showEditNode: function(node) { // ensure is allowed to edit if (node.get('can_edit')) { this.showNode(node); this.details.currentView.edit(); } // otherwise go back to details else { Ns.router.navigate('nodes/' + node.id, { trigger: true }); } }, /* * resets to view initial state */ reset: function () { this.content.currentView.closeLeafletPopup(); this.add.empty(); this.details.empty(); } }, { // static methods show: function (method, args) { var view; if (typeof Ns.body.currentView === 'undefined' || !(Ns.body.currentView instanceof Ns.views.map.Layout)) { view = new Ns.views.map.Layout(); Ns.body.show(view); } else { view = Ns.body.currentView; view.reset(); } // call method on Layout view is specified if (method) { view[method].apply(view, args); } }, /* * Resize page elements so that the leaflet map * takes most of the available space in the window */ resizeMap: function () { var overlayContainer = $('#map-overlay-container'), height, selector, width, setWidth = false, body = $('body'); body.css('overflow-x', 'hidden'); // map if (!overlayContainer.length) { height = $(window).height() - $('body > header').height(); selector = '#map-container, #map-toolbar'; } // node details else { height = overlayContainer.height() + parseInt(overlayContainer.css('top'), 10); selector = '#map-container'; } // set new height $(selector).height(height); width = $(window).width(); // take in consideration #map-add-node-js if visible if ($('#map-add-node-js').is(':visible')) { width = width - $('#map-add-node-js').outerWidth(); setWidth = true; } // take in consideration map toolbar if visible else if ($('#map-toolbar').is(':visible')) { width = width - $('#map-toolbar').outerWidth(); setWidth = true; } // set width only if map toolbar is showing if (setWidth){ $('#map').width(width); } else{ $('#map').attr('style', ''); } body.attr('style', ''); // TODO: this is ugly! // call leaflet invalidateSize() to download any gray spot if (Ns.body.currentView instanceof Ns.views.map.Layout && Ns.body.currentView.content && typeof Ns.body.currentView.content.currentView.map !== 'undefined'){ Ns.body.currentView.content.currentView.map.invalidateSize(); } } }); Ns.views.map.Content = Marionette.ItemView.extend({ template: false, collectionEvents: { // populate map as items are added to collection 'add': 'addGeoModelToMap', // remove items from map when models are removed 'remove': 'removeGeoModelFromMap' }, initialize: function (options) { this.parent = options.parent; this.collection = new Ns.collections.Geo(); this.popUpNodeTemplate = _.template($('#map-popup-node-template').html()); // link tweak this.popUpLinkTemplate = _.template($('#map-popup-link-template').html()); // reload data when user logs in or out this.listenTo(Ns.db.user, 'loggedin loggedout', this.reloadMapData); // bind to namespaced events $(window).on('resize.map', _.bind(this.resize, this)); $(window).on('beforeunload.map', _.bind(this.storeMapProperties, this)); // cleanup eventual alerts $.cleanupAlerts(); }, onShow: function () { this.initMap(); }, onDestroy: function () { // store current coordinates when changing view this.storeMapProperties(); // unbind the namespaced events $(window).off('beforeunload.map'); $(window).off('resize.map'); }, /* * get current map coordinates (lat, lng, zoom) */ getMapProperties: function () { var latLng = this.map.getCenter(); return { lat: latLng.lat, lng: latLng.lng, zoom: this.map.getZoom(), baseLayer: this.getCurrentBaseLayer() }; }, /* * store current map coordinates in localStorage */ storeMapProperties: function () { localStorage.setObject('map', this.getMapProperties()); }, /* * get latest stored coordinates or default ones */ rememberMapProperties: function () { return localStorage.getObject('map') || Ns.settings.map; }, /* * resize window event */ resize: function () { Ns.views.map.Layout.resizeMap(); // when narrowing the window to medium-small size and toolbar is hidden and any panel is still visible if ($(window).width() <= 767 && $('#map-toolbar').is(':hidden') && $('.side-panel:visible').length) { // close panel $('.mask').trigger('click'); } }, /* * initialize leaflet map */ initMap: function () { var self = this, memory = this.rememberMapProperties(); this.resize(); // init map this.map = $.loadDjangoLeafletMap(); // remember last coordinates this.map.setView([memory.lat, memory.lng], memory.zoom, { trackResize: true }); // store baseLayers this.baseLayers = {}; _.each(this.map.layerscontrol._layers, function (baseLayer) { self.baseLayers[baseLayer.name] = baseLayer.layer; // keep name reference self.baseLayers[baseLayer.name].name = baseLayer.name; }); // remember preferred baseLayer if (memory.baseLayer) { this.switchBaseLayer(memory.baseLayer); } // create (empty) clusters on map (will be filled by addGeoModelToMap) this.createClusters(); }, /** * changes base layer of the map, only if necessary * (calling the same action twice has no effect) */ switchBaseLayer: function(name){ // ignore if name is undefined if(typeof name === 'undefined'){ return; } // remove all base layers that are not relevant for (var key in this.baseLayers){ if (this.baseLayers[key].name !== name) { this.map.removeLayer(this.baseLayers[key]); } } // if the relevant layer is still not there add it if (!this.map.hasLayer(this.baseLayers[name])) { this.map.addLayer(this.baseLayers[name]); } }, /** * returns name of the current map base layer */ getCurrentBaseLayer: function () { for (var name in this.baseLayers){ if (Boolean(this.baseLayers[name]._map)) { return name; } } return null; }, /* * loads data from API */ initMapData: function () { Ns.changeTitle(gettext('Map')); Ns.menu.currentView.activate('map'); Ns.track(); Ns.state.onNodeClose = 'map'; // when a node-details is closed go back on map this.parent.toolbar.$el.addClass('enabled'); this.resize(); // load cached data if present if (Ns.db.geo.isEmpty() === false) { this.collection.add(Ns.db.geo.models); this.collection.trigger('ready'); } // otherwise fetch from server else { this.fetchMapData(); } // toggle legend group from map when visible attribute changes this.listenTo(Ns.db.legend, 'change:visible', this.toggleLegendGroup); // toggle layer data when visible attribute changes this.listenTo(Ns.db.layers, 'change:visible', this.toggleLayerData); }, /* * fetch map data, merging changes if necessary */ fetchMapData: function () { var self = this, // will contain fresh data geo = new Ns.collections.Geo(), // will be used to fetch data to merge in geo tmp = geo.clone(), additionalGeoJson = Ns.settings.additionalGeoJsonUrls, ready, fetch; // will be called when all sources have been fetched // we need to add 1 to account for the main geojson ready = _.after(additionalGeoJson.length + 1, function () { // reload models self.collection.remove(self.collection.models); self.collection.add(geo.models); // cache geo collection Ns.db.geo = self.collection; // trigger ready event self.collection.trigger('ready'); // unbind event self.collection.off('sync', ready); }); // fetch data and add it to collection fetch = function () { tmp.fetch().done(function () { geo.add(tmp.models); geo.trigger('sync'); }); }; geo.on('sync', ready); // fetch data from API fetch(); additionalGeoJson.forEach(function (url) { tmp._url = url; fetch(); }); // begin temporary tweak for links if (Ns.settings.links) { var links = new Ns.collections.Geo(); links._url = Ns.url('links.geojson'); links.fetch().done(function () { geo.add(links.models); geo.trigger('sync'); }); } // end tweak }, /** * reload map data in the background */ reloadMapData: function () { $.toggleLoading('hide'); // disable loading indicator while data gets refreshed Ns.state.autoToggleLoading = false; // fetch data this.fetchMapData(); // re-enable loading indicator once data is refreshed this.collection.once('ready', function(){ Ns.state.autoToggleLoading = true }); }, /** * prepare empty Leaflet.MarkerCluster objects */ createClusters: function () { var self = this, legend; // loop over each legend item Ns.db.legend.forEach(function (legendModel) { legend = legendModel.toJSON(); // group markers in clusters var cluster = new L.MarkerClusterGroup({ iconCreateFunction: function (cluster) { var count = cluster.getChildCount(), // determine size with the last number of the exponential notation // 0 for < 10, 1 for < 100, 2 for < 1000 and so on size = count.toExponential().split('+')[1]; return L.divIcon({ html: count, className: 'cluster cluster-size-' + size + ' marker-' + this.cssClass }); }, polygonOptions: { fillColor: legend.fill_color, stroke: legend.stroke_width > 0, weight: legend.stroke_width, color: legend.stroke_color, opacity: 0.4 }, cssClass: legend.slug, chunkedLoading: true, showCoverageOnHover: true, zoomToBoundsOnClick: true, removeOutsideVisibleBounds: true, disableClusteringAtZoom: Ns.settings.disableClusteringAtZoom, maxClusterRadius: Ns.settings.maxClusterRadius }); // store reference legendModel.cluster = cluster; // show cluster only if corresponding legend item is visible if(legend.visible){ self.map.addLayer(cluster); } }); }, /** * returns options for the initialization of tooltip for leaflet layers */ tooltipOptions: function(data) { return { container: '#map-js', placement: 'auto top', title: data.name, delay: { show: 600, hide: 0 } } }, /** * adds a geo model to its cluster * binds popup * called whenever a model is added to the collection */ addGeoModelToMap: function (model) { var self = this, leafletLayer = model.get('leaflet'), legend = model.get('legend'), data = model.toJSON(), layer = Ns.db.layers.get(data.layer), // link tweak template = model._type === 'node' ? this.popUpNodeTemplate : this.popUpLinkTemplate; // bind leaflet popup leafletLayer.bindPopup(template(data)); // mouse over / out events leafletLayer.on({ mouseover: function (e) { var l = e.target, type = l.feature.geometry.type; // opacity to 1 l.setStyle({ fillOpacity: 1 }); // bring to front if (!L.Browser.ie && !L.Browser.opera && type === 'Point') { l.bringToFront({ fillOpacity: 1 }); } }, mouseout: function (e) { e.target.setStyle({ fillOpacity: Ns.settings.leafletOptions.fillOpacity }); }, // when popup opens, change the URL fragment popupopen: function (e) { var fragment = Backbone.history.fragment; // do this only if in general map view if (fragment.indexOf('map') >= 0 && fragment.indexOf('nodes') < 0) { Ns.router.navigate('map/' + data.slug); } // destroy container to avoid the chance that the tooltip // might appear while showing the leaflet popup $(e.target._container).tooltip('destroy'); }, // when popup closes popupclose: function (e) { // (and no new popup opens) // URL fragment goes back to initial state var fragment = Backbone.history.fragment; setTimeout(function () { // do this only if in general map view if (self.map._popup === null && fragment.indexOf('map') >= 0 && fragment.indexOf('nodes') < 0) { Ns.router.navigate('map'); } }, 100); // rebind tooltip (it has been destroyed in popupopen event) $(e.target._container).tooltip(self.tooltipOptions(data)); }, add: function(e){ // create tootlip when leaflet layer is added to the view $(e.target._container).tooltip(self.tooltipOptions(data)); }, remove: function(e){ // ensure tooltip is removed when layer is removed from map $(e.target._container).tooltip('destroy'); } }); // show on map only if corresponding nodeshot layer is visible if (layer && layer.get('visible')) { legend.cluster.addLayer(leafletLayer); // avoid covering points if (leafletLayer._map && leafletLayer.feature.geometry.type !== 'Point') { leafletLayer.bringToBack(); } } }, /** * remove geo model from its cluster * called whenever a model is removed from the collection */ removeGeoModelFromMap: function (model) { var cluster = model.get('legend').cluster; cluster.removeLayer(model.get('leaflet')); }, /* * show / hide from map items of a legend group */ toggleLegendGroup: function (legend, visible) { var method = (visible) ? 'addLayer' : 'removeLayer'; this.map[method](legend.cluster); }, /* * show / hide from map items of a legend group */ toggleLayerData: function (layer, visible) { var geo = this.collection, method = (visible) ? 'addLayers' : 'removeLayers', l; Ns.db.legend.forEach(function(legend){ l = geo.whereCollection({ legend: legend, layer: layer.id }).pluck('leaflet'); legend.cluster[method](l); }); // needed to recalculate stats on legend this.trigger('layer-toggled'); }, /* * Open leaflet popup of the specified element */ openLeafletPopup: function (id) { var collection = this.collection, self = this, leafletLayer; // open leaflet pop up if ready if (collection.length && typeof collection !== 'undefined') { try { leafletLayer = this.collection.get(id).get('leaflet'); } catch (e) { $.createModal({ message: id + ' ' + gettext('not found'), onClose: function () { Ns.router.navigate('map'); } }); return; } try { leafletLayer.openPopup(); } // clustering plugin hides leafletLayers when clustered or outside viewport // so we have to zoom in and center the map catch (e){ this.map.fitBounds(leafletLayer.getBounds()); leafletLayer.openPopup(); } } // if not ready wait for map.collectionReady and call again else { this.collection.once('ready', function () { self.openLeafletPopup(id); }); } return; }, /* * Close leaflet popup if open */ closeLeafletPopup: function () { var popup = $('#map-js .leaflet-popup-close-button'); if (popup.length) { popup.get(0).click(); } }, /* * Go to specified latitude and longitude */ goToLatLng: function (latlng, zoom) { latlng = latlng.split(',') latlng = L.latLng(latlng[0], latlng[1]); var self = this, marker = L.marker(latlng); // used in search address feature if (!zoom) { marker.addTo(this.map); zoom = 18; } // go to marker and zoom in this.map.setView(latlng, zoom); // fade out marker if (typeof(marker) !== 'undefined' && this.map.hasLayer(marker)) { $([marker._icon, marker._shadow]).fadeOut(4000, function () { self.map.removeLayer(marker); }); } } }); Ns.views.map.Legend = Marionette.ItemView.extend({ id: 'map-legend', className: 'overlay inverse', template: '#map-legend-template', ui: { 'close': 'a.icon-close' }, events: { 'click @ui.close': 'toggleLegend', 'click li a': 'toggleGroup' }, collectionEvents: { // automatically render when toggling group or recounting 'change:visible counted': 'render' }, initialize: function (options) { this.parent = options.parent; this.collection = Ns.db.legend; this.legendButton = this.parent.toolbar.currentView.ui.legendButton; // display count in legend this.listenTo(this.parent.content.currentView.collection, 'ready', this.count); this.listenTo(this.parent.content.currentView, 'layer-toggled', this.count); }, onRender: function () { // default is true if (localStorage.getObject('legendOpen') === false) { this.$el.hide(); } else { this.legendButton.addClass('disabled'); } }, /* * calculate counts */ count: function () { this.collection.forEach(function (legend) { legend.set('count', legend.cluster.getLayers().length); }); // trigger once all legend items have been counted this.collection.trigger('counted'); }, /* * open or close legend */ toggleLegend: function (e) { e.preventDefault(); var legend = this.$el, button = this.legendButton, open; if (legend.is(':visible')) { legend.fadeOut(255); button.removeClass('disabled'); button.tooltip('enable'); open = false; } else { legend.fadeIn(255); button.addClass('disabled'); button.tooltip('disable').tooltip('hide'); open = true; } localStorage.setItem('legendOpen', open); }, /* * enable or disable something on the map * by clicking on its related legend control */ toggleGroup: function (e) { e.preventDefault(); var status = $(e.currentTarget).attr('data-status'), item = this.collection.get(status); item.set('visible', !item.get('visible')); } }); Ns.views.map.Toolbar = Marionette.ItemView.extend({ template: '#map-toolbar-template', ui: { 'buttons': 'a', 'switchMapMode': '#btn-map-mode', 'legendButton': '#btn-legend', 'toolsButton': 'a.icon-tools', 'prefButton': 'a.icon-config', 'layersControl': 'a.icon-layer-2' }, events: { 'click .icon-pin-add': 'addNode', 'click @ui.buttons': 'togglePanel', 'click @ui.switchMapMode': 'switchMapMode', // siblings events 'click @ui.legendButton': 'toggleLegend' }, initialize: function (options) { this.parent = options.parent; }, onRender: function () { var self = this; // init tooltip this.ui.buttons.tooltip(); // correction for map tools this.ui.toolsButton.click(function (e) { var button = $(this), prefButton = self.ui.prefButton; if (button.hasClass('active')) { prefButton.tooltip('disable'); } else { prefButton.tooltip('enable'); } }); // correction for map-filter this.ui.layersControl.click(function (e) { var button = $(this), otherButtons = self.$el.find('a.icon-config, a.icon-3d, a.icon-tools'); if (button.hasClass('active')) { otherButtons.tooltip('disable'); } else { otherButtons.tooltip('enable'); } }); }, /* * show / hide map toolbar on narrow screens */ toggleToolbar: function (e) { e.preventDefault(); // shortcut var toolbar = this.parent.toolbar.$el, target = $(e.currentTarget); // show toolbar if (toolbar.is(':hidden')) { // just add display:block // which overrides css media-query toolbar.show(); // overimpose on toolbar target.css('right', '-60px'); } // hide toolbar else { // instead of using jQuery.hide() which would hide the toolbar also // if the user enlarged the screen, we clear the style attribute // which will cause the toolbar to be hidden only on narrow screens toolbar.attr('style', ''); // close any open panel if ($('.side-panel:visible').length) { $('.mask').trigger('click'); } // eliminate negative margin correction target.css('right', '0'); } Ns.views.map.Layout.resizeMap(); }, /* * proxy to call add node */ addNode: function (e) { e.preventDefault(); this.parent.addNode(); }, /* * redirects to Ns.views.map.Panels */ toggleLegend: function (e) { this.parent.legend.currentView.toggleLegend(e); }, /* * redirects to Ns.views.map.Panels */ togglePanel: function (e) { this.parent.panels.currentView.togglePanel(e); }, /* * toggle 3D or 2D map */ switchMapMode: function (e) { e.preventDefault(); $.createModal({message: gettext('not implemented yet')}); } }); Ns.views.map.Panels = Marionette.ItemView.extend({ template: '#map-panels-template', ui: { 'switches': 'input.switch', 'scrollers': '.scroller', 'selects': '.selectpicker', 'tools': '.tool', 'distance': '#fn-map-tools .icon-ruler', 'area': '#fn-map-tools .icon-select-area', 'elevation': '#fn-map-tools .icon-elevation-profile' }, events: { 'click #fn-map-tools .notImplemented': 'toggleToolNotImplemented', 'click @ui.distance': 'toggleDistance', 'click @ui.area': 'toggleArea', 'click @ui.elevation': 'toggleElevation', 'click #toggle-toolbar': 'toggleToolbar', 'change .js-base-layers input': 'switchBaseLayer', 'switch-change #fn-map-layers .toggle-layer-data': 'toggleLayer', 'switch-change #fn-map-layers .toggle-legend-data': 'toggleLegend' }, initialize: function (options) { this.parent = options.parent; this.mapView = this.parent.content.currentView; this.toolbarView = this.parent.toolbar.currentView; this.toolbarButtons = this.toolbarView.ui.buttons; // listen to legend change event this.listenTo(Ns.db.legend, 'change:visible', this.syncLegendSwitch); this.populateBaseLayers(); // init tools if (Ns.settings.mapTools) { this.tools = { 'distance': new L.Polyline.Measure(this.mapView.map), 'area': new L.Polygon.Measure(this.mapView.map), 'elevation': new L.Polyline.Elevation(this.mapView.map) }; } }, // populate this.baseLayers populateBaseLayers: function () { var self = this, layer; this.baseLayers = []; // get ordering of baselayers django-leaflet options this.mapView.map.options.djoptions.layers.forEach(function (layerConfig) { layer = self.mapView.baseLayers[layerConfig[0]]; self.baseLayers.push({ checked: Boolean(layer._map), // if _map is not null it means this is the active layer name: layer.name }); }); }, serializeData: function(){ return { 'layers': Ns.db.layers.toJSON(), 'legend': Ns.db.legend.toJSON(), 'baseLayers': this.baseLayers } }, onRender: function () { this.ui.tools.tooltip(); // activate switch this.ui.switches.bootstrapSwitch().bootstrapSwitch('setSizeClass', 'switch-small'); // activate scroller this.ui.scrollers.scroller({ trackMargin: 6 }); // fancy selects this.ui.selects.selectpicker({ style: 'btn-special' }); }, /* * show / hide toolbar panels */ togglePanel: function (e) { e.preventDefault(); var button = $(e.currentTarget), panelId = button.attr('data-panel'), panel = $('#' + panelId), self = this, // determine distance from top distanceFromTop = button.offset().top - $('body > header').eq(0).outerHeight(), preferencesHeight; // if no panel return here if (!panel.length) { return; } // hide any open tooltip $('#map-toolbar .tooltip').hide(); panel.css('top', distanceFromTop); // adjust height of panel if marked as 'adjust-height' if (panel.hasClass('adjust-height')) { preferencesHeight = $('#map-toolbar').height() - distanceFromTop - 18; panel.height(preferencesHeight); } panel.fadeIn(25, function () { panel.find('.scroller').scroller('reset'); button.addClass('active'); button.tooltip('hide').tooltip('disable'); // create a mask for easy closing $.mask(panel, function (e) { // close function if (panel.is(':visible')) { panel.hide(); self.toolbarButtons.removeClass('active'); button.tooltip('enable'); // if clicking again on the same button avoid reopening the panel if ($(e.target).attr('data-panel') === panelId) { e.stopPropagation(); e.preventDefault(); } } }); }); }, toggleToolNotImplemented: function (e) { e.preventDefault(); $.createModal({ message: gettext('not implemented yet') }); return false; }, /* * toggle map tool */ toggleToolButton: function (e) { var button = $(e.currentTarget), active_buttons = $('#fn-map-tools .tool.active'); // if activating a tool if (!button.hasClass('active')) { // deactivate any other active_buttons.trigger('click'); button.addClass('active') .tooltip('hide') .tooltip('disable'); return true; // deactivate } else { button.removeClass('active') .tooltip('enable') .trigger('blur'); return false; } }, toggleDrawTool: function (toolName, e) { var result = this.toggleToolButton(e), tool = this.tools[toolName]; if (result) { tool.enable(); // if tool is disabled with ESC or other ways // sync the nodeshot UI tool.once('disabled', function () { this.toggleToolButton(e); }, this); } else { tool.off('disabled'); tool.disable(); } }, toggleDistance: function (e) { this.toggleDrawTool('distance', e); }, toggleArea: function (e) { this.toggleDrawTool('area', e); }, toggleElevation: function (e) { this.toggleDrawTool('elevation', e); }, drawElevation: function (geojson) { // local vars var points = [], self = this; // the elevation API expects latitude, longitude, so we have to reverse our coords geojson.geometry.coordinates.forEach(function(point){ points.push(point.reverse()); }); // query the elevation API $.getJSON(Ns.url('elevation/'), { // output is '<lat>,<lng>|<lat>,<lng>|<lat>,<lng' path: points.join('|') }).done(function(geojson){ // close tools panel $('.mask').trigger('click'); // create control var el = L.control.elevation({ position: 'bottomright', width: 1020, height: 299, margins: { top: 25, right: 40, bottom: 40, left: 70 }, }); el.addTo(self.mapView.map); var geojsonLayer = L.geoJson(geojson, { onEachFeature: el.addData.bind(el), style: function () { return { color: '#e6a1b3', opacity: 0.7 } } }).addTo(self.mapView.map); var close = $('<a href="#" class="icon-close"></a>'); $('#map-js .elevation.leaflet-control').append('<a href="#" class="icon-close"></a>'); $('#map-js .elevation.leaflet-control .icon-close').one('click', function (e) { e.preventDefault(); self.mapView.map.removeControl(el); self.mapView.map.removeLayer(geojsonLayer); }) }); }, /* * proxy to Ns.views.map.Toolbar.toggleToolbar */ toggleToolbar: function (e) { this.toolbarView.toggleToolbar(e); }, /** * changes base layer of the map * proxy to Ns.views.map.Content.switchBaseLayer */ switchBaseLayer: function (event) { this.mapView.switchBaseLayer($(event.target).attr('data-name')); }, /** * hide / show layer data on map */ toggleLayer: function (event, data) { var layer = Ns.db.layers.get(data.el.attr('data-slug')); layer.set('visible', data.value); }, /** * hide / show legend data on map */ toggleLegend: function(event, data){ this.parent.legend.currentView.$('a[data-status=' + data.el.attr('data-slug') + ']').trigger('click'); }, /** * sync legend state with switches in panel */ syncLegendSwitch: function(legend, state){ var input = this.$('#map-control-legend-' + legend.get('slug')); if(input.bootstrapSwitch('state') !== state){ // second parameter indicates wheter to skip triggering switch event input.bootstrapSwitch('toggleState', true); } } }); Ns.views.map.Add = Marionette.ItemView.extend({ template: '#map-add-node-template', tagName: 'article', ui: { 'formContainer': '#add-node-form-container' }, events: { 'click #add-node-form-container .btn-default': 'destroy', 'submit #add-node-form-container form': 'submitAddNode' }, initialize: function (options) { this.parent = options.parent; // references to objects of other views this.ext = { legend: this.parent.legend.$el, toolbar: this.parent.toolbar.$el, map: this.parent.content.$el, leafletMap: this.parent.content.currentView.map, geo: this.parent.content.currentView.collection, step1: $('#add-node-step1'), step2: $('#add-node-step2') }; // elements that must be hidden this.hidden = $().add(this.ext.legend) .add(this.ext.toolbar) .add(this.ext.map.find('.leaflet-control-attribution')); // needed for toggleLeafletLayers this.dimmed = false; }, serializeData: function(){ return { 'layers': Ns.db.layers.toJSON() }; }, onShow: function () { Ns.router.navigate('map/add'); Ns.changeTitle(gettext('Add node')); Ns.track(); // go to step1 when collection is ready if (this.ext.geo.length){ this.step1(); } else { this.listenToOnce(this.ext.geo, 'ready', this.step1); } // dynamic form this.form = new Backbone.Form({ model: new Ns.models.Node(), submitButton: gettext('Add node') }).render(); this.ui.formContainer.html(this.form.$el); this.$('input[type=checkbox]').bootstrapSwitch().bootstrapSwitch('setSizeClass', 'switch-small'); this.$('select').selectpicker({style: 'btn-special' }); }, /* * when the view is destroyed the map is taken backto its original state */ onBeforeDestroy: function () { this.closeAddNode(); // change url fragment but only if we are still on the map if (Backbone.history.fragment.substr(0, 3) == 'map'){ Ns.router.navigate('map'); } }, /* * proxy to Ns.views.map.Layout.resizeMap */ resizeMap: function() { Ns.views.map.Layout.resizeMap(); }, /* * hide elements that are not needed when adding a new node * show them back when finished */ toggleHidden: function(){ this.hidden.toggle(); this.resizeMap(); this.toggleLeafletLayers(); }, /* * dim out leaflet layers from map when adding a new node * reset default options when finished * clusters are toggled (hidden and shown back) through an additional style tag in <head> * because clusters are re-rendered whenever the map is moved or resized so inline changes * do not persist when resizing or moving */ toggleLeafletLayers: function () { var leafletOptions = Ns.settings.leafletOptions, tmpOpacity = leafletOptions.temporaryOpacity, clusterCss = $('#add-node-cluster-css'), dimOut = !this.dimmed, leaflet; // dim out or reset all leaflet layers this.ext.geo.forEach(function(model){ leaflet = model.get('leaflet'); if (dimOut) { leaflet.options.opacity = tmpOpacity; leaflet.options.fillOpacity = tmpOpacity; leaflet.setStyle(leaflet.options); } else { leaflet.options.opacity = leafletOptions.opacity; leaflet.options.fillOpacity = leafletOptions.fillOpacity; leaflet.setStyle(leaflet.options); } }); if (clusterCss.length === 0) { $('head').append('<style id="add-node-cluster-css">.cluster{ display: none }</style>'); } else{ clusterCss.remove(); } // change dimmed state this.dimmed = dimOut; }, /* * step1 of adding a new node */ step1: function (e) { var self = this, dialog = this.ext.step1, dialog_dimensions = dialog.getHiddenDimensions(); // hide toolbar and enlarge map this.toggleHidden(); // show step1 dialog.css({ width: dialog_dimensions.width+2, right: 0 }); dialog.fadeIn(255); // cancel this.ext.step1.find('button').one('click', function () { self.destroy() }); // on map click (only once) this.ext.leafletMap.once('click', function (e) { dialog.fadeOut(255); self.step2(e); }); }, step2: function (e) { var self = this, dialog = this.ext.step2, dialog_dimensions = dialog.getHiddenDimensions(), map = this.ext.leafletMap, callback, latlng, // draggable marker marker = L.marker([e.latlng.lat, e.latlng.lng], {draggable: true}).addTo(map); // keep a global reference this.newNodeMarker = marker; // set address on form this.setAddressFromLatLng(e.latlng); this.form.setValue('geometry', JSON.stringify(marker.toGeoJSON())); this.setGeometryFromMarker(marker); // update address when moving the marker marker.on('dragend', function (event) { latlng = event.target.getLatLng(); self.setAddressFromLatLng(latlng); self.setGeometryFromMarker(event.target); map.panTo(latlng); }); // zoom in to marker map.setView(marker.getLatLng(), 18, { animate: true }); // show step2 dialog = self.ext.step2, dialog_dimensions = dialog.getHiddenDimensions(); dialog.css({ width: dialog_dimensions.width+2, right: 0 }); dialog.fadeIn(255); // bind cancel button once this.ext.step2.find('.btn-default').one('click', function () { self.destroy() }); // bind confirm button once this.ext.step2.find('.btn-success').one('click', function () { callback = function () { self.resizeMap(); map.panTo(marker._latlng); }; dialog.fadeOut(255); // show form with a nice animation self.parent.add.$el.show().animate({ width: '+70%'}, { duration: 400, progress: callback, complete: callback }); }); }, /* * submit new node */ submitAddNode: function (e) { e.preventDefault(); var self = this, form = this.form, geojson = JSON.stringify(this.newNodeMarker.toGeoJSON().geometry), errorList = this.$('.error-list'), node = form.model, errors = form.commit(), geo; if (errors) { return false; } this.$('.help-block').text('').hide(); this.$('.error').removeClass('error'); this.$('.has-error').removeClass('has-error'); errorList.html('').hide(); node.save().done(function () { // convert to Geo model node = new Ns.models.Geo(node.toJSON()); // add to geo collection self.ext.geo.add(node); // destroy this view self.destroy(); // open new node popup node.get('leaflet').openPopup(); }).error(function (http) { // TODO: make this reusable var json = http.responseJSON, key, input, errorContainer; for (key in json) { input = self.$('input[name=' + key + ']'); if (input.length) { input.addClass('error'); errorContainer = input.parents('.form-group').find('.help-block'); errorContainer.text(json[key]) .removeClass('hidden') .addClass('has-error') .fadeIn(255); } else { errorList.show(); errorList.append('<li>' + json[key] + '</li>'); } } }); }, /* * cancel addNode operation * resets normal map functions */ closeAddNode: function () { var marker = this.newNodeMarker, container = this.parent.add.$el, map = this.ext.leafletMap, self = this, resetToOriginalState = function () { container.hide(); // show hidden elements again self.toggleHidden(); }; // unbind click events map.off('click'); this.ext.step1.find('button').off('click'); this.ext.step2.find('.btn-default').off('click'); this.ext.step2.find('.btn-success').off('click'); // remove marker if necessary if (marker) { map.removeLayer(marker); } // hide step1 if necessary if (this.ext.step1.is(':visible')) { this.ext.step1.fadeOut(255); } // hide step2 if necessary if (this.ext.step2.is(':visible')) { this.ext.step2.fadeOut(255); } // if container is visible if (container.is(':visible')) { // hide it with a nice animation container.animate({ width: '0' }, { duration: 400, progress: function () { self.resizeMap(); if (marker) { map.panTo(marker._latlng); } }, complete: resetToOriginalState }); } // reset original state else{ resetToOriginalState(); } }, /* * retrieve address from latlng through OSM Nominatim service * and set it on the add node form */ setAddressFromLatLng: function (latlng) { var self = this; $.geocode({ lat: latlng.lat, lon: latlng.lng, callback: function(result){ self.form.setValue('address', result.display_name); } }); }, /** * set geometry on model from marker geojson */ setGeometryFromMarker: function (marker) { this.form.setValue('geometry', JSON.stringify(marker.toGeoJSON().geometry)); } }); })();
ninuxorg/nodeshot
nodeshot/ui/default/static/ui/nodeshot/js/views/map.js
JavaScript
gpl-3.0
50,921
/******************************************************************************* * Copyright (c) 2013 Christian Wiwie. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Christian Wiwie - initial API and implementation ******************************************************************************/ /** * */ package de.clusteval.data.statistics; import java.io.File; import de.clusteval.framework.RLibraryRequirement; import de.clusteval.framework.repository.RegisterException; import de.clusteval.framework.repository.Repository; /** * @author Christian Wiwie * */ @RLibraryRequirement(requiredRLibraries = {"igraph"}) public class ClusteringCoefficientRDataStatistic extends DoubleValueDataStatistic { /* * (non-Javadoc) * * @see utils.Statistic#getAlias() */ @Override public String getAlias() { return "Clustering Coefficient (R)"; } /** * @param repository * @param register * @param changeDate * @param absPath * @throws RegisterException * */ public ClusteringCoefficientRDataStatistic(final Repository repository, final boolean register, final long changeDate, final File absPath) throws RegisterException { super(repository, register, changeDate, absPath, 0.0); } /** * @param repository * @param register * @param changeDate * @param absPath * @param value * @throws RegisterException */ public ClusteringCoefficientRDataStatistic(final Repository repository, final boolean register, final long changeDate, final File absPath, final double value) throws RegisterException { super(repository, register, changeDate, absPath, value); } /** * The copy constructor for this statistic. * * @param other * The object to clone. * @throws RegisterException */ public ClusteringCoefficientRDataStatistic( final ClusteringCoefficientRDataStatistic other) throws RegisterException { super(other); } /* * (non-Javadoc) * * @see data.statistics.DataStatistic#requiresGoldStandard() */ @Override public boolean requiresGoldStandard() { return false; } }
deric/clusteval-parent
clusteval-packages/src/main/java/de/clusteval/data/statistics/ClusteringCoefficientRDataStatistic.java
Java
gpl-3.0
2,303
YUI(M.yui.loader, {lang: M.local_mail_lang}).use('io-base', 'node', 'json-parse', 'panel', 'datatable-base', 'dd-plugin', 'moodle-form-dateselector', 'datatype-date', 'calendar-base', function(Y) { var mail_message_view = false; var mail_checkbox_labels_default = {}; var mail_view_type = ''; var mail_edit_label_panel; var mail_new_label_panel; var mail_undo_function = ''; var mail_undo_ids = ''; var mail_search_selected = ''; var mail_searchfrom_selected = ''; var mail_searchto_selected = ''; var mail_unread_selected = false; var mail_attach_selected = false; var mail_date_selected = ''; var mail_doing_search = false; var mail_after_message_search = false; var mail_before_message_search = false; var mail_perpageid = 0; var init = function(){ mail_view_type = Y.one('input[name="type"]').get('value'); if (Y.one('input[name="m"]')) { mail_message_view = true; Y.one('.mail_checkbox_all').remove(); } mail_enable_all_buttons(mail_message_view); if (!mail_message_view) { mail_select_none(); } if (mail_view_type == 'trash') { mail_remove_action('.mail_menu_action_markasstarred'); mail_remove_action('.mail_menu_action_markasunstarred'); } mail_update_menu_actions(); mail_create_edit_label_panel(); mail_create_new_label_panel(); mail_define_label_handlers(); }; var mail_define_label_handlers = function () { if (Y.one('#local_mail_form_new_label')) { //Click on new label color div Y.one('#local_mail_form_new_label').delegate('click', function(e) { e.stopPropagation(); mail_label_set_selected(this, 'new'); }, '.mail_label_color'); } if (Y.one('#local_mail_form_edit_label')) { //Click on edit label color div Y.one('#local_mail_form_edit_label').delegate('click', function(e) { e.stopPropagation(); mail_label_set_selected(this, 'edit'); }, '.mail_label_color'); } }; var mail_create_edit_label_panel = function () { var title = M.util.get_string('editlabel', 'local_mail'); var obj = (Y.one('.mail_list')?Y.one('.mail_list'):Y.one('.mail_view')); var position = obj.getXY(); var width = 400; var posx = position[0]+(Y.one('body').get('offsetWidth')/2)-width; mail_edit_label_panel = new Y.Panel({ srcNode : '#local_mail_form_edit_label', headerContent: title, width : width, zIndex : 5, centered : false, modal : true, visible : false, render : true, xy : [posx,position[1]], plugins : [Y.Plugin.Drag] }); mail_edit_label_panel.addButton({ value : M.util.get_string('submit', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_edit_label_panel.hide(); mail_doaction('setlabel'); } }); mail_edit_label_panel.addButton({ value : M.util.get_string('cancel', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_edit_label_panel.hide(); } }); }; var mail_create_new_label_panel = function () { var title = M.util.get_string('newlabel', 'local_mail'); var obj = (Y.one('.mail_list')?Y.one('.mail_list'):Y.one('.mail_view')); var position = obj.getXY(); var width = 400; var posx = position[0]+(Y.one('body').get('offsetWidth')/2)-width; mail_new_label_panel = new Y.Panel({ srcNode : '#local_mail_form_new_label', headerContent: title, width : width, zIndex : 5, centered : true, modal : true, visible : false, render : true, xy : [posx,position[1]], plugins : [Y.Plugin.Drag] }); mail_new_label_panel.addButton({ value : M.util.get_string('submit', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_new_label_panel.hide(); mail_doaction('newlabel'); } }); mail_new_label_panel.addButton({ value : M.util.get_string('cancel', 'moodle'), section: Y.WidgetStdMod.FOOTER, action : function (e) { e.preventDefault(); mail_new_label_panel.hide(); } }); }; var mail_hide_actions = function() { Y.all('.mail_menu_actions li').each(function(node){ node.hide(); }); mail_show_label_actions(false); }; var mail_show_label_actions = function(separator) { if (mail_view_type == 'label' && !mail_message_view) { if (separator) { Y.one('.mail_menu_action_separator').ancestor('li').show(); } Y.one('.mail_menu_action_editlabel').ancestor('li').show(); Y.one('.mail_menu_action_removelabel').ancestor('li').show(); } }; var mail_update_menu_actions = function() { var separator = false; mail_hide_actions(); if (mail_message_view) { if (mail_view_type == 'trash') { Y.one('.mail_menu_action_markasunread').ancestor('li').show(); } else { Y.one('.mail_menu_action_markasunread').ancestor('li').show(); if (Y.one('.mail_flags span').hasClass('mail_starred')) { Y.one('.mail_menu_action_markasunstarred').ancestor('li').show(); } else { Y.one('.mail_menu_action_markasstarred').ancestor('li').show(); } } } else { if (Y.all('.mail_selected.mail_unread').size()) { Y.one('.mail_menu_action_markasread').ancestor('li').show(); separator = true; } if (Y.all('.mail_selected.mail_unread').size() < Y.all('.mail_selected').size()) { Y.one('.mail_menu_action_markasunread').ancestor('li').show(); separator = true; } if (Y.all('.mail_selected span.mail_starred').size()) { Y.one('.mail_menu_action_markasunstarred').ancestor('li').show(); separator = true; } if (Y.all('.mail_selected span.mail_unstarred').size()) { Y.one('.mail_menu_action_markasstarred').ancestor('li').show(); separator = true; } } mail_show_label_actions(separator); }; var mail_toggle_menu = function() { var button = Y.one('.mail_checkbox_all'); var menu = Y.one('.mail_optselect'); var position = button.getXY(); if (!button.hasClass('mail_button_disabled')) { position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); } }; var mail_hide_menu_options = function() { Y.one('.mail_optselect').addClass('mail_hidden'); }; var mail_hide_menu_actions = function() { Y.one('.mail_actselect').addClass('mail_hidden'); }; var mail_hide_menu_labels = function() { if (mail_view_type != 'trash') { Y.one('.mail_labelselect').addClass('mail_hidden'); } }; var mail_hide_menu_search = function() { var menu = Y.one('#mail_menu_search'); if (menu) { menu.addClass('mail_hidden'); } if (M.form.dateselector.panel) { M.form.dateselector.panel.hide(); } }; var mail_toggle_menu_actions = function() { var button = Y.one('.mail_more_actions'); var menu = Y.one('.mail_actselect'); var position = button.getXY(); if (!button.hasClass('mail_button_disabled')) { position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); } }; var mail_toggle_menu_labels = function() { var button = Y.one('.mail_assignlbl'); var menu = Y.one('.mail_labelselect'); var position = button.getXY(); if (!button.hasClass('mail_button_disabled')) { position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); } }; var mail_toggle_menu_search = function() { var button = Y.one('#mail_search'); var menu = Y.one('#mail_menu_search'); var advsearch = Y.one('#mail_adv_search'); var position = button.getXY(); var date; position[1] += button.get('clientHeight') + 2; menu.toggleClass('mail_hidden'); menu.setXY(position); if (!menu.hasClass('mail_hidden')) { Y.one('#textsearch').focus(); if (!advsearch.hasClass('mail_hidden')) { mail_position_datepicker(); } if (mail_doing_search) { Y.one('#buttoncancelsearch').removeClass('mail_hidden'); } else { Y.one('#buttoncancelsearch').addClass('mail_hidden'); } } else { M.form.dateselector.panel.hide(); } }; var mail_toggle_adv_search = function() { var menu = Y.one('#mail_adv_search'); var status = Y.one('#mail_adv_status'); menu.toggleClass('mail_hidden'); if (menu.hasClass('mail_hidden')) { M.form.dateselector.panel.hide(); status.set('src', M.util.image_url('t/collapsed', 'moodle')); status.set('alt', 'collapsed'); } else { mail_position_datepicker(); status.set('src', M.util.image_url('t/expanded', 'moodle')); status.set('alt' ,'expanded'); } }; var mail_do_search = function() { mail_doing_search = true; mail_perpageid = 0; mail_search_selected = Y.one('#textsearch').get('value'); mail_searchfrom_selected = Y.one('#textsearchfrom').get('value'); mail_searchto_selected = Y.one('#textsearchto').get('value'); mail_unread_selected = Y.one('#searchunread').get('checked'); mail_attach_selected = Y.one('#searchattach').get('checked'); mail_select_none(); mail_check_selected(); Y.all('.mail_paging input').set('disabled', 'disabled'); mail_show_loading_image(); mail_doaction('search'); mail_hide_menu_search(); }; var mail_show_loading_image = function() { Y.one('.mail_list').addClass('mail_hidden'); Y.one('.mail_search_loading').removeClass('mail_hidden'); }; var mail_update_form_search = function() { Y.one('#textsearch').set('value', mail_search_selected); Y.one('#textsearchfrom').set('value', mail_searchfrom_selected); Y.one('#textsearchto').set('value', mail_searchto_selected); if (mail_unread_selected) { Y.one('#searchunread').set('checked', 'checked'); } if (mail_attach_selected) { Y.one('#searchattach').set('checked', 'checked'); } }; var mail_remove_action = function(action) { Y.one(action).ancestor('li').remove(); }; var mail_customize_menu_actions = function(checkbox) { var menu = Y.one('.mail_menu_actions'); var mailitem = checkbox.ancestor('.mail_item'); var separator = false; var nodes; if (mail_is_checkbox_checked(checkbox)) { //Read or unread if (mailitem.hasClass('mail_unread')) { menu.one('a.mail_menu_action_markasread').ancestor('li').show(); separator = true; } else { menu.one('a.mail_menu_action_markasunread').ancestor('li').show(); separator = true; } //Starred or unstarred if (mail_view_type != 'trash' && mailitem.one('.mail_flags span').hasClass('mail_starred')) { menu.one('a.mail_menu_action_markasunstarred').ancestor('li').show(); separator = true; } else { if (mail_view_type != 'trash') { menu.one('a.mail_menu_action_markasstarred').ancestor('li').show(); separator = true; } } } else { if (!Y.all('.mail_list .mail_selected').size()) { mail_hide_actions(); } else { //Read or unread if (mailitem.hasClass('mail_unread')) { if (!mailitem.siblings('.mail_selected.mail_unread').size()) { menu.one('a.mail_menu_action_markasread').ancestor('li').hide(); } } else { if (mailitem.siblings('.mail_selected.mail_unread').size() == mailitem.siblings('.mail_selected').size()) { menu.one('a.mail_menu_action_markasunread').ancestor('li').hide(); } } //Starred or unstarred if (mail_view_type != 'trash' && mailitem.one('.mail_flags a span').hasClass('mail_starred')) { nodes = mailitem.siblings(function(obj) { return obj.hasClass('mail_selected') && obj.one('.mail_flags a span.mail_starred'); }); if (!nodes.size()) { menu.one('a.mail_menu_action_markasunstarred').ancestor('li').hide(); } } else { nodes = mailitem.siblings(function(obj) { return obj.hasClass('mail_selected') && obj.one('.mail_flags a span.mail_unstarred'); }); if (mail_view_type != 'trash' && !nodes.size()) { menu.one('a.mail_menu_action_markasstarred').ancestor('li').hide(); } } } } mail_show_label_actions(separator); }; var mail_label_default_values = function () { var grouplabels; if (Y.one('.mail_labelselect').hasClass('mail_hidden')) { Y.each(M.local_mail.mail_labels, function (label, index) { mail_checkbox_labels_default[index] = 0; }); if (mail_message_view) { grouplabels = Y.all('.mail_group_labels span'); if (grouplabels) { mail_set_label_default_values(grouplabels); } } else { var nodes = mail_get_checkboxs_checked(); Y.each(nodes, function (node, index) { grouplabels = node.ancestor('.mail_item').all('.mail_group_labels span'); if (grouplabels) { mail_set_label_default_values(grouplabels); } }); } mail_label_set_values(); } }; var mail_set_label_default_values = function (grouplabels) { var classnames = []; var num; Y.each(grouplabels, function (grouplabel, index) { classnames = grouplabel.getAttribute('class').split(' '); Y.each(classnames, function(classname){ num = /mail_label_(\d+)/.exec(classname); if (num) { mail_checkbox_labels_default[num[1]] += 1; } }); }); if (mail_view_type == 'label') { num = parseInt(Y.one('input[name="itemid"]').get('value'), 10); mail_checkbox_labels_default[num] += 1; } }; var mail_menu_label_selection = function (node) { var checkbox = node.one('.mail_adv_checkbox'); if (checkbox) { mail_toggle_checkbox(checkbox); } }; var mail_customize_menu_label = function() { if (Y.all('.mail_menu_labels li').size() > 1) { if(mail_label_check_default_values()) { Y.one('.mail_menu_labels .mail_menu_label_newlabel').removeClass('mail_hidden'); Y.one('.mail_menu_labels .mail_menu_label_apply').addClass('mail_hidden'); } else { Y.one('.mail_menu_labels .mail_menu_label_newlabel').addClass('mail_hidden'); Y.one('.mail_menu_labels .mail_menu_label_apply').removeClass('mail_hidden'); } } }; var mail_label_check_default_values = function () { var isdefault = true; var classname; var labelid; var num; var labels = Y.all('.mail_menu_labels .mail_adv_checkbox'); if (!mail_message_view) { var total = mail_get_checkboxs_checked().size(); Y.each(labels, function(label, index) { classname = label.getAttribute('class'); num = /mail_label_value_(\d+)/.exec(classname); if (num) { labelid = num[1]; if (mail_checkbox_labels_default[labelid] == total) { isdefault = isdefault && label.hasClass('mail_checkbox1'); } else if(mail_checkbox_labels_default[labelid] > 0) { isdefault = isdefault && label.hasClass('mail_checkbox2'); } else { isdefault = isdefault && label.hasClass('mail_checkbox0'); } } }); } else { Y.each(labels, function(label, index) { classname = label.getAttribute('class'); num = /mail_label_value_(\d+)/.exec(classname); if (num) { labelid = num[1]; if (mail_checkbox_labels_default[labelid] == 1) { isdefault = isdefault && label.hasClass('mail_checkbox1'); } else { isdefault = isdefault && label.hasClass('mail_checkbox0'); } } }); } return isdefault; }; var mail_label_set_values = function () { var total = (mail_message_view?1:mail_get_checkboxs_checked().size()); var state; Y.each(mail_checkbox_labels_default, function(value, index){ if (value == total) { state = 1; } else if(value > 0) { state = 2; } else { state = 0; } mail_set_checkbox(Y.one('.mail_menu_labels .mail_label_value_'+index), state); }); }; var mail_get_label_value = function(checkbox){ var value; classnames = checkbox.getAttribute('class').split(' '); Y.each(classnames, function(classname){ num = /mail_label_value_(\d+)/.exec(classname); if (num) { value = num[1]; } }); return value; }; var mail_get_labels_checked = function(){ return Y.all('.mail_menu_labels .mail_checkbox1'); }; var mail_get_labels_thirdstate = function(){ return Y.all('.mail_menu_labels .mail_checkbox2'); }; var mail_get_labels_values = function(thirdstate){ var nodes = (thirdstate?mail_get_labels_thirdstate():mail_get_labels_checked()); var values = []; Y.each(nodes, function (node, index) { values.push(mail_get_label_value(node)); }); return values.join(); }; var mail_assign_labels = function (node) { node = (typeof node !== 'undefined' ? node : false); var grouplabels; var elem; var labelid = 0; if (mail_message_view) { grouplabels = Y.one('.mail_group_labels'); } else { grouplabels = node.ancestor('.mail_item').one('.mail_group_labels'); } if (mail_view_type == 'label') { labelid = parseInt(Y.one('input[name="itemid"]').get('value'), 10); } var lblstoadd = mail_get_labels_values(false).split(','); var lblstoremain = mail_get_labels_values(true).split(','); Y.each(M.local_mail.mail_labels, function (value, index) { if (Y.Array.indexOf(lblstoadd, index) != -1) { if (index != labelid) { elem = grouplabels.one('.mail_label_'+index); if (!elem) { elem = Y.Node.create('<span class="mail_label mail_label_'+M.local_mail.mail_labels[index].color+' mail_label_'+index+'">'+M.local_mail.mail_labels[index].name+'</span>'); grouplabels.append(elem); } } } else if (Y.Array.indexOf(lblstoremain, index) == -1) { if (!mail_message_view && index == labelid) { grouplabels.ancestor('.mail_item').remove(); } else { elem = grouplabels.one('.mail_label_'+index); if (elem) { elem.remove(); } } } }); }; var mail_check_selected = function() { mail_enable_all_buttons(Y.all('.mail_selected').size()); }; var mail_enable_button = function(button, bool) { bool = (typeof bool !== 'undefined' ? bool : false); if (bool) { button.removeClass('mail_button_disabled'); } else if(!button.hasClass('mail_checkbox_all')){ button.addClass('mail_button_disabled'); } }; var mail_enable_all_buttons = function(bool) { var mail_buttons = Y.all('.mail_toolbar .mail_buttons .mail_button'); Y.each(mail_buttons, (function(button) { button.removeClass('mail_hidden'); mail_enable_button(button, bool); })); if (Y.one('#mail_search')) { mail_enable_button(Y.one('#mail_search'), true); } if (Y.one('#buttonsearch')) { mail_enable_button(Y.one('#buttonsearch'), true); } if (Y.one('#buttoncancelsearch')) { mail_enable_button(Y.one('#buttoncancelsearch'), true); } if (mail_view_type == 'label') { mail_enable_button(Y.one('.mail_toolbar .mail_more_actions'), true); } }; var mail_get_checkboxs_checked = function(){ return Y.all('.mail_list .mail_checkbox1'); }; var mail_get_checkbox_value = function(checkbox){ var value; classnames = checkbox.getAttribute('class').split(' '); Y.each(classnames, function(classname){ num = /mail_checkbox_value_(\d+)/.exec(classname); if (num) { value = num[1]; } }); return value; }; var mail_get_checkboxs_values = function(){ var nodes = mail_get_checkboxs_checked(); var values = []; Y.each(nodes, function (node, index) { values.push(mail_get_checkbox_value(node)); }); return values.join(); }; var mail_set_checkbox = function(node, value){ if (value == 1) { node.removeClass('mail_checkbox0').removeClass('mail_checkbox2').addClass('mail_checkbox1'); } else if (value == 2) { node.removeClass('mail_checkbox0').removeClass('mail_checkbox1').addClass('mail_checkbox2'); } else { node.removeClass('mail_checkbox1').removeClass('mail_checkbox2').addClass('mail_checkbox0'); } }; var mail_toggle_checkbox = function(node){ if (node.hasClass('mail_checkbox0')) { mail_set_checkbox(node, 1); } else { mail_set_checkbox(node, 0); } }; var mail_is_checkbox_checked = function(node){ return node.hasClass('mail_checkbox1'); }; var mail_main_checkbox = function(){ if(!Y.all('.mail_selected').size()) { mail_set_checkbox(Y.one('.mail_checkbox_all > .mail_adv_checkbox'), 0); } else if(Y.all('.mail_selected').size() == Y.all('.mail_item').size()) { mail_set_checkbox(Y.one('.mail_checkbox_all > .mail_adv_checkbox'), 1); } else { mail_set_checkbox(Y.one('.mail_checkbox_all > .mail_adv_checkbox'), 2); } mail_check_selected(); }; var mail_select_all = function(){ var checkbox = Y.one('.mail_checkbox_all > .mail_adv_checkbox'); mail_set_checkbox(checkbox, 1); var nodes = Y.all('.mail_list .mail_adv_checkbox'); nodes.each(function(node) { mail_set_checkbox(node, 1); node.ancestor('.mail_item').addClass('mail_selected'); }); }; var mail_select_none = function(){ var checkbox = Y.one('.mail_checkbox_all > .mail_adv_checkbox'); mail_set_checkbox(checkbox, 0); var nodes = Y.all('.mail_list .mail_adv_checkbox'); nodes.each(function(node) { mail_set_checkbox(node, 0); node.ancestor('.mail_item').removeClass('mail_selected'); }); }; var mail_select_read = function(){ var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (!ancestor.hasClass('mail_unread')){ mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; var mail_select_unread = function() { var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (ancestor.hasClass('mail_unread')){ mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; var mail_select_starred = function() { var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (ancestor.one('.mail_starred')) { mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; var mail_select_unstarred = function() { var nodes = Y.all('.mail_item > .mail_adv_checkbox'); var ancestor; if (nodes) { nodes.each(function(node) { ancestor = node.ancestor('.mail_item'); if (ancestor.one('.mail_unstarred')) { mail_set_checkbox(node, 1); ancestor.addClass('mail_selected'); } else { mail_set_checkbox(node, 0); ancestor.removeClass('mail_selected'); } }); } }; //Success call var handleSuccess = function (transactionid, response, args) { var obj = Y.JSON.parse(response.responseText); var img; var node; if (obj.msgerror) { alert(obj.msgerror); } else { if (obj.html) { Y.one('#local_mail_main_form').setContent(obj.html); init(); mail_update_url(); } if (obj.search) { mail_perpageid = obj.search.perpageid; mail_doing_search = true; Y.one('#mail_search').addClass('mail_button_searching'); Y.one('.mail_paging input[name="prevpage"]').set('disabled', 'disabled'); Y.one('.mail_paging input[name="nextpage"]').set('disabled', 'disabled'); Y.one('.mail_paging > span').addClass('mail_hidden'); mail_search_selected = obj.search.query; mail_searchfrom_selected = obj.search.searchfrom; mail_searchto_selected = obj.search.searchto; mail_unread_selected = obj.search.unread; mail_attach_selected = obj.search.attach; mail_date_selected = obj.search.date; mail_update_form_search(); if (obj.search.prev) { Y.one('.mail_paging input[name="prevpage"]').set('disabled', ''); } if (obj.search.next) { Y.one('.mail_paging input[name="nextpage"]').set('disabled', ''); } if (!mail_message_view) { mail_before_message_search = obj.search.idbefore; mail_after_message_search = obj.search.idafter; } } if (obj.info) { if (obj.info.root) { node = Y.one('.mail_root span'); if (node) { node.setContent(obj.info.root); } node = Y.one('.mail_root'); if (node) { if(obj.info.root.match(/\(\d+\)/)) { node.addClass('local_mail_new_messages'); } else { node.removeClass('local_mail_new_messages'); } } } if (obj.info.inbox) { node = Y.one('.mail_inbox a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_inbox a'); if (node) { node.setContent(img+obj.info.inbox); } } } if (obj.info.drafts) { node = Y.one('.mail_drafts a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_drafts a'); if (node) { node.setContent(img+obj.info.drafts); } } } if (obj.info.courses) { Y.each(obj.info.courses, (function(value, index) { node = Y.one('.mail_course_'+index+' a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_course_'+index+' a'); if (node) { Y.one('.mail_course_'+index+' a').setContent(img+value); } } })); } if (obj.info.labels) { Y.each(obj.info.labels, (function(value, index) { node = Y.one('.mail_label_'+index+' a img'); if (node) { img = node.get('outerHTML'); node = Y.one('.mail_label_'+index+' a'); if (node) { node.setContent(img+value); } } })); } } //Undo last action if (obj.undo && mail_undo_function != 'undo') { var msg = M.util.get_string('undo'+mail_undo_function, 'local_mail', obj.undo.split(',').length); if (mail_undo_function == 'delete') { mail_undo_function = 'restore'; } else if (mail_undo_function == 'restore') { mail_undo_function = 'delete'; } mail_notification_message(msg); mail_undo_ids = obj.undo; } else { mail_undo_function = ''; } if(obj.redirect) { document.location.href = obj.redirect; } } }; //Failure call var handleFailure = function (transactionid, response, args) { console.log(response); }; //Update screen data and async call var mail_doaction = function(action, node) { node = (typeof node !== 'undefined' ? node : null); var nodes = mail_get_checkboxs_checked(); var obj; var child; var ancestor; var ids; var request; var mail_view; if(mail_message_view) { if(action == 'togglestarred') { obj = node.one('span'); if (obj.hasClass('mail_starred')) { action = 'unstarred'; obj.replaceClass('mail_starred', 'mail_unstarred'); node.set('title', M.util.get_string('unstarred','local_mail')); } else { action = 'starred'; obj.replaceClass('mail_unstarred', 'mail_starred'); node.set('title', M.util.get_string('starred','local_mail')); } } else if (action == 'delete' || action == 'restore') { mail_undo_function = action; mail_message_view = false; } else if (action == 'starred') { node = Y.one('.mail_flags span'); node.replaceClass('mail_unstarred', 'mail_starred'); node.ancestor('a').set('title', M.util.get_string('starred','local_mail')); } else if (action == 'unstarred') { node = Y.one('.mail_flags span'); node.replaceClass('mail_starred', 'mail_unstarred'); node.ancestor('a').set('title', M.util.get_string('unstarred','local_mail')); } else if(action == 'markasunread') { mail_message_view = false; } else if(action == 'goback') { mail_message_view = false; } else if(action == 'assignlabels') { mail_assign_labels(); } mail_view = true; ids = Y.one('input[name="m"]').get('value'); } else {//List messages view if(action == 'viewmail') { nodes.empty(); var url = node.get('href'); if (url.match(/compose\.php/)){ document.location.href = url; return 0; } else { ids = /m=(\d+)/.exec(node.get('href'))[1]; } } else if (action == 'delete') { mail_undo_function = action; ids = mail_get_checkboxs_values(); } else if (action == 'restore') { mail_undo_function = action; ids = mail_get_checkboxs_values(); } else if (action == 'discard') { ids = mail_get_checkboxs_values(); } else if (action == 'undo') { nodes.empty(); action = mail_undo_function; mail_undo_function = 'undo'; ids = mail_undo_ids; } else if (action == 'togglestarred') { obj = node.ancestor('.mail_item').one('.mail_adv_checkbox'); nodes = Y.all(obj); if (node.one('span').hasClass('mail_starred')) { action = 'unstarred'; } else { action = 'starred'; } ids = mail_get_checkbox_value(obj); } else if(action == 'perpage' || action == 'search'){ nodes.empty(); } else { ids = mail_get_checkboxs_values(); } if (nodes.size()) { nodes.each(function (node) { ancestor = node.ancestor('.mail_item'); if (action == 'starred') { child = ancestor.one('.mail_unstarred'); if(child) { child.replaceClass('mail_unstarred', 'mail_starred'); child.ancestor('a').set('title', M.util.get_string('starred','local_mail')); } } else if(action == 'unstarred') { if (mail_view_type == 'starred') { ancestor.remove(); } else { child = ancestor.one('.mail_starred'); if(child) { child.replaceClass('mail_starred', 'mail_unstarred'); child.ancestor('a').set('title', M.util.get_string('unstarred','local_mail')); } } } else if(action == 'markasread') { ancestor.removeClass('mail_unread'); } else if(action == 'markasunread') { ancestor.addClass('mail_unread'); } else if(action == 'delete' || action == 'restore' || action == 'discard') { ancestor.remove(); } else if(action == 'assignlabels') { mail_assign_labels(node); } }); } mail_view = false; } //Ajax call var cfg = { method: 'POST', data: { msgs: ids, sesskey: Y.one('input[name="sesskey"]').get('value'), type: mail_view_type, offset: Y.one('input[name="offset"]').get('value'), action: action, mailview: mail_view }, on: { success:handleSuccess, failure:handleFailure } }; if (Y.one('input[name="m"]')) { cfg.data.m = Y.one('input[name="m"]').get('value'); } if(Y.one('input[name="itemid"]')) { cfg.data.itemid = Y.one('input[name="itemid"]').get('value'); } if (action == 'perpage') { cfg.data.perpage = (node.get('innerText')?node.get('innerText'):node.get('textContent')); } if (action == 'assignlabels') { cfg.data.labelids = mail_get_labels_values(false); cfg.data.labeltsids = mail_get_labels_values(true); } if (action == 'setlabel') { obj = Y.one('#local_mail_edit_label_color'); cfg.data.labelname = Y.one('#local_mail_edit_label_name').get('value'); if (!cfg.data.labelname) { alert(M.util.get_string('erroremptylabelname', 'local_mail')); mail_label_edit(); return false; } else if (cfg.data.labelname.length > 100) { alert(M.util.get_string('maximumchars', 'moodle', 100)); mail_label_edit(); return false; } cfg.data.labelcolor = obj.get('value'); } if (action == 'newlabel') { obj = Y.one('#local_mail_new_label_color'); cfg.data.labelname = Y.one('#local_mail_new_label_name').get('value'); if (!cfg.data.labelname) { alert(M.util.get_string('erroremptylabelname', 'local_mail')); mail_label_new(); return false; } else if (cfg.data.labelname.length > 100) { alert(M.util.get_string('maximumchars', 'moodle', 100)); mail_label_new(); return false; } cfg.data.labelcolor = obj.get('value'); } if (action == 'nextpage' || action == 'prevpage' ) { obj = Y.one('#mail_loading_small'); var btn = Y.one('.mail_paging input[name="'+action+'"]'); var position = btn.getXY(); obj.removeClass('mail_hidden'); position[0] += (btn.get('offsetWidth')/2) - (obj.one('img').get('offsetWidth')/2); position[1] = btn.getXY()[1] + (obj.one('img').get('offsetHeight')/2); obj.setXY(position); } if (mail_doing_search) { //Go back when searching keeps current page if (action == 'goback') { if (mail_before_message_search) { cfg.data.before = mail_before_message_search; } else if (mail_after_message_search) { cfg.data.after = mail_after_message_search; } } cfg.data.search = mail_search_selected; cfg.data.searchfrom = mail_searchfrom_selected; cfg.data.searchto = mail_searchto_selected; cfg.data.unread = (mail_unread_selected?'1':''); cfg.data.attach = (mail_attach_selected?'1':''); cfg.data.time = mail_date_selected; cfg.data.perpageid = mail_perpageid; if (action == 'prevpage') { obj = Y.one('.mail_list .mail_item .mail_adv_checkbox'); if (obj) { cfg.data.after = mail_get_checkbox_value(obj); } cfg.data.action = 'search'; } else if (action == 'nextpage') { obj = Y.all('.mail_item:last-child .mail_adv_checkbox'); if (obj) { cfg.data.before = mail_get_checkbox_value(obj.shift()); cfg.data.perpageid = cfg.data.before; } cfg.data.action = 'search'; } cfg.data.searching = true; } if (mail_undo_function == 'undo') { cfg.data.undo = true; } request = Y.io(M.cfg.wwwroot + '/local/mail/ajax.php', cfg); }; var mail_label_confirm_delete = function(e) { var labelid; var message; var labelname = ''; labelid = Y.one('input[name="itemid"]').get('value'); labelname = M.local_mail.mail_labels[labelid].name; if (labelname.length > 25) { labelname = labelname.substring(0, 25) + '...'; } message = M.util.get_string('labeldeleteconfirm', 'local_mail', labelname); M.util.show_confirm_dialog(e, { 'callback' : mail_label_remove, 'message' : message, 'continuelabel': M.util.get_string('delete', 'local_mail') } ); }; var mail_label_remove = function() { var params = []; params.push('offset='+Y.one('input[name="offset"]').get('value')); params.push('sesskey='+Y.one('input[name="sesskey"]').get('value')); params.push('removelbl=1'); params.push('confirmlbl=1'); var url = Y.one('#local_mail_main_form').get('action'); document.location.href = url+'&'+params.join('&'); }; var mail_label_new = function() { mail_new_label_panel.show(); Y.one('#local_mail_form_new_label').removeClass('mail_hidden'); Y.one('#local_mail_new_label_name').focus(); }; var mail_label_edit = function() { var labelid = Y.one('input[name="itemid"]').get('value'); var labelname = M.local_mail.mail_labels[labelid].name; var labelcolor = M.local_mail.mail_labels[labelid].color; Y.one('#local_mail_edit_label_name').set('value', labelname); Y.all('.mail_label_color').removeClass('mail_label_color_selected'); if (!labelcolor) { Y.one('.mail_label_color.mail_label_nocolor').addClass('mail_label_color_selected'); labelcolor = ''; } else { Y.one('.mail_label_color.mail_label_' + labelcolor).addClass('mail_label_color_selected'); } Y.one('#local_mail_edit_label_color').set('value', labelcolor); mail_edit_label_panel.show(); Y.one('#local_mail_form_edit_label').removeClass('mail_hidden'); Y.one('#local_mail_edit_label_name').focus(); }; var mail_label_set_selected = function(obj, action) { Y.all('.mail_label_color').removeClass('mail_label_color_selected'); obj.addClass('mail_label_color_selected'); Y.one('#local_mail_' + action + '_label_color').set('value', obj.getAttribute('data-color')); }; var mail_update_url = function() { var params = []; var offset; var m; var type; if (history.pushState) { params.push('t='+mail_view_type); if (mail_message_view) { params.push('m='+Y.one('input[name="m"]').get('value')); } if (mail_view_type == 'course') { params.push('c='+Y.one('input[name="itemid"]').get('value')); } else { if (mail_view_type == 'label') { params.push('l='+Y.one('input[name="itemid"]').get('value')); } } offset = Y.one('input[name="offset"]').get('value'); if (parseInt(offset, 10) > 0) { params.push('offset='+offset); } history.pushState({}, document.title, M.cfg.wwwroot + '/local/mail/view.php?' + params.join('&')); } }; var mail_position_datepicker = function() { var menu = Y.one('#mail_menu_search'); var datepicker = Y.one('#dateselector-calendar-panel'); var search = Y.one('.mail_search_datepicker'); var position = menu.getXY(); position[0] += (menu.get('offsetWidth')/2) - (datepicker.get('offsetWidth')/2); position[1] = search.getXY()[1] - datepicker.get('offsetHeight'); datepicker.setXY(position); }; var mail_get_selected_date = function(cell, date) { mail_date_selected = cell.date.getFullYear() + ',' + cell.date.getMonth() + ',' + cell.date.getDate(); mail_set_selected_date(mail_date_selected); M.form.dateselector.panel.hide(); }; var mail_set_selected_date = function(date) { if (date) { var elems = date.split(','); date = Y.Date.format(new Date(elems[0], elems[1], elems[2]), {format:"%x"}) } else { date = Y.Date.format(new Date(), {format:"%x"}) } Y.one('#searchdate').set('text', date); }; var mail_notification_message = function(message) { if (message) { Y.one('#mail_notification').addClass('mail_enabled').removeClass('mail_novisible'); Y.one('#mail_notification_message').setContent(message); Y.one('#mail_notification_undo').removeClass('mail_novisible'); } else { Y.one('#mail_notification').removeClass('mail_enabled').addClass('mail_novisible'); Y.one('#mail_notification_message').setContent(''); Y.one('#mail_notification_undo').addClass('mail_novisible'); } }; var mail_reset_date_selected = function() { date = new Date(); mail_date_selected = date.getFullYear() + ',' + date.getMonth() + ',' + date.getDate(); M.form.dateselector.calendar.deselectDates(date); }; /*** Event listeners***/ //Background selection Y.one("#region-main").delegate('click', function(e) { var ancestor = this.ancestor('.mail_item'); mail_toggle_checkbox(this); ancestor.toggleClass('mail_selected'); mail_main_checkbox(); mail_customize_menu_actions(this); }, '.mail_list .mail_adv_checkbox'); //Select all/none Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_checkbox(this); mail_hide_menu_options(); mail_hide_menu_labels(); if (mail_is_checkbox_checked(this)) { mail_select_all(); } else { mail_select_none(); } mail_check_selected(); mail_update_menu_actions(); }, '.mail_checkbox_all > .mail_adv_checkbox'); //Toggle menu select all/none Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_menu(); mail_hide_menu_actions(); mail_hide_menu_labels(); mail_hide_menu_search(); }, '.mail_checkbox_all'); //Checkbox hides other menus Y.one("#region-main").delegate('click', function(e) { mail_hide_menu_options(); mail_hide_menu_labels(); }, '.mail_checkbox_all > .mail_adv_checkbox'); //Toggle menu actions Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_menu_actions(); mail_hide_menu_options(); mail_hide_menu_labels(); mail_hide_menu_search(); }, '.mail_more_actions'); //Toggle menu actions Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_label_default_values(); mail_customize_menu_label(); mail_toggle_menu_labels(); mail_hide_menu_options(); mail_hide_menu_actions(); mail_hide_menu_search(); }, '.mail_assignlbl'); //Menu select all Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_all(); mail_update_menu_actions(); }, '.mail_menu_option_all'); //Menu select none Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_none(); }, '.mail_menu_option_none'); //Menu select read Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_read(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_read'); //Menu select unread Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_unread(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_unread'); //Menu select starred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_starred(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_starred'); //Menu select unstarred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_toggle_menu(); mail_select_unstarred(); mail_main_checkbox(); mail_update_menu_actions(); }, '.mail_menu_option_unstarred'); Y.one("#region-main").delegate('click', function(e) { mail_check_selected(); }, '.mail_optselect'); Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); }, '.mail_labelselect'); //Menu action starred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('starred'); mail_update_menu_actions(); }, '.mail_menu_action_markasstarred'); //Menu action unstarred Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('unstarred'); mail_update_menu_actions(); }, '.mail_menu_action_markasunstarred'); //Menu action markasread Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('markasread'); mail_update_menu_actions(); }, '.mail_menu_action_markasread'); //Menu action markasunread Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('markasunread'); mail_update_menu_actions(); }, '.mail_menu_action_markasunread'); //Menu action editlabel Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_label_edit(); }, '.mail_menu_action_editlabel'); //Menu action removelabel Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_label_confirm_delete(e); }, '.mail_menu_action_removelabel'); //Starred and unstarred Y.one('#region-main').delegate('click', function(e) { e.preventDefault(); mail_doaction('togglestarred', this); mail_update_menu_actions(); }, '.mail_flags a'); //Delete button Y.one("#region-main").delegate('click', function(e) { if (!this.hasClass('mail_button_disabled')) { mail_doaction('delete'); } }, '#mail_delete'); //Discard button Y.one("#region-main").delegate('click', function(e) { if (!this.hasClass('mail_button_disabled')) { mail_doaction('discard'); } }, '#mail_discard'); //Restore button Y.one("#region-main").delegate('click', function(e) { if (!this.hasClass('mail_button_disabled')) { mail_doaction('restore'); } }, '#mail_restore'); //Prev page button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('prevpage'); }, 'input[name="prevpage"]'); //Prev page button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('nextpage'); }, 'input[name="nextpage"]'); //Go back button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('goback'); }, '.mail_goback'); //Mail per page Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('perpage', this); }, 'div.mail_perpage a'); //Hide all menus Y.on('click', function(e) { mail_hide_menu_options(); mail_hide_menu_actions(); mail_hide_menu_labels(); mail_hide_menu_search(); }, 'body'); //Show message Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doaction('viewmail', this); }, 'a.mail_link'); //Click apply changes on labels Y.one("#region-main").delegate('click', function(e) { mail_hide_menu_labels(); mail_doaction('assignlabels'); }, '.mail_menu_label_apply'); //Click new label Y.one("#region-main").delegate('click', function(e) { mail_hide_menu_labels(); mail_label_new(); }, '.mail_menu_label_newlabel'); //Click label on menu labels Y.one("#region-main").delegate('click', function(e) { mail_menu_label_selection(this); mail_customize_menu_label(); }, '.mail_menu_labels li'); //Click notification bar undo Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); var ancestor = Y.one('#mail_notification'); if (ancestor.hasClass('mail_enabled')) { ancestor.removeClass('mail_enabled').addClass('mail_novisible'); mail_doaction('undo'); } }, '#mail_notification_undo'); //Click cancel search button Y.one("#region-main").delegate('click', function(e) { e.preventDefault(); mail_doing_search = false; mail_hide_menu_search(); mail_doaction('goback'); mail_before_message_search = false; mail_after_message_search = false; mail_reset_date_selected(); }, '#buttoncancelsearch'); //Click search button Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); var date; mail_hide_menu_options(); mail_hide_menu_actions(); mail_hide_menu_labels(); mail_toggle_menu_search(); if (!mail_date_selected) { mail_reset_date_selected(); } mail_set_selected_date(mail_date_selected); }, '#mail_search'); //Click menu search Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); M.form.dateselector.panel.hide(); }, '#mail_menu_search'); //Click adv search Y.one("#region-main").delegate('click', function(e) { e.stopPropagation(); mail_toggle_adv_search(); }, '#mail_toggle_adv_search'); //Click date search Y.one("#local_mail_main_form").delegate('click', function(e) { e.stopPropagation(); if(Y.one('#dateselector-calendar-panel').hasClass('yui3-overlay-hidden')) { M.form.dateselector.panel.show(); } else { M.form.dateselector.panel.hide(); } }, '.mail_search_date'); Y.on('contentready', function() { if (M.form.dateselector.calendar) { M.form.dateselector.calendar.on('dateClick', mail_get_selected_date); M.form.dateselector.calendar.set('maximumDate', new Date()); M.form.dateselector.panel.set('zIndex', 1); Y.one('#dateselector-calendar-panel').setStyle('border', 0); M.form.dateselector.calendar.render(); } }, '#dateselector-calendar-panel'); //Click on button search Y.one("#region-main").delegate('keydown', function(e) { e.stopPropagation(); if (e.keyCode == 13) { this.focus(); mail_do_search(); } }, '#textsearch, #textsearchfrom, #textsearchto'); //Click on button search Y.one("#region-main").delegate('click', function(e) { mail_do_search(); }, '#buttonsearch'); //Initialize init(); mail_update_url(); });
nitro2010/moodle
local/mail/mail.js
JavaScript
gpl-3.0
58,550
package net.talviuni.proxyer; public interface TranslationInterface<S, T> { public Class<S> getSourceClass(); public Class<T> getTargetClass(); public <O extends Object> T translate(O objectToTranslate); }
JannuMies/poc-proxyer-thingy
src/main/java/net/talviuni/proxyer/TranslationInterface.java
Java
gpl-3.0
235
// Copyright (C) 2012, 2014, 2015, 2016, 2017 David Maxwell and Constantine Khroulev // // This file is part of PISM. // // PISM 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. // // PISM 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 PISM; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "IP_SSATaucTaoTikhonovProblemLCL.hh" #include "pism/util/IceGrid.hh" #include "pism/util/ConfigInterface.hh" namespace pism { namespace inverse { typedef IceModelVec2S DesignVec; typedef IceModelVec2V StateVec; // typedef TikhonovProblemListener<InverseProblem> Listener; // typedef typename Listener::Ptr ListenerPtr; IP_SSATaucTaoTikhonovProblemLCL::IP_SSATaucTaoTikhonovProblemLCL(IP_SSATaucForwardProblem &ssaforward, IP_SSATaucTaoTikhonovProblemLCL::DesignVec &d0, IP_SSATaucTaoTikhonovProblemLCL::StateVec &u_obs, double eta, IPFunctional<DesignVec> &designFunctional, IPFunctional<StateVec> &stateFunctional) : m_ssaforward(ssaforward), m_d0(d0), m_u_obs(u_obs), m_eta(eta), m_designFunctional(designFunctional), m_stateFunctional(stateFunctional) { PetscErrorCode ierr; IceGrid::ConstPtr grid = m_d0.get_grid(); double stressScale = grid->ctx()->config()->get_double("inverse.design.param_tauc_scale"); m_constraintsScale = grid->Lx()*grid->Ly()*4*stressScale; m_velocityScale = grid->ctx()->config()->get_double("inverse.ssa.velocity_scale", "m second-1"); int design_stencil_width = m_d0.get_stencil_width(); int state_stencil_width = m_u_obs.get_stencil_width(); m_d.reset(new DesignVec(grid, "design variable", WITH_GHOSTS, design_stencil_width)); m_d_Jdesign.create(grid, "Jdesign design variable", WITH_GHOSTS, design_stencil_width); m_dGlobal.create(grid, "design variable (global)", WITHOUT_GHOSTS, design_stencil_width); m_dGlobal.copy_from(m_d0); m_uGlobal.reset(new StateVec(grid, "state variable (global)", WITHOUT_GHOSTS, state_stencil_width)); m_u.create(grid, "state variable", WITH_GHOSTS, state_stencil_width); m_du.create(grid, "du", WITH_GHOSTS, state_stencil_width); m_u_Jdesign.create(grid, "Jdesign state variable", WITH_GHOSTS, state_stencil_width); m_u_diff.reset(new StateVec(grid, "state residual", WITH_GHOSTS, state_stencil_width)); m_d_diff.reset(new DesignVec(grid, "design residual", WITH_GHOSTS, design_stencil_width)); m_dzeta.create(grid,"dzeta",WITH_GHOSTS,design_stencil_width); m_grad_state.reset(new StateVec(grid, "state gradient", WITHOUT_GHOSTS, state_stencil_width)); m_grad_design.reset(new DesignVec(grid, "design gradient", WITHOUT_GHOSTS, design_stencil_width)); m_constraints.reset(new StateVec(grid,"PDE constraints",WITHOUT_GHOSTS,design_stencil_width)); DM da; m_ssaforward.get_da(&da); ierr = DMSetMatType(da, MATBAIJ); PISM_CHK(ierr, "DMSetMatType"); ierr = DMCreateMatrix(da, m_Jstate.rawptr()); PISM_CHK(ierr, "DMCreateMatrix"); int nLocalNodes = grid->xm()*grid->ym(); int nGlobalNodes = grid->Mx()*grid->My(); ierr = MatCreateShell(grid->com, 2*nLocalNodes, nLocalNodes, 2*nGlobalNodes, nGlobalNodes, this, m_Jdesign.rawptr()); PISM_CHK(ierr, "MatCreateShell"); ierr = MatShellSetOperation(m_Jdesign, MATOP_MULT, (void(*)(void))jacobian_design_callback); PISM_CHK(ierr, "MatShellSetOperation"); ierr = MatShellSetOperation(m_Jdesign, MATOP_MULT_TRANSPOSE, (void(*)(void))jacobian_design_transpose_callback); PISM_CHK(ierr, "MatShellSetOperation"); m_x.reset(new IPTwoBlockVec(m_dGlobal.get_vec(),m_uGlobal->get_vec())); } IP_SSATaucTaoTikhonovProblemLCL::~IP_SSATaucTaoTikhonovProblemLCL() { // empty } void IP_SSATaucTaoTikhonovProblemLCL::setInitialGuess(DesignVec &d0) { m_dGlobal.copy_from(d0); } IP_SSATaucTaoTikhonovProblemLCL::StateVec::Ptr IP_SSATaucTaoTikhonovProblemLCL::stateSolution() { m_x->scatterToB(m_uGlobal->get_vec()); m_uGlobal->scale(m_velocityScale); return m_uGlobal; } IP_SSATaucTaoTikhonovProblemLCL::DesignVec::Ptr IP_SSATaucTaoTikhonovProblemLCL::designSolution() { m_x->scatterToA(m_d->get_vec()); //CHKERRQ(ierr); return m_d; } void IP_SSATaucTaoTikhonovProblemLCL::connect(Tao tao) { PetscErrorCode ierr; ierr = TaoSetStateDesignIS(tao, m_x->blockBIndexSet() /*state*/, m_x->blockAIndexSet() /*design*/); PISM_CHK(ierr, "TaoSetStateDesignIS"); taoutil::TaoObjGradCallback<IP_SSATaucTaoTikhonovProblemLCL, &IP_SSATaucTaoTikhonovProblemLCL::evaluateObjectiveAndGradient>::connect(tao, *this); taoutil::TaoLCLCallbacks<IP_SSATaucTaoTikhonovProblemLCL>::connect(tao, *this, m_constraints->get_vec(), m_Jstate, m_Jdesign); taoutil::TaoMonitorCallback<IP_SSATaucTaoTikhonovProblemLCL>::connect(tao,*this); } void IP_SSATaucTaoTikhonovProblemLCL::monitorTao(Tao tao) { PetscErrorCode ierr; // Has to be a PetscInt because of the TaoGetSolutionStatus call. PetscInt its; ierr = TaoGetSolutionStatus(tao, &its, NULL, NULL, NULL, NULL, NULL); PISM_CHK(ierr, "TaoGetSolutionStatus"); int nListeners = m_listeners.size(); for (int k = 0; k < nListeners; k++) { m_listeners[k]->iteration(*this, m_eta, its, m_val_design, m_val_state, m_d, m_d_diff, m_grad_design, m_ssaforward.solution(), m_u_diff, m_grad_state, m_constraints); } } void IP_SSATaucTaoTikhonovProblemLCL::evaluateObjectiveAndGradient(Tao /*tao*/, Vec x, double *value, Vec gradient) { m_x->scatter(x,m_dGlobal.get_vec(),m_uGlobal->get_vec()); m_uGlobal->scale(m_velocityScale); // Variable 'm_dGlobal' has no ghosts. We need ghosts for computation with the design variable. m_d->copy_from(m_dGlobal); m_d_diff->copy_from(*m_d); m_d_diff->add(-1,m_d0); m_designFunctional.gradientAt(*m_d_diff, *m_grad_design); m_grad_design->scale(1/m_eta); m_u_diff->copy_from(*m_uGlobal); m_u_diff->add(-1, m_u_obs); m_stateFunctional.gradientAt(*m_u_diff, *m_grad_state); m_grad_state->scale(m_velocityScale); m_x->gather(m_grad_design->get_vec(), m_grad_state->get_vec(), gradient); m_designFunctional.valueAt(*m_d_diff, &m_val_design); m_stateFunctional.valueAt(*m_u_diff, &m_val_state); *value = m_val_design / m_eta + m_val_state; } TerminationReason::Ptr IP_SSATaucTaoTikhonovProblemLCL::formInitialGuess(Vec *x) { m_d->copy_from(m_dGlobal); TerminationReason::Ptr reason = m_ssaforward.linearize_at(*m_d); if (reason->failed()) { return reason; } m_uGlobal->copy_from(*m_ssaforward.solution()); m_uGlobal->scale(1.0 / m_velocityScale); m_x->gather(m_dGlobal.get_vec(), m_uGlobal->get_vec()); // This is probably irrelevant. m_uGlobal->scale(m_velocityScale); *x = *m_x; return GenericTerminationReason::success(); } void IP_SSATaucTaoTikhonovProblemLCL::evaluateConstraints(Tao, Vec x, Vec r) { PetscErrorCode ierr; m_x->scatter(x,m_dGlobal.get_vec(),m_uGlobal->get_vec()); m_uGlobal->scale(m_velocityScale); m_d->copy_from(m_dGlobal); m_u.copy_from(*m_uGlobal); m_ssaforward.set_design(*m_d); m_ssaforward.assemble_residual(m_u, r); ierr = VecScale(r,1./m_constraintsScale); PISM_CHK(ierr, "VecScale"); } void IP_SSATaucTaoTikhonovProblemLCL::evaluateConstraintsJacobianState(Tao, Vec x, Mat Jstate, Mat /*Jpc*/, Mat /*Jinv*/, MatStructure *s) { PetscErrorCode ierr; m_x->scatter(x, m_dGlobal.get_vec(), m_uGlobal->get_vec()); m_uGlobal->scale(m_velocityScale); m_d->copy_from(m_dGlobal); m_u.copy_from(*m_uGlobal); m_ssaforward.set_design(*m_d); m_ssaforward.assemble_jacobian_state(m_u, Jstate); *s = SAME_NONZERO_PATTERN; ierr = MatScale(Jstate, m_velocityScale / m_constraintsScale); PISM_CHK(ierr, "MatScale"); } void IP_SSATaucTaoTikhonovProblemLCL::evaluateConstraintsJacobianDesign(Tao, Vec x, Mat /*Jdesign*/) { // I'm not sure if the following are necessary (i.e. will the copies that happen // in evaluateObjectiveAndGradient be sufficient) but we'll do them here // just in case. m_x->scatter(x,m_dGlobal.get_vec(),m_uGlobal->get_vec()); m_uGlobal->scale(m_velocityScale); m_d_Jdesign.copy_from(m_dGlobal); m_u_Jdesign.copy_from(*m_uGlobal); } void IP_SSATaucTaoTikhonovProblemLCL::applyConstraintsJacobianDesign(Vec x, Vec y) { m_dzeta.copy_from_vec(x); m_ssaforward.set_design(m_d_Jdesign); m_ssaforward.apply_jacobian_design(m_u_Jdesign, m_dzeta, y); PetscErrorCode ierr = VecScale(y,1./m_constraintsScale); PISM_CHK(ierr, "VecScale"); } void IP_SSATaucTaoTikhonovProblemLCL::applyConstraintsJacobianDesignTranspose(Vec x, Vec y) { m_du.copy_from_vec(x); m_ssaforward.set_design(m_d_Jdesign); m_ssaforward.apply_jacobian_design_transpose(m_u_Jdesign, m_du, y); PetscErrorCode ierr = VecScale(y, 1.0 / m_constraintsScale); PISM_CHK(ierr, "VecScale"); } PetscErrorCode IP_SSATaucTaoTikhonovProblemLCL::jacobian_design_callback(Mat A, Vec x, Vec y) { try { IP_SSATaucTaoTikhonovProblemLCL *ctx; PetscErrorCode ierr = MatShellGetContext(A,&ctx); PISM_CHK(ierr, "MatShellGetContext"); ctx->applyConstraintsJacobianDesign(x,y); } catch (...) { MPI_Comm com = MPI_COMM_SELF; PetscErrorCode ierr = PetscObjectGetComm((PetscObject)A, &com); CHKERRQ(ierr); handle_fatal_errors(com); SETERRQ(com, 1, "A PISM callback failed"); } return 0; } PetscErrorCode IP_SSATaucTaoTikhonovProblemLCL::jacobian_design_transpose_callback(Mat A, Vec x, Vec y) { try { IP_SSATaucTaoTikhonovProblemLCL *ctx; PetscErrorCode ierr = MatShellGetContext(A,&ctx); PISM_CHK(ierr, "MatShellGetContext"); ctx->applyConstraintsJacobianDesignTranspose(x,y); } catch (...) { MPI_Comm com = MPI_COMM_SELF; PetscErrorCode ierr = PetscObjectGetComm((PetscObject)A, &com); CHKERRQ(ierr); handle_fatal_errors(com); SETERRQ(com, 1, "A PISM callback failed"); } return 0; } } // end of namespace inverse } // end of namespace pism
talbrecht/pism_pik
src/inverse/IP_SSATaucTaoTikhonovProblemLCL.cc
C++
gpl-3.0
11,536
import { combineReducers } from 'redux'; import listAcceptors from './listAcceptors'; import me from './wxe-auth'; import acceptors from './acceptors'; import { doneForm, toastState } from './ceeRegistration/ceeRegistration'; import { reducer as formReducer } from 'redux-form'; import stat from './stat'; import cee from './cee'; import { FETCH_FAILED } from '../constants'; const error = (state = null, action) => { switch (action.type) { case FETCH_FAILED: return action.error; default: return null; } }; export default combineReducers({ doneForm, toastState, listAcceptors, me, acceptors, cee, form: formReducer, stat, error, });
nagucc/jkef-wxe
src/reducers/index.js
JavaScript
gpl-3.0
678
package de.zargornet.registerp.utils.databasequeries; import org.bukkit.Location; import java.util.UUID; /** * Interface for database queries */ public interface IDatabaseQueries { void addAccount(UUID uuid, String password); void setPassword(UUID uuid, String newPassword); void remAccount(UUID uuid); String getPassword(UUID uuid); Location getLastPosition(UUID uuid); void setLastPosition(UUID uuid, Location loc); }
ZargorNET/RegisterP
src/main/java/de/zargornet/registerp/utils/databasequeries/IDatabaseQueries.java
Java
gpl-3.0
454
Bitrix 16.5 Business Demo = 4c29b358ae9ee4a55499de6372ff03d2
gohdan/DFC
known_files/hashes/bitrix/modules/iblock/install/components/bitrix/catalog.main/lang/en/.parameters.php
PHP
gpl-3.0
61
<?php class tables_webpage_status { /* private $_snapshot; private $_snapshotWebsite; function field__snapshot_id($record) { $app = Dataface_Application::getInstance(); $query = $app->getQuery(); return @$query['-snapshot-id'] ? intval($query['-snapshot-id']) : null; } function snapshotWebsite($record) { if (!isset($this->_snapshotWebsite)) { $this->_snapshotWebsite = SweteSite::loadSiteById($record->val('website_id')); } return $this->_snapshotWebsite; } function snapshot($record) { if (!isset($this->_snapshot)) { $snapId = $record->val('snapshot_id'); if (!isset($snapId)) { return null; } $snap = df_get_record('snapshots', array('snapshot_id' => '='. $snapId)); $status = $snap->val('pagestatus'); if ($status) { $status = json_decode($status, true); } else { $status = array(); } $this->_snapshot = $status; } return $this->_snapshot; } function field__snapshot_status_array($record) { $snap = $this->snapshot($record); if (!$snap) { return null; } $ws = $this->snapshotWebsite($record); if (!$ws) { return null; } $path = $record->val('pageurl } */ }
shannah/swete
swete-admin/tables/webpage_status/webpage_status.php
PHP
gpl-3.0
1,451
package com.eucalyptus.webui.shared.user; import java.util.Date; public class UserApp implements java.io.Serializable { private static final long serialVersionUID = 1L; private int id; private Date apptime; private EnumUserAppStatus status; private String comment; private String keyPair; private String securityGroup; private int ncpus; private int mem; private int disk; private int bw; private int userId; private int vmImageTypeId; private Date srvStartingTime; private Date srvEndingTime; private String euca_vm_instance_key; private int cpu_srv_id; private int mem_srv_id; private int disk_srv_id; private int bw_srv_id; private int public_ip_srv_id; private int private_ip_srv_id; public UserApp() { } public UserApp(int id, Date apptime, EnumUserAppStatus status, int del, String comment, int ncpus, int mem, int disk, int bw, String keyPair, String securityGroup, int userId, int vmImageTypeId, Date srvStartingTime, Date srvEndingTime, String euca_vm_instance_key, int cpu_srv_id, int mem_srv_id, int disk_srv_id, int bw_srv_id, int public_ip_srv_id, int private_ip_srv_id) { this.setUAId(id); this.setAppTime(apptime); this.setStatus(status); this.setSrvStartingTime(srvStartingTime); this.setSrvEndingingTime(srvEndingTime); this.setComment(comment); this.setNcpus(ncpus); this.setMem(mem); this.setDisk(disk); this.setBw(bw); this.setKeyPair(keyPair); this.setSecurityGroup(securityGroup); this.setUserId(userId); this.setVmImageTypeId(vmImageTypeId); this.setEucaVMInstanceKey(euca_vm_instance_key); this.setCPUSrvId(cpu_srv_id); this.setMemSrvId(mem_srv_id); this.setDiskSrvId(disk_srv_id); this.setBwSrvId(bw_srv_id); this.setPubIpSrvId(public_ip_srv_id); this.setPriIpSrvId(private_ip_srv_id); } public void setUAId(int ua_id) { this.id = ua_id; } public int getUAId() { return this.id; } public void setAppTime(Date apptime) { this.apptime = apptime; } public Date getAppTime() { return this.apptime; } public void setStatus(EnumUserAppStatus status) { this.status = status; } public EnumUserAppStatus getStatus() { return this.status; } public void setComment(String comment) { this.comment = comment; } public String getComments() { return this.comment; } public void setNcpus(int ncpus) { this.ncpus = ncpus; } public int getNcpus() { return this.ncpus; } public void setMem(int mem) { this.mem = mem; } public int getMem() { return this.mem; } public void setDisk(int disk) { this.disk = disk; } public int getDisk() { return this.disk; } public void setBw(int bw) { this.bw = bw; } public int getBw() { return this.bw; } public void setUserId(int userId) { this.userId = userId; } public int getUserId() { return this.userId; } public void setVmImageTypeId(int vmImageTypeId) { this.vmImageTypeId = vmImageTypeId; } public int getVmIdImageTypeId() { return this.vmImageTypeId; } public void setSrvStartingTime(Date startingTime) { this.srvStartingTime = startingTime; } public Date getSrvStartingTime() { return this.srvStartingTime; } public void setSrvEndingingTime(Date endingTime) { this.srvEndingTime = endingTime; } public Date getSrvEndingTime() { return this.srvEndingTime; } public void setKeyPair(String keyPair) { this.keyPair = keyPair; } public String getKeyPair() { return this.keyPair; } public void setSecurityGroup(String securityGroup) { this.securityGroup = securityGroup; } public String getSecurityGroup() { return this.securityGroup; } public void setEucaVMInstanceKey(String euca_vm_instance_key) { this.euca_vm_instance_key = euca_vm_instance_key; } public String getEucaVMInstanceKey() { return this.euca_vm_instance_key; } public void setCPUSrvId(int cpu_srv_id) { this.cpu_srv_id = cpu_srv_id; } public int getCPUSrvId() { return this.cpu_srv_id; } public void setMemSrvId(int mem_srv_id) { this.mem_srv_id = mem_srv_id; } public int getMemSrvId() { return this.mem_srv_id; } public void setDiskSrvId(int disk_srv_id) { this.disk_srv_id = disk_srv_id; } public int getDiskSrvId() { return this.disk_srv_id; } public void setBwSrvId(int bw_srv_id) { this.bw_srv_id = bw_srv_id; } public int getBwSrvId() { return this.bw_srv_id; } public void setPubIpSrvId(int public_ip_srv_id) { this.public_ip_srv_id = public_ip_srv_id; } public int getPubIpSrvId() { return this.public_ip_srv_id; } public void setPriIpSrvId(int private_ip_srv_id) { this.private_ip_srv_id = private_ip_srv_id; } public int getPriIpSrvId() { return this.private_ip_srv_id; } }
sosilent/euca
clc/modules/www/src/main/java/com/eucalyptus/webui/shared/user/UserApp.java
Java
gpl-3.0
4,714
/* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2016 HydroloGIS (www.hydrologis.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.geopaparazzi.core.maptools.tools; import android.content.Context; import android.graphics.Canvas; import android.graphics.PorterDuff.Mode; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageButton; import android.widget.LinearLayout; import org.mapsforge.android.maps.MapView; import java.util.HashMap; import java.util.Map; import eu.geopaparazzi.library.core.maps.SpatialiteMap; import eu.geopaparazzi.library.database.GPLog; import eu.geopaparazzi.library.features.EditManager; import eu.geopaparazzi.library.features.ILayer; import eu.geopaparazzi.library.features.Tool; import eu.geopaparazzi.library.features.ToolGroup; import eu.geopaparazzi.library.util.Compat; import eu.geopaparazzi.library.util.GPDialogs; import eu.geopaparazzi.spatialite.database.spatial.SpatialiteSourcesManager; import eu.geopaparazzi.spatialite.database.spatial.core.tables.SpatialVectorTable; import eu.geopaparazzi.core.R; /** * The main polygon layer editing tool group, which just shows the tool palette. * * @author Andrea Antonello (www.hydrologis.com) */ public class NoEditableLayerToolGroup implements ToolGroup, OnClickListener, OnTouchListener { private ImageButton selectAllButton; private MapView mapView; private int selectionColor; /** * Constructor. * * @param mapView the map view. */ public NoEditableLayerToolGroup(MapView mapView) { this.mapView = mapView; LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); selectionColor = Compat.getColor(parent.getContext(), R.color.main_selection); } public void activate() { if (mapView != null) mapView.setClickable(true); } public void initUI() { LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); Context context = parent.getContext(); ILayer editLayer = EditManager.INSTANCE.getEditLayer(); int padding = 2; selectAllButton = new ImageButton(context); selectAllButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); selectAllButton.setBackground(Compat.getDrawable(context, R.drawable.ic_editing_select_all_24dp)); selectAllButton.setPadding(0, padding, 0, padding); selectAllButton.setOnClickListener(this); selectAllButton.setOnTouchListener(this); parent.addView(selectAllButton); } public void disable() { EditManager.INSTANCE.setActiveTool(null); LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); if (parent != null) parent.removeAllViews(); } public void onClick(View v) { if (v == selectAllButton) { Tool currentTool = EditManager.INSTANCE.getActiveTool(); if (currentTool != null && currentTool instanceof InfoTool) { // if the same tool is re-selected, it is disabled EditManager.INSTANCE.setActiveTool(null); } else { // check maps enablement try { HashMap<SpatialiteMap, SpatialVectorTable> spatialiteMaps2TablesMap = SpatialiteSourcesManager.INSTANCE.getSpatialiteMaps2TablesMap(); boolean atLeastOneEnabled = false; for (Map.Entry<SpatialiteMap, SpatialVectorTable> entry : spatialiteMaps2TablesMap.entrySet()) { if (entry.getKey().isVisible) { atLeastOneEnabled = true; break; } } if (!atLeastOneEnabled) { LinearLayout parent = EditManager.INSTANCE.getToolsLayout(); if (parent != null) { Context context = parent.getContext(); GPDialogs.warningDialog(context, context.getString(R.string.no_queriable_layer_is_visible), null); } return; } } catch (Exception e) { GPLog.error(this, null, e); } Tool activeTool = new InfoTool(this, mapView); EditManager.INSTANCE.setActiveTool(activeTool); } } handleToolIcons(v); } @SuppressWarnings("deprecation") private void handleToolIcons(View activeToolButton) { Context context = activeToolButton.getContext(); Tool currentTool = EditManager.INSTANCE.getActiveTool(); if (selectAllButton != null) if (currentTool != null && activeToolButton == selectAllButton) { selectAllButton .setBackground(Compat.getDrawable(context, R.drawable.ic_editing_select_all_active_24dp)); } else { selectAllButton.setBackground(Compat.getDrawable(context, R.drawable.ic_editing_select_all_24dp)); } } public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { v.getBackground().setColorFilter(selectionColor, Mode.SRC_ATOP); v.invalidate(); break; } case MotionEvent.ACTION_UP: { v.getBackground().clearColorFilter(); v.invalidate(); break; } } return false; } public void onToolFinished(Tool tool) { } public void onToolDraw(Canvas canvas) { // nothing to draw } public boolean onToolTouchEvent(MotionEvent event) { return false; } public void onGpsUpdate(double lon, double lat) { // ignore } }
tghoward/geopaparazzi
geopaparazzi_core/src/main/java/eu/geopaparazzi/core/maptools/tools/NoEditableLayerToolGroup.java
Java
gpl-3.0
6,694
<?php namespace MageDeveloper\Dataviewer\Form\FormDataProvider; use MageDeveloper\Dataviewer\Domain\Model\Datatype; use MageDeveloper\Dataviewer\Domain\Model\Record; use MageDeveloper\Dataviewer\Domain\Repository\FieldRepository; use MageDeveloper\Dataviewer\Utility\LocalizationUtility as Locale; use TYPO3\CMS\Backend\Form\Container\SingleFieldContainer; use MageDeveloper\Dataviewer\Domain\Model\Field as Field; use MageDeveloper\Dataviewer\Domain\Model\FieldValue as FieldValue; use MageDeveloper\Dataviewer\Domain\Model\RecordValue as RecordValue; use TYPO3\CMS\Backend\Form\Element\AbstractFormElement as FormElement; use TYPO3\CMS\Backend\Form\FormDataProviderInterface; use TYPO3\CMS\Core\Utility\ExtensionManagementUtility; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Object\InvalidClassException; use TYPO3\CMS\Extbase\Object\ObjectManager; /** * MageDeveloper Dataviewer Extension * ----------------------------------- * * @category TYPO3 Extension * @package MageDeveloper\Dataviewer * @author Bastian Zagar * @copyright Magento Developers / magedeveloper.de <kontakt@magedeveloper.de> * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class PrepareDataviewerTca implements FormDataProviderInterface { /** * Object Manager * * @var \TYPO3\CMS\Extbase\Object\ObjectManager * @inject */ protected $objectManager; /** * Field Repository * * @var \MageDeveloper\Dataviewer\Domain\Repository\FieldRepository * @inject */ protected $fieldRepository; /** * Record Repository * * @var \MageDeveloper\Dataviewer\Domain\Repository\RecordRepository * @inject */ protected $recordRepository; /** * Datatype Repository * * @var \MageDeveloper\Dataviewer\Domain\Repository\DatatypeRepository * @inject */ protected $datatypeRepository; /** * Fieldtype Settings Service * * @var \MageDeveloper\Dataviewer\Service\Settings\FieldtypeSettingsService * @inject */ protected $fieldtypeSettingsService; /** * Constructor * * @return PrepareDataviewerTca */ public function __construct() { $this->objectManager = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class); $this->fieldRepository = $this->objectManager->get(\MageDeveloper\Dataviewer\Domain\Repository\FieldRepository::class); $this->recordRepository = $this->objectManager->get(\MageDeveloper\Dataviewer\Domain\Repository\RecordRepository::class); $this->datatypeRepository = $this->objectManager->get(\MageDeveloper\Dataviewer\Domain\Repository\DatatypeRepository::class); $this->fieldtypeSettingsService = $this->objectManager->get(\MageDeveloper\Dataviewer\Service\Settings\FieldtypeSettingsService::class); } /** * Prepares the temporary tca for the dataviewer stuff * * @param array $result * @return array */ public function addData(array $result) { if($result["tableName"] == "tx_dataviewer_domain_model_record") { /************************************************** * We need to prepare the databaseRow Information * ---------------------------------------------- * The row information is not existant because * our row is virtually created, so we just add * the uid from the form post, to get everything * right here **************************************************/ // If we have a posted value of the row uid, we use it here if($uid = GeneralUtility::_POST("databaseRowUid")) $result["databaseRow"]["uid"] = $uid; else if (!isset($result["databaseRow"]["uid"]) && GeneralUtility::_GET("uid")) $result["databaseRow"]["uid"] = GeneralUtility::_GET("uid"); /************************************************** * The row will be filled with the record values * to completely fill the field information * for the databaseRow **************************************************/ $record = null; if(is_numeric($result["databaseRow"]["uid"]) && $result["databaseRow"]["uid"] > 0) $record = $this->recordRepository->findByUid($result["databaseRow"]["uid"], false); if(!$record instanceof Record) $record = $this->objectManager->get(Record::class); $recordValues = $record->getRecordValues(); if($recordValues->count()) { foreach($recordValues as $_recordValue) { /* @var RecordValue $_recordValue */ if($_recordValue->getField() instanceof Field) $result["databaseRow"][$_recordValue->getField()->getUid()] = $_recordValue->getValueContent(); } } if($record->getDatatype() instanceof Datatype) { $datatype = $record->getDatatype(); } else { $datatypeUid = null; if($result["databaseRow"]["datatype"] > 0) { // We extract the datatype from the databaseRow if(is_array($result["databaseRow"]["datatype"])) $datatypeUid = reset($result["databaseRow"]["datatype"]); else $datatypeUid = (int)$result["databaseRow"]["datatype"]; } else { // We try to find the datatype uid in the url parameters $datatypeUid = (int)GeneralUtility::_GET("datatype"); } /* @var Datatype $datatype */ $datatype = $this->datatypeRepository->findByUid($datatypeUid, false); } // We can prepare the tca if record and datatype exists if($datatype instanceof Datatype && $record instanceof Record) $this->prepareProcessedTca($result, $datatype, $record); } return $result; } /** * Prepares the tca for a given datatype * * @param array $result * @param \MageDeveloper\Dataviewer\Domain\Model\Datatype $datatype * @param \MageDeveloper\Dataviewer\Domain\Model\Record $record * @return void */ public function prepareProcessedTca(&$result, Datatype $datatype, Record $record) { $fields = $datatype->getFields(); foreach ($fields as $_field) { /* @var Field $_field */ $fieldId = $_field->getUid(); // We retrieve the fieldtype configuration $fieldtypeConfig = $this->fieldtypeSettingsService->getFieldtypeConfiguration($_field->getType()); $fieldClass = $fieldtypeConfig->getFieldClass(); if ($this->objectManager->isRegistered($fieldClass)) { /* @var \MageDeveloper\Dataviewer\Form\Fieldtype\FieldtypeInterface $fieldtypeModel */ $fieldtypeModel = $this->objectManager->get($fieldClass); $fieldtypeModel->setField($_field); $fieldtypeModel->setRecord($record); $tca = $fieldtypeModel->buildTca(); $result["processedTca"]["columns"][$fieldId] = $tca["processedTca"]["columns"][$fieldId]; } } return; } }
magedeveloper/dataviewer
Classes/Form/FormDataProvider/PrepareDataviewerTca.php
PHP
gpl-3.0
6,581
#pragma once #include <Poco/Types.h> namespace Burst { struct CalculatedDeadline { Poco::UInt64 deadline; Poco::UInt64 nonce; }; enum class MemoryType { Buffer, Gensig, Deadlines, Bytes }; enum class MemoryCopyDirection { ToHost, ToDevice }; }
ragetti/creepMiner
src/gpu/gpu_declarations.hpp
C++
gpl-3.0
273
from django.db import models class Licensor(models.Model): name = models.CharField(max_length=255, unique=True) def __unicode__(self): return self.name class Meta: ordering = ['name']
jampueroc/scrapper_anime
visualizacion/models/licensor.py
Python
gpl-3.0
216
<?php /** * Nooku Platform - http://www.nooku.org/platform * * @copyright Copyright (C) 2011 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/nooku/nooku-platform for the canonical source repository */ namespace Nooku\Component\Tags; use Nooku\Library; /** * Taggable Controller Behavior * * @author Johan Janssens <http://github.com/johanjanssens> * @package Nooku\Component\Tags */ class ControllerBehaviorTaggable extends Library\BehaviorAbstract { public function __construct(Library\ObjectConfig $config) { parent::__construct($config); $this->_container = $config->container; $this->addCommandCallback('after.add' , '_saveTags'); $this->addCommandCallback('after.edit' , '_saveTags'); $this->addCommandCallback('after.delete', '_deleteTags'); } protected function _saveTags(Library\ControllerContextInterface $context) { if (!$context->response->isError()) { $entity = $context->result; $table = $entity->getTable()->getBase(); // Remove all existing relations if($entity->id && $entity->getTable()->getBase()) { $relations = $this->getObject('com:tags.model.relations') ->row($entity->id) ->table($table) ->fetch(); $relations->delete(); } if($entity->tags) { // Save tags as relations foreach ($entity->tags as $tag) { $properties = array( 'tags_tag_id' => $tag, 'row' => $entity->id, 'table' => $table ); $relation = $this->getObject('com:tags.model.relations') ->setState($properties) ->fetch(); if($relation->isNew()) { $relation = $this->getObject('com:tags.model.relations')->create(); $relation->setProperties($properties); $relation->save(); } } } return true; } } protected function _deleteTags(Library\ControllerContextInterface $context) { $entity = $context->result; $status = $entity->getStatus(); if($status == $entity::STATUS_DELETED || $status == 'trashed') { $id = $context->result->get('id'); $table = $context->result->getTable()->getBase(); if(!empty($id) && $id != 0) { $rows = $this->getObject('com:tags.model.relations') ->row($id) ->table($table) ->fetch(); $rows->delete(); } } } }
babsgosgens/nooku-ember-example-theme
component/tags/controller/behavior/taggable.php
PHP
gpl-3.0
3,027
// Hey look, // Antag Datums. namespace Content.Server.Mobs { /// <summary> /// The Role is a basic building block for, /// well, IC roles. /// This can be anything and is not necessarily limited to antagonists. /// </summary> public abstract class Role { /// <summary> /// The mind owning this role instance. /// </summary> public Mind Mind { get; } /// <summary> /// A friendly name for this role type. /// </summary> public abstract string Name { get; } protected Role(Mind mind) { Mind = mind; } /// <summary> /// Called when a mind (player) first gets this role, to greet them. /// </summary> public virtual void Greet() { } } }
MSylvia/space-station-14
Content.Server/Mobs/Role.cs
C#
gpl-3.0
846
package battlecode.world.signal; import battlecode.engine.signal.Signal; import battlecode.world.InternalRobot; import battlecode.common.ComponentType; import battlecode.common.MapLocation; import battlecode.common.RobotLevel; /** * Signifies that a robot just attacked * * @author adamd */ public class BugSignal extends Signal { private static final long serialVersionUID = 8064711239347833273L; /** TheID of the robot that attacked. */ public final int robotID; /** The location that the robot attacked */ public final MapLocation targetLoc; /** The height of the position that the robot attacked */ public final RobotLevel targetHeight; /** * Creates a signal for a robot broadcast. * * @param robot the robot that attacked * @param targetLoc the location that the robot attacked */ public BugSignal(InternalRobot robot, MapLocation targetLoc, RobotLevel targetHeight) { this.robotID = robot.getID(); this.targetLoc = targetLoc; this.targetHeight = targetHeight; } /** * Returns the ID of the robot that just broadcast. * * @return the messaging robot's ID */ public int getRobotID() { return robotID; } /** * Returns the location that the robot attacked * * @return the location that the robot attacked */ public MapLocation getTargetLoc() { return targetLoc; } /** * Returns the height of the position that the robot attacked * * @return the height of the position that the robot attacked */ public RobotLevel getTargetHeight() { return targetHeight; } }
pwnall/battlecode-server
src/main/battlecode/world/signal/BugSignal.java
Java
gpl-3.0
1,550
package no.uib.onyase.applications.engine.modules; import java.util.HashMap; /** * Iterator for the possible modifications carried by a peptide. * * @author Marc Vaudel */ public interface PeptideModificationsIterator { /** * Indicates whether there is a next profile. * * @return a boolean indicating whether there is a next profile */ public boolean hasNext(); /** * Returns the next profile. * * @return the next profile */ public HashMap<String, int[]> next(); }
mvaudel/onyase
src/main/java/no/uib/onyase/applications/engine/modules/PeptideModificationsIterator.java
Java
gpl-3.0
532
import socket import sys import time server_add = './bob_system_socket' sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) message = sys.argv[1]+" "+sys.argv[2] if sys.argv[1] == 'set': message+= " "+sys.argv[3] else: message+= " null" try: sock.connect(server_add) except socket.error, msg: print >>sys.stderr, msg sys.exit(1) sock.send(message) data = sock.recv(1024) if data: print 'reply from server:', data time.sleep(1) sock.close()
tibor0991/OBM-BOB
bob-main/test_sender.py
Python
gpl-3.0
455
import inspect from django.utils.translation import activate class MenuItemMixin: """ This mixins injects attributes that start with the 'menu_' prefix into the context generated by the view it is applied to. This behavior can be used to highlight an item of a navigation component. """ def get_context_data(self, **kwargs): context = super(MenuItemMixin, self).get_context_data(**kwargs) vattrs = inspect.getmembers(self, lambda a: not (inspect.isroutine(a))) menu_kwargs = dict(a for a in vattrs if a[0].startswith("menu_")) context.update(menu_kwargs) return context class ActivateLegacyLanguageViewMixin: """ """ def activate_legacy_language(self, *args, **kwargs): if "lang" in kwargs and kwargs["lang"] == "en" or self.request.GET.get("lang") == "en": activate("en") else: activate("fr")
erudit/eruditorg
eruditorg/base/viewmixins.py
Python
gpl-3.0
913
#include <iostream> #include <vector> using namespace std; typedef long long int64; #define FOR(i, a, b) for (int _end_ = (b), i = (a); i <= _end_; ++i) template <typename T> T gcd(T x, T y) { for (T t; x; t = x, x = y % x, y = t); return y; } int64 fpm(int64 b, int64 e, int64 m) { int64 t = 1; for (; e; e >>= 1, b = b * b % m) { e & 1 ? t = t * b % m : 0; } return t; } const int M = 100000000; const int64 N = 1e11; bool b[M + 1]; vector<int> get_primes(int n) { vector<int> P; FOR (i, 2, n) { if (!b[i]) P.push_back(i); int k = n / i; for (auto x : P) { if (x > k) break; b[x * i] = true; if (i % x == 0) break; } } return P; } auto primes = get_primes(M); int find_root(int p) { int x = p - 1; vector<int> v; for (auto &y : primes) { if (x == 1) break; if (y * y > x) break; if (x % y == 0) { v.push_back((p - 1) / y); for (; x /= y, x % y == 0; ); } } if (x != 1) v.push_back((p - 1) / x); x = p - 1; FOR (i, 2, p) { bool b = true; for (auto y : v) if (fpm(i, y, p) == 1) { b = false; break; } if (b) return i; } return -1; } int inv[15]; int main() { int64 ans = 0; int cnt = 0; FOR (i, 1, 15) { int g = gcd(i, 15); int x = i / g; int y = 15 / g; int e = 1; for (; y * e % x != 1 % x; ++e); inv[i % 15] = e; } for (auto p : primes) { int x = find_root(p); if (++cnt % 100000 == 0) { cerr << p << " " << x << endl; } int g = gcd(p - 1, 15); int y = (p - 1) / g; int64 b = fpm(x, (p - 1) / (2 * g) * inv[(p - 1) % 15] % y, p); int64 m = fpm(x, y, p); FOR (t, 1, g) { ans += (N + p - b) / p * p; b = b * m % p; } } cout << ans << endl; return 0; }
kkmonlee/Project-Euler-Solutions
CCPP/p421.cpp
C++
gpl-3.0
1,689
<?php declare(strict_types=1); namespace AawTeam\Minipoll\Domain\Model; /* * Copyright 2017 Agentur am Wasser | Maeder & Partner AG * * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\ObjectStorage; /** * Poll model */ class Poll extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { const STATUS_CLOSED = 0; const STATUS_OPEN = 1; const STATUS_BYDATE = 2; const DISPLAY_RESULTS_ALWAYS = 0; const DISPLAY_RESULTS_ONVOTE = 1; const DISPLAY_RESULTS_NEVER = 2; const DUPLICATION_CHECK_IP = 'ip'; const DUPLICATION_CHECK_COOKIE = 'cookie'; const DUPLICATION_CHECK_FEUSER = 'feuser'; const DUPLICATION_CHECK_FRONTEND_SESSION = 'frontend-session'; const DUPLICATION_CHECK_NONE = 'none'; /** * @var string */ protected $title; /** * @var string */ protected $description; /** * @var bool */ protected $useCaptcha; /** * @var string */ protected $duplicationCheck; /** * @var int */ protected $status; /** * @var \DateTime */ protected $openDatetime; /** * @var \DateTime */ protected $closeDatetime; /** * @var bool */ protected $allowMultiple; /** * @var int */ protected $displayResults; /** * @var ObjectStorage<PollOption> */ protected $options; /** * @var ObjectStorage<Participation> */ protected $participations; /** * @param string $title */ public function setTitle($title) { $this->title = $title; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param string $description */ public function setDescription($description) { $this->description = $description; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param boolean $useCaptcha */ public function setUseCaptcha($useCaptcha) { $this->useCaptcha = $useCaptcha; } /** * @return boolean */ public function getUseCaptcha() { return $this->useCaptcha; } /** * @param string $duplicationCheck */ public function setDuplicationCheck($duplicationCheck) { $this->duplicationCheck = $duplicationCheck; } /** * @return string */ public function getDuplicationCheck() { return $this->duplicationCheck; } /** * @param int $status */ public function setStatus($status) { $this->status = $status; } /** * @return int */ public function getStatus() { return $this->status; } /** * @param \DateTime $openDatetime */ public function setOpenDatetime(\DateTime $openDatetime) { $this->openDatetime = $openDatetime; } /** * @return \DateTime */ public function getOpenDatetime() { return $this->openDatetime; } /** * @param \DateTime $closeDatetime */ public function setCloseDatetime(\DateTime $closeDatetime) { $this->closeDatetime = $closeDatetime; } /** * @return \DateTime */ public function getCloseDatetime() { return $this->closeDatetime; } /** * @param bool $allowMultiple */ public function setAllowMultiple($allowMultiple) { $this->allowMultiple = $allowMultiple; } /** * @return boolean */ public function getAllowMultiple() { return $this->allowMultiple; } /** * @param int $displayResults */ public function setDisplayResults($displayResults) { $this->displayResults = $displayResults; } /** * @return int */ public function getDisplayResults() { return $this->displayResults; } /** * @param ObjectStorage $options */ public function setOptions(ObjectStorage $options) { $this->options = $options; } /** * @return ObjectStorage<PollOption> */ public function getOptions() { return $this->options; } /** * @param PollOption $option */ public function addOption(PollOption $option) { $this->options->attach($option); } /** * @param PollOption $option */ public function removeOption(PollOption $option) { $this->options->detach($option); } /** * @param ObjectStorage $participations */ public function setParticipations(ObjectStorage $participations) { $this->participations = $participations; } /** * @return ObjectStorage<Participation> */ public function getParticipations() { return $this->participations; } /** * @param Participation $participation */ public function addParticipation(Participation $participation) { $this->participations->attach($participation); } /** * @param Participation $participation */ public function removeParticipation(Participation $participation) { $this->participations->detach($participation); } /* Business logic stuff */ /** * @return boolean */ public function getIsOpen() { if ($this->status === static::STATUS_BYDATE) { return ($this->openDatetime === null || $this->openDatetime->getTimestamp() <= $GLOBALS['EXEC_TIME']) && ($this->closeDatetime === null || $this->closeDatetime->getTimestamp() >= $GLOBALS['EXEC_TIME']); } return $this->status === static::STATUS_OPEN; } /** * @return boolean */ public function getIsClosed() { return !$this->getIsOpen(); } }
aaw-team/minipoll
Classes/Domain/Model/Poll.php
PHP
gpl-3.0
6,328
window.onload = function() { document.getElementById('smile').innerHTML = ":)"; };
nishant-jain-94/express-app
public/javascripts/main.js
JavaScript
gpl-3.0
85
class Boilerplate::User < ActiveRecord::Base end
geraud/boilerplate
app/models/boilerplate/user.rb
Ruby
gpl-3.0
50
<?php /* ---------------------------------------------------------------------- * views/bundles/mediaviewer_html.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2011-2015 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ $t_rep = $this->getVar('t_object_representation'); $vn_representation_id = $t_rep->getPrimaryKey(); $vn_item_id = $this->getVar('item_id'); $t_object = $this->getVar('t_object'); $va_display_options = $this->getVar('display_options'); $vs_display_type = $this->getVar('display_type'); $vs_poster_version = $this->getVar('poster_version'); $vs_show_version = $this->getVar('version'); $vs_container_id = $this->getVar('containerID'); $va_reps = $this->getVar('reps'); if($vs_display_type == 'media_overlay'){ if(sizeof($va_reps) > 1){ $vs_version = "icon"; $vn_num_cols = 1; if(sizeof($va_reps) > 5){ $vn_num_cols = 2; } if(sizeof($va_reps) > 14){ $va_reps = $t_object->getRepresentations(array('tinyicon'), null, array("return_with_access" => $va_access_values)); $vs_version = "tinyicon"; $vn_num_cols = 2; } ?> <!-- multiple rep thumbnails - ONLY for media overlay --> <div class="caMediaOverlayRepThumbs"> <?php $i = 0; foreach($va_reps as $vn_rep_id => $va_rep_info){ print "<a href='#' ".(($vn_rep_id == $vn_representation_id) ? "class='selectedRep' " : "")."onClick='jQuery(\"#{$vs_container_id}\").load(\"".caNavUrl($this->request, '', '*', 'GetRepresentationInfo', array('representation_id' => (int)$vn_rep_id, 'object_id' => (int)$t_object->getPrimaryKey()))."\");'>".$va_rep_info['tags'][$vs_version]."</a>"; $i++; if($i == $vn_num_cols){ $i = 0; print "<br/>"; } } ?> </div><!-- end caMediaOverlayRepThumbs --> <?php } ?> <!-- Controls - only for media overlay --> <div class="caMediaOverlayControls"> <div class='close'><a href="#" onclick="caMediaPanel.hidePanel(); return false;" title="close"><i class="fa fa-times"></i></a></div> <?php if(caObjectsDisplayDownloadLink($this->request, (int)$t_object->getPrimaryKey()) && $this->request->user->canDoAction('can_download_media')){ ?> <div class='download'> <?php # -- get version to download configured in media_display.conf $va_download_display_info = caGetMediaDisplayInfo('download', $t_rep->getMediaInfo('media', 'INPUT', 'MIMETYPE')); $vs_download_version = $va_download_display_info['display_version']; print caNavLink($this->request, "<i class=\"fa fa-download\"></i>", '', '', '*', 'DownloadRepresentation', array('representation_id' => $t_rep->getPrimaryKey(), "object_id" => $t_object->getPrimaryKey(), "download" => 1, "version" => $vs_download_version)); ?> </div> <?php } ?> <div class='objectInfo'> <?php $vs_label = $t_object->getLabelForDisplay(); print (mb_strlen($vs_label) > 80) ? mb_substr($vs_label, 0, 80)."..." : $vs_label; if($t_object->get("idno")){ print " [".$t_object->get("idno")."]"; } ?> </div> <div class='repNav'> <?php if ($vn_id = $this->getVar('previous_representation_id')) { print "<a href='#' onClick='jQuery(\"#{$vs_container_id}\").load(\"".caNavUrl($this->request, '', '*', 'GetRepresentationInfo', array('representation_id' => (int)$vn_id, 'object_id' => (int)$t_object->getPrimaryKey()))."\");'>←</a>"; } if (sizeof($va_reps) > 1) { print ' '._t("%1 of %2", $this->getVar('representation_index'), sizeof($va_reps)).' '; } if ($vn_id = $this->getVar('next_representation_id')) { print "<a href='#' onClick='jQuery(\"#{$vs_container_id}\").load(\"".caNavUrl($this->request, '', '*', 'GetRepresentationInfo', array('representation_id' => (int)$vn_id, 'object_id' => (int)$t_object->getPrimaryKey()))."\");'>→</a>"; } ?> </div> </div><!-- end caMediaOverlayControls --> <?php } ?> <div <?php print ($vs_display_type == 'media_overlay') ? 'id="caMediaOverlayContent"' : ''; ?>> <?php // return standard tag if (!is_array($va_display_options)) { $va_display_options = array(); } $va_display_options['help_load_url'] = caNavUrl($this->request, '', 'Detail', 'ViewerHelp'); if ($this->request->isLoggedIn()) { $va_display_options['annotation_load_url'] = caNavUrl($this->request, '', 'Detail', 'GetAnnotations', array('object_id' => $t_object->getPrimaryKey(), 'representation_id' => $t_rep->getPrimaryKey(), 'item_id' => $vn_item_id)); $va_display_options['annotation_save_url'] = caNavUrl($this->request, '', 'Detail', 'SaveAnnotations', array('object_id' => $t_object->getPrimaryKey(), 'representation_id' => $t_rep->getPrimaryKey(), 'item_id' => $vn_item_id)); $va_display_options['read_only'] = false; $va_display_options['scale'] = $t_rep->getMediaScale('media'); } else { $va_display_options['read_only'] = true; } $vs_tag = $t_rep->getMediaTag('media', $vs_show_version, array_merge($va_display_options, array( 'id' => ($vs_display_type == 'media_overlay') ? 'caMediaOverlayContentMedia_'.$t_rep->getPrimaryKey() : 'caMediaDisplayContentMedia_'.$t_rep->getPrimaryKey(), 'viewer_base_url' => $this->request->getBaseUrlPath(), 'class' => ($vs_display_type == 'media_overlay') ? 'caMediaOverlayContentMedia' : '', 'poster' => $this->getVar('poster'), 'posterURL' => $this->getVar('posterURL') ))); # --- should the media be clickable to open the overlay? if($va_display_options['no_overlay'] || $vs_display_type == 'media_overlay'){ print $vs_tag; }else{ if ($t_object && $t_rep) { // Images get zoomed on click; everything else requires a click on the magnifying glass icon print $t_rep->representationIsOfClass('image') ? "<a href='#' onclick='caMediaPanel.showPanel(\"".caNavUrl($this->request, '', 'Detail', 'GetRepresentationInfo', array('object_id' => $t_object->getPrimaryKey(), 'representation_id' => $t_rep->getPrimaryKey(), 'overlay' => 1))."\"); return false;' >".$vs_tag."</a>" : $vs_tag; } } ?> </div><!-- end caMediaOverlayContent/ caMediaDisplayContent -->
libis/pa_cct
themes/ncep/views/bundles/mediaviewer_html.php
PHP
gpl-3.0
6,958
// // Copyright (c) 2014 Scott Ellis and Richard Barnett // // This file is part of SyntroNet // // SyntroNet 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. // // SyntroNet 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 SyntroNet. If not, see <http://www.gnu.org/licenses/>. // #include "CFSClient.h" #include "SyntroCFS.h" #include "SyntroCFSDefs.h" SyntroCFS::SyntroCFS(CFSClient *client, QString filePath) : m_parent(client), m_filePath(filePath) { } SyntroCFS::~SyntroCFS() { } bool SyntroCFS::cfsOpen(SYNTRO_CFSHEADER *) { return true; } void SyntroCFS::cfsClose() { } void SyntroCFS::cfsRead(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg, SYNTROCFS_STATE *, unsigned int) { SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_READ_INDEX_RES, cfsMsg->cfsType); cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE); } void SyntroCFS::cfsWrite(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg, SYNTROCFS_STATE *, unsigned int) { SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_WRITE_INDEX_RES, cfsMsg->cfsType); cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE); } void SyntroCFS::cfsQuery(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg) { SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_QUERY_RES, cfsMsg->cfsType); cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE); } void SyntroCFS::cfsCancelQuery(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg) { SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_CANCEL_QUERY_RES, cfsMsg->cfsType); cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE); } void SyntroCFS::cfsFetchQuery(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg) { SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_FETCH_QUERY_RES, cfsMsg->cfsType); cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE); } unsigned int SyntroCFS::cfsGetRecordCount() { return 0; } SYNTRO_EHEAD *SyntroCFS::cfsBuildResponse(SYNTRO_EHEAD *ehead, int length) { SYNTRO_EHEAD *responseE2E = m_parent->clientBuildLocalE2EMessage(m_parent->m_CFSPort, &(ehead->sourceUID), SyntroUtils::convertUC2ToUInt(ehead->sourcePort), sizeof(SYNTRO_CFSHEADER) + length); SYNTRO_CFSHEADER *responseHdr = (SYNTRO_CFSHEADER *)(responseE2E + 1); memset(responseHdr, 0, sizeof(SYNTRO_CFSHEADER)); SyntroUtils::convertIntToUC4(length, responseHdr->cfsLength); return responseE2E; } SYNTRO_EHEAD *SyntroCFS::cfsBuildQueryResponse(SYNTRO_EHEAD *ehead, int length) { SYNTRO_EHEAD *responseE2E = m_parent->clientBuildLocalE2EMessage(m_parent->m_CFSPort, &(ehead->sourceUID), SyntroUtils::convertUC2ToUInt(ehead->sourcePort), sizeof(SYNTRO_QUERYRESULT_HEADER) + length); SYNTRO_QUERYRESULT_HEADER *responseHdr = (SYNTRO_QUERYRESULT_HEADER *)(responseE2E + 1); memset(responseHdr, 0, sizeof(SYNTRO_QUERYRESULT_HEADER)); SyntroUtils::convertIntToUC4(length, responseHdr->cfsHeader.cfsLength); return responseE2E; } void SyntroCFS::cfsReturnError(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg, int responseCode) { SyntroUtils::swapEHead(ehead); SyntroUtils::convertIntToUC4(0, cfsMsg->cfsLength); SyntroUtils::convertIntToUC2(responseCode, cfsMsg->cfsParam); #ifdef CFS_THREAD_TRACE TRACE2("Sent error response to %s, response %d", qPrintable(SyntroUtils::displayUID(&ehead->destUID)), SyntroUtils::convertUC2ToInt(cfsMsg->cfsParam)); #endif m_parent->sendMessage(ehead, sizeof(SYNTRO_CFSHEADER)); }
robotage/SyntroCore
SyntroDB/SyntroCFS.cpp
C++
gpl-3.0
4,257
/* * File: SynIO.hpp * Author: Matteo Di Carlo * Created on March 17, 2016, 9:05 PM * * Copyright (C) 2016 Matteo Di Carlo - www.gleeno.com * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SYNIO_HPP #define SYNIO_HPP #include <iostream> #include <fstream> #include "Synapsis/Common/Status.hpp" #include <json/json.h> class SynIO { public: status_t getTextFile(std::string* source, std::string* result); //todo: setTextFile status_t getJsonFile (std::string* source, Json::Value* result); static int toJson(void* source, Json::Value* result); }; #endif /* SYNIO_HPP */
Gleeno/DomAlgo
Software/DomAlgoServer/src/Synapsis/Core/SynIO.hpp
C++
gpl-3.0
1,208
package br.unesp.exemplo.api.valueobjects; import java.io.Serializable; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonTypeName; /** * Value Object para comunicação REST da entidade Inscricao PUT (atualização) * @author Alessandro Moraes */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeName("Inscricao") public class InscricaoVOPut implements Serializable { private static final long serialVersionUID = 8853148012477575858L; @NotNull private String nome; @NotNull private String cpf; @NotNull private String email; private String tamanhoCamiseta; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTamanhoCamiseta() { return tamanhoCamiseta; } public void setTamanhoCamiseta(String tamanhoCamiseta) { this.tamanhoCamiseta = tamanhoCamiseta; } }
amoraes/spring-boot-unesp
services/src/main/java/br/unesp/exemplo/api/valueobjects/InscricaoVOPut.java
Java
gpl-3.0
1,180
/* 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; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace dnSpy.Roslyn.Text.Tagging { /// <summary> /// Async tagger base class. Multiple <see cref="GetTags(NormalizedSnapshotSpanCollection)"/> /// calls are handled by one task to prevent too many created tasks. /// </summary> /// <typeparam name="TTagType">Type of tag, eg. <see cref="IClassificationTag"/></typeparam> /// <typeparam name="TUserAsyncState">User async state type</typeparam> /// <remarks> /// All tags are cached. The cache is invalidated whenever <see cref="GetTags(NormalizedSnapshotSpanCollection)"/> /// is called with a new snapshot. /// /// It currently doesn't try to re-use the old calculated tags. It could return those (after /// TranslateTo()'ing them to the new snapshot) while it executes the async code in the background /// that calculates the new tags. /// </remarks> abstract class AsyncTagger<TTagType, TUserAsyncState> : ITagger<TTagType>, IDisposable where TTagType : ITag where TUserAsyncState : new() { readonly Dictionary<int, IEnumerable<ITagSpan<TTagType>>> cachedTags; readonly object lockObj; SnapshotState? lastSnapshotState; public event EventHandler<SnapshotSpanEventArgs> TagsChanged; sealed class SnapshotState { public bool TaskStarted { get; set; } public GetTagsStateImpl GetTagsStateImpl { get; } public ITextSnapshot Snapshot { get; } public CancellationToken CancellationToken { get; } readonly CancellationTokenSource cancellationTokenSource; public SnapshotState(ITextSnapshot snapshot) { Snapshot = snapshot ?? throw new ArgumentNullException(nameof(snapshot)); cancellationTokenSource = new CancellationTokenSource(); CancellationToken = cancellationTokenSource.Token; GetTagsStateImpl = new GetTagsStateImpl(CancellationToken); } public void Cancel() { if (canceled) return; canceled = true; cancellationTokenSource.Cancel(); } bool canceled; int refCounter; public void AddRef() => Interlocked.Increment(ref refCounter); public void FreeRef() { int newValue = Interlocked.Decrement(ref refCounter); Debug.Assert(newValue >= 0); if (newValue == 0) Dispose(); } void Dispose() { cancellationTokenSource.Dispose(); GetTagsStateImpl.Dispose(); } } protected readonly struct TagsResult { public SnapshotSpan Span { get; } public ITagSpan<TTagType>[] Tags { get; } public TagsResult(SnapshotSpan span, ITagSpan<TTagType>[] tags) { if (span.Snapshot is null) throw new ArgumentException(); Span = span; Tags = tags ?? throw new ArgumentNullException(nameof(tags)); } } protected abstract class GetTagsState { public CancellationToken CancellationToken { get; } public abstract void AddResult(TagsResult result); public TUserAsyncState UserAsyncState { get; } protected GetTagsState(CancellationToken cancellationToken) { CancellationToken = cancellationToken; UserAsyncState = new TUserAsyncState(); } } sealed class GetTagsStateImpl : GetTagsState { readonly List<TagsResult> tagsResultList; readonly List<NormalizedSnapshotSpanCollection> jobs; readonly List<TagsResult> currentResult; HashSet<SnapshotSpan>? snapshotHash; public GetTagsStateImpl(CancellationToken cancellationToken) : base(cancellationToken) { tagsResultList = new List<TagsResult>(); jobs = new List<NormalizedSnapshotSpanCollection>(); currentResult = new List<TagsResult>(); } public override void AddResult(TagsResult result) { CancellationToken.ThrowIfCancellationRequested(); currentResult.Add(result); } public void OnStartNewJob(NormalizedSnapshotSpanCollection spans) => currentResult.Clear(); public void OnEndNewJob(NormalizedSnapshotSpanCollection spans) { AddMissingResults(spans); tagsResultList.AddRange(currentResult); currentResult.Clear(); } void AddMissingResults(NormalizedSnapshotSpanCollection spans) { if (currentResult.Count == spans.Count) return; // Make sure all spans with no extra info are also cached so GetTags() only gets called once per snapshot span // Common case if (spans.Count == 1 && currentResult.Count == 0) { currentResult.Add(new TagsResult(spans[0], Array.Empty<ITagSpan<TTagType>>())); return; } if (snapshotHash is null) snapshotHash = new HashSet<SnapshotSpan>(); foreach (var r in currentResult) snapshotHash.Add(r.Span); foreach (var span in spans) { if (!snapshotHash.Contains(span)) currentResult.Add(new TagsResult(span, Array.Empty<ITagSpan<TTagType>>())); } snapshotHash.Clear(); } public TagsResult[] GetResult() { Debug.Assert(jobs.Count == 0); Debug.Assert(currentResult.Count == 0); Debug.Assert(snapshotHash is null || snapshotHash.Count == 0); var result = tagsResultList.ToArray(); tagsResultList.Clear(); currentResult.Clear(); snapshotHash?.Clear(); return result; } public NormalizedSnapshotSpanCollection? TryGetJob() { if (jobs.Count == 0) return null; int index = jobs.Count - 1; var job = jobs[index]; jobs.RemoveAt(index); return job; } public void AddJob(NormalizedSnapshotSpanCollection spans) => jobs.Add(spans); public void Dispose() => (UserAsyncState as IDisposable)?.Dispose(); } protected AsyncTagger() { cachedTags = new Dictionary<int, IEnumerable<ITagSpan<TTagType>>>(); lockObj = new object(); } protected void RefreshAllTags(ITextSnapshot snapshot) { Debug.Assert(!(snapshot is null)); if (snapshot is null) return; lock (lockObj) { lastSnapshotState?.Cancel(); lastSnapshotState?.FreeRef(); lastSnapshotState = null; cachedTags.Clear(); } TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length))); } public IEnumerable<ITagSpan<TTagType>> GetTags(NormalizedSnapshotSpanCollection spans) { if (spans.Count == 0) return Enumerable.Empty<ITagSpan<TTagType>>(); var snapshot = spans[0].Snapshot; // The common case is spans.Count == 1, so try to prevent extra allocations IEnumerable<ITagSpan<TTagType>>? singleResult = null; List<ITagSpan<TTagType>>? multipleResults = null; SnapshotSpan? singleMissingSpan = null; List<SnapshotSpan>? multipleMissingSpans = null; lock (lockObj) { if (lastSnapshotState?.Snapshot != snapshot) { lastSnapshotState?.Cancel(); lastSnapshotState?.FreeRef(); cachedTags.Clear(); lastSnapshotState = new SnapshotState(snapshot); lastSnapshotState.AddRef(); } Debug.Assert(!(lastSnapshotState is null)); foreach (var span in spans) { if (cachedTags.TryGetValue(span.Start.Position, out var tags)) { if (singleResult is null) singleResult = tags; else { if (multipleResults is null) multipleResults = new List<ITagSpan<TTagType>>(singleResult); multipleResults.AddRange(tags); } } else { if (singleMissingSpan is null) singleMissingSpan = span; else { if (multipleMissingSpans is null) multipleMissingSpans = new List<SnapshotSpan>() { singleMissingSpan.Value }; multipleMissingSpans.Add(span); } } } } Debug.Assert(multipleResults is null || multipleResults.Count >= 2); Debug.Assert(multipleMissingSpans is null || multipleMissingSpans.Count >= 2); if (!(singleMissingSpan is null)) { if (spans.Count != (multipleMissingSpans?.Count ?? 1)) { spans = !(multipleMissingSpans is null) ? new NormalizedSnapshotSpanCollection(multipleMissingSpans) : new NormalizedSnapshotSpanCollection(singleMissingSpan.Value); } lock (lockObj) { var lastSnapshotStateTmp = lastSnapshotState; lastSnapshotStateTmp.GetTagsStateImpl.AddJob(spans); if (!lastSnapshotStateTmp.TaskStarted) { lastSnapshotStateTmp.TaskStarted = true; lastSnapshotStateTmp.AddRef(); GetTagsAsync(lastSnapshotStateTmp) .ContinueWith(t => { lastSnapshotStateTmp.FreeRef(); var ex = t.Exception; if (t.IsCompleted && !t.IsCanceled && !t.IsFaulted) SaveResult(t.Result); }); } } } return multipleResults ?? singleResult ?? Enumerable.Empty<ITagSpan<TTagType>>(); } void SaveResult(TagsResult[] tagsResultList) { if (tagsResultList.Length == 0) return; bool sameSnapshot; lock (lockObj) { sameSnapshot = tagsResultList[0].Span.Snapshot == lastSnapshotState?.Snapshot; if (sameSnapshot) { foreach (var result in tagsResultList) cachedTags[result.Span.Span.Start] = result.Tags; } } if (sameSnapshot) { foreach (var result in tagsResultList) TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(result.Span)); } } async Task<TagsResult[]> GetTagsAsync(SnapshotState snapshotState) { try { NormalizedSnapshotSpanCollection? spans; for (;;) { lock (lockObj) { spans = snapshotState.GetTagsStateImpl.TryGetJob(); if (spans is null) { snapshotState.TaskStarted = false; return snapshotState.GetTagsStateImpl.GetResult(); } } snapshotState.GetTagsStateImpl.OnStartNewJob(spans); await GetTagsAsync(snapshotState.GetTagsStateImpl, spans).ConfigureAwait(false); snapshotState.GetTagsStateImpl.OnEndNewJob(spans); } } catch (OperationCanceledException) { throw; } catch { return Array.Empty<TagsResult>(); } } protected abstract Task GetTagsAsync(GetTagsState state, NormalizedSnapshotSpanCollection spans); public void Dispose() { DisposeInternal(); lastSnapshotState?.Cancel(); } protected virtual void DisposeInternal() { } } }
manojdjoshi/dnSpy
dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/AsyncTagger.cs
C#
gpl-3.0
10,697