repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
shared-repos/context | src/Context.Interfaces/Services/IServiceManager.cs | 208 | using System;
using System.ComponentModel.Design;
namespace Context.Interfaces.Services
{
public interface IServiceManager : IServiceContainer
{
object GetService(Guid serviceId);
}
}
| mit |
TonkWorks/scripts | manage.py | 253 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webscripts.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| mit |
ionagamed/munchkin | logic/packs/pack1/doors/harpies.js | 674 | import { Card } from '../../../Card';
import { Monster } from '../helpers/Monster';
const id = 'harpies';
class harpies extends Monster {
constructor() {
super();
this.id = id;
this.pack = 'pack1';
this.kind = 'door';
this.type = 'monster';
this.treasure = 2;
}
badThing(player, table) {
player.decreaseLevel(2);
}
getAttackAgainst(players) {
var isWizard = false;
players.map(x => {
if(x.hasClassDisadvantages('wizard'))
isWizard = true;
});
if (isWizard) return 9;
return 4;
}
}
Card.cards[id] = new harpies();
| mit |
ryancanulla/deftSample | app/view/Viewport.js | 264 | Ext.define('Deft-Sample.view.Viewport', {
extend: 'Ext.container.Viewport',
requires:[
'Ext.layout.container.Fit',
'Deft-Sample.view.Main'
],
layout: {
type: 'fit'
},
items: [{
xtype: 'app-main'
}]
});
| mit |
llun/eyes | app/controllers/HTTPFormProbes.java | 1833 | package controllers;
import java.util.HashMap;
import models.Quota;
import models.Server;
import models.User;
import models.probe.HTTPFormProbe;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.i18n.Messages;
import play.mvc.Controller;
import play.mvc.With;
@With(Secure.class)
public class HTTPFormProbes extends Controller {
public static void create(@Required Long server, @Required String name,
@Required String serverURL, @Required Integer expectResponse,
String[] keys, String[] values) {
if (Validation.hasErrors()) {
params.flash();
Validation.keep();
flash.put("message", Messages.get("probe.http.form.error"));
} else {
Server instance = Server.findById(server);
if (Quota.canCreateProbe(User.fromUsername(Security.connected()),
instance)) {
HashMap<String, String> properties = new HashMap<String, String>();
for (int i = 0; i < keys.length; i++) {
if (keys[i].trim().length() > 0) {
properties.put(keys[i], values[i]);
}
}
HTTPFormProbe probe = new HTTPFormProbe(instance, name, serverURL,
expectResponse, properties);
probe.save();
}
}
Servers.show(server);
}
public static void check(@Required Long server, @Required Long probe) {
if (!Validation.hasErrors()) {
HTTPFormProbe instance = HTTPFormProbe.findById(probe);
instance.status = instance.check();
instance.save();
}
Servers.show(server);
}
public static void delete(@Required Long server, @Required Long probe) {
if (!Validation.hasErrors()) {
HTTPFormProbe instance = HTTPFormProbe.findById(probe);
if (instance != null) {
instance.delete();
}
}
Servers.show(server);
}
}
| mit |
adamclifford/Wyam | src/extensions/Wyam.Feeds/Syndication/Extensions/ExtensibleBase.cs | 4676 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.Xml.Serialization;
namespace Wyam.Feeds.Syndication.Extensions
{
/// <summary>
/// Allows any generic extensions expressed as XmlElements and XmlAttributes
/// </summary>
public abstract class ExtensibleBase : INamespaceProvider
{
protected const string ContentPrefix = "content";
protected const string ContentNamespace = "http://purl.org/rss/1.0/modules/content/";
protected const string ContentEncodedElement = "encoded";
protected const string WfwPrefix = "wfw";
protected const string WfwNamespace = "http://wellformedweb.org/CommentAPI/";
protected const string WfwCommentElement = "comment";
protected const string WfwCommentRssElement = "commentRss";
protected const string SlashPrefix = "slash";
protected const string SlashNamespace = "http://purl.org/rss/1.0/modules/slash/";
//protected const string SlashSectionElement = "section";
//protected const string SlashDepartmentElement = "department";
protected const string SlashCommentsElement = "comments";
//protected const string SlashHitParadeElement = "hit_parade";
[XmlAnyElement]
public readonly List<XmlElement> ElementExtensions = new List<XmlElement>();
[XmlIgnore]
public bool ElementExtensionsSpecified
{
get { return ElementExtensions.Count > 0; }
set { }
}
[XmlAnyAttribute]
public readonly List<XmlAttribute> AttributeExtensions = new List<XmlAttribute>();
[XmlIgnore]
public bool AttributeExtensionsSpecified
{
get { return AttributeExtensions.Count > 0; }
set { }
}
/// <summary>
/// Applies the extensions in adapter to ExtensibleBase
/// </summary>
/// <param name="adapter"></param>
public void AddExtensions(IExtensionAdapter adapter)
{
if (adapter == null)
{
return;
}
IEnumerable<XmlAttribute> attributes = adapter.GetAttributeEntensions();
if (attributes != null)
{
AttributeExtensions.AddRange(attributes);
}
IEnumerable<XmlElement> elements = adapter.GetElementExtensions();
if (elements != null)
{
ElementExtensions.AddRange(elements);
}
}
/// <summary>
/// Extracts the extensions in this ExtensibleBase into adapter
/// </summary>
/// <param name="adapter"></param>
protected void FillExtensions(IExtensionAdapter adapter)
{
if (adapter == null)
{
return;
}
adapter.SetAttributeEntensions(AttributeExtensions);
adapter.SetElementExtensions(ElementExtensions);
}
public virtual void AddNamespaces(XmlSerializerNamespaces namespaces)
{
foreach (XmlAttribute node in AttributeExtensions)
{
if (string.IsNullOrEmpty(node.Prefix))
{
// do not let extensions overwrite the default namespace
continue;
}
namespaces.Add(node.Prefix, node.NamespaceURI);
}
foreach (XmlElement node in ElementExtensions)
{
if (string.IsNullOrEmpty(node.Prefix))
{
// do not let extensions overwrite the default namespace
continue;
}
namespaces.Add(node.Prefix, node.NamespaceURI);
}
}
public static string ConvertToString(DateTime dateTime)
{
return XmlConvert.ToString(dateTime, XmlDateTimeSerializationMode.Utc);
}
public static DateTime? ConvertToDateTime(string value)
{
DateTime dateTime;
if (!DateTime.TryParse(value, out dateTime))
{
return null;
}
return dateTime;
}
protected static string ConvertToString(Uri uri) =>
uri == null ? null : Uri.EscapeUriString(uri.ToString());
protected static Uri ConvertToUri(string value)
{
Uri uri;
if (string.IsNullOrEmpty(value) ||
!Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out uri))
{
return null;
}
return uri;
}
}
} | mit |
rexonms/react-redux-mongo | server/tests/server.test.js | 7213 | const expect = require('expect')
const request = require('supertest')
const {app} = require('./../server')
const {Todo} = require('./../models/todo')
const { ObjectID } = require('mongodb')
var mockTodos = [
{ _id: ObjectID("58863139d6166e3f70b7762d"), task: "First Todo", completed: false },
{ _id: ObjectID("58863117d6166e3f70b7762b"), task: "Second Todo", completed: true }
]
// lifecycle method
// Remove all database record before every test so that we have a clean database
beforeEach((done) => { // function with done argument
Todo.remove({}) // Remove everything from Todo
.then(() => {
return Todo.insertMany(mockTodos)
}).then(() => done())
})
/******************************************
* ACTIONS
*******************************************/
describe (`POST /api actions test`, () => {
let errorMessage = 'Must provide action. Accepted actions are add,remove,update'
it('should FAIL when an action is not sent', (done) => {
request(app)
.post('/api')
.send()
.expect(400)
.expect(res => {
expect(res.error.text).toBe(errorMessage)
})
.end((err, res) => {
if (err) {
return (done(err))
}
done()
})
})
it('should FAIL when an wrong action is sent', (done) => {
request(app)
.post('/api')
.send()
.expect(400)
.expect(res => {
expect(res.error.text).toBe(errorMessage)
})
.end((err, res) => {
if (err) {
return (done(err))
}
done()
})
})
})
/******************************************
* ACTION: add
*******************************************/
describe(`POST /api with action "add"`, () => {
it('should create a new todo task', (done) => {
let todo = {
action: "add",
task: "Task added via test suite"
}
request(app)
.post('/api')
.send(todo)
.expect(200)
.expect((res) => {
// Asserting that we get proper response
expect(res.body.task).toBe(todo.task)
})
.end((err, res) => {
if (err) {
return done(err)
}
// Asserting that the data did get save in db
Todo.find().then((todos) => {
expect(todos.length).toBe(3)
expect(todos[2].task).toBe(todo.task)
done()
}).catch((e) => done(e))
})
})
it('Should NOT create a todo with an task text body data', (done) => {
let task = {
action: "add",
task: ""
}
let error = 'The action "add" must have a task'
request(app)
.post('/api')
.send(task)
.expect(200)
.expect((res) => {
expect(res.body.error).toBe(error)
})
.end((err, req) => {
if (err) {
return done(err)
}
Todo.find().then(todos => {
expect(todos.length).toBe(2)
done()
}).catch((e) => done(e))
})
})
it('Should NOT create a todo with an task text body data', (done) => {
let task = {
action: "add",
task: ""
}
let error = 'The action "add" must have a task'
request(app)
.post('/api')
.send(task)
.expect(200)
.expect((res) => {
expect(res.body.error).toBe(error)
})
.end((err, req) => {
if (err) {
return done(err)
}
Todo.find().then(todos => {
expect(todos.length).toBe(2)
done()
}).catch((e) => done(e))
})
})
})
/******************************************
* ACTION: update
*******************************************/
describe(`POST /api with action "update"`, () => {
let error = 'The action "update" must have id and completed'
// happy path
it('Should update the status of todo task', (done) => {
let updateTodo = {
action: "update",
id :'58863139d6166e3f70b7762d',
completed: true
}
request(app)
.post('/api')
.send(updateTodo)
.expect(200)
.expect((res) => {
expect(res.body.completed).toBe(updateTodo.completed)
})
.end((err, res) => {
if (err) {
return done(err)
}
done()
})
})
it('Should fail if the id or completed is not provided', (done) => {
let updateTodo = {
action: "update",
id :'',
completed: ''
}
request(app)
.post('/api')
.send(updateTodo)
.expect(200)
.expect(res => {
expect(res.body.error).toBe(error)
})
.end((err, res) => {
if (err) {
return done(err)
}
done()
})
})
})
/******************************************
* ACTION: Remove
*******************************************/
describe(`POST /api with action "remove"`, () => {
//
let error = 'The action "remove" must have a id'
// happy path
it('Should remove todo task', (done) => {
let removeTodo = {
action: "remove",
id :'58863139d6166e3f70b7762d',
}
request(app)
.post('/api')
.send(removeTodo)
.expect(200)
.expect((res) => {
expect(res.body.todoId).toBe(removeTodo.id)
})
.end((err, res) => {
if (err) {
return done(err)
}
done()
})
})
it('Should fail if the id is not provided', (done) => {
let removeTodo = {
action: "remove",
id :"",
}
request(app)
.post('/api')
.send(removeTodo)
.expect(200)
.expect(res => {
expect(res.body.error).toBe(error)
})
.end((err, res) => {
if (err) {
return done(err)
}
done()
})
})
})
/******************************************
* GET TODOS
*******************************************/
describe('GET /api', () => {
it('Should get all todos', (done) => {
request(app)
.get('/api')
.send()
.expect(200)
.expect(res => {
expect(res.body.data.length).toBe(2)
})
.end(done)
})
}) | mit |
360cbs/xxworkshop_android | src/com/xxworkshop/common/Installation.java | 3236 | /*
* @(#)Installation.java Project:ProgramList
* Date:2012-8-7
*
* Copyright (c) 2011 CFuture09, Institute of Software,
* Guangdong Ocean University, Zhanjiang, GuangDong, China.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xxworkshop.common;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
import android.provider.Settings.Secure;
import android.util.Log;
/**
* 安装工具类,该类用于生成程序在该设备的唯一标识符。
*
* @author Geek_Soledad ([email protected])
*/
public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION-"
+ UUID.nameUUIDFromBytes("androidkit".getBytes());
/**
* 返回该设备在此程序上的唯一标识符。
*
* @param context
* Context对象。
* @return 表示该设备在此程序上的唯一标识符。
*/
public static String getID(Context context) {
if (sID == null) {
synchronized (Installation.class) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
writeInstallationFile(context, installation);
}
sID = readInstallationFile(installation);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return sID;
}
/**
* 将表示此设备在该程序上的唯一标识符写入程序文件系统中。
*
* @param installation
* 保存唯一标识符的File对象。
* @return 唯一标识符。
* @throws IOException
* IO异常。
*/
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile accessFile = new RandomAccessFile(installation, "r");
byte[] bs = new byte[(int) accessFile.length()];
accessFile.readFully(bs);
accessFile.close();
return new String(bs);
}
/**
* 读出保存在程序文件系统中的表示该设备在此程序上的唯一标识符。
*
* @param context
* Context对象。
* @param installation
* 保存唯一标识符的File对象。
* @throws IOException
* IO异常。
*/
private static void writeInstallationFile(Context context, File installation)
throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String uuid = UUID.nameUUIDFromBytes(
Secure.getString(context.getContentResolver(), Secure.ANDROID_ID).getBytes())
.toString();
Log.i("cfuture09-androidkit", uuid);
out.write(uuid.getBytes());
out.close();
}
}
| mit |
aleksigron/graphics-toolkit | src/Rendering/UniformBuffer.hpp | 5655 | #pragma once
#include <cstdint>
#include "Math/Vec2.hpp"
#include "Math/Vec3.hpp"
#include "Math/Vec4.hpp"
#include "Math/Mat4x4.hpp"
namespace UniformBuffer
{
inline void SetScalarFloat(unsigned char* buffer, size_t offset, float value)
{
*reinterpret_cast<float*>(buffer + offset) = value;
}
inline void SetScalarInt(unsigned char* buffer, size_t offset, int value)
{
*reinterpret_cast<int*>(buffer + offset) = value;
}
inline void SetScalarVec2f(unsigned char* buffer, size_t offset, const Vec2f& value)
{
*reinterpret_cast<float*>(buffer + offset + 0) = value.x;
*reinterpret_cast<float*>(buffer + offset + 4) = value.y;
}
inline void SetScalarVec3f(unsigned char* buffer, size_t offset, const Vec3f& value)
{
*reinterpret_cast<float*>(buffer + offset + 0) = value.x;
*reinterpret_cast<float*>(buffer + offset + 4) = value.y;
*reinterpret_cast<float*>(buffer + offset + 8) = value.z;
}
inline void SetScalarVec4f(unsigned char* buffer, size_t offset, const Vec4f& value)
{
*reinterpret_cast<float*>(buffer + offset + 0) = value.x;
*reinterpret_cast<float*>(buffer + offset + 4) = value.y;
*reinterpret_cast<float*>(buffer + offset + 8) = value.z;
*reinterpret_cast<float*>(buffer + offset + 12) = value.w;
}
inline void SetScalarMat3x3f(unsigned char* buffer, size_t offset, const Mat3x3f& value)
{
for (size_t i = 0; i < 3; ++i)
for (size_t j = 0; j < 3; ++j)
*reinterpret_cast<float*>(buffer + offset + i * 16 + j * 4) = value[i * 3 + j];
}
inline void SetScalarMat4x4f(unsigned char* buffer, size_t offset, const Mat4x4f& value)
{
for (size_t i = 0; i < 16; ++i)
*reinterpret_cast<float*>(buffer + offset + i * 4) = value[i];
}
inline void SetArrayFloatOne(unsigned char* buffer, size_t offset, size_t index, float value)
{
*reinterpret_cast<float*>(buffer + offset + index * 16) = value;
}
inline void SetArrayFloatMany(unsigned char* buffer, size_t offset, size_t count, const float* values)
{
for (size_t i = 0; i < count; ++i)
*reinterpret_cast<float*>(buffer + offset + i * 16) = values[i];
}
inline void SetArrayIntOne(unsigned char* buffer, size_t offset, size_t index, int value)
{
*reinterpret_cast<int*>(buffer + offset + index * 16) = value;
}
inline void SetArrayIntMany(unsigned char* buffer, size_t offset, size_t count, const int* values)
{
for (size_t i = 0; i < count; ++i)
*reinterpret_cast<int*>(buffer + offset + i * 16) = values[i];
}
inline void SetArrayVec2fOne(unsigned char* buffer, size_t offset, size_t index, const Vec2f& value)
{
*reinterpret_cast<float*>(buffer + offset + index * 16 + 0) = value.x;
*reinterpret_cast<float*>(buffer + offset + index * 16 + 4) = value.y;
}
inline void SetArrayVec2fMany(unsigned char* buffer, size_t offset, size_t count, const Vec2f* values)
{
for (size_t i = 0; i < count; ++i)
{
*reinterpret_cast<float*>(buffer + offset + i * 16 + 0) = values[i].x;
*reinterpret_cast<float*>(buffer + offset + i * 16 + 4) = values[i].y;
}
}
inline void SetArrayVec3fOne(unsigned char* buffer, size_t offset, size_t index, const Vec3f& value)
{
*reinterpret_cast<float*>(buffer + offset + index * 16 + 0) = value.x;
*reinterpret_cast<float*>(buffer + offset + index * 16 + 4) = value.y;
*reinterpret_cast<float*>(buffer + offset + index * 16 + 8) = value.z;
}
inline void SetArrayVec3fMany(unsigned char* buffer, size_t offset, size_t count, const Vec3f* values)
{
for (size_t i = 0; i < count; ++i)
{
*reinterpret_cast<float*>(buffer + offset + i * 16 + 0) = values[i].x;
*reinterpret_cast<float*>(buffer + offset + i * 16 + 4) = values[i].y;
*reinterpret_cast<float*>(buffer + offset + i * 16 + 8) = values[i].z;
}
}
inline void SetArrayVec4fOne(unsigned char* buffer, size_t offset, size_t index, const Vec4f& value)
{
*reinterpret_cast<float*>(buffer + offset + index * 16 + 0) = value.x;
*reinterpret_cast<float*>(buffer + offset + index * 16 + 4) = value.y;
*reinterpret_cast<float*>(buffer + offset + index * 16 + 8) = value.z;
*reinterpret_cast<float*>(buffer + offset + index * 16 + 12) = value.w;
}
inline void SetArrayVec4fMany(unsigned char* buffer, size_t offset, size_t count, const Vec4f* values)
{
for (size_t i = 0; i < count; ++i)
{
*reinterpret_cast<float*>(buffer + offset + i * 16 + 0) = values[i].x;
*reinterpret_cast<float*>(buffer + offset + i * 16 + 4) = values[i].y;
*reinterpret_cast<float*>(buffer + offset + i * 16 + 8) = values[i].z;
*reinterpret_cast<float*>(buffer + offset + i * 16 + 12) = values[i].w;
}
}
inline void SetArrayMat3x3fOne(unsigned char* buffer, size_t offset, size_t index, const Mat3x3f& value)
{
for (size_t j = 0; j < 3; ++j)
for (size_t k = 0; k < 3; ++k)
*reinterpret_cast<float*>(buffer + offset + index * 64 + j * 16 + k) = value[j * 3 + k];
}
inline void SetArrayMat3x3fMany(unsigned char* buffer, size_t offset, size_t count, const Mat3x3f* values)
{
for (size_t i = 0; i < count; ++i)
for (size_t j = 0; j < 3; ++j)
for (size_t k = 0; k < 3; ++k)
*reinterpret_cast<float*>(buffer + offset + i * 64 + j * 16 + k) = values[i][j * 3 + k];
}
inline void SetArrayMat4x4fOne(unsigned char* buffer, size_t offset, size_t index, const Mat4x4f& value)
{
for (size_t i = 0; i < 16; ++i)
*reinterpret_cast<float*>(buffer + offset + index * 64 + i * 4) = value[i];
}
inline void SetArrayMat4x4fMany(unsigned char* buffer, size_t offset, size_t count, const Mat4x4f* values)
{
for (size_t i = 0; i < count; ++i)
for (size_t j = 0; j < 16; ++j)
*reinterpret_cast<float*>(buffer + offset + i * 64 + j * 4) = values[i][j];
}
}
| mit |
it114/trevor | www/js/controllers/about.js | 193 | angular.module('controller.about', [])
.controller('AboutCtrl', function($scope, $stateParams, $window) {
$scope.goTo = function (url) {
$window.open(url, '_system');
} ;
}); | mit |
angelikatyborska/fitness-class-schedule | spec/models/trainer_spec.rb | 641 | require 'rails_helper'
RSpec.describe Trainer do
it_behaves_like 'occupiable', :trainer
describe 'validations' do
it { is_expected.to validate_presence_of :first_name }
it { is_expected.to validate_presence_of :last_name }
it { is_expected.to validate_presence_of :description }
end
describe 'database columns' do
it { is_expected.to have_db_column :first_name }
it { is_expected.to have_db_column :last_name }
it { is_expected.to have_db_column :description }
it { is_expected.to have_db_column :photo }
end
describe 'associations' do
it { is_expected.to have_many :schedule_items }
end
end | mit |
Charmax/SteamAuth | inc/api.php | 58 | <?php
define("API_KEY", "INSERT YOUR API KEY HERE");
?> | mit |
kunitoki/nublas | manage.py | 255 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nublas.tests.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| mit |
NorthernDemon/Cargo-Global-Snapshot | src/main/scala/com/global/snapshot/Main.scala | 1503 | package com.global.snapshot
import akka.actor.{ActorRef, ActorSystem}
import akka.event.Logging.LogLevel
import com.global.snapshot.actors.CargoStations
import com.global.snapshot.actors.CargoStations._
import scala.annotation.tailrec
import scala.io.StdIn
object Main extends App {
val system = ActorSystem("cargo")
try {
val stations = system.actorOf(CargoStations.props, "stations")
stations ! Start
println("> Press ENTER to switch to the CLI")
readCommand(stations)
stations ! Stop
} finally {
system.terminate()
}
@tailrec
private def readCommand(stations: ActorRef): Unit = {
val command = StdIn.readLine()
val commands = "Type in one of the following commands: log, join, leave, marker, exit"
command match {
case "log" =>
println("Started logging the actors")
system.eventStream.setLogLevel(LogLevel(4))
case "join" =>
println("Berlin station is joining")
stations ! Join
case "leave" =>
println("Berlin station is leaving")
stations ! Leave
case "marker" =>
println("Sending out the marker")
stations ! StartMarker
case "exit" =>
println("Shutting down the stations")
case "" =>
system.eventStream.setLogLevel(LogLevel(1))
println(">Logs are off. " + commands)
case unknown => println(s">Don't know how to $unknown something. $commands")
}
if (command == "exit") () else readCommand(stations)
}
}
| mit |
Phpillip/phpillip | src/Provider/PygmentsServiceProvider.php | 587 | <?php
namespace Phpillip\Provider;
use Silex\Application;
use Silex\ServiceProviderInterface;
/**
* Parsedown Service Provider
*/
class PygmentsServiceProvider implements ServiceProviderInterface
{
/**
* {@inheritdoc}
*/
public function register(Application $app)
{
if ($app['pygments_class']::isAvailable()) {
$app['pygments'] = $app->share(function ($app) {
return new $app['pygments_class']();
});
}
}
/**
* {@inheritdoc}
*/
public function boot(Application $app)
{
}
}
| mit |
bankiru/seo-engine | Resolver/SourceRegistry.php | 963 | <?php
namespace Bankiru\Seo\Resolver;
use Bankiru\Seo\SourceInterface;
final class SourceRegistry
{
/** @var SourceInterface[] */
private $sources = [];
/**
* @return SourceInterface[]
*/
public function all()
{
return $this->sources;
}
/**
* @param string $key
* @param SourceInterface $source
*/
public function add($key, SourceInterface $source)
{
$this->sources[$key] = $source;
}
/**
* @param string $key
*
* @return bool
*/
public function has($key)
{
return array_key_exists($key, $this->sources);
}
/**
* @param string $key
*
* @return SourceInterface
* @throws \OutOfBoundsException
*/
public function get($key)
{
if (!$this->has($key)) {
throw new \OutOfBoundsException('Source not found: '.$key);
}
return $this->sources[$key];
}
}
| mit |
SonarSource-VisualStudio/sonar-scanner-msbuild | Tests/TestUtilities/Properties/AssemblyInfo.cs | 1012 | /*
* SonarScanner for MSBuild
* Copyright (C) 2016-2020 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* 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
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System.Reflection;
[assembly: AssemblyTitle("TestUtilities")]
[assembly: AssemblyProduct("TestUtilities")]
[assembly: AssemblyDescription("")]
| mit |
sveltejs/svelte | test/js/samples/bind-width-height/expected.js | 1308 | /* generated by Svelte vX.Y.Z */
import {
SvelteComponent,
add_render_callback,
add_resize_listener,
detach,
element,
init,
insert,
noop,
safe_not_equal
} from "svelte/internal";
function create_fragment(ctx) {
let div;
let div_resize_listener;
return {
c() {
div = element("div");
div.textContent = "some content";
add_render_callback(() => /*div_elementresize_handler*/ ctx[2].call(div));
},
m(target, anchor) {
insert(target, div, anchor);
div_resize_listener = add_resize_listener(div, /*div_elementresize_handler*/ ctx[2].bind(div));
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
div_resize_listener();
}
};
}
function instance($$self, $$props, $$invalidate) {
let { w } = $$props;
let { h } = $$props;
function div_elementresize_handler() {
w = this.offsetWidth;
h = this.offsetHeight;
$$invalidate(0, w);
$$invalidate(1, h);
}
$$self.$$set = $$props => {
if ('w' in $$props) $$invalidate(0, w = $$props.w);
if ('h' in $$props) $$invalidate(1, h = $$props.h);
};
return [w, h, div_elementresize_handler];
}
class Component extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, { w: 0, h: 1 });
}
}
export default Component; | mit |
orchestral/notifier | tests/Unit/MessageTest.php | 876 | <?php
namespace Orchestra\Notifier\Tests\Unit;
use Orchestra\Notifier\Message;
use PHPUnit\Framework\TestCase;
class MessageTest extends TestCase
{
/** @test */
public function it_has_proper_signature()
{
$stub = new Message();
$this->assertInstanceOf('Illuminate\Support\Fluent', $stub);
}
/** @test */
public function it_can_be_initiated()
{
$view = 'foo.bar';
$data = ['data' => 'foo'];
$subject = 'Hello world';
$stub = Message::create($view, $data, $subject);
$this->assertEquals($view, $stub->view);
$this->assertEquals($data, $stub->data);
$this->assertEquals($subject, $stub->subject);
$this->assertEquals($view, $stub->getView());
$this->assertEquals($data, $stub->getData());
$this->assertEquals($subject, $stub->getSubject());
}
}
| mit |
neilmiddleton/attr_secure | lib/attr_secure/adapters/sequel.rb | 478 | module AttrSecure
module Adapters
module Sequel
def self.valid?(object)
object.respond_to?(:<) && object < ::Sequel::Model
rescue NameError
false
end
def self.write_attribute(object, attribute, value)
object[attribute.to_sym] = value
end
def self.read_attribute(object, attribute)
object[attribute.to_sym]
end
end
end
end
if defined?(Sequel)
Sequel::Model.send(:extend, AttrSecure)
end
| mit |
Papercloud/dre | spec/dummy/app/models/user.rb | 59 | class User < ActiveRecord::Base
acts_as_device_owner
end
| mit |
artsy/emission | Example/Emission/index.storybooks.js | 504 | import { AppRegistry } from "react-native"
import { getStorybookUI, configure, addDecorator } from "@storybook/react-native"
import React from "react"
import { Theme } from "@artsy/palette"
import { loadStories } from "../../storybook/storyLoader"
// import your stories
configure(() => {
addDecorator(storyFn => <Theme>{storyFn()}</Theme>)
loadStories()
}, module)
const StorybookUI = getStorybookUI({ port: 9001, host: "localhost" })
AppRegistry.registerComponent("Storybook", () => StorybookUI)
| mit |
marlonandrade/linkeepit | db/migrate/20141122131807_remove_user_from_taggings.rb | 129 | class RemoveUserFromTaggings < ActiveRecord::Migration
def change
remove_reference :taggings, :user, index: true
end
end
| mit |
bongbot/mozart | spec/views/contacts/_edit.haml_spec.rb | 2032 | # Copyright (c) 2008-2013 Michael Dvorkin and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe "/contacts/_edit" do
include ContactsHelper
before do
login_and_assign
assign(:account, @account = FactoryGirl.create(:account))
assign(:accounts, [@account])
assign(:users, [current_user])
assign(:contact, FactoryGirl.create(:contact))
end
it "should render [edit contact] form" do
assign(:contact, @contact = FactoryGirl.create(:contact))
render
expect(view).to render_template(partial: "contacts/_top_section")
expect(view).to render_template(partial: "contacts/_extra")
expect(view).to render_template(partial: "shared/_web")
expect(view).to render_template(partial: "_permissions")
expect(rendered).to have_tag("form[class=edit_contact]") do
with_tag "input[type=hidden][id=contact_user_id][value='#{@contact.user_id}']"
end
end
# it "should pick default assignee (Myself)" do
# assign(:users, [current_user])
# assign(:contact, FactoryGirl.create(:contact, assignee: nil))
#
# render
# expect(rendered).to have_tag("select[id=contact_assigned_to]") do |options|
# expect(options.to_s).not_to include(%(selected="selected"))
# end
# end
#
it "should show correct assignee" do
@user = FactoryGirl.create(:user)
assign(:users, [current_user, @user])
assign(:contact, FactoryGirl.create(:contact, assignee: @user))
render partial: "contacts/edit", locals: {edit: true}
expect(rendered).to have_tag("select[id=contact_assigned_to]") do |_options|
with_tag "option[selected=selected]"
with_tag "option[value='#{@user.id}']"
end
end
it_should_behave_like "background" do
let(:model) { :contact }
end
end
| mit |
drupalhunter-team/TrackMonitor | ExternalComponents/Ultimate Toolbox/source/OXShortcutBar.cpp | 235122 | // ====================================================================================
// Class Implementation :
// COXSHBDropSource & COXSHBDropTarget & COXSHBEdit & COXSHBListCtrl & COXShortcutBar
// ====================================================================================
// Source file : OXShortcutBar.cpp
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <windowsx.h>
// v93 update 03 - 64-bit
#include "UTB64Bit.h"
#include "OXShortcutBar.h"
#include "OXSkins.h"
#include "UTBStrOp.h"
#pragma warning(disable : 4100 4786 4345)
#include <functional>
#include <set>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
struct LVITEM_less : public std::binary_function<LVITEM*, LVITEM*, bool>
{
bool operator()(const LVITEM* pItem1, const LVITEM* pItem2) const
{
CString strItem1(pItem1->pszText);
CString strItem2(pItem2->pszText);
return (strItem1 < strItem2);
}
};
// format for drag'n'drop item
CLIPFORMAT COXShortcutBar::m_nChildWndItemFormat=
(CLIPFORMAT)::RegisterClipboardFormat(_T("Shortcut bar child window item"));
/////////////////////////////////////////////////////////////////////////////
// COXSHBEdit
COXSHBEdit::COXSHBEdit()
{
m_pSHBED=NULL;
// by default use standard window background color
COLORREF clrBackground=::GetSysColor(COLOR_WINDOW);
// create brush used to fill background
VERIFY(m_brush.CreateSolidBrush(clrBackground));
m_bIsEditing=FALSE;
}
COXSHBEdit::~COXSHBEdit()
{
delete m_pSHBED;
}
BEGIN_MESSAGE_MAP(COXSHBEdit, CEdit)
//{{AFX_MSG_MAP(COXSHBEdit)
ON_WM_KILLFOCUS()
ON_WM_SETFOCUS()
ON_CONTROL_REFLECT(EN_UPDATE, OnUpdate)
ON_WM_CTLCOLOR_REFLECT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COXSHBEdit message handlers
LRESULT COXSHBEdit::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
BOOL bFinishEdit=FALSE;
// we finish editing if user click any mouse button or press Enter or ESC key
switch(message)
{
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_MOUSEMOVE:
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
{
// check if mouse cursor point is over the control's window
CRect rectClient;
GetClientRect(rectClient);
POINTS points=MAKEPOINTS(lParam);
CPoint point(points.x,points.y);
if(!rectClient.PtInRect(point))
{
::SetCursor(LoadCursor(NULL, IDC_ARROW));
// if the mouse cursor is over some other window then we should forward the
// message to this window and if the mouse message is other than WM_MOUSEMOVE
// then we should finish the editing
bFinishEdit=(message==WM_MOUSEMOVE) ? FALSE : TRUE;
// find target window
ClientToScreen(&point);
CWnd* pWnd=WindowFromPoint(point);
ASSERT_VALID(pWnd);
ASSERT(::IsWindow(pWnd->GetSafeHwnd()));
ASSERT(pWnd!=this);
// clarify type of message that should be sent: WM_NC* and WM_* messages
int nHitTest=(int)pWnd->SendMessage(
WM_NCHITTEST,0,MAKELONG(point.x,point.y));
if(nHitTest==HTCLIENT)
{
pWnd->ScreenToClient(&point);
lParam=MAKELONG(point.x,point.y);
}
else
{
// convert the messages in their WM_NC* counterparts
switch(message)
{
case WM_LBUTTONDOWN:
{
message=WM_NCLBUTTONDOWN;
break;
}
case WM_RBUTTONDOWN:
{
message=WM_NCRBUTTONDOWN;
break;
}
case WM_MBUTTONDOWN:
{
message=WM_NCMBUTTONDOWN;
break;
}
case WM_LBUTTONDBLCLK:
{
message=WM_NCLBUTTONDBLCLK;
break;
}
case WM_RBUTTONDBLCLK:
{
message=WM_NCRBUTTONDBLCLK;
break;
}
case WM_MBUTTONDBLCLK:
{
message=WM_NCMBUTTONDBLCLK;
break;
}
case WM_MOUSEMOVE:
{
message=WM_NCMOUSEMOVE;
break;
}
}
lParam=MAKELONG(point.x,point.y);
}
wParam=nHitTest;
// finish editing if needed
if(bFinishEdit)
{
FinishEdit(TRUE);
}
// forward message to underlaying window
pWnd->SendMessage(message,wParam,lParam);
// change cursor if needed
pWnd->SendMessage(WM_SETCURSOR,(WPARAM)pWnd->GetSafeHwnd(),
(LPARAM)MAKELONG(nHitTest,message));
/* // if we haven't finished editing and we've lost capture then
// recapture mouse messages
if(m_bIsEditing && ::IsWindow(GetSafeHwnd()) &&
::GetCapture()!=GetSafeHwnd())
{
SetCapture();
}*/
}
else
{
::SetCursor(LoadCursor(NULL, IDC_IBEAM));
}
break;
}
case WM_KEYDOWN:
{
// successfully finish editing if Enter key was pressed
if(wParam == VK_RETURN)
{
bFinishEdit=TRUE;
FinishEdit(TRUE);
}
// cancel editing if ESC key was pressed
else if(wParam == VK_ESCAPE)
{
bFinishEdit=TRUE;
FinishEdit(FALSE);
}
break;
}
}
// if we've finished editing then there is no sense to handle message
if(bFinishEdit)
{
return TRUE;
}
LRESULT lResult=CEdit::WindowProc(message,wParam,lParam);
// restore capture if we lost it as a result of
// processing the current message
if(m_bIsEditing && ::IsWindow(GetSafeHwnd()) && ::GetCapture()!=GetSafeHwnd())
{
SetCapture();
}
return lResult;
}
void COXSHBEdit::OnKillFocus(CWnd* pNewWnd)
{
CEdit::OnKillFocus(pNewWnd);
// TODO: Add your message handler code here
// finish editing if we haven't done it previously
if(::GetCapture()==GetSafeHwnd())
{
FinishEdit(TRUE);
}
}
void COXSHBEdit::OnSetFocus(CWnd* pOldWnd)
{
CEdit::OnSetFocus(pOldWnd);
// TODO: Add your message handler code here
// capture mouse messages
SetCapture();
}
void COXSHBEdit::OnUpdate()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CEdit::OnInitDialog()
// function to send the EM_SETEVENTMASK message to the control
// with the ENM_UPDATE flag ORed into the lParam mask.
// TODO: Add your control notification handler code here
// here is the place where we enlarge edit control window if needed
//
if(m_pSHBED && (m_pSHBED->nMask&SHBEIF_ENLARGE)!=0 &&
(m_pSHBED->nMask&SHBEIF_RECTMAX)!=0 && m_pSHBED->bEnlargeAsTyping)
{
// get window rect
CRect rectWindow;
GetWindowRect(rectWindow);
// get typed text
CString sText;
GetWindowText(sText);
// get edit style to take into account text allignment while recalculating
// control's window coordinates
DWORD dwStyle=GetStyle();
// define min rect that edit control window can be (if min rect is not specified
// explicitly then we use as min the rect of window that was set in StartEdit
// function)
CRect rectMin;
if((m_pSHBED->nMask&SHBEIF_RECTMIN)!=0)
{
rectMin=m_pSHBED->rectMin;
}
else
{
rectMin=m_pSHBED->rectDisplay;
}
// min rect mustn't be empty
ASSERT(!rectMin.IsRectEmpty());
if(!sText.IsEmpty())
{
// window rect mustn't be more than max rect
ASSERT(rectWindow.Width()<=m_pSHBED->rectMax.Width() &&
rectWindow.Height()<=m_pSHBED->rectMax.Height() &&
rectWindow.Width()>=rectMin.Width() &&
rectWindow.Height()>=rectMin.Height());
// get the rect used to display text
CRect rectDisplay;
GetRect(rectDisplay);
ClientToScreen(&rectDisplay);
// get margins between display and window rects to keep them in
// enlarged/shrinked window
CRect rectMargins(rectDisplay.left-rectWindow.left,
rectWindow.right-rectDisplay.right,rectDisplay.top-rectWindow.top,
rectWindow.bottom-rectDisplay.bottom);
// set the font used to draw text
CClientDC dc(this);
CFont* pOldFont=NULL;
if((HFONT)m_font)
{
pOldFont=dc.SelectObject(&m_font);
}
// calculate the size of updated window text constrained by the size
// of max rect
CRect rectMax=m_pSHBED->rectMax;
rectMax-=rectMax.TopLeft();
CRect rectText=rectMax;
rectText.right-=(rectMargins.left+rectMargins.right);
rectText.bottom-=(rectMargins.top+rectMargins.bottom);
// calculate
dc.DrawText(sText,rectText,DT_CALCRECT|DT_VCENTER|DT_CENTER|
((dwStyle&ES_MULTILINE)!=0 ? DT_WORDBREAK|DT_EDITCONTROL : 0));
// take into account original margins
rectText.right+=(rectMargins.left+rectMargins.right);
rectText.bottom+=(rectMargins.top+rectMargins.bottom);
// don't forget about max rect
VERIFY(rectText.IntersectRect(rectMax,rectText));
// make sure text rect is no less than min rect
//
if(rectText.Width()<rectMin.Width())
{
rectText.right=rectText.left+rectMin.Width();
}
if(rectText.Height()<rectMin.Height())
{
rectText.bottom=rectText.top+rectMin.Height();
}
// calculate enlarged/shrinked edit control window rect taking into
// account text alignment
//
CRect rectEnlarged=m_pSHBED->rectMax;
// width
int nXMargin=rectMax.Width()-rectText.Width();
ASSERT(nXMargin>=0);
if(nXMargin>0)
{
if((dwStyle&ES_RIGHT)!=0)
{
rectEnlarged.left+=nXMargin;
}
else if((dwStyle&ES_CENTER)!=0)
{
rectEnlarged.right-=nXMargin/2;
rectEnlarged.left=rectEnlarged.right-rectText.Width();
}
else
{
//ES_LEFT
rectEnlarged.right-=nXMargin;
}
}
// height
int nYMargin=rectMax.Height()-rectText.Height();
ASSERT(nYMargin>=0);
if(nYMargin>=0)
{
rectEnlarged.bottom-=nYMargin;
}
// resize it!
MoveWindow(rectEnlarged);
if(pOldFont)
{
dc.SelectObject(pOldFont);
}
}
else
{
// resize it!
MoveWindow(rectMin);
}
// get client rect
CRect rectClient;
GetClientRect(rectClient);
// set the rect used to display text
SetRectNP(rectClient);
}
}
HBRUSH COXSHBEdit::CtlColor(CDC* pDC, UINT nCtlColor)
{
// TODO: Change any attributes of the DC here
UNREFERENCED_PARAMETER(nCtlColor);
ASSERT(nCtlColor==CTLCOLOR_EDIT);
// fill the background
COLORREF clrBackground=::GetSysColor(COLOR_WINDOW);
if((m_pSHBED->nMask&SHBEIF_CLRBACK))
{
clrBackground=m_pSHBED->clrBack;
}
pDC->SetBkColor(clrBackground);
if((m_pSHBED->nMask&SHBEIF_CLRTEXT))
{
pDC->SetTextColor(m_pSHBED->clrText);
}
// use our brush to fill the part of the control that is not covered by text
return (HBRUSH)m_brush;
// TODO: Return a non-NULL brush if the parent's handler should not be called
}
BOOL COXSHBEdit::StartEdit(LPSHBE_DISPLAY pSHBED)
{
// window have to be created at this moment
ASSERT(::IsWindow(m_hWnd));
// verify SHBE_DISPLAY structure
if(pSHBED && !VerifyDisplayInfo(pSHBED))
{
TRACE(_T("COXSHBEdit::StartEdit: LPSHBE_DISPLAY is invalid"));
return FALSE;
}
// save style, text, ctrlID, parent window and size
DWORD dwStyle=GetStyle();
CString sText;
GetWindowText(sText);
CRect rectWindow;
GetWindowRect(rectWindow);
UINT nCtrlID=GetDlgCtrlID();
CWnd* pWnd=GetParent();
ASSERT(pWnd);
// if pSHBED is not NULL then get new attributes
if(pSHBED)
{
// save SHBE_DISPLAY structure
if(m_pSHBED==NULL)
{
m_pSHBED=new SHBE_DISPLAY;
}
m_pSHBED->Copy(pSHBED);
// get new window text
if((m_pSHBED->nMask&SHBEIF_TEXT)!=0)
{
sText=m_pSHBED->lpText;
}
// get new window rect
if((m_pSHBED->nMask&SHBEIF_RECTDISPLAY)!=0)
{
rectWindow=m_pSHBED->rectDisplay;
}
// get new edit control style
if((m_pSHBED->nMask&SHBEIF_STYLE)!=0)
{
dwStyle=m_pSHBED->dwStyle;
}
// get font to be used to draw text
if((m_pSHBED->nMask&SHBEIF_FONT)!=0)
{
if((HFONT)m_font)
{
m_font.DeleteObject();
}
if(m_pSHBED->pFont)
{
LOGFONT lf;
if(m_pSHBED->pFont->GetLogFont(&lf)!=0)
{
VERIFY(m_font.CreateFontIndirect(&lf));
}
}
}
// adjust window to be compliant with min rect
if((m_pSHBED->nMask&SHBEIF_RECTMIN)!=0)
{
rectWindow.left=__min(m_pSHBED->rectMin.left,rectWindow.left);
rectWindow.top=__min(m_pSHBED->rectMin.top,rectWindow.top);
rectWindow.right=__max(m_pSHBED->rectMin.right,rectWindow.right);
rectWindow.bottom=__max(m_pSHBED->rectMin.bottom,rectWindow.bottom);
}
}
else
{
delete m_pSHBED;
}
// destroy the edit control
if(DestroyWindow()==0)
{
TRACE(_T("COXSHBEdit::StartEdit: failed to destroy window"));
return FALSE;
}
// recreate it using saved and updated properties
if(!Create(dwStyle,rectWindow,pWnd,nCtrlID))
{
TRACE(_T("COXSHBEdit::StartEdit: failed to create window"));
return FALSE;
}
// set new font to window
if((HFONT)m_font)
{
SetFont(&m_font,TRUE);
}
// change the text of window
SetWindowText(sText);
// set background brush
if((m_pSHBED->nMask&SHBEIF_CLRBACK))
{
COLORREF clrBackground=m_pSHBED->clrBack;
if((HBRUSH)m_brush!=NULL)
{
m_brush.DeleteObject();
}
VERIFY(m_brush.CreateSolidBrush(clrBackground));
}
// set selection
if(m_pSHBED && (m_pSHBED->nMask&SHBEIF_SELRANGE)!=0)
{
SetSel(m_pSHBED->ptSelRange.x,m_pSHBED->ptSelRange.y,TRUE);
}
// get client rect
CRect rectClient;
GetClientRect(rectClient);
// set the rect used to display text
SetRect(rectClient);
// show edit control and set the focus to it
m_bIsEditing=TRUE;
ShowWindow(SW_SHOW);
SetFocus();
return TRUE;
}
void COXSHBEdit::FinishEdit(BOOL bOK)
{
// window should be created at this moment
ASSERT(::IsWindow(GetSafeHwnd()));
m_bIsEditing=FALSE;
// release capture if we've still got it
if(GetCapture()==this)
{
ReleaseCapture();
}
// Send Notification to parent
NMSHBEDIT nmshbe;
nmshbe.hdr.code=SHBEN_FINISHEDIT;
nmshbe.bOK=bOK;
SendSHBENotification(&nmshbe);
// hide the window
ShowWindow(SW_HIDE);
}
// helper function to send edit control notifications
LRESULT COXSHBEdit::SendSHBENotification(LPNMSHBEDIT pNMSHBE)
{
// notify parent
CWnd* pParentWnd=GetParent();
VERIFY(pParentWnd);
// fill notification structure
pNMSHBE->hdr.hwndFrom=GetSafeHwnd();
pNMSHBE->hdr.idFrom=GetDlgCtrlID();
// send the notification message
return (pParentWnd->SendMessage(
WM_NOTIFY,(WPARAM)GetDlgCtrlID(),(LPARAM)pNMSHBE));
}
BOOL COXSHBEdit::VerifyDisplayInfo(LPSHBE_DISPLAY pSHBED)
{
ASSERT(pSHBED);
// verify mask
if((pSHBED->nMask&~(SHBEIF_TEXT|SHBEIF_RECTDISPLAY|SHBEIF_RECTMAX|
SHBEIF_STYLE|SHBEIF_ENLARGE|SHBEIF_SELRANGE|SHBEIF_FONT|SHBEIF_RECTMIN|
SHBEIF_CLRTEXT|SHBEIF_CLRBACK))!=0)
{
TRACE(_T("COXSHBEdit::VerifyDisplayInfo: unspecified mask used"));
return FALSE;
}
// verify if max rect have to be specified
if((pSHBED->nMask&SHBEIF_ENLARGE)!=0 && (pSHBED->nMask&SHBEIF_RECTMAX)==0)
{
TRACE(_T("COXSHBEdit::VerifyDisplayInfo: enlargement as typing is specified while max rect is not"));
return FALSE;
}
// verify selection if any set
if((pSHBED->nMask&SHBEIF_SELRANGE)!=0 && !(pSHBED->ptSelRange.x==0 &&
pSHBED->ptSelRange.y==-1) && !(pSHBED->ptSelRange.x==-1))
{
CString sText;
if((pSHBED->nMask&SHBEIF_TEXT)!=0)
{
sText=pSHBED->lpText;
}
else
{
GetWindowText(sText);
}
int nLength=sText.GetLength();
if(pSHBED->ptSelRange.x>=nLength || pSHBED->ptSelRange.y>=nLength)
{
TRACE(_T("COXSHBEdit::VerifyDisplayInfo: invalid selection range"));
return FALSE;
}
}
// verify if rectDisplay is not empty
CRect rectDisplay;
GetClientRect(rectDisplay);
if(((pSHBED->nMask&SHBEIF_RECTDISPLAY)!=0 && pSHBED->rectDisplay.IsRectEmpty()) ||
((pSHBED->nMask&SHBEIF_RECTDISPLAY)==0 && rectDisplay.IsRectEmpty()))
{
TRACE(_T("COXSHBEdit::VerifyDisplayInfo: empty display rect specified"));
return FALSE;
}
else
{
rectDisplay=pSHBED->rectDisplay;
}
// verify if display rect is within max rect
CRect rectIntersect;
if((pSHBED->nMask&SHBEIF_RECTMAX)!=0)
{
rectIntersect.IntersectRect(pSHBED->rectMax,rectDisplay);
if(rectIntersect!=rectDisplay)
{
TRACE(_T("COXSHBEdit::VerifyDisplayInfo: display rect is bigger than specified max rect"));
return FALSE;
}
}
// verify if min rect is within max rect
if((pSHBED->nMask&SHBEIF_RECTMIN)!=0 && (pSHBED->nMask&SHBEIF_RECTMAX)!=0)
{
rectIntersect.IntersectRect(pSHBED->rectMax,pSHBED->rectMin);
if(rectIntersect!=pSHBED->rectMin)
{
TRACE(_T("COXSHBEdit::VerifyDisplayInfo: max rect doesn't include min rect"));
return FALSE;
}
}
// verify if min rect is not empty
if((pSHBED->nMask&SHBEIF_RECTMIN)!=0 && (pSHBED->rectMin.IsRectEmpty()))
{
TRACE(_T("COXSHBEdit::VerifyDisplayInfo: min rect mustn't be empty"));
return FALSE;
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// COXSHBListCtrl
DWORD COXSHBListCtrl::m_dwComCtlVersion=0;
const int IDT_OXSHBLIST_CHECKMOUSE=275;
const int ID_OXSHBLIST_CHECKMOUSE_DELAY=200;
IMPLEMENT_DYNCREATE(COXSHBListCtrl, CListCtrl)
COXSHBListCtrl::COXSHBListCtrl()
{
m_pShortcutBar=NULL;
m_hGroup=NULL;
m_nSelectedItem=-1;
m_nHotItem=-1;
m_nLastHotItem=-1;
m_nActiveItem=-1;
m_nDropHilightItem=-1;
m_nDragItem=-1;
m_nEditItem=-1;
m_rectTopScrollButton.SetRectEmpty();
m_rectBottomScrollButton.SetRectEmpty();
m_ptOrigin=CPoint(0,0);
m_bMouseIsOver=FALSE;
m_bScrollingUp=FALSE;
m_bScrollingDown=FALSE;
m_bAutoScrolling=FALSE;
m_bCreatingDragImage=FALSE;
m_pDragImage=NULL;
m_nSuspectDragItem=-1;
m_bDragDropOwner=FALSE;
m_bDragDropOperation=FALSE;
m_nScrollTimerID=0;
m_nCheckMouseTimerID=0;
m_nInsertItemBefore=-1;
if(m_dwComCtlVersion==0)
{
DWORD dwMajor, dwMinor;
if(SUCCEEDED(GetComCtlVersion(&dwMajor, &dwMinor)))
{
m_dwComCtlVersion=MAKELONG((WORD)dwMinor, (WORD)dwMajor);
}
else
{
// assume that neither IE 3.0 nor IE 4.0 installed
m_dwComCtlVersion=0x00040000;
}
}
}
COXSHBListCtrl::~COXSHBListCtrl()
{
// clean up maps of all rectangles
m_mapItemToBoundRect.RemoveAll();
m_mapItemToImageRect.RemoveAll();
m_mapItemToTextRect.RemoveAll();
delete m_pDragImage;
if(::IsWindow(GetSafeHwnd()))
DestroyWindow();
}
BEGIN_MESSAGE_MAP(COXSHBListCtrl, CListCtrl)
//{{AFX_MSG_MAP(COXSHBListCtrl)
ON_WM_ERASEBKGND()
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_RBUTTONDOWN()
ON_WM_RBUTTONUP()
ON_WM_MBUTTONDOWN()
ON_WM_MBUTTONUP()
ON_WM_TIMER()
ON_WM_DESTROY()
ON_WM_LBUTTONDBLCLK()
//}}AFX_MSG_MAP
ON_MESSAGE(SHBLCM_HANDLEDRAG, OnHandleDrag)
ON_MESSAGE(SHBLCM_CHECKCAPTURE, OnCheckCapture)
ON_NOTIFY_EX(TTN_NEEDTEXTA, 0, OnItemToolTip)
ON_NOTIFY_EX(TTN_NEEDTEXTW, 0, OnItemToolTip)
ON_MESSAGE(SHBDTM_DRAGENTER, OnDragEnter)
ON_MESSAGE(SHBDTM_DRAGLEAVE, OnDragLeave)
ON_MESSAGE(SHBDTM_DRAGOVER, OnDragOver)
ON_MESSAGE(SHBDTM_DROP, OnDrop)
ON_MESSAGE(SHBM_SETSHBGROUP, OnSetSHBGroup)
ON_MESSAGE(SHBM_SHBINFOCHANGED, OnSHBInfoChanged)
ON_MESSAGE(SHBM_GROUPINFOCHANGED, OnGroupInfoChanged)
ON_MESSAGE(SHBM_POPULATECONTEXTMENU, OnPopulateContextMenu)
ON_NOTIFY(SHBEN_FINISHEDIT, SHB_IDCEDIT, OnChangeItemText)
ON_MESSAGE(LVM_CREATEDRAGIMAGE, OnCreateDragImage)
ON_MESSAGE(LVM_DELETEALLITEMS, OnDeleteAllItems)
ON_MESSAGE(LVM_DELETEITEM, OnDeleteItem)
ON_MESSAGE(LVM_EDITLABEL, OnEditLabel)
ON_MESSAGE(LVM_ENSUREVISIBLE, OnEnsureVisible)
ON_MESSAGE(LVM_FINDITEM, OnFindItem)
ON_MESSAGE(LVM_GETBKCOLOR, OnGetBkColor)
ON_MESSAGE(LVM_GETCOUNTPERPAGE, OnGetCountPerPage)
ON_MESSAGE(LVM_GETEDITCONTROL, OnGetEditControl)
ON_MESSAGE(LVM_GETHOTITEM, OnGetHotItem)
ON_MESSAGE(LVM_GETITEMPOSITION, OnGetItemPosition)
ON_MESSAGE(LVM_GETITEMRECT, OnGetItemRect)
ON_MESSAGE(LVM_GETORIGIN, OnGetOrigin)
ON_MESSAGE(LVM_GETTEXTBKCOLOR, OnGetTextBkColor)
ON_MESSAGE(LVM_GETTEXTCOLOR, OnGetTextColor)
ON_MESSAGE(LVM_GETTOPINDEX, OnGetTopIndex)
ON_MESSAGE(LVM_GETVIEWRECT, OnGetViewRect)
ON_MESSAGE(LVM_HITTEST, OnHitTest)
ON_MESSAGE(LVM_INSERTITEM, OnInsertItem)
ON_MESSAGE(LVM_REDRAWITEMS, OnRedrawItems)
ON_MESSAGE(LVM_SCROLL, OnScroll)
ON_MESSAGE(LVM_SETBKCOLOR, OnSetBkColor)
ON_MESSAGE(LVM_SETHOTITEM, OnSetHotItem)
ON_MESSAGE(LVM_SETITEM, OnSetItem)
ON_MESSAGE(LVM_SETITEMTEXT, OnSetItemText)
ON_MESSAGE(LVM_SETTEXTBKCOLOR, OnSetTextBkColor)
ON_MESSAGE(LVM_SETTEXTCOLOR, OnSetTextColor)
ON_MESSAGE(LVM_SORTITEMS, OnSortItems)
ON_MESSAGE(LVM_UPDATE, OnUpdate)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COXSHBListCtrl message handlers
void COXSHBListCtrl::PreSubclassWindow()
{
// TODO: Add your specialized code here and/or call the base class
// Currently we support only LVS_ICON and LVS_SMALLICON views
DWORD dwStyle=GetStyle();
if((dwStyle&LVS_LIST)!=0)
{
ModifyStyle(LVS_LIST,0);
ModifyStyle(0,LVS_ICON);
}
if((dwStyle&LVS_REPORT)!=0)
{
ModifyStyle(LVS_REPORT,0);
ModifyStyle(0,LVS_ICON);
}
_AFX_THREAD_STATE* pThreadState=AfxGetThreadState();
// hook not already in progress
if(pThreadState->m_pWndInit==NULL)
{
if(!InitListControl())
{
TRACE(_T("COXSHBListCtrl::PreSubclassWindow: failed to initialize list control\n"));
}
}
CListCtrl::PreSubclassWindow();
}
BOOL COXSHBListCtrl::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID)
{
BOOL bResult=CListCtrl::Create(dwStyle, rect, pParentWnd, nID);
if(bResult)
{
// Initialize edit control
if(!InitListControl())
{
TRACE(_T("COXSHBListCtrl::Create: failed to initialize list control"));
return FALSE;
}
}
return bResult;
}
OXINTRET COXSHBListCtrl::OnToolHitTest(CPoint point, TOOLINFO* pTI) const
{
ASSERT_VALID(this);
ASSERT(::IsWindow(m_hWnd));
if((GetBarStyle()&SHBS_INFOTIP)==0)
return -1;
// now hit test against COXSHBListCtrl items
UINT nHitFlags;
int nHit=HitTest(point,&nHitFlags,TRUE);
if(nHitFlags==SHBLC_ONITEM)
nHit=-1;
if(nHit!=-1 && pTI!= NULL)
{
#if _MFC_VER<=0x0421
if(pTI->cbSize>=sizeof(TOOLINFO))
return nHit;
#endif
// set window handle
pTI->hwnd=GetSafeHwnd();
// get item bounding rect
CRect rect;
VERIFY(GetItemRect(nHit,rect,LVIR_BOUNDS));
pTI->rect=rect;
// found matching item, return its index + 1, we cannot use zero index
nHit++;
pTI->uId=nHit;
// set text to LPSTR_TEXTCALLBACK in order to get TTN_NEEDTEXT message when
// it's time to display tool tip
pTI->lpszText=LPSTR_TEXTCALLBACK;
}
return nHit;
}
BOOL COXSHBListCtrl::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
UNREFERENCED_PARAMETER(pDC);
return TRUE;
}
void COXSHBListCtrl::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// We provide all drawing functionality. We optimized it as good as it possible.
// get client rect
CRect rect;
GetClientRect(rect);
// Save DC
int nSavedDC=dc.SaveDC();
ASSERT(nSavedDC);
// draw scroll buttons if we have to
if((GetBarStyle()&SHBS_NOSCROLL)==0)
{
DrawScrollButtons(&dc);
dc.ExcludeClipRect(m_rectTopScrollButton);
dc.ExcludeClipRect(m_rectBottomScrollButton);
}
// fill background with color assoicated with control
FillBackground(&dc);
// check integrity
int nCount=GetItemCount();
VERIFY(m_mapItemToBoundRect.GetCount()==nCount);
VERIFY(m_mapItemToTextRect.GetCount()==nCount);
// draw items
for(int nIndex=0; nIndex<nCount; nIndex++)
{
VERIFY(m_mapItemToBoundRect.Lookup(nIndex,rect));
// take into account view origin
rect-=m_ptOrigin;
// draw only if visible
if(dc.RectVisible(&rect))
{
// to reduce flickering use compatible device context to draw in
//
CRect rectItem=rect;
rectItem-=rect.TopLeft();
CDC dcCompatible;
if(!dcCompatible.CreateCompatibleDC(&dc))
{
TRACE(_T("COXSHBListCtrl::OnPaint:Failed to create compatible DC"));
return;
}
CBitmap bitmap;
if(!bitmap.CreateCompatibleBitmap(&dc, rectItem.Width(),
rectItem.Height()))
{
TRACE(_T("COXSHBListCtrl::OnPaint:Failed to create compatible bitmap"));
return;
}
CBitmap* pOldBitmap=dcCompatible.SelectObject(&bitmap);
// fill standard DRAWITEMSTRUCT struct
DRAWITEMSTRUCT dis;
dis.CtlType=ODT_LISTVIEW;
dis.CtlID=GetDlgCtrlID();
dis.itemID=(UINT)nIndex;
dis.itemAction=ODA_DRAWENTIRE;
dis.itemState=ODS_DEFAULT;
dis.hwndItem=GetSafeHwnd();
dis.hDC=dcCompatible.GetSafeHdc();
dis.rcItem=rectItem;
dis.itemData=(DWORD)0;
if (m_pShortcutBar != NULL)
{
if (HasBkColor())
m_pShortcutBar->GetShortcutBarSkin()->FillBackground(&dcCompatible, rect, this,
TRUE, GetBkColor());
else
m_pShortcutBar->GetShortcutBarSkin()->FillBackground(&dcCompatible, rect, this);
}
else
{
COLORREF clrBackground=GetBkColor();
CBrush brush(clrBackground);
dc.FillRect(rectItem,&brush);
}
// this function is responsible for drawing of any item
DrawItem(&dis);
// copy drawn image
dc.BitBlt(rect.left, rect.top, rect.Width(),
rect.Height(), &dcCompatible, 0, 0, SRCCOPY);
if(pOldBitmap)
dcCompatible.SelectObject(pOldBitmap);
}
}
DrawPlaceHolder(&dc);
// Restore dc
dc.RestoreDC(nSavedDC);
// Do not call CWnd::OnPaint() for painting messages
}
void COXSHBListCtrl::OnSize(UINT nType, int cx, int cy)
{
CListCtrl::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
// recalculate items positions
CalculateBoundRects();
}
void COXSHBListCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CListCtrl::OnMouseMove(nFlags, point);
// as soon as mouse is over the control we capture all mouse messages
// (don't do anything if we are editing group header text)
if(GetEditItem()==-1 && ((m_pShortcutBar==NULL) ? TRUE :
(m_pShortcutBar->GetEditGroup()==NULL)))
{
CheckCapture();
}
}
void COXSHBListCtrl::OnLButtonDblClk(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
// we don't handle double clicks
COXSHBListCtrl::OnLButtonDown(nFlags, point);
}
void COXSHBListCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
UNREFERENCED_PARAMETER(nFlags);
// we should probably activate underneath window
CWnd* pWnd=GetParent();
ASSERT(pWnd);
pWnd->ShowWindow(SW_SHOW);
// find if mouse left button was pressed over any item
UINT nHitFlags;
int nItem=HitTest(point,&nHitFlags);
if(nItem!=-1 && nHitFlags!=SHBLC_ONITEM)
{
// mark this item as selected
int nOldSelectedItem=SelectItem(nItem);
// notify parent of starting drag'n'drop if needed
if((GetBarStyle()&SHBS_DISABLEDRAGITEM)==0)
{
// in result of selecting we could have done any reposition
// so we'd better double check if selected item is still there
int nSuspectItem=HitTest(point,&nHitFlags);
if(nItem!=-1 && nHitFlags!=SHBLC_ONITEM && nSuspectItem==nItem)
{
// there shouldn't be any item currently being dragged
ASSERT(GetDragItem()==-1);
m_ptClickedLButton=point;
// define the point of hot spot on future drag image
if((GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0)
{
CRect rectImageText;
VERIFY(GetItemRect(nItem,&rectImageText,LVIR_BOUNDS));
ASSERT(rectImageText.PtInRect(m_ptClickedLButton));
m_ptDragImage=m_ptClickedLButton-rectImageText.TopLeft();
}
// mark the item as possible drag item (we initialize drag and drop
// operation when user move cursor while mouse left button is down)
m_nSuspectDragItem=nItem;
}
}
// update selected and old selected items
Update(nItem);
if(nOldSelectedItem!=-1 && nOldSelectedItem!=nItem)
Update(nOldSelectedItem);
}
// check if we have to start scrolling
if(nHitFlags==SHBLC_ONTOPSCROLLBUTTON)
{
StartScrolling(TRUE);
}
else if(nHitFlags==SHBLC_ONBOTTOMSCROLLBUTTON)
{
StartScrolling(FALSE);
}
else if(m_bAutoScrolling)
{
StopScrolling();
}
// check if we lost mouse capture
PostCheckCapture();
}
void COXSHBListCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CWnd::OnLButtonUp(nFlags, point);
// any drag'n'drop operation must be finished at this moment
ASSERT(GetDragItem()==-1);
// reset suspect drag item index
m_nSuspectDragItem=-1;
// find if mouse left button was unpressed over any item
UINT nHitFlags;
int nItem=HitTest(point,&nHitFlags);
if(nItem!=-1 && nHitFlags!=SHBLC_ONITEM)
{
// if it is the selected item then activate it
if(GetSelectedItem()==nItem)
{
int nOldItem=ActivateItem(nItem);
if(nOldItem!=-1 && nOldItem!=nItem)
// redraw old active item (only one item can be active at the moment)
Update(nOldItem);
}
// redraw new active item
Update(nItem);
}
// double check
ASSERT(!(m_bScrollingUp&m_bScrollingDown));
// stop any scrolling
if(m_bScrollingUp || m_bScrollingDown)
StopScrolling();
// check if we lost mouse capture
PostCheckCapture();
}
void COXSHBListCtrl::OnMButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
UNREFERENCED_PARAMETER(nFlags);
UNREFERENCED_PARAMETER(point);
// check if we lost mouse capture
PostCheckCapture();
}
void COXSHBListCtrl::OnMButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CListCtrl::OnMButtonUp(nFlags, point);
// check if we lost mouse capture
PostCheckCapture();
}
void COXSHBListCtrl::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
UNREFERENCED_PARAMETER(nFlags);
UNREFERENCED_PARAMETER(point);
// check if we lost mouse capture
PostCheckCapture();
}
void COXSHBListCtrl::OnRButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CListCtrl::OnRButtonUp(nFlags, point);
if(m_dwComCtlVersion<_IE40_COMCTL_VERSION)
{
ClientToScreen(&point);
PostMessage(WM_CONTEXTMENU,(WPARAM)GetSafeHwnd(),
(LPARAM)MAKELONG(point.x,point.y));
}
// check if we lost mouse capture
PostCheckCapture();
}
/////////////////////////////////////////////////////////////////////////////
// OnHandleDrag sets up the drag image, calls DoDragDrop and cleans up
// after the drag drop operation finishes.
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnHandleDrag(WPARAM wParam, LPARAM lParam)
{
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_HANDLEDRAGITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=(int)wParam;
nmshb.lParam=lParam;
// check if parent of the shortcut bar would like to handle drag'n'drop itself
if(SendSHBNotification(&nmshb))
return (LONG)0;
// get data source object that is represented by lParam. It's our responsibility
// to eventually delete this object
COleDataSource* pDataSource=(COleDataSource*)lParam;
ASSERT(pDataSource!=NULL);
// get item index which is represented by wParam
int nItem=(int)wParam;
// validate item index
ASSERT(GetDragItem()==nItem);
ASSERT(nItem>=0 && nItem<GetItemCount());
// unselect the item that will be dragged
VERIFY(SelectItem(-1)==nItem);
Update(nItem);
// get current cursor position
POINT point;
GetCursorPos(&point);
// get the drop source object
COleDropSource* pOleDropSource=GetDropSource();
ASSERT(pOleDropSource!=NULL);
// mark the control as the one which launched drag'n'drop operation
m_bDragDropOwner=TRUE;
// create drag image and start dragging
if((GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0)
{
// delete previously created drag image
if(m_pDragImage)
{
delete m_pDragImage;
m_pDragImage=NULL;
}
m_pDragImage=CreateDragImage(nItem);
ASSERT(m_pDragImage);
// changes the cursor to the drag image
VERIFY(m_pDragImage->BeginDrag(0,m_ptDragImage));
}
// start drag'n'drop operation
DROPEFFECT dropEffect=((COleDataSource*)pDataSource)->
DoDragDrop(DROPEFFECT_COPY|DROPEFFECT_MOVE,NULL,pOleDropSource);
if(DROPEFFECT_MOVE==dropEffect)
{
// if item was moved in to theCalendar same list control and inserted index
// is less or equal to the dragged one then increase the index by one to
// remove the item with right index
if(m_nInsertItemBefore!=-1 && m_nInsertItemBefore<=GetDragItem())
nItem++;
// delete item if it was moved
DeleteItem(nItem);
}
int nOldInsertItemBefore=m_nInsertItemBefore;
m_nInsertItemBefore=-1;
// unmark as the control which launched drag'n'drop operation
m_bDragDropOwner=FALSE;
// remove drag image
if((GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0)
{
ASSERT(m_pDragImage);
// end dragging
m_pDragImage->EndDrag();
}
// reset drag item
SetDragItem(-1);
//delete drag source (we are responsible to do that)
delete pDataSource;
// redraw the list control if any item was deleted and/or inserted
if(DROPEFFECT_MOVE==dropEffect ||
(DROPEFFECT_COPY==dropEffect && nOldInsertItemBefore!=-1))
RedrawWindow();
GetCursorPos(&point);
ScreenToClient(&point);
// send WM_LBUTTONUP message
SendMessage(WM_LBUTTONUP,((GetKeyState(VK_CONTROL)<0) ? MK_CONTROL : 0)|
((GetKeyState(VK_SHIFT)<0) ? MK_SHIFT : 0),(LPARAM)MAKELONG(point.x,point.y));
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
::ZeroMemory((void*)&nmshb,sizeof(nmshb));
nmshb.hdr.code=SHBN_ENDDRAGDROPITEM;
nmshb.hGroup=m_hGroup;
nmshb.lParam=dropEffect;
// notify parent
SendSHBNotification(&nmshb);
return (LONG)0;
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnCheckCapture(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
// the only purpose of this handler is to set mouse capture back in case we lost it
return ((LONG)CheckCapture());
}
BOOL COXSHBListCtrl::OnItemToolTip(UINT id, NMHDR* pNMHDR, LRESULT* pResult)
{
UNREFERENCED_PARAMETER(id);
ASSERT(pNMHDR->code==TTN_NEEDTEXTA || pNMHDR->code==TTN_NEEDTEXTW);
if(pNMHDR->idFrom>0)
{
// need to handle both ANSI and UNICODE versions of the message
TOOLTIPTEXTA* pTTTA=(TOOLTIPTEXTA*)pNMHDR;
TOOLTIPTEXTW* pTTTW=(TOOLTIPTEXTW*)pNMHDR;
// idFrom must be the item index
if (pNMHDR->code==TTN_NEEDTEXTA)
ASSERT((pTTTA->uFlags&TTF_IDISHWND)==0);
else
ASSERT((pTTTW->uFlags&TTF_IDISHWND)==0);
SHBINFOTIP shbit;
::ZeroMemory(&shbit,sizeof(shbit));
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_GETITEMINFOTIP;
nmshb.hGroup=m_hGroup;
nmshb.nItem=(int)pNMHDR->idFrom-1;
nmshb.lParam=(LPARAM)(&shbit);
*pResult=SendSHBNotification(&nmshb);
// copy the text
#ifndef _UNICODE
if(pNMHDR->code==TTN_NEEDTEXTA)
lstrcpyn(pTTTA->szText,shbit.szText,countof(pTTTA->szText));
else
_mbstowcsz(pTTTW->szText,shbit.szText,countof(pTTTW->szText));
#else
if (pNMHDR->code==TTN_NEEDTEXTA)
_wcstombsz(pTTTA->szText,shbit.szText,countof(pTTTA->szText));
else
lstrcpyn(pTTTW->szText,shbit.szText,countof(pTTTW->szText));
#endif
if(pNMHDR->code==TTN_NEEDTEXTA)
{
if(shbit.lpszText==NULL)
pTTTA->lpszText=pTTTA->szText;
else
pTTTA->lpszText=(LPSTR)shbit.lpszText;
pTTTA->hinst=shbit.hinst;
}
else
{
if(shbit.lpszText==NULL)
pTTTW->lpszText=pTTTW->szText;
else
pTTTW->lpszText=(LPWSTR)shbit.lpszText;
pTTTW->hinst=shbit.hinst;
}
return TRUE; // message was handled
}
else
{
*pResult=0;
return TRUE;
}
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnDragEnter(WPARAM wParam, LPARAM lParam)
{
// list control should be valid drop target
if((GetBarStyle()&SHBS_DISABLEDROPITEM)!=0)
return (LONG)FALSE;
// set flag that specifies that drag'n'drop operation is active
m_bDragDropOperation=TRUE;
// reset the hot item
int nOldHotItem=SetHotItem(-1);
if(nOldHotItem!=-1)
Update(nOldHotItem);
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DRAGENTER;
nmshb.hGroup=m_hGroup;
nmshb.lParam=lParam;
// check if parent of the shortcut bar would like to handle drag'n'drop itself
if(SendSHBNotification(&nmshb))
return (LONG)TRUE;
// lParam is the pointer to SHBDROPTARGETACTION structure
LPSHBDROPTARGETACTION pSHBDTAction=(LPSHBDROPTARGETACTION)lParam;
ASSERT(pSHBDTAction!=NULL);
ASSERT(pSHBDTAction->pWnd);
ASSERT(pSHBDTAction->pWnd->GetSafeHwnd()==GetSafeHwnd());
// if this control launched the drag'n'drop operation then
// display the drag image if needed
if((GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0 && m_bDragDropOwner)
{
CPoint point=pSHBDTAction->point;
ClientToScreen(&point);
ASSERT(m_pDragImage);
VERIFY(m_pDragImage->DragEnter(GetDesktopWindow(),point));
}
return (LONG)OnDragOver(wParam,lParam);
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnDragOver(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if((GetBarStyle()&SHBS_DISABLEDROPITEM)!=0)
return (LONG)FALSE;
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DRAGOVER;
nmshb.hGroup=m_hGroup;
nmshb.lParam=lParam;
// check if parent of the shortcut bar would like to handle drag'n'drop itself
if(SendSHBNotification(&nmshb))
return (LONG)TRUE;
// lParam is the pointer to SHBDROPTARGETACTION structure
LPSHBDROPTARGETACTION pSHBDTAction=(LPSHBDROPTARGETACTION)lParam;
ASSERT(pSHBDTAction!=NULL);
ASSERT(pSHBDTAction->pWnd);
ASSERT(pSHBDTAction->pWnd->GetSafeHwnd()==GetSafeHwnd());
BOOL bDrawDragImage=FALSE;
// if we launched the drag'n'drop operation then move drag image if needed
if((GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0 && m_bDragDropOwner)
{
ASSERT(m_pDragImage);
CPoint ptScreen=pSHBDTAction->point;
ClientToScreen(&ptScreen);
// move the drag image
VERIFY(m_pDragImage->DragMove(ptScreen));
bDrawDragImage=TRUE;
}
// analize the current cursor position
//
// it must be within client area of the control
CRect rectClient;
GetClientRect(rectClient);
ASSERT(rectClient.PtInRect(pSHBDTAction->point));
// deflate the client rectangle to match the valid area where we can
// display items
rectClient.DeflateRect(ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,
ID_EDGEBOTTOMMARGIN);
CPoint point=pSHBDTAction->point;
// take into account the control's origin
point+=m_ptOrigin;
// anylize view rectangle
CRect rectView;
GetViewRect(rectView);
int nInsertItemBefore=-1;
// Can we use this object?
if(!pSHBDTAction->pDataObject->
IsDataAvailable(COXShortcutBar::m_nChildWndItemFormat))
pSHBDTAction->result=(LRESULT)DROPEFFECT_NONE;
// if cursor is located higher then view rectangle or there is no items
// in the control
else if(point.y<=rectView.top || GetItemCount()==0)
{
// Check if the control key was pressed
if((pSHBDTAction->dwKeyState & MK_CONTROL)==MK_CONTROL)
pSHBDTAction->result=(LRESULT)DROPEFFECT_COPY;
else
pSHBDTAction->result=(LRESULT)DROPEFFECT_MOVE;
// if droped item must be inserted at the top
nInsertItemBefore=0;
}
// if cursor is located lower than last item
else if(point.y>rectView.bottom)
{
// Check if the control key was pressed
if((pSHBDTAction->dwKeyState & MK_CONTROL)==MK_CONTROL)
pSHBDTAction->result=(LRESULT)DROPEFFECT_COPY;
else
pSHBDTAction->result=(LRESULT)DROPEFFECT_MOVE;
// if droped item must be inserted at the bottom
nInsertItemBefore=GetItemCount();
}
// if cursor is out of deflated client rectangle
else if(!rectClient.PtInRect(pSHBDTAction->point))
pSHBDTAction->result=(LRESULT)DROPEFFECT_NONE;
// otherwise cursor is over list control view area
else
{
// discover the location
UINT nHitFlags;
int nItem=HitTest(pSHBDTAction->point,&nHitFlags,TRUE);
if(nItem==-1)
{
// Check if the control key was pressed
if((pSHBDTAction->dwKeyState & MK_CONTROL)==MK_CONTROL)
{
pSHBDTAction->result=(LRESULT)DROPEFFECT_COPY;
}
else
{
pSHBDTAction->result=(LRESULT)DROPEFFECT_MOVE;
}
// find the closest item
LV_FINDINFO lvfi;
lvfi.flags=LVFI_NEARESTXY;
lvfi.pt=pSHBDTAction->point;
lvfi.vkDirection=VK_DOWN;
int nItem=FindItem(&lvfi);
// assume that cursor is located lower than last item
if(nItem==-1)
{
nItem=GetItemCount();
}
ASSERT(nItem>=0 && nItem<=GetItemCount());
nInsertItemBefore=nItem;
}
else
{
pSHBDTAction->result=(LRESULT)DROPEFFECT_NONE;
}
}
// check if we need to scroll the list control in order to show more items
//
// autoscrolling margins
rectClient.DeflateRect(ID_DRAGDROPLEFTMARGIN,ID_DRAGDROPTOPMARGIN,
ID_DRAGDROPRIGHTMARGIN,ID_DRAGDROPBOTTOMMARGIN);
if(!rectClient.PtInRect(pSHBDTAction->point))
{
// check autoscrolling
if(!m_bScrollingUp && pSHBDTAction->point.y<rectClient.top &&
!m_rectTopScrollButton.IsRectEmpty())
{
// scroll up
m_bAutoScrolling=TRUE;
StartScrolling(TRUE);
}
else if(!m_bScrollingDown && pSHBDTAction->point.y>=rectClient.bottom &&
!m_rectBottomScrollButton.IsRectEmpty())
{
// scroll down
m_bAutoScrolling=TRUE;
StartScrolling(FALSE);
}
}
// check conditions to stop autoscrolling
else if(m_bAutoScrolling)
{
StopScrolling();
}
// redraw placeholders on the list control
if(m_nInsertItemBefore!=nInsertItemBefore)
{
if(bDrawDragImage)
{
// unlock window updates
VERIFY(m_pDragImage->DragShowNolock(FALSE));
}
// remove old placeholder
CRect rectPlaceHolder;
if(m_nInsertItemBefore!=-1)
{
rectPlaceHolder=GetPlaceHolderRect(m_nInsertItemBefore);
m_nInsertItemBefore=-1;
RedrawWindow(rectPlaceHolder);
}
// draw new placeholder
m_nInsertItemBefore=nInsertItemBefore;
if(m_nInsertItemBefore!=-1)
{
rectPlaceHolder=GetPlaceHolderRect(m_nInsertItemBefore);
RedrawWindow(rectPlaceHolder);
}
if(bDrawDragImage)
{
// lock window updates
VERIFY(m_pDragImage->DragShowNolock(TRUE));
}
}
return (LONG)TRUE;
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnDragLeave(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if((GetBarStyle()&SHBS_DISABLEDROPITEM)!=0)
return (LONG)FALSE;
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DRAGLEAVE;
nmshb.hGroup=m_hGroup;
nmshb.lParam=lParam;
// check if parent of the shortcut bar would like to handle drag'n'drop itself
if(SendSHBNotification(&nmshb))
{
// reset flag that specifies that drag'n'drop operation is active
m_bDragDropOperation=FALSE;
return (LONG)TRUE;
}
// lParam is the pointer to SHBDROPTARGETACTION structure
LPSHBDROPTARGETACTION pSHBDTAction=(LPSHBDROPTARGETACTION)lParam;
ASSERT(pSHBDTAction!=NULL);
ASSERT(pSHBDTAction->pWnd);
ASSERT(pSHBDTAction->pWnd->GetSafeHwnd()==GetSafeHwnd());
// if we launched the drag'n'drop operation then remove drag image if it was used
if((GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0 && m_bDragDropOwner)
{
ASSERT(m_pDragImage);
// remove dragging image
VERIFY(m_pDragImage->DragLeave(GetDesktopWindow()));
}
// remove placeholder image if any was drawn
if(m_nInsertItemBefore!=-1)
{
CRect rectPlaceHolder=GetPlaceHolderRect(m_nInsertItemBefore);
m_nInsertItemBefore=-1;
RedrawWindow(rectPlaceHolder);
}
// check conditions to stop autoscrolling
if(m_bAutoScrolling)
StopScrolling();
// reset flag that specifies that drag'n'drop operation is active
m_bDragDropOperation=FALSE;
return (LONG)TRUE;
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnDrop(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if((GetBarStyle()&SHBS_DISABLEDROPITEM)!=0)
return (LONG)FALSE;
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DROP;
nmshb.hGroup=m_hGroup;
nmshb.lParam=lParam;
// check if parent of the shortcut bar would like to handle drag'n'drop itself
if(SendSHBNotification(&nmshb))
{
m_bDragDropOperation=FALSE;
return (LONG)TRUE;
}
// lParam is the pointer to SHBDROPTARGETACTION structure
LPSHBDROPTARGETACTION pSHBDTAction=(LPSHBDROPTARGETACTION)lParam;
ASSERT(pSHBDTAction!=NULL);
ASSERT(pSHBDTAction->pWnd);
ASSERT(pSHBDTAction->pWnd->GetSafeHwnd()==GetSafeHwnd());
// if dragged item is to be copied or moved
if((pSHBDTAction->dropEffect&DROPEFFECT_COPY)!=0 ||
(pSHBDTAction->dropEffect&DROPEFFECT_MOVE)!=0)
{
// data must be in the specific format
ASSERT(pSHBDTAction->pDataObject->
IsDataAvailable(COXShortcutBar::m_nChildWndItemFormat));
if(m_nInsertItemBefore!=-1)
{
// Get the drag item info
//
HGLOBAL hgData=pSHBDTAction->pDataObject->
GetGlobalData(COXShortcutBar::m_nChildWndItemFormat);
ASSERT(hgData);
// lock it
BYTE* lpItemData=(BYTE*)GlobalLock(hgData);
// get item text
CString sText((LPTSTR)lpItemData);
lpItemData+=(sText.GetLength()+1)*sizeof(TCHAR);
// get item lParam
DWORD lParam=*(DWORD*)lpItemData;
lpItemData+=sizeof(DWORD);
// get the count of images associated with the draged item
DWORD nImageCount=*(DWORD*)lpItemData;
lpItemData+=sizeof(DWORD);
int nImageIndex=-1;
for(int nIndex=0; nIndex<(int)nImageCount; nIndex++)
{
// get image info from dragged data
SHBIMAGEDROPINFO imageInfo;
memcpy((void*)&imageInfo,(void*)lpItemData,sizeof(SHBIMAGEDROPINFO));
lpItemData+=sizeof(SHBIMAGEDROPINFO);
DWORD nImageSize=*(DWORD*)lpItemData;
ASSERT(nImageSize>0);
lpItemData+=sizeof(DWORD);
void* pImageBuffer=malloc(nImageSize);
ASSERT(pImageBuffer!=NULL);
memcpy(pImageBuffer,(void*)lpItemData,nImageSize);
ASSERT(pImageBuffer!=NULL);
// move to the next image info structure
lpItemData+=nImageSize;
// we are interested only in "NORMAL" images
if(imageInfo.imageType==SHBIT_NORMAL)
{
if(imageInfo.imageState==SHBIS_LARGE)
{
CImageList* pil=GetImageList(LVSIL_NORMAL);
if(pil==NULL)
pil=&m_ilLarge;
int nNewItemIndex=CopyImageToIL(pil,pImageBuffer,nImageSize);
ASSERT(nNewItemIndex!=-1);
ASSERT(nImageIndex==-1 || nNewItemIndex==nImageIndex);
nImageIndex=nNewItemIndex;
if(GetImageList(LVSIL_NORMAL)==NULL)
SetImageList(&m_ilLarge,LVSIL_NORMAL);
}
else if(imageInfo.imageState==SHBIS_SMALL)
{
CImageList* pil=GetImageList(LVSIL_SMALL);
if(pil==NULL)
pil=&m_ilSmall;
int nNewItemIndex=CopyImageToIL(pil,pImageBuffer,nImageSize);
ASSERT(nNewItemIndex!=-1);
ASSERT(nImageIndex==-1 || nNewItemIndex==nImageIndex);
nImageIndex=nNewItemIndex;
if(GetImageList(LVSIL_SMALL)==NULL)
SetImageList(&m_ilSmall,LVSIL_SMALL);
}
}
ASSERT(pImageBuffer!=NULL);
free(pImageBuffer);
}
// insert new item
//
LV_ITEM lvi;
ZeroMemory((void*)&lvi,sizeof(lvi));
lvi.mask=LVIF_TEXT;
lvi.pszText=(LPTSTR)((LPCTSTR)sText);
lvi.iSubItem=0;
lvi.iItem=m_nInsertItemBefore;
// set image info
if(nImageIndex!=-1)
{
lvi.mask|=LVIF_IMAGE;
lvi.iImage=nImageIndex;
}
// set lParam info
if(m_bDragDropOwner)
{
lvi.mask|=LVIF_PARAM;
lvi.lParam=lParam;
}
int nInsertedItem=InsertItem(&lvi);
ASSERT(nInsertedItem!=-1);
//////////////////////////////
// get the amount of bytes of additional info
SHBADDITIONALDROPINFO shbadi;
shbadi.nBufferLength=*(DWORD*)lpItemData;
lpItemData+=sizeof(DWORD);
if(shbadi.nBufferLength>0)
{
// get additional info
shbadi.pBuffer=(void*)lpItemData;
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_SETADDITIONALDROPINFO;
nmshb.hGroup=m_hGroup;
nmshb.nItem=m_nInsertItemBefore;
nmshb.lParam=(LPARAM)&shbadi;
SendSHBNotification(&nmshb);
lpItemData+=shbadi.nBufferLength;
}
// unlock it
GlobalUnlock(hgData);
// free it
GlobalFree(hgData);
// if we haven't launched the drag'n'drop operation then we have to redraw
// the control here to display newly inserted item
if(!m_bDragDropOwner)
{
m_nInsertItemBefore=-1;
RedrawWindow();
}
// drag'n'drop operation completed successfully
pSHBDTAction->result=(LRESULT)TRUE;
}
else
pSHBDTAction->result=(LRESULT)FALSE;
}
else
pSHBDTAction->result=(LRESULT)FALSE;
m_bDragDropOperation=FALSE;
if(!m_bDragDropOwner)
{
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_ENDDRAGDROPITEM;
nmshb.hGroup=m_hGroup;
nmshb.lParam=pSHBDTAction->result!=0 ?
pSHBDTAction->dropEffect : DROPEFFECT_NONE;
// notify parent
SendSHBNotification(&nmshb);
}
// we handled the message
return (LONG)TRUE;
}
void COXSHBListCtrl::OnChangeItemText(NMHDR* pNotifyStruct, LRESULT* result)
{
// this function handles SHBEN_FINISHEDIT that is sent by edit control
// to notify its parent that editing was finished
ASSERT(::IsWindow(m_edit.GetSafeHwnd()));
ASSERT(m_nEditItem>=0 && m_nEditItem<GetItemCount());
LPNMSHBEDIT lpNMSHBE=(LPNMSHBEDIT)pNotifyStruct;
// check if editing wasn't canceled
if(lpNMSHBE->bOK)
{
// get the edit control text
CString sText;
m_edit.GetWindowText(sText);
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_ENDITEMEDIT;
nmshb.hGroup=m_hGroup;
nmshb.nItem=m_nEditItem;
nmshb.lParam=(LPARAM)((LPCTSTR)sText);
// check if parent rejects the updated text
if(!SendSHBNotification(&nmshb))
{
// change the text of item
if(!SetItemText(m_nEditItem,0,sText.GetBuffer(sText.GetLength())))
{
TRACE(_T("COXSHBListCtrl::OnChangeItemText: failed to set text to item: %s"),sText);
}
sText.ReleaseBuffer();
}
}
// clear edit item index
m_nEditItem=-1;
*result=0;
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnPopulateContextMenu(WPARAM wParam, LPARAM lParam)
{
// Handles SHBM_POPULATECONTEXTMENU message that is fired by parent shortcut bar
// in order to populate context menu with our own items
UNREFERENCED_PARAMETER(wParam);
LPSHBCONTEXTMENU pSHBCM=(LPSHBCONTEXTMENU)lParam;
// double check that the message came from its parent shortcut bar and
// corresponding group
if(pSHBCM->pShortcutBar==m_pShortcutBar && pSHBCM->hGroup==m_hGroup)
{
CPoint point=pSHBCM->point;
ScreenToClient(&point);
// find if right mouse was clicked over any item
UINT nFlags;
int nItem=HitTest(point,&nFlags);
if(nItem!=-1 && nFlags!=SHBLC_ONITEM)
{
ASSERT(nItem>=0 && nItem<GetItemCount());
// add two items to menu to edit and remove items from the control
CMenu* pMenu=pSHBCM->pMenu;
if((GetBarStyle()&SHBS_EDITITEMS)!=0)
{
CString sItem;
VERIFY(sItem.LoadString(IDS_OX_SHBLC_IDMRENAMEITEM_TEXT));
if(pMenu->GetMenuItemCount()>0)
pMenu->AppendMenu(MF_SEPARATOR);
pMenu->AppendMenu(MF_STRING,SHBLC_IDMRENAMEITEM,
sItem);
VERIFY(sItem.LoadString(IDS_OX_SHBLC_IDMREMOVEITEM_TEXT));
pMenu->AppendMenu(MF_STRING,SHBLC_IDMREMOVEITEM,
sItem);
}
}
}
return ((LONG)0);
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnSetSHBGroup(WPARAM wParam, LPARAM lParam)
{
// Handles SHBM_SETSHBGROUP message that is fired by parent shortcut bar
// as soon as this control associated with any group
UNREFERENCED_PARAMETER(wParam);
// cast parent to shortcut bar
CWnd* pWnd=GetParent();
ASSERT(pWnd);
// check if it's really shortcut bar
if(pWnd->IsKindOf(RUNTIME_CLASS(COXShortcutBar)))
{
m_hGroup=(HSHBGROUP)lParam;
ASSERT(m_hGroup);
m_pShortcutBar=(COXShortcutBar*)pWnd;
}
return ((LONG)0);
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnSHBInfoChanged(WPARAM wParam, LPARAM lParam)
{
// Handles SHBM_SHBINFOCHANGED message that is fired by parent shortcut bar
// to notify its child window that some of shortcut bar properties have changed.
// lParam specifies mask of updated properties
UNREFERENCED_PARAMETER(wParam);
ASSERT(m_pShortcutBar!=NULL);
ASSERT(m_hGroup!=NULL);
UINT nMask=(UINT)lParam;
// if size of scroll buttons has changed then we should recalculate
// corresponding rectangles
if((nMask&SHBIF_SCRLBTNSIZE)!=0)
{
CalculateScrollRects();
}
// if style of shortcut bar has been changed then we should recalculate
// corresponding rectangles and redraw the window
if((nMask&SHBIF_SHBSTYLE)!=0)
{
CalculateScrollRects();
RedrawWindow();
}
return ((LONG)0);
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnGroupInfoChanged(WPARAM wParam, LPARAM lParam)
{
// Handles SHBM_GROUPINFOCHANGED message that is fired by parent shortcut bar
// to notify its child window that some of associated with this control
// shortcut bar group properties have changed. lParam specifies mask of updated
// properties
UNREFERENCED_PARAMETER(wParam);
ASSERT(m_pShortcutBar!=NULL);
ASSERT(m_hGroup!=NULL);
UINT nMask=(UINT)lParam;
// if descriptor changed then reposition all items
if((nMask&SHBIF_DESCRIPTOR)!=0)
{
CalculateBoundRects();
}
// if view chnged then reset the view origin and redraw the control
if((nMask&SHBIF_VIEW)!=0)
{
Scroll(-m_ptOrigin);
CalculateBoundRects();
}
return ((LONG)0);
}
LRESULT COXSHBListCtrl::OnCreateDragImage(WPARAM wParam, LPARAM lParam)
{
return (LRESULT)CreateDragImage((int)wParam,(LPPOINT)lParam);
}
LRESULT COXSHBListCtrl::OnDeleteAllItems(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DELETEALLITEMS;
nmshb.hGroup=m_hGroup;
SendSHBNotification(&nmshb);
LRESULT result=Default();
// recalculate all item position (actually remove all information about items)
if((BOOL)result)
{
m_ptOrigin=CPoint(0,0);
SelectItem(-1);
ActivateItem(-1);
CalculateBoundRects();
RedrawWindow();
}
return result;
}
LRESULT COXSHBListCtrl::OnDeleteItem(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DELETEITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=(int)wParam;
SendSHBNotification(&nmshb);
LRESULT result=Default();
// reposition items and redraw the control
if((BOOL)result)
{
// change the origin of the control if the last item was deleted
// and it was the top item at the moment
if(GetTopIndex()==-1)
m_ptOrigin=CPoint(0,0);
// if deleted item had lower index than the selected item index
// then decrease it by one
if(GetSelectedItem()>(int)wParam)
m_nSelectedItem--;
// if deleted item was the selected one then reset the index of selected item
else if(GetSelectedItem()==(int)wParam)
m_nSelectedItem=-1;
// if deleted item had lower index than the active item index
// then decrease it by one
if(GetActiveItem()>(int)wParam)
m_nActiveItem--;
// if deleted item was the active one then reset the index of active item item
else if(GetActiveItem()==(int)wParam)
m_nActiveItem=-1;
// reposition the items and redraw the control if there is no active
// drag'n'drop operation
CalculateBoundRects();
if(!m_bDragDropOperation)
{
RedrawWindow();
}
}
return result;
}
LRESULT COXSHBListCtrl::OnEditLabel(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
return (LRESULT)EditLabel((int)wParam);
}
LRESULT COXSHBListCtrl::OnEnsureVisible(WPARAM wParam, LPARAM lParam)
{
return (LRESULT)EnsureVisible((int)wParam,(BOOL)lParam);
}
LRESULT COXSHBListCtrl::OnFindItem(WPARAM wParam, LPARAM lParam)
{
// we provide our own functionality to find items dpecified by their position
if(((LV_FINDINFO*)lParam)->flags&LVFI_NEARESTXY)
return (LONG)FindItem((LV_FINDINFO*)lParam,(int)wParam);
else
return (LRESULT)Default();
}
LRESULT COXSHBListCtrl::OnGetBkColor(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(wParam);
if(m_pShortcutBar)
return (LRESULT)GetBkColor();
else
return Default();
}
LRESULT COXSHBListCtrl::OnGetCountPerPage(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(wParam);
return (LRESULT)GetCountPerPage();
}
LRESULT COXSHBListCtrl::OnGetEditControl(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(wParam);
return (LRESULT)GetEditControl();
}
// v9.3 - update 03 - 64-bit - changed LONG ret type to LRESULT
LRESULT COXSHBListCtrl::OnGetHotItem(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(wParam);
return (LONG)GetHotItem();
}
LRESULT COXSHBListCtrl::OnGetItemPosition(WPARAM wParam, LPARAM lParam)
{
return GetItemPosition((int)wParam,(LPPOINT)lParam);
}
LRESULT COXSHBListCtrl::OnGetItemRect(WPARAM wParam, LPARAM lParam)
{
return GetItemRect((int)wParam,(LPRECT)lParam,((LPRECT)lParam)->left);
}
LRESULT COXSHBListCtrl::OnGetOrigin(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
return GetOrigin((LPPOINT)lParam);
}
LRESULT COXSHBListCtrl::OnGetTextBkColor(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(wParam);
if(m_pShortcutBar)
return GetTextBkColor();
else
return Default();
}
LRESULT COXSHBListCtrl::OnGetTextColor(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(wParam);
if(m_pShortcutBar)
return GetTextColor();
else
return Default();
}
LRESULT COXSHBListCtrl::OnGetTopIndex(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(wParam);
return (LRESULT)GetTopIndex();
}
LRESULT COXSHBListCtrl::OnGetViewRect(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
return (LRESULT)GetViewRect((LPRECT)lParam);
}
LRESULT COXSHBListCtrl::OnHitTest(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
return (LRESULT)HitTest((LPLVHITTESTINFO)lParam);
}
LRESULT COXSHBListCtrl::OnInsertItem(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
LRESULT result=Default();
// reposition items and redraw the control
if((int)result!=-1)
{
// In the case this control was created as a child window of shortcut bar group
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_INSERTITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=((LV_ITEM*)lParam)->iItem;
nmshb.lParam=lParam;
SendSHBNotification(&nmshb);
// if inserted item had lower or equal index as the selected item index
// then increase the last by one
if(GetSelectedItem()>=(int)result)
m_nSelectedItem++;
// if inserted item had lower or equal index as the active item index
// then increase the last by one
if(GetActiveItem()>=(int)result)
m_nActiveItem++;
// reposition the items and redraw the control if there is no active
// drag'n'drop operation
CalculateBoundRects();
if(!m_bDragDropOperation)
{
RedrawWindow();
}
}
return result;
}
LRESULT COXSHBListCtrl::OnRedrawItems(WPARAM wParam, LPARAM lParam)
{
return RedrawItems((int)wParam,(int)lParam);
}
LRESULT COXSHBListCtrl::OnScroll(WPARAM wParam, LPARAM lParam)
{
return Scroll((int)wParam,(int)lParam);
}
LRESULT COXSHBListCtrl::OnSetBkColor(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if(m_pShortcutBar)
return SetBkColor((COLORREF)lParam);
else
return Default();
}
LRESULT COXSHBListCtrl::OnSetHotItem(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
return SetHotItem((int)wParam);
}
LRESULT COXSHBListCtrl::OnSetItem(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
LRESULT result=Default();
if((BOOL)result)
{
// reposition items and redraw the control
CalculateBoundRects();
RedrawWindow();
}
return result;
}
LRESULT COXSHBListCtrl::OnSetItemText(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
LRESULT result= Default();
if((BOOL)result)
{
// reposition items and redraw the control
CalculateBoundRects();
RedrawWindow();
}
return result;
}
LRESULT COXSHBListCtrl::OnSetTextBkColor(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if(m_pShortcutBar)
return SetTextBkColor((COLORREF)lParam);
else
return Default();
}
LRESULT COXSHBListCtrl::OnSetTextColor(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if(m_pShortcutBar)
return SetTextColor((COLORREF)lParam);
else
return Default();
}
LRESULT COXSHBListCtrl::OnSortItems(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
LRESULT result=Default();
// reposition items and redraw the control
if((BOOL)result)
{
// reset active and selected items
SelectItem(-1);
ActivateItem(-1);
// reposition items and redraw the control
CalculateBoundRects();
RedrawWindow();
}
return result;
}
LRESULT COXSHBListCtrl::OnUpdate(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
return Update((int)wParam);
}
// v9.3 - update 03 - 64-bit - using OXTPARAM here - see UTB64Bit.h
void COXSHBListCtrl::OnTimer(OXTPARAM nIDEvent)
{
// TODO: Add your message handler code here and/or call default
// we use timer to provide scrolling functionality
if(m_nScrollTimerID==nIDEvent)
{
// for pshycho
ASSERT(m_bScrollingUp || m_bScrollingDown);
CRect rectClient;
GetClientRect(rectClient);
// deflate the client rectangle to match the valid area where we can
// display items
rectClient.DeflateRect(ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,
ID_EDGEBOTTOMMARGIN);
ASSERT(rectClient.top<rectClient.bottom);
UINT nHitFlags;
// get cursor position when the last mouse message was fired
DWORD dwMessagePos=::GetMessagePos();
CPoint point(GET_X_LPARAM(dwMessagePos),GET_Y_LPARAM(dwMessagePos));
ScreenToClient(&point);
HitTest(point,&nHitFlags);
// if any drag and drop operation is undergoing then cheat the control
if(m_bDragDropOperation)
{
if(m_bScrollingUp)
nHitFlags=SHBLC_ONTOPSCROLLBUTTON;
else
nHitFlags=SHBLC_ONBOTTOMSCROLLBUTTON;
if((GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0 && m_bDragDropOwner)
{
ASSERT(m_pDragImage);
// unlock window updates
VERIFY(m_pDragImage->DragShowNolock(FALSE));
}
}
// if we are still over the scroll butoon
if(m_bScrollingUp && nHitFlags==SHBLC_ONTOPSCROLLBUTTON)
{
if(!m_bDragDropOperation)
ASSERT(!m_rectTopScrollButton.IsRectEmpty());
RedrawWindow(m_rectTopScrollButton);
// scroll up
CRect rect;
int nItem=GetTopIndex();
if(nItem==-1)
nItem=GetItemCount()-1;
else
{
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
if(m_ptOrigin.y+rectClient.top<=rect.top)
{
ASSERT(nItem>0);
nItem--;
}
}
ASSERT((nItem>=0 && nItem<GetItemCount()));
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
int nOffset=rect.top-rectClient.top-m_ptOrigin.y;
Scroll(CSize(0,nOffset));
// check if we scrolled to the top
if(m_rectTopScrollButton.IsRectEmpty())
StopScrolling();
}
else if(m_bScrollingDown && nHitFlags==SHBLC_ONBOTTOMSCROLLBUTTON)
{
if(!m_bDragDropOperation)
ASSERT(!m_rectBottomScrollButton.IsRectEmpty());
RedrawWindow(m_rectBottomScrollButton);
// scroll down
CRect rect;
int nItem=GetTopIndex();
ASSERT(nItem>=0 && nItem<GetItemCount());
if(nItem==GetItemCount()-1)
{
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
int nOffset=rect.bottom-rectClient.bottom-m_ptOrigin.y;
Scroll(CSize(0,nOffset));
}
else
{
nItem++;
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
int nOffset=rect.top-rectClient.top-m_ptOrigin.y;
Scroll(CSize(0,nOffset));
}
// check if we scrolled to the bottom
if(m_rectBottomScrollButton.IsRectEmpty())
StopScrolling();
}
if(m_bDragDropOperation && (GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0 &&
m_bDragDropOwner)
{
ASSERT(m_pDragImage);
// lock window updates
VERIFY(m_pDragImage->DragShowNolock(TRUE));
}
}
else if(nIDEvent==m_nCheckMouseTimerID)
{
if(!m_bDragDropOperation)
PostMessage(SHBLCM_CHECKCAPTURE);
}
else
CListCtrl::OnTimer(nIDEvent);
}
void COXSHBListCtrl::OnDestroy()
{
CListCtrl::OnDestroy();
// TODO: Add your message handler code here
// just kill timers
if(m_nScrollTimerID!=0)
{
KillTimer(m_nScrollTimerID);
m_nScrollTimerID=0;
}
if(m_nCheckMouseTimerID!=0)
{
KillTimer(m_nCheckMouseTimerID);
m_nCheckMouseTimerID=0;
}
}
/////////////////////////////////////////////////////////////////////////////
BOOL COXSHBListCtrl::CreateEditControl()
{
if(::IsWindow(m_edit.GetSafeHwnd()))
return TRUE;
// Create an invisible edit control
CRect rect(0,0,0,0);
BOOL bResult=m_edit.Create(WS_BORDER,rect,this,SHB_IDCEDIT);
return bResult;
}
BOOL COXSHBListCtrl::CheckCapture()
{
// As soon as we get first mouse message we have to capture all of them in order
// to handle hot items
// Check whether the mouse is over the list control
CRect rectWindow;
GetWindowRect(rectWindow);
CPoint point;
::GetCursorPos(&point);
CWnd* pWnd=CWnd::WindowFromPoint(point);
ASSERT(pWnd!=NULL);
BOOL bIsMouseOver=(pWnd->GetSafeHwnd()==GetSafeHwnd());
if(bIsMouseOver && IsWindowEnabled())
{
// Moved inside this control window. Capture the mouse
// SetCapture();
if(m_nCheckMouseTimerID==0)
{
m_nCheckMouseTimerID=SetTimer(IDT_OXSHBLIST_CHECKMOUSE,
ID_OXSHBLIST_CHECKMOUSE_DELAY,NULL);
ASSERT(m_nCheckMouseTimerID!=0);
}
m_bMouseIsOver=TRUE;
}
else
{
// ... We release the mouse capture (may have already lost it)
// we could have dragged something
if(!IsLButtonDown())
{
// ReleaseCapture();
if(m_nCheckMouseTimerID!=0)
{
KillTimer(m_nCheckMouseTimerID);
m_nCheckMouseTimerID=0;
}
m_bMouseIsOver=FALSE;
int nOldHotItem=SetHotItem(-1);
if(nOldHotItem!=-1)
Update(nOldHotItem);
return FALSE;
}
m_bMouseIsOver=FALSE;
}
// handle all mouse messages
AnticipateMouseMessages();
// return TRUE if we have all mouse input
// return (GetCapture()==this);
return TRUE;
}
void COXSHBListCtrl::PostCheckCapture()
{
// check if mouse capture was lost during last mouse message handling
}
void COXSHBListCtrl::CalculateBoundRects()
{
// clean up map of all bound rectangles
m_mapItemToBoundRect.RemoveAll();
m_mapItemToImageRect.RemoveAll();
m_mapItemToTextRect.RemoveAll();
// clean up scroll buttons rectangles
m_rectTopScrollButton.SetRectEmpty();
m_rectBottomScrollButton.SetRectEmpty();
int nCount=GetItemCount();
// if there is no item then our mission is completed
if(nCount==0)
{
return;
}
CRect rect;
GetClientRect(rect);
// if client rect is empty then our mission is completed too
if(rect.IsRectEmpty())
{
for(int nIndex=0; nIndex<nCount; nIndex++)
{
m_mapItemToBoundRect.SetAt(nIndex,rect);
m_mapItemToImageRect.SetAt(nIndex,rect);
m_mapItemToTextRect.SetAt(nIndex,rect);
}
return;
}
// deflate rect to leave some space that won't be taken by items
rect.DeflateRect(
ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,ID_EDGEBOTTOMMARGIN);
// item positions depend on type of view
int nView=GetView();
// get corresponding item list to show items
CImageList* pil=NULL;
if(nView==SHB_LARGEICON)
{
pil=GetImageList(LVSIL_NORMAL);
}
else if(nView==SHB_SMALLICON)
{
pil=GetImageList(LVSIL_SMALL);
}
IMAGEINFO imageInfo;
CRect rectImage;
CRect rectText;
CString sItemText;
// loop through all items
for(int nIndex=0; nIndex<nCount; nIndex++)
{
// get text
sItemText=GetItemText(nIndex,0);
// get image index
int nImage=GetItemImage(nIndex);
if(pil!=NULL && nImage>=0)
{
VERIFY(pil->GetImageInfo(nImage,&imageInfo));
rectImage=imageInfo.rcImage;
rectImage.InflateRect(3,3);
rectImage-=rectImage.TopLeft();
}
else
{
rectImage.SetRectEmpty();
}
// calculate text rect and adjust it with image rect
rectText=AdjustTextRect(sItemText,rectImage,rect.Width());
if(nView==SHB_LARGEICON)
{
rect.bottom=rect.top+rectImage.Height()+rectText.Height()+
ID_IMAGETEXTVERTMARGIN;
}
else if(nView==SHB_SMALLICON)
{
rect.bottom=rect.top+__max(rectImage.Height(),rectText.Height());
}
else
{
ASSERT(FALSE);
}
if(nView==SHB_LARGEICON)
{
int nMargin=rectImage.Width()-rect.Width();
rectImage.left=rect.left-nMargin/2;
rectImage.right=rect.right+nMargin/2+nMargin%2;
}
// save calculated rects
m_mapItemToBoundRect.SetAt(nIndex,rect);
m_mapItemToImageRect.SetAt(nIndex,rectImage);
m_mapItemToTextRect.SetAt(nIndex,rectText);
rect.top=rect.bottom+((nIndex==nCount-1) ? 0 : ID_ITEMMARGIN);
}
// recalculate scroll buttons rects
CalculateScrollRects();
}
CRect COXSHBListCtrl::AdjustTextRect(CString sText,CRect& rectImage, int nMaxWidth)
{
// takes on input text, image rect an max width that it can take
//
CRect rect;
rect.SetRectEmpty();
if(sText.IsEmpty() || nMaxWidth<=0)
return rect;
CClientDC dc(this);
// Save DC
int nSavedDC=dc.SaveDC();
ASSERT(nSavedDC);
// set font
CFont* pOldFont=NULL;
CFont font;
if(m_pShortcutBar)
{
LPLOGFONT pLF=m_pShortcutBar->GetGroupTextFont(m_hGroup);
ASSERT(pLF);
VERIFY(font.CreateFontIndirect(pLF));
pOldFont=dc.SelectObject(&font);
}
else
{
CFont* pFont=GetFont();
if(pFont!=NULL)
pOldFont=dc.SelectObject(pFont);
}
int nView=GetView();
// depending on type of view calculate the text rect
if(nView==SHB_LARGEICON)
{
rect.right=nMaxWidth-(ID_TEXTLEFTMARGIN+ID_TEXTRIGHTMARGIN);
dc.DrawText(sText,rect,DT_VCENTER|DT_CENTER|DT_WORDBREAK|DT_CALCRECT|
DT_EDITCONTROL);
rect.InflateRect(0,0,ID_TEXTLEFTMARGIN+ID_TEXTRIGHTMARGIN,
ID_TEXTTOPMARGIN+ID_TEXTBOTTOMMARGIN);
// adjust text and image rects
//
int nHeight=rect.Height();
rect.top+=rectImage.bottom+
(rectImage.bottom==rectImage.top ? 0 : ID_IMAGETEXTVERTMARGIN);
rect.bottom=rect.top+nHeight;
int nWidth=rect.Width();
if(nWidth>nMaxWidth)
rect.right=nMaxWidth;
else
{
int nMargin=nMaxWidth-nWidth;
rect.left=nMargin/2;
rect.right=rect.left+nWidth;
}
}
else if(nView==SHB_SMALLICON && rectImage.Width()<nMaxWidth)
{
dc.DrawText(sText,rect,DT_VCENTER|DT_LEFT|DT_CALCRECT);
rect.InflateRect(0,0,ID_TEXTLEFTMARGIN+ID_TEXTRIGHTMARGIN,
ID_TEXTTOPMARGIN+ID_TEXTBOTTOMMARGIN);
// adjust text and image rects
//
int nHeight=rect.Height();
rect.top=rectImage.top;
rect.bottom=rect.top+nHeight;
int nMargin=nHeight-rectImage.Height();
if(nMargin>0)
{
rectImage.OffsetRect(0,nMargin/2);
}
else if(nMargin<0)
{
rect.top-=nMargin/2;
rect.bottom=rect.top+nHeight;
}
if(rectImage.left!=rectImage.right)
{
int nWidth=rect.Width();
rect.left+=rectImage.right+ID_IMAGETEXTHORZMARGIN;
rect.right=rect.left+nWidth;
}
// if there is no any image associated with the item thn in small icon view
// offset the text rectangle a little bit to make it look nicer
else
rect.left+=ID_TEXTLEFTMARGIN;
if(rect.right>nMaxWidth)
rect.right=nMaxWidth;
}
if(pOldFont!=NULL)
dc.SelectObject(pOldFont);
// Restore dc
dc.RestoreDC(nSavedDC);
return rect;
}
void COXSHBListCtrl::CalculateScrollRects()
{
// clean up scroll buttons rectangles
m_rectTopScrollButton.SetRectEmpty();
m_rectBottomScrollButton.SetRectEmpty();
// define scroll buttons rectangles
//
CRect rect;
GetClientRect(rect);
rect.DeflateRect(
ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,ID_EDGEBOTTOMMARGIN);
if(rect.top>=rect.bottom)
{
return;
}
CSize sizeScrollButton=GetScrollButtonSize();
if(m_ptOrigin.y!=0)
{
// define rect for top scroll button
m_rectTopScrollButton.top=rect.top;
m_rectTopScrollButton.right=rect.right;
m_rectTopScrollButton.bottom=rect.top+sizeScrollButton.cy;
m_rectTopScrollButton.left=rect.right-sizeScrollButton.cx;
}
CRect rectScrollable;
if(GetScrollableRect(rectScrollable))
{
if(rect.bottom+m_ptOrigin.y<rectScrollable.bottom)
{
// define rect for bottom scroll button
m_rectBottomScrollButton.bottom=rect.bottom;
m_rectBottomScrollButton.right=rect.right;
m_rectBottomScrollButton.top=rect.bottom-sizeScrollButton.cy;
m_rectBottomScrollButton.left=rect.right-sizeScrollButton.cx;
}
}
}
void COXSHBListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// Draws any item. It defined as virtual in case you want to draw items yourself.
// But you should be careful - this control is highly optimized to be drawn in the
// most efficient way. Don't ruin it!
int nItem=(int)lpDrawItemStruct->itemID;
ASSERT(nItem>=0 && nItem<GetItemCount());
// we use this routine to create drag image too
if(!m_bCreatingDragImage)
{
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DRAWITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=nItem;
nmshb.lParam=(LPARAM)lpDrawItemStruct;
// In the case you handled this notification you could have provided all
// the drawing functionality so we check if you don't want us to run
// the standard implementation
if(SendSHBNotification(&nmshb))
{
return;
}
}
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);
// Get the header rect
CRect rectItem(lpDrawItemStruct->rcItem);
// Save DC
int nSavedDC=dc.SaveDC();
ASSERT(nSavedDC);
int nView=GetView();
// Draw Image
//
int nImage=GetItemImage(nItem);
if(nImage>=0)
{
CImageList* pil=NULL;
if(nView==SHB_LARGEICON)
{
pil=GetImageList(LVSIL_NORMAL);
}
else if(nView==SHB_SMALLICON)
{
pil=GetImageList(LVSIL_SMALL);
}
if(pil!=NULL)
{
CRect rectImage;
VERIFY(m_mapItemToImageRect.Lookup(nItem,rectImage));
rectImage.DeflateRect(1,1);
if(!m_bCreatingDragImage)
{
COLORREF clrTopLeft=UpdateColor(GetBkColor(),64);
COLORREF clrBottomRight=UpdateColor(GetBkColor(),-128);
// Draw bounding rectangles if needed
if(GetHotItem()==nItem)
{
if (m_pShortcutBar != NULL)
{
// Part if a shorcut bar
BOOL bSelected = (GetSelectedItem() == nItem && IsLButtonDown()) ? TRUE : FALSE;
m_pShortcutBar->GetShortcutBarSkin()->DrawItemBorder(&dc, rectImage, TRUE, bSelected, this);
}
else
{
// Not part of a shortcut bar
if(IsLButtonDown() && GetSelectedItem()==nItem)
dc.Draw3dRect(rectImage,clrBottomRight,clrTopLeft);
else
dc.Draw3dRect(rectImage,clrTopLeft,clrBottomRight);
}
}
else if(GetActiveItem()==nItem &&
(GetBarStyle() & SHBS_SHOWACTIVEALWAYS)!=0)
{
if (m_pShortcutBar != NULL)
m_pShortcutBar->GetShortcutBarSkin()->DrawItemBorder(&dc, rectImage, FALSE, TRUE, this);
else
dc.Draw3dRect(rectImage,clrBottomRight,clrTopLeft);
}
}
// Draw icon
rectImage.DeflateRect(2,2);
pil->Draw(&dc,nImage,rectImage.TopLeft(),ILD_TRANSPARENT);
}
}
// Draw text
//
CString sText=GetItemText(nItem,0);
CRect rectText;
VERIFY(m_mapItemToTextRect.Lookup(nItem,rectText));
if(!rectText.IsRectEmpty() && !sText.IsEmpty())
{
// set transparent mode
dc.SetBkMode(TRANSPARENT);
// set text color
COLORREF clrText=GetTextColor();
VERIFY(clrText!=ID_COLOR_NONE);
dc.SetTextColor(clrText);
// set font
CFont* pOldFont=NULL;
CFont font;
if(m_pShortcutBar)
{
LPLOGFONT pLF=m_pShortcutBar->GetGroupTextFont(m_hGroup);
ASSERT(pLF);
VERIFY(font.CreateFontIndirect(pLF));
pOldFont=dc.SelectObject(&font);
}
else
{
CFont* pFont=GetFont();
if(pFont!=NULL)
{
pOldFont=dc.SelectObject(pFont);
}
}
if(!m_bCreatingDragImage)
{
// update font if special style was set
if((GetBarStyle()&SHBS_UNDERLINEHOTITEM)!=0 &&
GetHotItem()==nItem)
{
CFont* pFont=dc.GetCurrentFont();
ASSERT(pFont);
LOGFONT lf;
VERIFY(pFont->GetLogFont(&lf));
lf.lfUnderline=TRUE;
if(pOldFont!=NULL)
dc.SelectObject(pOldFont);
if((HFONT)font!=NULL)
font.DeleteObject();
VERIFY(font.CreateFontIndirect(&lf));
pOldFont=dc.SelectObject(&font);
}
}
// draw text
if(nView==SHB_LARGEICON)
{
rectText.DeflateRect(ID_TEXTLEFTMARGIN,ID_TEXTTOPMARGIN,
ID_TEXTRIGHTMARGIN,ID_TEXTBOTTOMMARGIN);
dc.DrawText(sText,rectText,DT_CENTER|DT_VCENTER|DT_WORDBREAK|
DT_EDITCONTROL|DT_END_ELLIPSIS);
}
else if(nView==SHB_SMALLICON)
{
dc.DrawText(sText,rectText,DT_LEFT|DT_VCENTER|DT_SINGLELINE);
}
else
{
ASSERT(FALSE);
}
if(pOldFont!=NULL)
{
dc.SelectObject(pOldFont);
}
}
// Restore dc
dc.RestoreDC(nSavedDC);
// Detach the dc before returning
dc.Detach();
}
void COXSHBListCtrl::DrawScrollButtons(CDC* pDC)
{
// draw scroll buttons only if needed
//
if((GetBarStyle()&SHBS_NOSCROLL)!=0)
{
TRACE(_T("COXSHBListCtrl::DrawScrollButtons: scroll buttons won't be displayed - SHBS_NOSCROLL style is set"));
return ;
}
// check if we need to draw any of scroll buttons
BOOL m_bDrawTopButton=((!m_rectTopScrollButton.IsRectEmpty()) &
pDC->RectVisible(&m_rectTopScrollButton));
BOOL m_bDrawBottomButton=((!m_rectBottomScrollButton.IsRectEmpty()) &
pDC->RectVisible(&m_rectBottomScrollButton));
if(!m_bDrawTopButton && !m_bDrawBottomButton)
{
return;
}
// Save DC
int nSavedDC=pDC->SaveDC();
ASSERT(nSavedDC);
// check if the curent cursor position is over one of the scroll button
CPoint point;
::GetCursorPos(&point);
ScreenToClient(&point);
UINT nFlags;
HitTest(point,&nFlags);
// use standard frame control as scroll button
if(m_bDrawBottomButton)
pDC->DrawFrameControl(m_rectBottomScrollButton,DFC_SCROLL,DFCS_SCROLLDOWN|
((nFlags==SHBLC_ONBOTTOMSCROLLBUTTON && m_bScrollingDown &&
(IsLButtonDown() || m_bAutoScrolling)) ? DFCS_PUSHED : 0));
if(m_bDrawTopButton)
pDC->DrawFrameControl(m_rectTopScrollButton,DFC_SCROLL,DFCS_SCROLLUP|
((nFlags==SHBLC_ONTOPSCROLLBUTTON && m_bScrollingUp &&
(IsLButtonDown() || m_bAutoScrolling)) ? DFCS_PUSHED : 0));
// Restore dc
pDC->RestoreDC(nSavedDC);
}
void COXSHBListCtrl::DrawPlaceHolder(CDC* pDC)
{
// draw place holder to drop dragged item only if needed
//
if(m_nInsertItemBefore<0 || m_nInsertItemBefore>GetItemCount())
return ;
// get rectangle that can be used to draw placeholder
CRect rectPlaceHolder=GetPlaceHolderRect(m_nInsertItemBefore);
if(!pDC->RectVisible(&rectPlaceHolder))
return;
ASSERT(!rectPlaceHolder.IsRectEmpty());
// Save DC
int nSavedDC=pDC->SaveDC();
ASSERT(nSavedDC);
// by default use black color
COLORREF clr=RGB(0,0,0);
// if the background color is too close to the black then use white color
// to draw the placeholder
if(IsColorCloseTo(clr,GetBkColor(),64))
clr=RGB(255,255,255);
CPen pen(PS_SOLID,1,clr);
CPen* pOldPen=pDC->SelectObject(&pen);
// place holder for the top item
if(m_nInsertItemBefore==0)
{
pDC->MoveTo(rectPlaceHolder.left,rectPlaceHolder.top);
pDC->LineTo(rectPlaceHolder.right,rectPlaceHolder.top);
int nHeight=2*ID_HEIGHTPLACEHOLDER/3;
for(int nIndex=1; nIndex<=nHeight; nIndex++)
{
pDC->MoveTo(rectPlaceHolder.left,rectPlaceHolder.top+nIndex);
pDC->LineTo(rectPlaceHolder.left+(nHeight-nIndex),
rectPlaceHolder.top+nIndex);
pDC->MoveTo(rectPlaceHolder.right-(nHeight-nIndex),
rectPlaceHolder.top+nIndex);
pDC->LineTo(rectPlaceHolder.right,rectPlaceHolder.top+nIndex);
}
}
// place holder for the bottom item
else if(m_nInsertItemBefore==GetItemCount())
{
pDC->MoveTo(rectPlaceHolder.left,rectPlaceHolder.bottom-1);
pDC->LineTo(rectPlaceHolder.right,rectPlaceHolder.bottom-1);
int nHeight=2*ID_HEIGHTPLACEHOLDER/3;
for(int nIndex=1; nIndex<=nHeight; nIndex++)
{
pDC->MoveTo(rectPlaceHolder.left,rectPlaceHolder.bottom-nIndex);
pDC->LineTo(rectPlaceHolder.left+(nHeight-nIndex),
rectPlaceHolder.bottom-nIndex);
pDC->MoveTo(rectPlaceHolder.right-(nHeight-nIndex),
rectPlaceHolder.bottom-nIndex);
pDC->LineTo(rectPlaceHolder.right,rectPlaceHolder.bottom-nIndex);
}
}
// place holder is located between two existing items
else
{
pDC->MoveTo(rectPlaceHolder.left,(rectPlaceHolder.top+rectPlaceHolder.bottom)/2);
pDC->LineTo(rectPlaceHolder.right,(rectPlaceHolder.top+rectPlaceHolder.bottom)/2);
int nHeight=ID_HEIGHTPLACEHOLDER/2;
for(int nIndex=1; nIndex<=nHeight; nIndex++)
{
pDC->MoveTo(rectPlaceHolder.left,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2+nIndex);
pDC->LineTo(rectPlaceHolder.left+nHeight-nIndex,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2+nIndex);
pDC->MoveTo(rectPlaceHolder.right-nHeight+nIndex,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2+nIndex);
pDC->LineTo(rectPlaceHolder.right,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2+nIndex);
pDC->MoveTo(rectPlaceHolder.left,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2-nIndex);
pDC->LineTo(rectPlaceHolder.left+nHeight-nIndex,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2-nIndex);
pDC->MoveTo(rectPlaceHolder.right-nHeight+nIndex,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2-nIndex);
pDC->LineTo(rectPlaceHolder.right,
(rectPlaceHolder.top+rectPlaceHolder.bottom)/2-nIndex);
}
}
if(pOldPen!=NULL)
pDC->SelectObject(pOldPen);
// Restore dc
pDC->RestoreDC(nSavedDC);
}
void COXSHBListCtrl::FillBackground(CDC* pDC)
{
// just fill background with preset background color
COLORREF clrBackground = GetBkColor();
VERIFY(clrBackground!=ID_COLOR_NONE);
CBrush brush(clrBackground);
CRect rect;
GetClientRect(rect);
int iSavedDC = pDC->SaveDC();
// Exclude parts that will be covered by items
int nItem;
POSITION pos=m_mapItemToBoundRect.GetStartPosition();
while(pos!=NULL)
{
CRect rectExclude;
m_mapItemToBoundRect.GetNextAssoc(pos,nItem,rectExclude);
rectExclude -= m_ptOrigin;
ASSERT(nItem>=0 && nItem<GetItemCount());
pDC->ExcludeClipRect(rectExclude);
}
// Fill only region that wasn't taken by items
if (m_pShortcutBar != NULL)
{
if (HasBkColor())
m_pShortcutBar->GetShortcutBarSkin()->FillBackground(pDC, rect, this, TRUE, GetBkColor());
else
m_pShortcutBar->GetShortcutBarSkin()->FillBackground(pDC, rect, this);
}
else
pDC->FillSolidRect(rect, clrBackground);
pDC->RestoreDC(iSavedDC);
}
int COXSHBListCtrl::HitTest(CPoint pt, UINT* pFlags, BOOL bOnlyItems/* = FALSE*/) const
{
// Scroll buttons have the highest priority (top buttom is prior to bottom button).
// As long as scroll buttons may cover list control items you can specify
// bOnlyItems argument as TRUE to test the specified point only on item locations.
//
if(!bOnlyItems && (GetBarStyle()&SHBS_NOSCROLL)==0)
{
// point is over the top scroll button
if(!m_rectTopScrollButton.IsRectEmpty() &&
m_rectTopScrollButton.PtInRect(pt))
{
*pFlags=SHBLC_ONTOPSCROLLBUTTON;
return -1;
}
// point is over the bottom scroll button
if(!m_rectBottomScrollButton.IsRectEmpty() &&
m_rectBottomScrollButton.PtInRect(pt))
{
*pFlags=SHBLC_ONBOTTOMSCROLLBUTTON;
return -1;
}
}
int nItem=-1;
*pFlags=0;
// adjust point
pt+=m_ptOrigin;
// get rect that covers all current visible items
CRect rectView;
GetViewRect(rectView,TRUE);
if(rectView.PtInRect(pt))
{
*pFlags=LVHT_NOWHERE;
CRect rect;
// try to find item rect that include the point
POSITION pos=m_mapItemToBoundRect.GetStartPosition();
while(pos!=NULL)
{
m_mapItemToBoundRect.GetNextAssoc(pos,nItem,rect);
ASSERT(nItem>=0 && nItem<GetItemCount());
if(rect.PtInRect(pt))
{
// point can be within image rect, text rect, on image and text
// united rect or on item rect
CRect rectImage;
VERIFY(m_mapItemToImageRect.Lookup(nItem,rectImage));
rectImage+=rect.TopLeft();
// point is on the image
if(rectImage.PtInRect(pt))
*pFlags=LVHT_ONITEMICON;
else
{
CRect rectText;
VERIFY(m_mapItemToTextRect.Lookup(nItem,rectText));
rectText+=rect.TopLeft();
// point is on the text
if(rectText.PtInRect(pt))
*pFlags=LVHT_ONITEMLABEL;
else
{
CRect rectImageAndText;
rectImageAndText.left=__min(rectImage.left,rectText.left);
rectImageAndText.right=__max(rectImage.right,rectText.right);
rectImageAndText.top=__min(rectImage.top,rectText.top);
rectImageAndText.bottom=__max(rectImage.bottom,rectText.bottom);
// point is on the item bounding rectangle
if(rectImageAndText.PtInRect(pt))
*pFlags=SHBLC_ONIMAGEANDTEXT;
// point is on the entire item rectangle
else
*pFlags=SHBLC_ONITEM;
}
}
break;
}
}
if(*pFlags==LVHT_NOWHERE)
nItem=-1;
}
else
{
if(pt.x<rectView.left)
*pFlags|=LVHT_TOLEFT;
else if(pt.x>rectView.right)
*pFlags|=LVHT_TORIGHT;
if(pt.y<rectView.top)
*pFlags|=LVHT_ABOVE;
else if(pt.y>rectView.bottom)
*pFlags|=LVHT_BELOW;
}
return nItem;
}
BOOL COXSHBListCtrl::GetViewRect(LPRECT lpRectView,
BOOL bOnlyVisible/* = FALSE*/) const
{
// try to find rect that cover all list control items (if bOnlyVisible is TRUE,
// then only visible items)
CRect rectClient;
GetClientRect(rectClient);
// deflate client rect by margins so there is some space in the control that
// is not covered by items
rectClient.DeflateRect(ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,
ID_EDGEBOTTOMMARGIN);
CRect rectView=rectClient;
int nBottom=0;
CRect rect;
int nItem;
POSITION pos=m_mapItemToBoundRect.GetStartPosition();
while(pos!=NULL)
{
m_mapItemToBoundRect.GetNextAssoc(pos,nItem,rect);
ASSERT(nItem>=0 && nItem<GetItemCount());
if(nBottom<rect.bottom)
nBottom=rect.bottom;
if(bOnlyVisible && nBottom>rectClient.bottom+m_ptOrigin.y)
break;
}
rectView.bottom=nBottom;
if(bOnlyVisible)
{
rectView.top=__max(rectView.top,rectView.top+m_ptOrigin.y);
rectView.bottom=__min(rectView.bottom,rectClient.bottom+m_ptOrigin.y);
}
lpRectView->left=rectView.left;
lpRectView->right=rectView.right;
lpRectView->top=rectView.top;
lpRectView->bottom=rectView.bottom;
return TRUE;
}
BOOL COXSHBListCtrl::GetItemRect(int nItem, LPRECT lpRect, UINT nCode) const
{
ASSERT(nItem>=0 && nItem<GetItemCount());
CRect rect;
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
rect-=m_ptOrigin;
switch(nCode)
{
case LVIR_ICON:
{
// image rect
CRect rectImage;
rectImage.SetRectEmpty();
m_mapItemToImageRect.Lookup(nItem,rectImage);
rectImage+=rect.TopLeft();
lpRect->left=rectImage.left;
lpRect->top=rectImage.top;
lpRect->right=rectImage.right;
lpRect->bottom=rectImage.bottom;
break;
}
case LVIR_LABEL:
{
// text rect
CRect rectText;
rectText.SetRectEmpty();
VERIFY(m_mapItemToTextRect.Lookup(nItem,rectText));
rectText+=rect.TopLeft();
lpRect->left=rectText.left;
lpRect->top=rectText.top;
lpRect->right=rectText.right;
lpRect->bottom=rectText.bottom;
break;
}
case LVIR_BOUNDS:
{
// image and text united rect
CRect rectImage;
rectImage.SetRectEmpty();
m_mapItemToImageRect.Lookup(nItem,rectImage);
rectImage+=rect.TopLeft();
CRect rectText;
rectText.SetRectEmpty();
VERIFY(m_mapItemToTextRect.Lookup(nItem,rectText));
rectText+=rect.TopLeft();
lpRect->left=__min(rectText.left,rectImage.left);
lpRect->top=__min(rectText.top,rectImage.top);
lpRect->right=__max(rectText.right,rectImage.right);
lpRect->bottom=__max(rectText.bottom,rectImage.bottom);
break;
}
case SHBLC_ENTIREITEM:
{
// entire item rect
lpRect->left=rect.left;
lpRect->top=rect.top;
lpRect->right=rect.right;
lpRect->bottom=rect.bottom;
break;
}
default:
ASSERT(FALSE);
}
return TRUE;
}
BOOL COXSHBListCtrl::GetItemPosition(int nItem, LPPOINT lpPoint) const
{
ASSERT(nItem>=0 && nItem<GetItemCount());
CRect rect;
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
// adjust rect
rect-=m_ptOrigin;
lpPoint->x=rect.left;
lpPoint->y=rect.right;
return TRUE;
}
BOOL COXSHBListCtrl::GetScrollableRect(CRect& rectScrollable, int nTopItem /*=-1*/) const
{
// return the size of rect that list control can be scrolled to
//
CRect rectClient;
GetClientRect(rectClient);
// deflate client rect by margins so there is some space in the control that
// is not covered by items
rectClient.DeflateRect(ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,
ID_EDGEBOTTOMMARGIN);
if(rectClient.top>=rectClient.bottom)
return FALSE;
CRect rectView;
GetViewRect(rectView);
rectScrollable=rectView;
// if all items fit the client area then just return view rect as the
// scrollable one
if((rectView.Height()+m_ptOrigin.y)<=rectClient.Height())
return TRUE;
// if the last item is visible then just return client rect plus origin offset
// as scrollable one
if(rectView.Height()<=(rectClient.Height()+m_ptOrigin.y))
{
rectScrollable.bottom+=rectClient.Height()+m_ptOrigin.y-rectView.Height();
return TRUE;
}
CRect rect;
// we can specify the top item that should be taken into account while
// calculating the scrollable rect as argument or if it is set to -1 then
// we will found it using GetTopIndex function
if(nTopItem==-1)
{
nTopItem=GetTopIndex();
VERIFY(m_mapItemToBoundRect.Lookup(nTopItem,rect));
if(m_ptOrigin.y+rectClient.top>rect.top)
if(nTopItem==GetItemCount()-1)
return TRUE;
else
nTopItem++;
}
// resulted top item must be in the valid range
ASSERT(nTopItem>=0 && nTopItem<GetItemCount());
VERIFY(m_mapItemToBoundRect.Lookup(nTopItem,rect));
int nTop=rect.top;
VERIFY(m_mapItemToBoundRect.Lookup(GetItemCount()-1,rect));
int nBottom=rect.bottom;
if(nBottom-nTop<rectClient.Height())
rectScrollable.bottom+=rectClient.Height()-(nBottom-nTop);
ASSERT(rectScrollable.Height()>=rectView.Height());
return TRUE;
}
DWORD COXSHBListCtrl::GetBarStyle() const
{
if(m_pShortcutBar)
return m_pShortcutBar->GetBarStyle();
else
{
// we use the set of our styles to define the list control functionality
//
DWORD dwBarStyle=0;
DWORD dwStyle=GetStyle();
if((dwStyle&LVS_EDITLABELS)!=0)
dwBarStyle|=SHBS_EDITITEMS;
if((dwStyle&LVS_NOSCROLL)!=0)
dwBarStyle|=SHBS_NOSCROLL;
if((dwStyle&LVS_SHOWSELALWAYS)!=0)
dwBarStyle|=SHBS_SHOWACTIVEALWAYS;
if((dwStyle&LVS_NOSCROLL)!=0)
dwBarStyle|=SHBS_NOSCROLL;
DWORD dwExStyle=GetExStyle();
if((dwExStyle&LVS_EX_UNDERLINEHOT)!=0)
dwBarStyle|=SHBS_UNDERLINEHOTITEM;
if((dwExStyle&LVS_EX_INFOTIP)!=0)
dwBarStyle|=SHBS_INFOTIP;
return dwBarStyle;
}
}
LRESULT COXSHBListCtrl::SendSHBNotification(LPNMSHORTCUTBAR pNMSHB) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
// if parent window of that control is shortcut bar then send notification to
// its parent
if(m_pShortcutBar)
{
return m_pShortcutBar->SendSHBNotification(pNMSHB);
}
else
{
// send standard shortcut bar notification to list control parent using
// NMSHORTCUTBAR structure
// notify parent
CWnd* pParentWnd=GetOwner();
if(pParentWnd)
{
// fill notification structure
pNMSHB->hdr.hwndFrom=GetSafeHwnd();
pNMSHB->hdr.idFrom=GetDlgCtrlID();
return (pParentWnd->SendMessage(
WM_NOTIFY,(WPARAM)GetDlgCtrlID(),(LPARAM)pNMSHB));
}
else
{
return (LRESULT)0;
}
}
}
int COXSHBListCtrl::GetView() const
{
// At the moment we defined only two views: Large Icons & Small Icons
if(m_pShortcutBar)
{
int nView=m_pShortcutBar->GetGroupView(m_hGroup);
VERIFY(m_pShortcutBar->VerifyView(nView));
return nView;
}
else
{
DWORD dwStyle=GetStyle();
if((dwStyle&LVS_SMALLICON)!=0)
return SHB_SMALLICON;
else
return SHB_LARGEICON;
}
}
CSize COXSHBListCtrl::GetScrollButtonSize() const
{
if(m_pShortcutBar)
return m_pShortcutBar->GetScrollButtonSize();
else
return CSize(DFLT_SCROLLBUTTONWIDTH,DFLT_SCROLLBUTTONHEIGHT);
}
UINT COXSHBListCtrl::GetScrollingDelay() const
{
if(m_pShortcutBar)
return m_pShortcutBar->GetScrollingDelay();
else
return DFLT_SCROLLINGDELAY;
}
UINT COXSHBListCtrl::GetAutoScrollingDelay() const
{
if(m_pShortcutBar)
return m_pShortcutBar->GetAutoScrollingDelay();
else
return DFLT_AUTOSCROLLINGDELAY;
}
int COXSHBListCtrl::SelectItem(int nItem)
{
ASSERT(nItem<GetItemCount());
if(nItem==m_nSelectedItem)
return m_nSelectedItem;
int nOldItem=m_nSelectedItem;
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_SELECTITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=nItem;
if(SendSHBNotification(&nmshb))
return m_nSelectedItem;
m_nSelectedItem=nItem;
return nOldItem;
}
int COXSHBListCtrl::SetHotItem(int nItem)
{
ASSERT(nItem<GetItemCount());
if(nItem==m_nHotItem)
return m_nHotItem;
int nOldItem=m_nHotItem;
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_HOTITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=nItem;
if(SendSHBNotification(&nmshb))
return m_nHotItem;
m_nHotItem=nItem;
m_nLastHotItem=nOldItem;
return nOldItem;
}
int COXSHBListCtrl::ActivateItem(int nItem)
{
ASSERT(nItem<GetItemCount());
if(nItem==m_nActiveItem)
{
return m_nActiveItem;
}
int nOldItem=m_nActiveItem;
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_ACTIVATEITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=nItem;
if(SendSHBNotification(&nmshb))
{
return m_nActiveItem;
}
m_nActiveItem=nItem;
Update(nOldItem);
Update(m_nActiveItem);
return nOldItem;
}
int COXSHBListCtrl::SetDropTargetItem(int nItem)
{
ASSERT(nItem<GetItemCount());
int nOldItem=m_nDropHilightItem;
m_nDropHilightItem=nItem;
return nOldItem;
}
int COXSHBListCtrl::SetDragItem(int nItem)
{
ASSERT(nItem<GetItemCount());
if(nItem==m_nDragItem)
return m_nDragItem;
int nOldItem=m_nDragItem;
m_nDragItem=nItem;
if(nItem!=-1)
{
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_BEGINDRAGITEM;
nmshb.hGroup=m_hGroup;
nmshb.nItem=nItem;
nmshb.lParam=(LPARAM)&m_ptDragImage;
SendSHBNotification(&nmshb);
// CF_TEXT format
//
// get our data ready to cache
CString sText=GetItemText(nItem,0);
// allocate our data object
COleDataSource* pDataSource;
pDataSource = new COleDataSource;
// Load a CF_TEXT to the data object
HGLOBAL hgCF_TEXTData=GlobalAlloc(GPTR,(sText.GetLength()+1)*sizeof(TCHAR));
BYTE* lpCF_TEXTData=(BYTE*)GlobalLock(hgCF_TEXTData);
lstrcpy((LPTSTR)lpCF_TEXTData,sText);
GlobalUnlock(hgCF_TEXTData);
// save the text data
pDataSource->CacheGlobalData(CF_TEXT,hgCF_TEXTData);
//////////////////////
// internal COXShortcutBar::m_nChildWndItemFormat format
//
// (text) + (NULL) + lParam + (number of images elements) +
// (SHBIMAGEDROPINFO + size of image list + ImageList) +
// (SHBIMAGEDROPINFO + size of image list + ImageList) + ...+
// (size of additional information) + (additional information)
//
// in this case we use only two images (large and small)
//
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
SHBADDITIONALDROPINFO shbadi;
::ZeroMemory(&nmshb,sizeof(NMSHORTCUTBAR));
nmshb.hdr.code=SHBN_GETADDITIONALDROPINFO;
nmshb.hGroup=m_hGroup;
nmshb.nItem=nItem;
nmshb.lParam=(LPARAM)&shbadi;
SendSHBNotification(&nmshb);
// check the integrity
ASSERT((shbadi.nBufferLength>0 && shbadi.pBuffer!=NULL) ||
(shbadi.nBufferLength==0 && shbadi.pBuffer==NULL));
// get image index
int nImage=GetItemImage(nItem);
DWORD nLargeImageSize=0;
void* pilLargeBuffer=NULL;
DWORD nSmallImageSize=0;
void* pilSmallBuffer=NULL;
// create image lists for large and small button correspondingly
if(nImage>=0)
{
CImageList* pil=GetImageList(LVSIL_NORMAL);
if(pil!=NULL)
pilLargeBuffer=CopyImageFromIL(pil,nImage,nLargeImageSize);
pil=GetImageList(LVSIL_SMALL);
if(pil!=NULL)
pilSmallBuffer=CopyImageFromIL(pil,nImage,nSmallImageSize);
}
int nEntryMemSize=(sText.GetLength()+1)*sizeof(TCHAR)+
sizeof(DWORD)+sizeof(DWORD);
DWORD nImageCount=0;
if(nImage>=0)
{
if(nLargeImageSize>0)
{
nEntryMemSize+=sizeof(SHBIMAGEDROPINFO)+sizeof(DWORD)+nLargeImageSize;
nImageCount++;
}
if(nSmallImageSize>0)
{
nEntryMemSize+=sizeof(SHBIMAGEDROPINFO)+sizeof(DWORD)+nSmallImageSize;
nImageCount++;
}
}
nEntryMemSize+=sizeof(DWORD)+shbadi.nBufferLength;
// allocate the memory
HGLOBAL hgItemData=GlobalAlloc(GPTR,nEntryMemSize);
BYTE* lpItemData=(BYTE*)GlobalLock(hgItemData);
ZeroMemory(lpItemData,nEntryMemSize);
// write item text into global memory
lstrcpy((LPTSTR)lpItemData,sText);
lpItemData+=(sText.GetLength()+1)*sizeof(TCHAR);
// write item lParam into global memory
(*(DWORD*)lpItemData)=(DWORD)GetItemData(nItem);
lpItemData+=sizeof(DWORD);
// write the item image info to gloabal memory
//
// set number of images associated with the item
(*(DWORD*)lpItemData)=nImageCount;
lpItemData+=sizeof(DWORD);
if(nLargeImageSize>0)
{
// fill special image info structure
SHBIMAGEDROPINFO imageInfo;
// our image is the "NORMAL" one
imageInfo.imageType=SHBIT_NORMAL;
imageInfo.imageState=SHBIS_LARGE;
// write SHBIMAGEDROPINFO structure
memcpy((void*)lpItemData,(void*)&imageInfo,sizeof(SHBIMAGEDROPINFO));
lpItemData+=sizeof(SHBIMAGEDROPINFO);
// write the size of image
(*(DWORD*)lpItemData)=nLargeImageSize;
lpItemData+=sizeof(DWORD);
// write image list
memcpy((void*)lpItemData,pilLargeBuffer,nLargeImageSize);
lpItemData+=nLargeImageSize;
}
if(nSmallImageSize>0)
{
// fill special image info structure
SHBIMAGEDROPINFO imageInfo;
// our image is the "NORMAL" one
imageInfo.imageType=SHBIT_NORMAL;
imageInfo.imageState=SHBIS_SMALL;
// write SHBIMAGEDROPINFO structure
memcpy((void*)lpItemData,(void*)&imageInfo,sizeof(SHBIMAGEDROPINFO));
lpItemData+=sizeof(SHBIMAGEDROPINFO);
// write the size of image
(*(DWORD*)lpItemData)=nSmallImageSize;
lpItemData+=sizeof(DWORD);
// write image list
memcpy((void*)lpItemData,pilSmallBuffer,nSmallImageSize);
lpItemData+=nSmallImageSize;
}
// write the additional item info to gloabal memory
//
// set the amount of bytes of additional info
(*(DWORD*)lpItemData)=shbadi.nBufferLength;
lpItemData+=sizeof(DWORD);
if(shbadi.nBufferLength>0)
{
// write additional info
memcpy((void*)lpItemData,shbadi.pBuffer,shbadi.nBufferLength);
lpItemData+=shbadi.nBufferLength;
}
GlobalUnlock(hgItemData);
// save the item data
pDataSource->CacheGlobalData(COXShortcutBar::m_nChildWndItemFormat,hgItemData);
if(pilLargeBuffer!=NULL)
free(pilLargeBuffer);
if(pilSmallBuffer!=NULL)
free(pilSmallBuffer);
// post special message to handle drag'n'drop operation
PostMessage(SHBLCM_HANDLEDRAG,(WPARAM)nItem,(LPARAM)pDataSource);
}
return nOldItem;
}
BOOL COXSHBListCtrl::Update(int nItem)
{
if(nItem<0 || nItem>=GetItemCount())
return FALSE;
// get the item rect
CRect rectItem;
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rectItem));
// adjust it
rectItem-=m_ptOrigin;
CRect rect;
if(m_mapItemToImageRect.Lookup(nItem,rect))
{
rect+=rectItem.TopLeft();
// redraw image rect
RedrawWindow(rect);
}
VERIFY(m_mapItemToTextRect.Lookup(nItem,rect));
rect+=rectItem.TopLeft();
// redraw text rect
RedrawWindow(rect);
return TRUE;
}
BOOL COXSHBListCtrl::RedrawItems(int nFirst, int nLast)
{
for(int nIndex=nFirst; nIndex<=nLast; nIndex++)
if(!Update(nIndex))
return FALSE;
return TRUE;
}
void COXSHBListCtrl::AnticipateMouseMessages()
{
CPoint point;
::GetCursorPos(&point);
ScreenToClient(&point);
// test the cursor position
UINT nHitFlags;
int nItem=HitTest(point,&nHitFlags);
if(!m_bMouseIsOver || (nItem!=-1 &&
(nHitFlags==SHBLC_ONITEM || nHitFlags==SHBLC_ONIMAGEANDTEXT)))
{
nItem=-1;
}
int nOldHotItem=SetHotItem(nItem);
if(GetDragItem()==-1 && nItem!=-1 &&
(GetBarStyle()&SHBS_DISABLEDRAGITEM)==0 && m_nSuspectDragItem==nItem)
{
if(abs(point.x-m_ptClickedLButton.x)+abs(point.y-m_ptClickedLButton.y)>8)
{
m_ptDragImage+=point-m_ptClickedLButton;
// assign item being dragged
SetDragItem(nItem);
}
}
// reset suspect drag item index
if(!IsLButtonDown() || GetDragItem()!=-1)
m_nSuspectDragItem=-1;
// update changed items
//
if(nItem!=-1)
Update(nItem);
if(nItem!=nOldHotItem && nOldHotItem!=-1)
Update(nOldHotItem);
// update scroll button images
//
if(m_bScrollingUp && nHitFlags!=SHBLC_ONTOPSCROLLBUTTON)
RedrawWindow(m_rectTopScrollButton);
if(m_bScrollingDown && nHitFlags!=SHBLC_ONBOTTOMSCROLLBUTTON)
RedrawWindow(m_rectBottomScrollButton);
// check autoscrolling
if((GetBarStyle()&SHBS_AUTOSCROLL)!=0 && GetDragItem()==-1)
{
if(!m_bScrollingUp && nHitFlags==SHBLC_ONTOPSCROLLBUTTON)
{
m_bAutoScrolling=TRUE;
StartScrolling(TRUE);
}
else if(!m_bScrollingDown && nHitFlags==SHBLC_ONBOTTOMSCROLLBUTTON)
{
m_bAutoScrolling=TRUE;
StartScrolling(FALSE);
}
}
// check conditions to stop autoscrolling
if(m_bAutoScrolling && ((m_bScrollingUp && nHitFlags!=SHBLC_ONTOPSCROLLBUTTON) ||
(m_bScrollingDown && nHitFlags!=SHBLC_ONBOTTOMSCROLLBUTTON)))
{
StopScrolling();
}
}
BOOL COXSHBListCtrl::Scroll(CSize size)
{
// origin mustn't be negative
ASSERT(m_ptOrigin.x>=0 || m_ptOrigin.y>=0);
if(GetItemCount()==0)
{
return FALSE;
}
CRect rectClient;
GetClientRect(rectClient);
if(rectClient.IsRectEmpty())
{
return FALSE;
}
// deflate client rect to leave some space free of items
rectClient.DeflateRect(
ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,ID_EDGEBOTTOMMARGIN);
// get current top index
int nTopItem=GetTopIndex();
ASSERT(nTopItem>=0 && nTopItem<GetItemCount());
// scroll up
if(size.cy<0)
nTopItem=(nTopItem>0) ? nTopItem-1 : nTopItem;
else
// scroll down
if(size.cy>0)
nTopItem=(nTopItem==GetItemCount()-1) ? nTopItem : nTopItem+1;
// get scrollbale rect to check validility of scroll operation
CRect rectScrollable;
if(!GetScrollableRect(rectScrollable,nTopItem))
return FALSE;
CRect rectAggregate=rectClient;
rectAggregate+=m_ptOrigin;
rectAggregate+=size;
// scroll up
if(size.cy<0)
{
int nTopMargin=rectAggregate.top-rectScrollable.top;
if(nTopMargin<=size.cy)
{
size.cy=0;
}
else
{
size.cy-=(nTopMargin<0) ? nTopMargin : 0;
ASSERT(size.cy<0);
}
}
else
// scroll down
if(size.cy>0)
{
int nBottomMargin=rectAggregate.bottom-rectScrollable.bottom;
if(nBottomMargin>=size.cy)
size.cy=0;
else
{
size.cy-=(nBottomMargin>0) ? nBottomMargin : 0;
ASSERT(size.cy>0);
}
}
// scroll left
if(size.cx<0)
{
int nLeftMargin=rectAggregate.left-rectScrollable.left;
if(nLeftMargin<=size.cx)
{
size.cx=0;
}
else
{
size.cx-=(nLeftMargin<0) ? nLeftMargin : 0;
ASSERT(size.cx<0);
}
}
else
// scroll right
if(size.cx>0)
{
int nRightMargin=rectAggregate.right-rectScrollable.right;
if(nRightMargin>=size.cx)
{
size.cx=0;
}
else
{
size.cx-=(nRightMargin>0) ? nRightMargin : 0;
ASSERT(size.cx>0);
}
}
if(size.cx==0 && size.cy==0)
return FALSE;
// update view origin
m_ptOrigin.x+=size.cx;
m_ptOrigin.y+=size.cy;
// reposition items and redraw the control
CalculateScrollRects();
RedrawWindow();
return TRUE;
}
int COXSHBListCtrl::FindItem(LV_FINDINFO* pFindInfo, int nStart/* = -1*/) const
{
int nCount=GetItemCount();
if(nCount==0)
return -1;
// verify nStart argument
ASSERT(nStart+1>=0 && nStart<nCount);
int nItem=-1;
// only if searching by coordinates specified we provide our own implementation
if(pFindInfo->flags&LVFI_NEARESTXY)
{
CPoint point=pFindInfo->pt;
// adjuxt the coordinates
point+=m_ptOrigin;
int nNearestDistance=-1;
int nNearestItem=-1;
CRect rect;
for(int nIndex=nStart+1; nIndex<nCount+
((pFindInfo->flags&LVFI_WRAP) ? nStart+1 : 0); nIndex++)
{
nItem=nIndex;
if(nItem>=nCount)
nItem-=nCount;
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
// bottom mustn't be include (the same way PtInRect works)
if(rect.PtInRect(point) || (point.y>=rect.top && point.y<rect.bottom))
{
// if the point is in entire item rect then the search is completed
nNearestItem=nItem;
break;
}
int nMargin=-1;
switch(pFindInfo->vkDirection)
{
// search for upper items
case VK_UP:
{
nMargin=point.y-rect.bottom;
break;
}
// search for down items
case VK_DOWN:
{
nMargin=rect.top-point.y;
break;
}
}
if(nMargin>0 && (nNearestDistance==-1 || nNearestDistance>nMargin))
{
nNearestDistance=nMargin;
nNearestItem=nItem;
}
}
nItem=nNearestItem;
}
else
nItem=CListCtrl::FindItem(pFindInfo,nStart);
return nItem;
}
int COXSHBListCtrl::GetTopIndex() const
{
LV_FINDINFO lvfi;
lvfi.flags=LVFI_NEARESTXY;
lvfi.pt.x=0;
lvfi.pt.y=ID_EDGETOPMARGIN;
lvfi.vkDirection=VK_DOWN;
return FindItem(&lvfi);
}
BOOL COXSHBListCtrl::EnsureVisible(int nItem, BOOL bPartialOK)
{
if(nItem<0 || nItem>=GetItemCount())
return FALSE;
// entire item rectangle
CRect rect;
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
// visible view rectangle
CRect rectViewVisible;
GetViewRect(rectViewVisible,TRUE);
// if entire item rectangle height is more the than the visible rectangle height
// and partial visibility is not Ok then we've got Mission Impossible
if(rect.Height()>=rectViewVisible.Height() && !bPartialOK)
return FALSE;
// if their intersection is not empty and partial visibility is Ok
// then the mission is completed
CRect rectIntersection;
if(rectIntersection.IntersectRect(rectViewVisible,rect) && bPartialOK)
return TRUE;
// if their intersection is equal to the entire item rectangle
// then the mission is completed either
if(rectIntersection==rect)
return TRUE;
// scroll the control to update view origin
//
if(rect.bottom<rectViewVisible.top)
Scroll(CSize(0,rect.top-rectViewVisible.top));
else if(rect.top>rectViewVisible.bottom)
Scroll(CSize(0,rect.bottom-rectViewVisible.bottom));
else if(rect.bottom>rectViewVisible.bottom)
Scroll(CSize(0,rect.bottom-rectViewVisible.bottom));
else if(rect.top<rectViewVisible.top)
Scroll(CSize(0,rect.top-rectViewVisible.top));
if(bPartialOK)
return TRUE;
GetViewRect(rectViewVisible,TRUE);
// check if size of item is more than visible rect
if(rectIntersection.IntersectRect(rectViewVisible,rect) && rectIntersection==rect)
return TRUE;
else
return FALSE;
}
COXSHBEdit* COXSHBListCtrl::EditLabel(int nItem)
{
ASSERT(nItem>=0 && nItem<GetItemCount());
// validate edit control
ASSERT(::IsWindow(m_edit.GetSafeHwnd()));
// check if editing is allowed
if((GetBarStyle()&SHBS_EDITITEMS)==0)
{
TRACE(_T("COXSHBListCtrl::EditLabel: cannot edit item - SHBS_EDITITEMS style wasn't set"));
return NULL;
}
// finish edit if any is undergoing
if(m_nEditItem!=-1)
{
m_edit.FinishEdit(TRUE);
m_nEditItem=-1;
}
CString sText=GetItemText(nItem,0);
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_BEGINITEMEDIT;
nmshb.hGroup=m_hGroup;
nmshb.nItem=nItem;
nmshb.lParam=(LPARAM)((LPCTSTR)sText);
// check if parent doesn't let us to edit item text
if(SendSHBNotification(&nmshb))
return NULL;
CRect rectClient;
GetClientRect(rectClient);
rectClient.DeflateRect(
ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,ID_EDGEBOTTOMMARGIN);
CRect rectText;
if(!GetItemRect(nItem,rectText,LVIR_LABEL))
{
TRACE(_T("COXSHBListCtrl::EditLabel: failed to get item text rectangle"));
return NULL;
}
if(rectText.IsRectEmpty())
{
rectText.SetRectEmpty();
CRect rectImage;
if(!GetItemRect(nItem,rectImage,LVIR_ICON))
{
TRACE(_T("COXSHBListCtrl::EditLabel: failed to get item image rectangle"));
return NULL;
}
CRect rectItem;
if(!GetItemRect(nItem,rectItem,SHBLC_ENTIREITEM))
{
TRACE(_T("COXSHBListCtrl::EditLabel: failed to get full item rectangle"));
return NULL;
}
rectText=AdjustTextRect(_T(" "),rectImage,rectItem.Width());
ASSERT(!rectText.IsRectEmpty());
}
CRect rectIntersect;
if(!rectIntersect.IntersectRect(rectClient,rectText) ||
rectIntersect!=rectText)
{
TRACE(_T("COXSHBListCtrl::EditLabel: failed to edit - item text rectangle is not entirely visible"));
return NULL;
}
int nView=GetView();
// make some adjustments to make our edit rect look prettier
if(nView==SHB_SMALLICON)
{
rectText.OffsetRect(-ID_TEXTLEFTMARGIN,0);
VERIFY(rectIntersect.IntersectRect(rectClient,rectText));
}
// get font to use in edit control
CFont font;
LPLOGFONT pLF=NULL;
LOGFONT lf;
if(m_pShortcutBar)
{
pLF=m_pShortcutBar->GetGroupTextFont(m_hGroup);
}
else
{
CFont* pFont=GetFont();
ASSERT(pFont!=NULL);
VERIFY(pFont->GetLogFont(&lf));
pLF=&lf;
}
ASSERT(pLF!=NULL);
VERIFY(font.CreateFontIndirect(pLF));
CRect rectMax;
CRect rectMin;
// fill SHBE_DISPLAY structure to fill editing properties depending on view
SHBE_DISPLAY shbed;
shbed.nMask=SHBEIF_TEXT|SHBEIF_RECTDISPLAY|SHBEIF_RECTMAX|SHBEIF_STYLE|
SHBEIF_ENLARGE|SHBEIF_SELRANGE|SHBEIF_FONT|SHBEIF_RECTMIN;
shbed.lpText=sText;
shbed.rectDisplay=rectText;
if(nView==SHB_LARGEICON)
{
shbed.dwStyle=WS_BORDER|ES_CENTER|ES_MULTILINE|ES_AUTOVSCROLL;
rectMax=rectClient;
rectMax.top=rectText.top;
rectMin=rectText;
if(rectText.Width()<ID_EDITMINWIDTH)
{
rectMin.left=(rectText.left+rectText.right-ID_EDITMINWIDTH)/2;
rectMin.right=rectMin.left+ID_EDITMINWIDTH;
if(rectMin.left<rectMax.left)
rectMax.left=rectMin.left;
if(rectMin.right>rectMax.right)
rectMax.right=rectMin.right;
}
}
else if(nView==SHB_SMALLICON)
{
shbed.dwStyle=WS_BORDER|ES_AUTOHSCROLL|ES_LEFT;
rectMax=rectText;
rectMax.right=rectClient.right;
rectMin=rectText;
if(rectText.Width()<ID_EDITMINWIDTH)
{
rectMin.right=rectMin.left+ID_EDITMINWIDTH;
if(rectMin.right>rectMax.right)
rectMax.right=rectMin.right;
}
}
else
{
ASSERT(FALSE);
}
shbed.rectMax=rectMax;
shbed.rectMin=rectMin;
shbed.bEnlargeAsTyping=TRUE;
shbed.ptSelRange=CPoint(0,-1);
shbed.pFont=&font;
if(!m_edit.StartEdit(&shbed))
{
TRACE(_T("COXSHBListCtrl::EditLabel: COXSHBEdit::StartEdit failed"));
return NULL;
}
m_nEditItem=nItem;
return &m_edit;
}
COLORREF COXSHBListCtrl::GetBkColor() const
{
if(m_pShortcutBar)
{
ASSERT(m_hGroup);
COLORREF clrBackground=m_pShortcutBar->GetGroupBkColor(m_hGroup);
ASSERT(clrBackground!=ID_COLOR_NONE);
return clrBackground;
}
else
{
return CListCtrl::GetBkColor();
}
}
BOOL COXSHBListCtrl::HasBkColor() const
{
if(m_pShortcutBar)
{
ASSERT(m_hGroup);
return m_pShortcutBar->HasGroupBkColor(m_hGroup);
}
else
return FALSE;
}
BOOL COXSHBListCtrl::SetBkColor(COLORREF clr)
{
if(m_pShortcutBar)
{
ASSERT(m_hGroup);
return m_pShortcutBar->SetGroupBkColor(m_hGroup,clr);
}
else
return CListCtrl::SetBkColor(clr);
}
COLORREF COXSHBListCtrl::GetTextColor() const
{
if(m_pShortcutBar)
{
ASSERT(m_hGroup);
COLORREF clrText=m_pShortcutBar->GetGroupTextColor(m_hGroup);
ASSERT(clrText!=ID_COLOR_NONE);
return clrText;
}
else
return CListCtrl::GetTextColor();
}
BOOL COXSHBListCtrl::SetTextColor(COLORREF clr)
{
if(m_pShortcutBar)
{
ASSERT(m_hGroup);
return m_pShortcutBar->SetGroupTextColor(m_hGroup,clr);
}
else
return CListCtrl::SetTextColor(clr);
}
COLORREF COXSHBListCtrl::GetTextBkColor() const
{
if(m_pShortcutBar)
return GetBkColor();
else
return CListCtrl::GetTextBkColor();
}
BOOL COXSHBListCtrl::SetTextBkColor(COLORREF clr)
{
if(m_pShortcutBar)
{
return FALSE;
}
else
return CListCtrl::SetTextBkColor(clr);
}
int COXSHBListCtrl::GetCountPerPage() const
{
// result of this function depends on current origin and may vary
//
CRect rectView;
GetViewRect(rectView,TRUE);
int nCount=0;
if(!rectView.IsRectEmpty())
{
CRect rect;
int nItem;
POSITION pos=m_mapItemToBoundRect.GetStartPosition();
while(pos!=NULL)
{
m_mapItemToBoundRect.GetNextAssoc(pos,nItem,rect);
ASSERT(nItem>=0 && nItem<GetItemCount());
if(rect.IntersectRect(rectView,rect))
nCount++;
}
}
return nCount;
}
CImageList* COXSHBListCtrl::CreateDragImage(int nItem, LPPOINT lpPoint /*= NULL*/)
{
UNREFERENCED_PARAMETER(lpPoint);
ASSERT(nItem>=0 && nItem<GetItemCount());
m_bCreatingDragImage=TRUE;
// IMPORTANT //
// it's caller responsibility to delete created image list
CImageList* m_pDragImageList=new CImageList;
CRect rectImageText;
VERIFY(GetItemRect(nItem,&rectImageText,LVIR_BOUNDS));
CRect rectItem;
VERIFY(GetItemRect(nItem,&rectItem,SHBLC_ENTIREITEM));
// create image list
m_pDragImageList->Create(rectImageText.Width(),rectImageText.Height(),TRUE,0,1);
CClientDC dcClient(this);
CDC dc;
VERIFY(dc.CreateCompatibleDC(&dcClient));
CDC dcCopy;
VERIFY(dcCopy.CreateCompatibleDC(&dcClient));
CBitmap bitmapItem;
VERIFY(bitmapItem.CreateCompatibleBitmap(&dcClient,rectItem.Width(),
rectItem.Height()));
CBitmap* pOldBitmap=dc.SelectObject(&bitmapItem);
rectImageText-=rectItem.TopLeft();
rectItem-=rectItem.TopLeft();
DRAWITEMSTRUCT dis;
dis.CtlType=ODT_LISTVIEW;
dis.CtlID=GetDlgCtrlID();
dis.itemID=nItem;
dis.itemAction=ODA_DRAWENTIRE;
dis.itemState=ODS_DEFAULT;
dis.hwndItem=GetSafeHwnd();
dis.hDC=dc;
dis.rcItem=rectItem;
dis.itemData=(DWORD)0;
// use DawItem to create drag image
DrawItem(&dis);
CBitmap bitmapImageText;
VERIFY(bitmapImageText.CreateCompatibleBitmap(&dcClient,rectImageText.Width(),
rectImageText.Height()));
CBitmap* pOldCopyBitmap=dcCopy.SelectObject(&bitmapImageText);
dcCopy.BitBlt(0,0,rectImageText.Width(),rectImageText.Height(),
&dc,rectImageText.left,rectImageText.top,SRCCOPY);
if(pOldCopyBitmap)
dcCopy.SelectObject(pOldCopyBitmap);
if(pOldBitmap)
dc.SelectObject(pOldBitmap);
VERIFY(m_pDragImageList->Add(&bitmapImageText,GetBkColor())!=-1);
m_bCreatingDragImage=FALSE;
return m_pDragImageList;
}
void COXSHBListCtrl::StartScrolling(BOOL bScrollingUp)
{
if(m_bScrollingUp || m_bScrollingDown)
StopScrolling();
ASSERT(m_nScrollTimerID==0);
ASSERT(!m_bScrollingUp && !m_bScrollingDown);
ASSERT(GetItemCount()>0);
int nOldSelectedItem=SelectItem(-1);
if(nOldSelectedItem!=-1)
Update(nOldSelectedItem);
CRect rectClient;
GetClientRect(rectClient);
// deflate the client rectangle to match the valid area where we can
// display items
rectClient.DeflateRect(ID_EDGELEFTMARGIN,ID_EDGETOPMARGIN,ID_EDGERIGHTMARGIN,
ID_EDGEBOTTOMMARGIN);
ASSERT(rectClient.top<rectClient.bottom);
// if any drag'n'drop operation is active and the control has launched it
// then we need to apply some additional effort to redraw things smoothly
if(m_bDragDropOperation && (GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0 &&
m_bDragDropOwner)
{
ASSERT(m_pDragImage);
// unlock window updates
VERIFY(m_pDragImage->DragShowNolock(FALSE));
}
if(bScrollingUp)
{
m_bScrollingUp=TRUE;
RedrawWindow(m_rectTopScrollButton);
if(!m_bDragDropOperation)
{
// scroll up once
CRect rect;
int nItem=GetTopIndex();
if(nItem==-1)
nItem=GetItemCount()-1;
else
{
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
if(m_ptOrigin.y+rectClient.top<=rect.top)
{
ASSERT(nItem>0);
nItem--;
}
}
ASSERT((nItem>=0 && nItem<GetItemCount()));
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
int nOffset=rect.top-rectClient.top-m_ptOrigin.y;
Scroll(CSize(0,nOffset));
}
}
else
{
m_bScrollingDown=TRUE;
RedrawWindow(m_rectBottomScrollButton);
if(!m_bDragDropOperation)
{
// scroll down once
CRect rect;
int nItem=GetTopIndex();
ASSERT(nItem>=0 && nItem<GetItemCount());
if(nItem==GetItemCount()-1)
{
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
int nOffset=rect.bottom-rectClient.bottom-m_ptOrigin.y;
Scroll(CSize(0,nOffset));
}
else
{
nItem++;
VERIFY(m_mapItemToBoundRect.Lookup(nItem,rect));
int nOffset=rect.top-rectClient.top-m_ptOrigin.y;
Scroll(CSize(0,nOffset));
}
}
}
if(m_bDragDropOperation && (GetBarStyle()&SHBS_DRAWITEMDRAGIMAGE)!=0 &&
m_bDragDropOwner)
{
ASSERT(m_pDragImage);
// lock window updates
VERIFY(m_pDragImage->DragShowNolock(TRUE));
}
// set timer
//
UINT nDelay=(m_bAutoScrolling ? GetAutoScrollingDelay() : GetScrollingDelay());
// adjustment for drag'n'drop operation
if(m_bDragDropOperation)
nDelay/=4;
m_nScrollTimerID=SetTimer(ID_SCROLLINGTIMER,nDelay,NULL);
ASSERT(m_nScrollTimerID!=0);
}
void COXSHBListCtrl::StopScrolling()
{
ASSERT(m_nScrollTimerID!=0);
// kill timer
KillTimer(m_nScrollTimerID);
m_nScrollTimerID=0;
// redraw scroll buttons
//
if(!m_rectTopScrollButton.IsRectEmpty())
RedrawWindow(m_rectTopScrollButton);
if(!m_rectBottomScrollButton.IsRectEmpty())
RedrawWindow(m_rectBottomScrollButton);
m_bScrollingUp=FALSE;
m_bScrollingDown=FALSE;
m_bAutoScrolling=FALSE;
}
BOOL COXSHBListCtrl::InitListControl()
{
ASSERT(::IsWindow(GetSafeHwnd()));
// create edit control used to edit header text
if(!CreateEditControl())
{
TRACE(_T("COXSHBListCtrl::InitListControl: failed to create edit control"));
return FALSE;
}
// tooltips is always enabled
EnableToolTips(TRUE);
// register OLE Drag'n'Drop
COleDropTarget* pOleDropTarget=GetDropTarget();
ASSERT(pOleDropTarget!=NULL);
if(!pOleDropTarget->Register(this))
{
TRACE(_T("COXSHBListCtrl::InitListControl: failed to register the control with COleDropTarget\n"));
TRACE(_T("COXSHBListCtrl: you've probably forgot to initialize OLE libraries using AfxOleInit function"));
}
return TRUE;
}
COleDropSource* COXSHBListCtrl::GetDropSource()
{
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_GETDROPSOURCE;
nmshb.hGroup=m_hGroup;
nmshb.lParam=(LPARAM)NULL;
COleDropSource* pOleDropSource=NULL;
// check if parent want to set its own drop target object
if(SendSHBNotification(&nmshb) && nmshb.lParam!=NULL)
pOleDropSource=(COleDropSource*)nmshb.lParam;
else
{
// we have to call this function, otherwise assertions will happen all
// the time COXSHBDropSource specific message will be fired
m_oleDropSource.SetOwner(this);
pOleDropSource=&m_oleDropSource;
}
ASSERT(pOleDropSource!=NULL);
return pOleDropSource;
}
COleDropTarget* COXSHBListCtrl::GetDropTarget()
{
// In the case this control was created as a child window
// of shortcut bar group fill structure for notification of
// parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_GETDROPTARGET;
nmshb.hGroup=m_hGroup;
nmshb.lParam=(LPARAM)NULL;
COleDropTarget* pOleDropTarget=NULL;
// check if parent want to set its own drop target object
if(SendSHBNotification(&nmshb) && nmshb.lParam!=NULL)
pOleDropTarget=(COleDropTarget*)nmshb.lParam;
else
pOleDropTarget=(COleDropTarget*)&m_oleDropTarget;
ASSERT(pOleDropTarget!=NULL);
return pOleDropTarget;
}
CRect COXSHBListCtrl::GetGapBetweenItems(int nItemBefore)
{
ASSERT(nItemBefore>=0 && nItemBefore<=GetItemCount());
// returns the gap before nItemBefore item
//
CRect rect;
GetClientRect(rect);
// if the requested gap is between top border and top item or
// bottom border and bottom item
if(nItemBefore==GetItemCount() || nItemBefore==0)
{
if(GetItemCount()==0 || nItemBefore==0)
rect.bottom=rect.top+ID_EDGETOPMARGIN;
else
{
CRect rectItem;
VERIFY(GetItemRect(nItemBefore-1,rectItem,SHBLC_ENTIREITEM));
rect.top=rectItem.bottom+m_ptOrigin.y;
rect.bottom=rect.top+ID_EDGEBOTTOMMARGIN;
}
}
// if the requested gap is between items
else
{
CRect rectItem;
VERIFY(GetItemRect(nItemBefore,rectItem,SHBLC_ENTIREITEM));
rect.bottom=rectItem.top+m_ptOrigin.y;
rect.top=rect.bottom-ID_ITEMMARGIN;
}
return rect;
}
CRect COXSHBListCtrl::GetPlaceHolderRect(int nItemBefore)
{
ASSERT(nItemBefore>=0 && nItemBefore<=GetItemCount());
// place holder rectangle must lay around or within the gap between items
CRect rect=GetGapBetweenItems(nItemBefore);
rect-=m_ptOrigin;
// if the requested place holder is between top border and top item or
// bottom border and bottom item
if(nItemBefore==GetItemCount() || nItemBefore==0)
{
if(GetItemCount()==0 || nItemBefore==0)
rect.bottom=rect.top+2*ID_HEIGHTPLACEHOLDER/3;
else
rect.top=rect.bottom-2*ID_HEIGHTPLACEHOLDER/3;
}
// if the requested place holder is between items
else
{
int nGapHeight=rect.Height();
rect.bottom+=ID_HEIGHTPLACEHOLDER/2+ID_HEIGHTPLACEHOLDER%2-nGapHeight/2;
rect.top-=ID_HEIGHTPLACEHOLDER/2-nGapHeight/2;
}
return rect;
}
int COXSHBListCtrl::GetItemImage(const int nItem)
{
ASSERT(nItem>=0 && nItem<GetItemCount());
// image list used to display item depends on type of view
int nView=GetView();
// get corresponding item list to show items
CImageList* pil=NULL;
if(nView==SHB_LARGEICON)
pil=GetImageList(LVSIL_NORMAL);
else if(nView==SHB_SMALLICON)
pil=GetImageList(LVSIL_SMALL);
// if there is no any image list associated with the control then always return -1
if(pil==NULL)
return -1;
LV_ITEM lvi;
lvi.mask=LVIF_IMAGE;
lvi.iItem=nItem;
lvi.iSubItem=0;
VERIFY(GetItem(&lvi));
if(lvi.iImage<pil->GetImageCount())
return lvi.iImage;
else
return -1;
}
HRESULT COXSHBListCtrl::GetComCtlVersion(LPDWORD pdwMajor, LPDWORD pdwMinor)
{
if(IsBadWritePtr(pdwMajor, sizeof(DWORD)) ||
IsBadWritePtr(pdwMinor, sizeof(DWORD)))
{
return E_INVALIDARG;
}
// get handle of the common control DLL
BOOL bAlreadyLoaded=TRUE;
HINSTANCE hComCtl=::GetModuleHandle(_T("comctl32.dll"));
if(hComCtl==NULL)
{
// load the DLL
hComCtl=::LoadLibrary(_T("comctl32.dll"));
bAlreadyLoaded=FALSE;
}
if(hComCtl)
{
HRESULT hr=S_OK;
DLLGETVERSIONPROC pDllGetVersion;
/*
You must get this function explicitly because earlier versions of the DLL
don't implement this function. That makes the lack of implementation of the
function a version marker in itself.
*/
pDllGetVersion=(DLLGETVERSIONPROC)GetProcAddress(hComCtl, "DllGetVersion");
if(pDllGetVersion)
{
DLLVERSIONINFO dvi;
ZeroMemory(&dvi, sizeof(dvi));
dvi.cbSize=sizeof(dvi);
hr = (*pDllGetVersion)(&dvi);
if(SUCCEEDED(hr))
{
*pdwMajor = dvi.dwMajorVersion;
*pdwMinor = dvi.dwMinorVersion;
}
else
{
hr = E_FAIL;
}
}
else
{
// If GetProcAddress failed, then the DLL is a version previous
// to the one shipped with IE 3.x.
*pdwMajor = 4;
*pdwMinor = 0;
}
if(!bAlreadyLoaded)
::FreeLibrary(hComCtl);
return hr;
}
return E_FAIL;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// COXShortcutBar
IMPLEMENT_DYNCREATE(COXShortcutBar, CWnd)
COXShortcutBar::COXShortcutBar()
{
m_pImageList=NULL;
m_hDropHilightGroup=NULL;
m_hExpandedGroup=NULL;
m_hEditGroup=NULL;
m_hHotGroup=NULL;
m_hPressedGroup=NULL;
m_hDragGroup=NULL;
m_pShortcutBarSkin = NULL;
m_nSortOrder=0;
m_dwBarStyle=0;
m_rectChildWnd.SetRectEmpty();
m_nLastHandle=0;
// create default font used to draw text in headers
if((HFONT)m_fontDefault==NULL)
{
if(!m_fontDefault.CreateFont(
-11,0,0,0,FW_REGULAR,0,0,0,0,0,0,0,0,_T("MS Sans Serif")))
{
TRACE(_T("COXShortcutBar::COXShortcutBar: failed to create default font"));
ASSERT(FALSE);
AfxThrowMemoryException();
}
}
m_bCreatingDragImage=FALSE;
m_pDragImage=NULL;
m_nGroupMargin=DFLT_GROUPMARGIN;
m_rectChildWndMargins=CRect(DFLT_LEFTMARGIN,DFLT_TOPMARGIN,
DFLT_RIGHTMARGIN,DFLT_BOTTOMMARGIN);
m_sizeMin=CSize(DFLT_MINWIDTH,DFLT_MINHEIGHT);
m_sizeScrollButton=CSize(DFLT_SCROLLBUTTONWIDTH,DFLT_SCROLLBUTTONHEIGHT);
m_nScrollingDelay=DFLT_SCROLLINGDELAY;
m_nAutoScrollingDelay=DFLT_AUTOSCROLLINGDELAY;
m_nAutoExpandDelay=DFLT_WAITFORAUTOEXPAND;
m_nWaitForDragHeaderID=0;
m_hSuspectDragGroup=NULL;
m_nWaitForAutoExpandID=0;
m_hSuspectAutoExpandGroup=NULL;
m_nCheckMouseIsOverGroupID=0;
m_hLastMouseIsOverGroup=NULL;
}
COXShortcutBar::~COXShortcutBar()
{
HSHBGROUP hGroup;
// if window is not destroyed yet then dlete all groups in the way the parent
// window will get notification
if(::IsWindow(GetSafeHwnd()))
VERIFY(DeleteAllGroups());
// delete all SHB_DESCRIPTOR structures we allocated
LPSHB_DESCRIPTOR pDescriptor;
// v9.3 - update 03 - 64-bit - switch param type - TD
#ifdef _WIN64
INT_PTR nOrder;
#else
int nOrder;
#endif
POSITION pos=m_mapDescriptors.GetStartPosition();
while(pos!=NULL)
{
m_mapDescriptors.GetNextAssoc(pos,pDescriptor,nOrder);
ASSERT(pDescriptor!=NULL);
delete pDescriptor;
}
m_mapDescriptors.RemoveAll();
// delete all SHB_GROUPINFO structures we allocated
LPSHB_GROUPINFO pGroupInfo;
pos=m_mapHandleToInfo.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToInfo.GetNextAssoc(pos,hGroup,pGroupInfo);
ASSERT(hGroup!=NULL);
ASSERT(pGroupInfo!=NULL);
delete pGroupInfo;
}
m_mapHandleToInfo.RemoveAll();
// delete all COXSHBListCtrl controls we created
COXSHBListCtrl* pListCtrl;
pos=m_mapHandleToListCtrl.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToListCtrl.GetNextAssoc(pos,hGroup,pListCtrl);
ASSERT(hGroup!=NULL);
ASSERT(pListCtrl!=NULL);
ASSERT_VALID(pListCtrl);
delete pListCtrl;
}
m_mapHandleToListCtrl.RemoveAll();
// clean up map of all bound rectangles
m_mapHandleToBoundRect.RemoveAll();
// dlete drag image if any was created
delete m_pDragImage;
// destroy window if it hasn't been destroyed yet
if(::IsWindow(GetSafeHwnd()))
{
DestroyWindow();
}
if (m_pShortcutBarSkin != NULL)
delete m_pShortcutBarSkin;
}
BEGIN_MESSAGE_MAP(COXShortcutBar, CWnd)
//{{AFX_MSG_MAP(COXShortcutBar)
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONDOWN()
ON_WM_CONTEXTMENU()
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_ERASEBKGND()
ON_WM_NCHITTEST()
ON_WM_LBUTTONUP()
ON_WM_DESTROY()
ON_WM_TIMER()
//}}AFX_MSG_MAP
ON_NOTIFY_EX(TTN_NEEDTEXTA, 0, OnHeaderToolTip)
ON_NOTIFY_EX(TTN_NEEDTEXTW, 0, OnHeaderToolTip)
ON_NOTIFY(SHBEN_FINISHEDIT, SHB_IDCEDIT, OnChangeGroupHeaderText)
ON_MESSAGE(SHBDTM_DRAGOVER, OnDragOver)
ON_MESSAGE(SHBDTM_DRAGLEAVE, OnDragLeave)
ON_COMMAND(SHB_IDMLARGEICON, OnLargeIcon)
ON_COMMAND(SHB_IDMSMALLICON, OnSmallIcon)
ON_COMMAND(SHB_IDMADDNEWGROUP, OnAddNewGroup)
ON_COMMAND(SHB_IDMREMOVEGROUP, OnRemoveGroup)
ON_COMMAND(SHB_IDMRENAMEGROUP, OnRenameGroup)
ON_COMMAND(SHBLC_IDMREMOVEITEM, OnRemoveLCItem)
ON_COMMAND(SHBLC_IDMRENAMEITEM, OnRenameLCItem)
ON_UPDATE_COMMAND_UI(SHB_IDMLARGEICON, OnUpdateLargeIcon)
ON_UPDATE_COMMAND_UI(SHB_IDMSMALLICON, OnUpdateSmallIcon)
END_MESSAGE_MAP()
BOOL COXShortcutBar::Create(CWnd* pParentWnd, const RECT& rect,
DWORD dwBarStyle/* = SHBS_EDITHEADERS|SHBS_EDITITEMS|
SHBS_DISABLEDRAGDROPITEM|SHBS_DISABLEDRAGDROPHEADER*/,
UINT nID/* = 0xffff*/,
DWORD dwStyle/* = WS_CHILD|WS_VISIBLE*/,
DWORD dwExStyle/* = 0*/)
{
// create our own window class
WNDCLASS wndClass;
wndClass.style=CS_DBLCLKS;
wndClass.lpfnWndProc=AfxWndProc;
wndClass.cbClsExtra=0;
wndClass.cbWndExtra=0;
wndClass.hInstance=AfxGetInstanceHandle();
wndClass.hIcon=NULL;
wndClass.hCursor=::LoadCursor(NULL,IDC_ARROW);
wndClass.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
wndClass.lpszMenuName=NULL;
wndClass.lpszClassName=_T("OXShortcutBar");
if(!AfxRegisterClass(&wndClass))
{
TRACE(_T("COXShortcutBar::Create: failed to register shortcut bar window class"));
return FALSE;
}
// force WS_CHILD style
dwStyle|=WS_CHILD;
// create window
if(!CWnd::CreateEx(
dwExStyle,wndClass.lpszClassName,_T(""),dwStyle,rect,pParentWnd,nID,NULL))
{
TRACE(_T("COXShortcutBar::Create: failed to create the shortcut bar control\n"));
return FALSE;
}
// set Shortcut bar specific style
if(!SetBarStyle(dwBarStyle))
{
return FALSE;
}
// initialize shortcut bar
if(!InitShortcutBar())
{
TRACE(_T("COXShortcutBar::Create: failed to initialize the shortcut bar"));
return FALSE;
}
return TRUE;
}
// v9.3 - update 03 - 64-bit - using OXINTRET here
OXINTRET COXShortcutBar::OnToolHitTest(CPoint point, TOOLINFO* pTI) const
{
ASSERT_VALID(this);
ASSERT(::IsWindow(GetSafeHwnd()));
// the control should be designated to provide tooltips
if((GetBarStyle()&SHBS_INFOTIP)==0)
return -1;
int nHit=-1;
// now hit test against COXSHBListCtrl items
UINT nHitFlags;
HSHBGROUP hGroup=HitTest(point,&nHitFlags);
if(nHitFlags!=SHB_ONHEADER)
hGroup=NULL;
if(hGroup!=NULL && pTI!= NULL)
{
#if _MFC_VER<=0x0421
if(pTI->cbSize>=sizeof(TOOLINFO))
return nHit;
#endif
pTI->hwnd=GetSafeHwnd();
CRect rect;
VERIFY(GetGroupHeaderRect(hGroup,rect));
pTI->rect=rect;
//
pTI->uId=(UINT)PtrToUint(hGroup);
// set text to LPSTR_TEXTCALLBACK in order to get TTN_NEEDTEXT message when
// it's time to display tool tip
pTI->lpszText=LPSTR_TEXTCALLBACK;
// return found group handle
nHit=(int)PtrToInt(hGroup);
}
return nHit;
}
BOOL COXShortcutBar::OnCmdMsg(UINT nID, int nCode, void* pExtra,
AFX_CMDHANDLERINFO* pHandlerInfo)
{
// TODO: Add your specialized code here and/or call the base class
ASSERT(::IsWindow(GetSafeHwnd()));
// pump through parent
CWnd* pParentWnd=GetParent();
if(pParentWnd!=NULL && !pParentWnd->IsKindOf(RUNTIME_CLASS(COXShortcutBar)) &&
pParentWnd->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
{
return TRUE;
}
// then pump through itself
if (CWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
{
return TRUE;
}
// pump through child window of expanded group
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup!=NULL)
{
HWND hwndChild=GetGroupChildWndHandle(hGroup);
ASSERT(hwndChild);
CWnd* pChildWnd=CWnd::FromHandle(hwndChild);
if(pChildWnd!=NULL && !pChildWnd->IsKindOf(RUNTIME_CLASS(COXShortcutBar)) &&
pChildWnd->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
{
return TRUE;
}
}
// last but not least, pump through app
CWinApp* pApp=AfxGetApp();
if(pApp!=NULL && pApp->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
{
return TRUE;
}
return FALSE;
}
void COXShortcutBar::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
UINT nHitFlags;
HSHBGROUP hGroup=HitTest(point,&nHitFlags);
// reset handle to the group that is positioned under mouse cursor
SetMouseIsOverGroup((nHitFlags==SHB_ONHEADER ? hGroup : NULL));
// reset pressed group handle
if(m_hPressedGroup!=NULL && !IsLButtonDown())
{
BOOL bFlat=((GetBarStyle() & SHBS_FLATGROUPBUTTON)==SHBS_FLATGROUPBUTTON);
// reset pressed group
HSHBGROUP hOldPressedGroup=m_hPressedGroup;
m_hPressedGroup=NULL;
if(bFlat)
{
// redraw header
UpdateHeader(hOldPressedGroup);
}
}
// if dragging any group
if(GetDragGroup()!=NULL)
{
if(nHitFlags==SHB_ONCHILD)
{
hGroup=NULL;
}
BOOL bDrawDragImage=FALSE;
ASSERT((GetBarStyle()&SHBS_DISABLEDRAGDROPHEADER)==0);
ASSERT((nFlags&MK_LBUTTON)!=0);
// move drag image if needed
if((GetBarStyle()&SHBS_DRAWHEADERDRAGIMAGE)!=0)
{
ASSERT(m_pDragImage);
CPoint ptScreen=point;
ClientToScreen(&ptScreen);
// move the drag image
VERIFY(m_pDragImage->DragMove(ptScreen));
bDrawDragImage=TRUE;
}
// Drag image could be over of one of headers while cursor not. Assuming
// that our drag image width is less or equals to the width of the
// client window of the shortcut bar control
if(hGroup==NULL)
{
CRect rectDragImage;
if((GetBarStyle()&SHBS_DRAWHEADERDRAGIMAGE)!=0)
{
// get drag image bounding rectangle
IMAGEINFO imageInfo;
m_pDragImage->GetImageInfo(0,&imageInfo);
rectDragImage=imageInfo.rcImage;
rectDragImage-=rectDragImage.TopLeft();
// get client coordinate of drag image bounding rectangle
CPoint ptTopLeft=point;
ptTopLeft-=m_ptDragImage;
rectDragImage+=ptTopLeft;
}
else
{
VERIFY(GetGroupHeaderRect(GetDragGroup(),rectDragImage));
}
CRect rect;
GetClientRect(rect);
CRect rectIntersect;
// check if make sense to search for intersection
if(rectIntersect.IntersectRect(rect,rectDragImage))
{
rectIntersect.IntersectRect(m_rectChildWnd,rectDragImage);
if(!(rectIntersect==rectDragImage))
{
int nMaxSpace=0;
HSHBGROUP hSuspectGroup;
POSITION pos=m_mapHandleToBoundRect.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToBoundRect.
GetNextAssoc(pos,hSuspectGroup,rect);
if(rectIntersect.IntersectRect(rect,rectDragImage) &&
rectIntersect.Width()*rectIntersect.Height()>nMaxSpace)
{
hGroup=hSuspectGroup;
nMaxSpace=rectIntersect.Width()*rectIntersect.Height();
}
}
}
}
}
// set drop target group
HSHBGROUP hOldDropHilightGroup=SetDropTargetGroup(hGroup);
BOOL bRedrawOldDropTarget=((hGroup!=hOldDropHilightGroup) &
(GetDragGroup()!=hOldDropHilightGroup) & (hOldDropHilightGroup!=NULL));
BOOL bRedrawNewDropTarget=((hGroup!=hOldDropHilightGroup) &
(GetDragGroup()!=hGroup) & (hGroup!=NULL));
BOOL bUnlock=bDrawDragImage && (bRedrawOldDropTarget || bRedrawNewDropTarget);
if(bUnlock)
{
// unlock window updates
VERIFY(m_pDragImage->DragShowNolock(FALSE));
}
// redraw affected headers
if(bRedrawOldDropTarget)
{
UpdateHeader(hOldDropHilightGroup);
}
if(bRedrawNewDropTarget)
{
UpdateHeader(hGroup);
}
// set corresponding cursor
if(hGroup==NULL || hGroup==GetDragGroup())
{
SetCursor(LoadCursor(NULL,IDC_NO));
}
else
{
SetCursor(LoadCursor(NULL,IDC_ARROW));
}
if(bUnlock)
{
// lock window updates
VERIFY(m_pDragImage->DragShowNolock(TRUE));
}
}
// about to drag the group
else if(nHitFlags==SHB_ONHEADER && m_nWaitForDragHeaderID==0 &&
IsLButtonDown() && hGroup==m_hSuspectDragGroup && hGroup!=NULL)
{
if((GetBarStyle()&SHBS_DISABLEDRAGDROPHEADER)==0)
{
// there shouldn't be any group currently being dragged
ASSERT(GetDragGroup()==NULL);
// create drag image and start dragging
if((GetBarStyle() & SHBS_DRAWHEADERDRAGIMAGE)!=0)
{
// delete previously created drag image
if(m_pDragImage)
{
delete m_pDragImage;
m_pDragImage=NULL;
}
m_pDragImage=CreateGroupDragImage(hGroup);
ASSERT(m_pDragImage);
// changes the cursor to the drag image
VERIFY(m_pDragImage->BeginDrag(0,m_ptDragImage));
CPoint ptScreen=point;
ClientToScreen(&ptScreen);
VERIFY(m_pDragImage->DragEnter(GetDesktopWindow(),ptScreen));
// unlock window updates
VERIFY(m_pDragImage->DragShowNolock(FALSE));
}
// capture all mouse messages
SetCapture();
// assign group being dragged
SetDragGroup(hGroup);
// redraw dragged group header
UpdateHeader(hGroup);
if((GetBarStyle()&SHBS_DRAWHEADERDRAGIMAGE)!=0)
{
// lock window updates
VERIFY(m_pDragImage->DragShowNolock(TRUE));
}
}
}
// about to auto expand the collapsed group
else if(m_nWaitForDragHeaderID==0 && !IsLButtonDown() && hGroup!=NULL &&
hGroup!=GetExpandedGroup() && (GetBarStyle()&SHBS_AUTOEXPAND)!=0 &&
GetEditGroup()==NULL)
{
if(m_hSuspectAutoExpandGroup!=hGroup || nHitFlags!=SHB_ONHEADER)
{
// kill timer
if(m_nWaitForAutoExpandID!=0)
{
ASSERT(m_hSuspectAutoExpandGroup!=NULL);
KillTimer(m_nWaitForAutoExpandID);
m_nWaitForAutoExpandID=0;
m_hSuspectAutoExpandGroup=NULL;
}
else
{
ASSERT(m_hSuspectAutoExpandGroup==NULL);
}
}
if(m_hSuspectAutoExpandGroup!=hGroup && nHitFlags==SHB_ONHEADER)
{
ASSERT(m_hSuspectAutoExpandGroup==NULL);
m_hSuspectAutoExpandGroup=hGroup;
// set timer
m_nWaitForAutoExpandID=SetTimer(
ID_WAITFORAUTOEXPANDTIMER,GetAutoExpandDelay(),NULL);
ASSERT(m_nWaitForAutoExpandID!=0);
}
}
CWnd::OnMouseMove(nFlags, point);
}
void COXShortcutBar::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
VERIFY(m_mapHandleToBoundRect.GetCount()==m_mapHandleToInfo.GetCount());
UINT nHitFlags;
HSHBGROUP hGroup=HitTest(point,&nHitFlags);
if(nHitFlags==SHB_ONHEADER)
{
BOOL bFlat=((GetBarStyle() & SHBS_FLATGROUPBUTTON)==SHBS_FLATGROUPBUTTON);
// user clicked on header
//
ASSERT(hGroup!=NULL);
ASSERT(m_hPressedGroup==NULL);
m_hPressedGroup=hGroup;
if(bFlat)
{
UpdateHeader(m_hPressedGroup);
}
else
{
ExpandGroup(hGroup);
}
// group drag'n'drop
if((GetBarStyle() & SHBS_DISABLEDRAGDROPHEADER)==0)
{
// in result of group expanding the header cordinates could have changed
HSHBGROUP hSuspectGroup=HitTest(point,&nHitFlags);
if(nHitFlags==SHB_ONHEADER && hSuspectGroup==hGroup)
{
// kill timer
if(m_nWaitForDragHeaderID!=0)
{
KillTimer(m_nWaitForDragHeaderID);
m_nWaitForDragHeaderID=0;
}
// set timer
m_nWaitForDragHeaderID=SetTimer(
ID_WAITFORDRAGHEADERTIMER,DFLT_WAITFORDRAGHEADER,NULL);
ASSERT(m_nWaitForDragHeaderID!=0);
// set the group as a suspect for drag'n'drop operation
m_hSuspectDragGroup=hGroup;
// define the point of hot spot on future drag image
if((GetBarStyle()&SHBS_DRAWHEADERDRAGIMAGE)!=0)
{
CRect rectHeader;
VERIFY(GetGroupHeaderRect(hGroup,&rectHeader));
m_ptDragImage=point;
ASSERT(rectHeader.PtInRect(m_ptDragImage));
m_ptDragImage-=rectHeader.TopLeft();
}
}
}
}
CWnd::OnLButtonDown(nFlags, point);
}
void COXShortcutBar::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
// if dragging any group
if(GetDragGroup()!=NULL)
{
if((GetBarStyle()&SHBS_DRAWHEADERDRAGIMAGE)!=0)
{
ASSERT(m_pDragImage!=NULL);
// end dragging
VERIFY(m_pDragImage->DragLeave(GetDesktopWindow()));
m_pDragImage->EndDrag();
}
// reset drag group
HSHBGROUP hOldDragGroup=SetDragGroup(NULL);
ASSERT(hOldDragGroup!=NULL);
HSHBGROUP hOldDropTargetGroup=SetDropTargetGroup(NULL);
if(hOldDropTargetGroup!=NULL)
{
// notify parent
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DROPGROUP;
nmshb.hGroup=hOldDragGroup;
nmshb.lParam=(LPARAM)hOldDropTargetGroup;
if(!SendSHBNotification(&nmshb))
{
// all the corresponding actions
//
// reodering of drag and drop target items
int nOrder=GetGroupOrder(hOldDropTargetGroup);
ASSERT(nOrder>=0 && nOrder<GetGroupCount());
VERIFY(SetGroupOrder(hOldDragGroup,nOrder));
RedrawBar();
}
else
{
UpdateHeader(hOldDropTargetGroup);
UpdateHeader(hOldDragGroup);
}
}
else
{
UpdateHeader(hOldDragGroup);
}
if(::GetCapture()==GetSafeHwnd())
{
// stop intercepting all mouse messages
::ReleaseCapture();
}
}
else if(m_hPressedGroup!=NULL)
{
BOOL bFlat=((GetBarStyle() & SHBS_FLATGROUPBUTTON)==SHBS_FLATGROUPBUTTON);
// reset pressed group
HSHBGROUP hOldPressedGroup=m_hPressedGroup;
m_hPressedGroup=NULL;
if(bFlat)
{
UINT nHitFlags;
HSHBGROUP hGroup=HitTest(point,&nHitFlags);
if(nHitFlags==SHB_ONHEADER && hGroup==hOldPressedGroup)
{
if(GetExpandedGroup()!=hGroup)
{
// expand
ExpandGroup(hGroup);
}
else
{
// redraw header
UpdateHeader(hGroup);
}
}
}
}
CWnd::OnLButtonUp(nFlags, point);
}
void COXShortcutBar::OnContextMenu(CWnd* pWnd, CPoint point)
{
// TODO: Add your message handler code here
UNREFERENCED_PARAMETER(pWnd);
// kill timer for group auto expanding
if(m_nWaitForAutoExpandID!=0)
{
KillTimer(m_nWaitForAutoExpandID);
m_nWaitForAutoExpandID=0;
m_hSuspectAutoExpandGroup=NULL;
}
// create popup menu
//
CMenu menu;
if(menu.CreatePopupMenu())
{
// we populate context menu depending on the place where right click happened
ScreenToClient(&point);
UINT nFlags;
HSHBGROUP hGroup=HitTest(point,&nFlags);
if(nFlags==SHB_ONHEADER)
{
ASSERT(hGroup);
}
else if(nFlags==SHB_ONCHILD)
{
hGroup=GetExpandedGroup();
ASSERT(hGroup);
}
else if(nFlags==SHB_NOWHERE)
{
hGroup=GetExpandedGroup();
}
else
{
ASSERT(FALSE);
}
// assign it as current hot group
m_hHotGroup=hGroup;
ClientToScreen(&point);
// fill in SHBCONTEXTMENU structure to use it in message and notification
SHBCONTEXTMENU shbcm;
shbcm.pMenu=&menu;
shbcm.pShortcutBar=this;
shbcm.hGroup=hGroup;
shbcm.point=point;
// Add New Group item
CString sItem;
VERIFY(sItem.LoadString(IDS_OX_SHB_IDMADDNEWGROUP_TEXT));
if((GetBarStyle()&SHBS_EDITHEADERS)!=0)
{
menu.AppendMenu(MF_STRING,SHB_IDMADDNEWGROUP,sItem);
}
// if any group exist
if(hGroup)
{
VERIFY(sItem.LoadString(IDS_OX_SHB_IDMLARGEICON_TEXT));
// view type items
if((GetBarStyle()&SHBS_EDITHEADERS)!=0)
{
menu.AppendMenu(MF_SEPARATOR);
}
menu.AppendMenu(MF_STRING|MF_CHECKED,SHB_IDMLARGEICON,sItem);
VERIFY(sItem.LoadString(IDS_OX_SHB_IDMSMALLICON_TEXT));
menu.AppendMenu(MF_STRING|MF_CHECKED,SHB_IDMSMALLICON,sItem);
if((GetBarStyle()&SHBS_EDITHEADERS)!=0)
{
menu.AppendMenu(MF_SEPARATOR);
// remove/rename group
VERIFY(sItem.LoadString(IDS_OX_SHB_IDMREMOVEGROUP_TEXT));
menu.AppendMenu(MF_STRING,SHB_IDMREMOVEGROUP,sItem);
VERIFY(sItem.LoadString(IDS_OX_SHB_IDMRENAMEGROUP_TEXT));
menu.AppendMenu(MF_STRING,SHB_IDMRENAMEGROUP,sItem);
}
// check/uncheck view type menu items
HSHBGROUP hExpandedGroup=GetExpandedGroup();
if(hExpandedGroup)
{
int nView=GetGroupView(hExpandedGroup);
menu.CheckMenuItem(SHB_IDMLARGEICON,MF_BYCOMMAND|
((nView==SHB_LARGEICON) ? MF_CHECKED : MF_UNCHECKED));
menu.CheckMenuItem(SHB_IDMSMALLICON,MF_BYCOMMAND|
((nView==SHB_LARGEICON) ? MF_UNCHECKED : MF_CHECKED));
}
// if right click was over child window the we have to give it a chance to
// populate context menu with its items
if(nFlags==SHB_ONCHILD)
{
ASSERT(hGroup==hExpandedGroup);
HWND hWnd=GetGroupChildWndHandle(hGroup);
ASSERT(hWnd);
::SendMessage(hWnd,SHBM_POPULATECONTEXTMENU,
(WPARAM)0,(LPARAM)&shbcm);
}
}
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_CONTEXTMENU;
nmshb.hGroup=hGroup;
nmshb.lParam=(LPARAM)(&shbcm);
// if parent didn't reject to display menu then do that
if(!SendSHBNotification(&nmshb) && menu.GetMenuItemCount()>0)
{
menu.TrackPopupMenu(
TPM_LEFTALIGN|TPM_LEFTBUTTON,point.x,point.y, this);
}
}
menu.DestroyMenu();
}
void COXShortcutBar::PreSubclassWindow()
{
// TODO: Add your specialized code here and/or call the base class
_AFX_THREAD_STATE* pThreadState=AfxGetThreadState();
// hook not already in progress
if(pThreadState->m_pWndInit==NULL)
{
// set default shortcut bar style
m_dwBarStyle=SHBS_EDITHEADERS|SHBS_EDITITEMS|
SHBS_DISABLEDRAGDROPITEM|SHBS_DISABLEDRAGDROPHEADER;
DWORD dwStyle=GetStyle();
// check if subclassed window has WS_CHILD style
VERIFY((dwStyle & WS_CHILD)==WS_CHILD);
if(!InitShortcutBar())
{
TRACE(_T("COXShortcutBar::PreSubclassWindow: failed to initialize shortcut bar\n"));
}
}
CWnd::PreSubclassWindow();
}
void COXShortcutBar::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
CRect rect;
GetClientRect(rect);
// Save DC
int nSavedDC=dc.SaveDC();
ASSERT(nSavedDC);
// Set clipping region
dc.IntersectClipRect(rect);
if(!m_rectChildWnd.IsRectEmpty())
{
dc.ExcludeClipRect(m_rectChildWnd);
}
// fill background with expanded group color
FillBackground(&dc);
int nCount= PtrToInt(GetGroupCount());
VERIFY(m_mapHandleToBoundRect.GetCount()==nCount);
HSHBGROUP hGroup;
// draw group headers one after another
for(int nIndex=0; nIndex<nCount; nIndex++)
{
hGroup=FindGroupByOrder(nIndex);
VERIFY(hGroup!=NULL);
VERIFY(m_mapHandleToBoundRect.Lookup(hGroup,rect));
// draw header only if it's visible
if(dc.RectVisible(&rect))
{
CRect rectHeader=rect;
rectHeader-=rect.TopLeft();
CDC dcCompatible;
if(!dcCompatible.CreateCompatibleDC(&dc))
{
TRACE(_T("COXShortcutBar::OnPaint:Failed to create compatible DC\n"));
return;
}
CBitmap bitmap;
if(!bitmap.CreateCompatibleBitmap(&dc, rectHeader.Width(),
rectHeader.Height()))
{
TRACE(_T("COXShortcutBar::OnPaint:Failed to create compatible bitmap\n"));
return;
}
CBitmap* pOldBitmap=dcCompatible.SelectObject(&bitmap);
// fill standard DRAWITEMSTRUCT to send it to DrawHeader function
//
DRAWITEMSTRUCT dis;
dis.CtlType=0;
dis.CtlID=GetDlgCtrlID();
dis.itemID=(UINT) PtrToUint(hGroup);
dis.itemAction=ODA_DRAWENTIRE;
dis.itemState=ODS_DEFAULT;
dis.hwndItem=GetSafeHwnd();
dis.hDC=dcCompatible.GetSafeHdc();
dis.rcItem=rectHeader;
dis.itemData=(DWORD)PtrToUlong(hGroup);
DrawHeader(&dis);
dc.BitBlt(rect.left, rect.top, rect.Width(),
rect.Height(), &dcCompatible, 0, 0, SRCCOPY);
if(pOldBitmap)
{
dcCompatible.SelectObject(pOldBitmap);
}
}
}
// Restore dc
dc.RestoreDC(nSavedDC);
// Do not call CWnd::OnPaint() for painting messages
}
void COXShortcutBar::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
// reposition groups
CalculateBoundRects();
// redraw control
RedrawBar();
}
BOOL COXShortcutBar::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
UNREFERENCED_PARAMETER(pDC);
return TRUE;
}
#if _MSC_VER >= 1400
LRESULT COXShortcutBar::OnNcHitTest(CPoint point)
#else
UINT COXShortcutBar::OnNcHitTest(CPoint point)
#endif
{
UNREFERENCED_PARAMETER(point);
return HTCLIENT;
}
void COXShortcutBar::OnDestroy()
{
CWnd::OnDestroy();
// TODO: Add your message handler code here
// just kill timers
if(m_nWaitForDragHeaderID!=0)
{
KillTimer(m_nWaitForDragHeaderID);
}
if(m_nWaitForAutoExpandID!=0)
{
KillTimer(m_nWaitForAutoExpandID);
}
if(m_nCheckMouseIsOverGroupID!=0)
{
KillTimer(m_nCheckMouseIsOverGroupID);
}
}
// v9.3 - update 03 - 64-bit - using OXTPARAM here - see UTB64Bit.h
void COXShortcutBar::OnTimer(OXTPARAM nIDEvent)
{
// TODO: Add your message handler code here and/or call default
// reset pressed group handle
if(m_hPressedGroup!=NULL && !IsLButtonDown())
{
BOOL bFlat=((GetBarStyle() & SHBS_FLATGROUPBUTTON)==SHBS_FLATGROUPBUTTON);
// reset pressed group
HSHBGROUP hOldPressedGroup=m_hPressedGroup;
m_hPressedGroup=NULL;
if(bFlat)
{
// redraw header
UpdateHeader(hOldPressedGroup);
}
}
if(m_nWaitForDragHeaderID==nIDEvent)
{
ASSERT(GetDragGroup()==NULL);
// kill time after time has expired
KillTimer(m_nWaitForDragHeaderID);
m_nWaitForDragHeaderID=0;
}
else if(m_nWaitForAutoExpandID==nIDEvent)
{
ASSERT(m_hSuspectAutoExpandGroup!=NULL);
ASSERT(GetExpandedGroup()!=m_hSuspectAutoExpandGroup);
// kill time after time has expired
KillTimer(m_nWaitForAutoExpandID);
m_nWaitForAutoExpandID=0;
CPoint point;
::GetCursorPos(&point);
ScreenToClient(&point);
// test the current cursor point
UINT nHitFlags;
HSHBGROUP hGroup=HitTest(point,&nHitFlags);
// expand the m_hSuspectAutoExpandGroup group if the mouse is still over it
if(nHitFlags==SHB_ONHEADER && m_hSuspectAutoExpandGroup==hGroup)
{
ExpandGroup(hGroup);
}
else
{
m_hSuspectAutoExpandGroup=NULL;
}
}
else if(m_nCheckMouseIsOverGroupID==nIDEvent)
{
CPoint point;
::GetCursorPos(&point);
ScreenToClient(&point);
// test the current cursor point
UINT nHitFlags;
HSHBGROUP hGroup=HitTest(point,&nHitFlags);
// reset handle to the group that is positioned under mouse cursor
SetMouseIsOverGroup((nHitFlags==SHB_ONHEADER ? hGroup : NULL));
}
else
{
CWnd::OnTimer(nIDEvent);
}
}
BOOL COXShortcutBar::OnHeaderToolTip(UINT id, NMHDR* pNMHDR, LRESULT* pResult)
{
UNREFERENCED_PARAMETER(id);
ASSERT(pNMHDR->code==TTN_NEEDTEXTA || pNMHDR->code==TTN_NEEDTEXTW);
// need to handle both ANSI and UNICODE versions of the message
TOOLTIPTEXTA* pTTTA=(TOOLTIPTEXTA*)pNMHDR;
TOOLTIPTEXTW* pTTTW=(TOOLTIPTEXTW*)pNMHDR;
// idFrom must be the handle to the group
if (pNMHDR->code==TTN_NEEDTEXTA)
ASSERT((pTTTA->uFlags&TTF_IDISHWND)==0);
else
ASSERT((pTTTW->uFlags&TTF_IDISHWND)==0);
SHBINFOTIP shbit;
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_GETHEADERINFOTIP;
nmshb.hGroup=(HSHBGROUP)pNMHDR->idFrom;
nmshb.lParam=(LPARAM)(&shbit);
*pResult=SendSHBNotification(&nmshb);
#ifndef _UNICODE
if(pNMHDR->code==TTN_NEEDTEXTA)
lstrcpyn(pTTTA->szText,shbit.szText,countof(pTTTA->szText));
else
_mbstowcsz(pTTTW->szText,shbit.szText,countof(pTTTW->szText));
#else
if (pNMHDR->code==TTN_NEEDTEXTA)
_wcstombsz(pTTTA->szText,shbit.szText,countof(pTTTA->szText));
else
lstrcpyn(pTTTW->szText,shbit.szText,countof(pTTTW->szText));
#endif
if(pNMHDR->code==TTN_NEEDTEXTA)
{
if(shbit.lpszText==NULL)
pTTTA->lpszText=pTTTA->szText;
else
pTTTA->lpszText=(LPSTR)shbit.lpszText;
pTTTA->hinst=shbit.hinst;
}
else
{
if(shbit.lpszText==NULL)
pTTTW->lpszText=pTTTW->szText;
else
pTTTW->lpszText=(LPWSTR)shbit.lpszText;
pTTTW->hinst=shbit.hinst;
}
return TRUE; // message was handled
}
void COXShortcutBar::OnChangeGroupHeaderText(NMHDR* pNotifyStruct, LRESULT* result)
{
// handle SHBEN_FINISHEDIT notification from COXSHBEdit control
ASSERT(::IsWindow(m_edit.GetSafeHwnd()));
ASSERT(m_hEditGroup);
LPNMSHBEDIT lpNMSHBE=(LPNMSHBEDIT)pNotifyStruct;
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_ENDHEADEREDIT;
nmshb.hGroup=m_hEditGroup;
// if editing wasn't cancelled
if(lpNMSHBE->bOK)
{
// get updated text
CString sText;
m_edit.GetWindowText(sText);
nmshb.lParam=(LPARAM)((LPCTSTR)sText);
if(!SendSHBNotification(&nmshb))
{
// change header text
if(!SetGroupText(m_hEditGroup,sText))
{
TRACE(_T("COXSHBListCtrl::OnChangeGroupHeaderText: failed to set text to item: %s"),sText);
}
else
{
CRect rectHeader;
if(GetGroupHeaderRect(m_hEditGroup,rectHeader))
RedrawWindow(rectHeader);
}
sText.ReleaseBuffer();
}
}
else
{
nmshb.lParam=(LPARAM)((LPCTSTR)GetGroupText(nmshb.hGroup));
SendSHBNotification(&nmshb);
}
m_hEditGroup=NULL;
*result=0;
}
// v9.3 - update 03 - 64-bit - return value was declared as LONG - changed to LRESULT
LRESULT COXShortcutBar::OnDragOver(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if((GetBarStyle()&SHBS_DISABLEDROPITEM)!=0)
{
return (LONG)FALSE;
}
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DRAGOVER;
nmshb.lParam=lParam;
// check if parent of the shortcut bar would like to handle drag'n'drop itself
if(SendSHBNotification(&nmshb))
{
return (LONG)TRUE;
}
// lParam is the pointer to SHBDROPTARGETACTION structure
LPSHBDROPTARGETACTION pSHBDTAction=(LPSHBDROPTARGETACTION)lParam;
ASSERT(pSHBDTAction!=NULL);
ASSERT(pSHBDTAction->pWnd);
ASSERT(pSHBDTAction->pWnd->GetSafeHwnd()==GetSafeHwnd());
// set returned drop effect
pSHBDTAction->result=(LRESULT)DROPEFFECT_NONE;
// we are not dragging any group
ASSERT(GetDragGroup()==NULL);
// and are not waiting for drag any group
ASSERT(m_nWaitForDragHeaderID==0);
// test current cursor position
UINT nHitFlags;
HSHBGROUP hGroup=HitTest(pSHBDTAction->point,&nHitFlags);
if(hGroup!=NULL && hGroup!=GetExpandedGroup())
{
// kill timer for group autoexpanding
if(m_hSuspectAutoExpandGroup!=hGroup || nHitFlags!=SHB_ONHEADER)
{
// kill timer
if(m_nWaitForAutoExpandID!=0)
{
ASSERT(m_hSuspectAutoExpandGroup!=NULL);
KillTimer(m_nWaitForAutoExpandID);
m_nWaitForAutoExpandID=0;
m_hSuspectAutoExpandGroup=NULL;
}
else
{
ASSERT(m_hSuspectAutoExpandGroup==NULL);
}
}
// set timer for group autoexpanding
if(m_hSuspectAutoExpandGroup!=hGroup && nHitFlags==SHB_ONHEADER)
{
ASSERT(m_hSuspectAutoExpandGroup==NULL);
m_hSuspectAutoExpandGroup=hGroup;
// set timer
m_nWaitForAutoExpandID=SetTimer(
ID_WAITFORAUTOEXPANDTIMER,GetAutoExpandDelay()/4,NULL);
ASSERT(m_nWaitForAutoExpandID!=0);
}
}
return (LONG)TRUE;
}
// v9.3 - update 03 - 64-bit - return value was declared as LONG - changed to LRESULT
LRESULT COXShortcutBar::OnDragLeave(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
if((GetBarStyle()&SHBS_DISABLEDROPITEM)!=0)
{
return (LONG)FALSE;
}
// fill structure for notification of parent window of this shortcut bar
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DRAGLEAVE;
nmshb.lParam=lParam;
// check if parent of the shortcut bar would like to handle drag'n'drop itself
if(SendSHBNotification(&nmshb))
{
return (LONG)TRUE;
}
// lParam is the pointer to SHBDROPTARGETACTION structure
LPSHBDROPTARGETACTION pSHBDTAction=(LPSHBDROPTARGETACTION)lParam;
ASSERT(pSHBDTAction!=NULL);
ASSERT(pSHBDTAction->pWnd);
ASSERT(pSHBDTAction->pWnd->GetSafeHwnd()==GetSafeHwnd());
// kill timer
if(m_nWaitForAutoExpandID!=0)
{
ASSERT(m_hSuspectAutoExpandGroup!=NULL);
KillTimer(m_nWaitForAutoExpandID);
m_nWaitForAutoExpandID=0;
m_hSuspectAutoExpandGroup=NULL;
}
return (LONG)TRUE;
}
void COXShortcutBar::OnLargeIcon()
{
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup==NULL)
return;
int nView=GetGroupView(hGroup);
if(nView!=SHB_LARGEICON)
{
// change view in result of selecting context menu item
VERIFY(SetGroupView(hGroup,SHB_LARGEICON));
ShowChildWnd(hGroup);
}
}
void COXShortcutBar::OnSmallIcon()
{
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup==NULL)
return;
int nView=GetGroupView(hGroup);
if(nView!=SHB_SMALLICON)
{
// change view in result of selecting context menu item
VERIFY(SetGroupView(hGroup,SHB_SMALLICON));
ShowChildWnd(hGroup);
}
}
void COXShortcutBar::OnAddNewGroup()
{
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_TEXT;
shbGroup.nTextMax=0;
shbGroup.pszText=_T("");
// add empty group
HSHBGROUP hGroup=InsertGroup(&shbGroup);
if(hGroup!=NULL)
{
if(GetGroupCount()==1)
ExpandGroup(hGroup);
else
{
CalculateBoundRects();
RedrawBar();
}
// edit header
EditGroupHeader(hGroup);
}
}
void COXShortcutBar::OnRemoveGroup()
{
HSHBGROUP hGroup=GetHotGroup();
if(hGroup!=NULL)
{
VERIFY(DeleteGroup(hGroup));
}
}
void COXShortcutBar::OnRenameGroup()
{
HSHBGROUP hGroup=GetHotGroup();
if(hGroup!=NULL)
{
EditGroupHeader(hGroup);
}
}
void COXShortcutBar::OnRemoveLCItem()
{
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup==NULL || GetGroupChildWnd(hGroup)!=NULL)
return;
// remove COXSHBListCtrl item in result of selecting context menu item
//
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
ASSERT(pListCtrl);
ASSERT(::IsWindow(pListCtrl->GetSafeHwnd()));
int nItem=pListCtrl->GetHotItem();
if(nItem==-1)
nItem=pListCtrl->GetLastHotItem();
if(nItem!=-1)
DeleteLCItem(hGroup,nItem);
}
void COXShortcutBar::OnRenameLCItem()
{
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup==NULL || GetGroupChildWnd(hGroup)!=NULL)
return;
// edit COXSHBListCtrl item text in result of selecting context menu item
//
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
ASSERT(pListCtrl);
ASSERT(::IsWindow(pListCtrl->GetSafeHwnd()));
int nItem=pListCtrl->GetHotItem();
if(nItem==-1)
nItem=pListCtrl->GetLastHotItem();
if(nItem!=-1)
{
pListCtrl->EnsureVisible(nItem,FALSE);
EditLCItem(hGroup,nItem);
}
}
// Update handlers
//
void COXShortcutBar::OnUpdateLargeIcon(CCmdUI* pCmdUI)
{
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup==NULL)
return;
int nView=GetGroupView(hGroup);
pCmdUI->SetCheck((nView==SHB_LARGEICON));
}
void COXShortcutBar::OnUpdateSmallIcon(CCmdUI* pCmdUI)
{
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup==NULL)
return;
int nView=GetGroupView(hGroup);
pCmdUI->SetCheck((nView==SHB_SMALLICON));
}
/////////////////////////////////////////////////////////////////////////////
LPSHB_DESCRIPTOR COXShortcutBar::AddDescriptor()
{
ASSERT(::IsWindow(GetSafeHwnd()));
// Internal function to dynamically allocate descriptor structure.
// We keep track of all created descriptors and delete them in destructor
LPSHB_DESCRIPTOR pDescriptor=NULL;
try
{
pDescriptor=new SHB_DESCRIPTOR;
}
catch (CMemoryException* pException)
{
UNREFERENCED_PARAMETER(pException);
TRACE(_T("COXShortcutBar::AddDescriptor: failed to allocate memory for SHB_DESCRIPTOR"));
return NULL;
}
ASSERT(pDescriptor!=NULL);
m_mapDescriptors.SetAt(pDescriptor,m_mapDescriptors.GetCount());
return pDescriptor;
}
void COXShortcutBar::DrawHeader(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
ASSERT(::IsWindow(GetSafeHwnd()));
HSHBGROUP hGroup=(HSHBGROUP)(INT_PTR)lpDrawItemStruct->itemID;
ASSERT(hGroup);
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DRAWHEADER;
nmshb.hGroup=hGroup;
nmshb.lParam=(LPARAM)lpDrawItemStruct;
if(SendSHBNotification(&nmshb))
{
return;
}
GetShortcutBarSkin()->DrawHeader(lpDrawItemStruct, this);
}
/////////////////////////////////////////////////////////////////////////////
BOOL COXShortcutBar::SetBarStyle(DWORD dwBarStyle)
{
if(!VerifyBarStyle(dwBarStyle))
{
return FALSE;
}
m_dwBarStyle=dwBarStyle;
if(::IsWindow(GetSafeHwnd()))
{
// Notify child windows that style have been changed
SendMessageToDescendants(
SHBM_SHBINFOCHANGED,(WPARAM)0,(LPARAM)SHBIF_SHBSTYLE);
}
return TRUE;
}
CImageList* COXShortcutBar::SetImageList(CImageList* pImageList)
{
// it's progammer's responsibility to create and keep image list alive
CImageList* pOldImageList=m_pImageList;
m_pImageList=pImageList;
return pOldImageList;
}
// functions to work with groups
//
BOOL COXShortcutBar::ChildWndIsLC(HSHBGROUP hGroup) const
{
ASSERT(hGroup);
ASSERT(::IsWindow(GetSafeHwnd()));
// we assume child window always exist
//
HWND hwndChild=GetGroupChildWnd(hGroup);
if(hwndChild)
{
return FALSE;
}
else
{
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
ASSERT(pListCtrl!=NULL);
return TRUE;
}
}
COXSHBListCtrl* COXShortcutBar::GetGroupListCtrl(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl;
if(!m_mapHandleToListCtrl.Lookup(hGroup,pListCtrl))
{
return NULL;
}
ASSERT(pListCtrl!=NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl;
}
BOOL COXShortcutBar::GetGroupInfo(HSHBGROUP hGroup,
LPSHB_GROUPINFO pGroupInfo,
BOOL bSubstitute/* = FALSE*/)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
ASSERT(pGroupInfo);
if(!VerifyGroupInfo(pGroupInfo))
{
return FALSE;
}
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
TRACE(_T("COXShortcutBar::GetGroupInfo: group wasn't created"));
return FALSE;
}
ASSERT(pSavedGroupInfo!=NULL);
// CopyGroupInfo provide all we need to copy information
return CopyGroupInfo(pGroupInfo,pSavedGroupInfo,
(bSubstitute ? SHB_CPYINFO_COPY|SHB_CPYINFO_GET : SHB_CPYINFO_GET));
}
BOOL COXShortcutBar::SetGroupInfo(HSHBGROUP hGroup,
const LPSHB_GROUPINFO pGroupInfo,
BOOL bSubstitute/* = FALSE*/)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
ASSERT(pGroupInfo);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
TRACE(_T("COXShortcutBar::SetGroupInfo: group wasn't created"));
return FALSE;
}
ASSERT(pSavedGroupInfo!=NULL);
if(CopyGroupInfo(pSavedGroupInfo,pGroupInfo,
(bSubstitute ? SHB_CPYINFO_COPY|SHB_CPYINFO_SET : SHB_CPYINFO_SET)))
{
// recalc rectangles if changed order
if((pGroupInfo->nMask&(SHBIF_ORDER)))
CalculateBoundRects();
// recalc rectangles if changed descriptor both of shortcut bar and child window
if((pGroupInfo->nMask&(SHBIF_DESCRIPTOR)))
CalculateBoundRects();
// if changed view then scroll list control to the top
// if changed child window
if((pGroupInfo->nMask&SHBIF_CHILDWND))
{
if(pGroupInfo->hwndChild==NULL)
{
// if child window was removed we have to create COXSHBListCrl
// for such window because every group have to have child window
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl!=NULL)
{
try
{
pListCtrl=new COXSHBListCtrl();
}
catch (CMemoryException* pException)
{
UNREFERENCED_PARAMETER(pException);
TRACE(_T("COXShortcutBar::SetGroupInfo: failed to allocate memory for COXSHBListCtrl"));
return FALSE;
}
m_mapHandleToListCtrl.SetAt(hGroup,pListCtrl);
ASSERT(pListCtrl);
if(!CreateListControl(hGroup))
{
m_mapHandleToListCtrl.RemoveKey(hGroup);
delete pListCtrl;
return FALSE;
}
}
}
else
{
// send message to child window about aknowledging it and set group to it
ASSERT(::IsWindow(pGroupInfo->hwndChild));
::SendMessage(pGroupInfo->hwndChild,SHBM_SETSHBGROUP,(WPARAM)0,
(LPARAM)hGroup);
}
}
//send message to child window so it has chance to react on changed group info
HWND hwndChild=GetGroupChildWndHandle(hGroup);
ASSERT(hwndChild);
::SendMessage(hwndChild,SHBM_GROUPINFOCHANGED,(WPARAM)0,
(LPARAM)pGroupInfo->nMask);
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// All following SetGroup* functions eventually call SetGroupInfo function
//
///////////////////////////////////////////////////////////////////////////////
int COXShortcutBar::GetGroupImage(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo) ||
(pSavedGroupInfo->nMask&SHBIF_IMAGE)==0)
{
return -1;
}
ASSERT(pSavedGroupInfo!=NULL);
return pSavedGroupInfo->nImage;
}
BOOL COXShortcutBar::SetGroupImage(HSHBGROUP hGroup, int nImage)
{
ASSERT(hGroup);
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_IMAGE;
shbGroup.nImage=nImage;
return SetGroupInfo(hGroup,&shbGroup);
}
int COXShortcutBar::GetGroupImageExpanded(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return -1;
}
ASSERT(pSavedGroupInfo!=NULL);
if((pSavedGroupInfo->nMask&SHBIF_IMAGEEXPANDED)!=0)
{
return pSavedGroupInfo->nImageExpanded;
}
else
{
return GetGroupImage(hGroup);
}
}
BOOL COXShortcutBar::SetGroupImageExpanded(HSHBGROUP hGroup, int nImageExpanded)
{
ASSERT(hGroup);
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_IMAGEEXPANDED;
shbGroup.nImageExpanded=nImageExpanded;
return SetGroupInfo(hGroup,&shbGroup);
}
CString COXShortcutBar::GetGroupText(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo) ||
(pSavedGroupInfo->nMask&SHBIF_TEXT)==0)
{
return _T("");
}
ASSERT(pSavedGroupInfo!=NULL);
// copy text
return CString(pSavedGroupInfo->pszText, pSavedGroupInfo->nTextMax);
}
BOOL COXShortcutBar::SetGroupText(HSHBGROUP hGroup, CString sText)
{
ASSERT(hGroup);
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_TEXT;
shbGroup.pszText=sText.GetBuffer(sText.GetLength());
shbGroup.nTextMax=sText.GetLength();
sText.ReleaseBuffer();
return SetGroupInfo(hGroup,&shbGroup);
}
BOOL COXShortcutBar::SetGroupText(HSHBGROUP hGroup, LPCTSTR pszText,
int nTextMax)
{
ASSERT(hGroup);
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_TEXT;
shbGroup.pszText=(LPTSTR)pszText;
shbGroup.nTextMax=nTextMax;
return SetGroupInfo(hGroup,&shbGroup);
}
LPARAM COXShortcutBar::GetGroupData(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo) ||
(pSavedGroupInfo->nMask&SHBIF_PARAM)==0)
{
return NULL;
}
ASSERT(pSavedGroupInfo!=NULL);
return pSavedGroupInfo->lParam;
}
BOOL COXShortcutBar::SetGroupData(HSHBGROUP hGroup, LPARAM lParam)
{
ASSERT(hGroup);
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_PARAM;
shbGroup.lParam=lParam;
return SetGroupInfo(hGroup,&shbGroup);
}
int COXShortcutBar::GetGroupOrder(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo) ||
(pSavedGroupInfo->nMask&SHBIF_ORDER)==0)
{
return -1;
}
ASSERT(pSavedGroupInfo!=NULL);
return pSavedGroupInfo->nOrder;
}
BOOL COXShortcutBar::SetGroupOrder(HSHBGROUP hGroup, int nOrder)
{
ASSERT(hGroup);
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_ORDER;
shbGroup.nOrder=nOrder;
return SetGroupInfo(hGroup,&shbGroup);
}
int COXShortcutBar::GetGroupView(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return -1;
}
ASSERT(pSavedGroupInfo!=NULL);
if((pSavedGroupInfo->nMask&SHBIF_VIEW)==0)
{
return SHB_LARGEICON;
}
return pSavedGroupInfo->nView;
}
BOOL COXShortcutBar::SetGroupView(HSHBGROUP hGroup, int nView)
{
// this function can be called with hGroup=NULL. In this case we
// set specified view to every group in shortcut bar
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_VIEW;
shbGroup.nView=nView;
if(hGroup!=NULL)
return SetGroupInfo(hGroup,&shbGroup);
else
{
if(!VerifyView(nView))
return FALSE;
LPSHB_GROUPINFO pGroupInfo;
POSITION pos=m_mapHandleToInfo.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToInfo.GetNextAssoc(pos,hGroup,pGroupInfo);
ASSERT(hGroup!=NULL);
ASSERT(pGroupInfo!=NULL);
if(!SetGroupInfo(hGroup,&shbGroup))
return FALSE;
}
}
return TRUE;
}
LPSHB_DESCRIPTOR COXShortcutBar::GetGroupDescriptor(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo) ||
(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR)==0)
{
return NULL;
}
ASSERT(pSavedGroupInfo!=NULL);
return pSavedGroupInfo->pDescriptor;
}
BOOL COXShortcutBar::SetGroupDescriptor(HSHBGROUP hGroup,
const LPSHB_DESCRIPTOR pDescriptor)
{
// this function can be called with hGroup=NULL. In this case we
// set specified view to every group in shortcut bar
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_DESCRIPTOR;
shbGroup.pDescriptor=pDescriptor;
if(hGroup!=NULL)
{
return SetGroupInfo(hGroup,&shbGroup);
}
else
{
if(!VerifyDescriptor(pDescriptor))
return FALSE;
LPSHB_GROUPINFO pGroupInfo;
POSITION pos=m_mapHandleToInfo.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToInfo.GetNextAssoc(pos,hGroup,pGroupInfo);
ASSERT(hGroup!=NULL);
ASSERT(pGroupInfo!=NULL);
if(!SetGroupInfo(hGroup,&shbGroup))
return FALSE;
}
}
return TRUE;
}
HWND COXShortcutBar::GetGroupChildWnd(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo) ||
(pSavedGroupInfo->nMask&SHBIF_CHILDWND)==0)
{
return NULL;
}
ASSERT(pSavedGroupInfo!=NULL);
return pSavedGroupInfo->hwndChild;
}
BOOL COXShortcutBar::SetGroupChildWnd(HSHBGROUP hGroup, HWND hwndChild)
{
ASSERT(hGroup);
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_CHILDWND;
shbGroup.hwndChild=hwndChild;
return SetGroupInfo(hGroup,&shbGroup);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// All following SetGroup* functions eventually call SetGroupDescriptor function
//
///////////////////////////////////////////////////////////////////////////////
COLORREF COXShortcutBar::GetGroupBkColor(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return ID_COLOR_NONE;
}
ASSERT(pSavedGroupInfo!=NULL);
if(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_CLRBACK)
{
return pSavedGroupInfo->pDescriptor->clrBackground;
}
else
{
return GetShortcutBarSkin()->GetBackgroundColor(this);
}
}
BOOL COXShortcutBar::HasGroupBkColor(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
return FALSE;
ASSERT(pSavedGroupInfo!=NULL);
if(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_CLRBACK)
return TRUE;
else
return FALSE;
}
BOOL COXShortcutBar::SetGroupBkColor(HSHBGROUP hGroup, COLORREF clr)
{
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_CLRBACK;
descriptor.clrBackground=clr;
return SetGroupDescriptor(hGroup,&descriptor);
}
COLORREF COXShortcutBar::GetGroupTextColor(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return ID_COLOR_NONE;
}
ASSERT(pSavedGroupInfo!=NULL);
if(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_CLRTEXT)
return pSavedGroupInfo->pDescriptor->clrText;
else
return GetShortcutBarSkin()->GetGroupTextColor(this);
}
BOOL COXShortcutBar::SetGroupTextColor(HSHBGROUP hGroup, COLORREF clr)
{
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_CLRTEXT;
descriptor.clrText=clr;
return SetGroupDescriptor(hGroup,&descriptor);
}
COLORREF COXShortcutBar::GetGroupHeaderBkColor(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
return ID_COLOR_NONE;
ASSERT(pSavedGroupInfo!=NULL);
if(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_HDRCLRBACK)
{
return pSavedGroupInfo->pDescriptor->clrHeaderBackground;
}
else
{
return ::GetSysColor(COLOR_BTNFACE);
}
}
BOOL COXShortcutBar::SetGroupHeaderBkColor(HSHBGROUP hGroup, COLORREF clr)
{
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_HDRCLRBACK;
descriptor.clrHeaderBackground=clr;
return SetGroupDescriptor(hGroup,&descriptor);
}
COLORREF COXShortcutBar::GetGroupHeaderTextColor(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return ID_COLOR_NONE;
}
ASSERT(pSavedGroupInfo!=NULL);
if(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_HDRCLRTEXT)
{
return pSavedGroupInfo->pDescriptor->clrHeaderText;
}
else
{
return ::GetSysColor(COLOR_BTNTEXT);
}
}
BOOL COXShortcutBar::SetGroupHeaderTextColor(HSHBGROUP hGroup, COLORREF clr)
{
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_HDRCLRTEXT;
descriptor.clrHeaderText=clr;
return SetGroupDescriptor(hGroup,&descriptor);
}
UINT COXShortcutBar::GetGroupHeaderTextFormat(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return 0;
}
ASSERT(pSavedGroupInfo!=NULL);
if(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_HDRTEXTFMT)
{
return pSavedGroupInfo->pDescriptor->nHeaderTextFormat;
}
else
{
return DFLT_HDRTEXTFMT;
}
}
BOOL COXShortcutBar::SetGroupHeaderTextFormat(HSHBGROUP hGroup, UINT nFormat)
{
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_HDRTEXTFMT;
descriptor.nHeaderTextFormat=nFormat;
return SetGroupDescriptor(hGroup,&descriptor);
}
LPLOGFONT COXShortcutBar::GetGroupTextFont(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return NULL;
}
ASSERT(pSavedGroupInfo!=NULL);
if(!(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_FONT))
{
// we have to declare it as const to comply with const function definition
const CWnd* pWnd=this;
// get child window handle
HWND hwndChild=GetGroupChildWndHandle(hGroup);
if(hwndChild!=NULL)
{
// try child window's font first of all
pWnd=CWnd::FromHandle(hwndChild);
if(!pWnd->GetFont())
{
pWnd=this;
}
}
// get font of child or this window
CFont* pFont=pWnd->GetFont();
if(pFont)
{
static LOGFONT lf;
VERIFY(pFont->GetLogFont(&lf));
return &lf;
}
else
{
return NULL;
}
}
return &pSavedGroupInfo->pDescriptor->lfText;
}
BOOL COXShortcutBar::SetGroupTextFont(HSHBGROUP hGroup, const LPLOGFONT pLF)
{
ASSERT(pLF);
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_FONT;
if(!CopyLogFont(&descriptor.lfText,pLF))
{
TRACE(_T("COXShortcutBar::SetGroupTextFont: failed to get log font"));
return FALSE;
}
return SetGroupDescriptor(hGroup,&descriptor);
}
BOOL COXShortcutBar::SetGroupTextFont(HSHBGROUP hGroup, CFont* pFont)
{
ASSERT(pFont);
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_FONT;
if(!pFont->GetLogFont(&descriptor.lfText))
{
TRACE(_T("COXShortcutBar::SetGroupTextFont: failed to get log font"));
return FALSE;
}
return SetGroupDescriptor(hGroup,&descriptor);
}
LPLOGFONT COXShortcutBar::GetGroupHeaderTextFont(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return NULL;
}
ASSERT(pSavedGroupInfo!=NULL);
if(!(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_HDRFONT))
{
// use default font
ASSERT((HFONT)m_fontDefault!=NULL);
static LOGFONT lf;
VERIFY(m_fontDefault.GetLogFont(&lf));
return &lf;
}
return &pSavedGroupInfo->pDescriptor->lfHeader;
}
BOOL COXShortcutBar::SetGroupHeaderTextFont(HSHBGROUP hGroup, const LPLOGFONT pLF)
{
ASSERT(pLF);
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_HDRFONT;
if(!CopyLogFont(&descriptor.lfHeader,pLF))
{
TRACE(_T("COXShortcutBar::SetGroupHeaderTextFont: failed to get log font"));
return FALSE;
}
return SetGroupDescriptor(hGroup,&descriptor);
}
BOOL COXShortcutBar::SetGroupHeaderTextFont(HSHBGROUP hGroup, CFont* pFont)
{
ASSERT(pFont);
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_HDRFONT;
if(!pFont->GetLogFont(&descriptor.lfHeader))
{
TRACE(_T("COXShortcutBar::SetGroupHeaderTextFont: failed to get log font"));
return FALSE;
}
return SetGroupDescriptor(hGroup,&descriptor);
}
int COXShortcutBar::GetGroupHeaderHeight(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return -1;
}
ASSERT(pSavedGroupInfo!=NULL);
if(pSavedGroupInfo->nMask&SHBIF_DESCRIPTOR &&
pSavedGroupInfo->pDescriptor->nMask&SHBIF_HDRHEIGHT)
{
return pSavedGroupInfo->pDescriptor->nHeaderHeight;
}
else
{
COXShortcutBar * me = const_cast<COXShortcutBar *>(this);
COXShortcutBarSkin * skin = me->GetShortcutBarSkin();
switch(skin->GetType())
{
case OXSkinClassic:
return DFLT_HDRHEIGHT;
break;
case OXSkinOffice2003:
return DFLT_HDRHEIGHT2003;
break;
case OXSkinOfficeXP:
return DFLT_HDRHEIGHTXP;
break;
default:
return DFLT_HDRHEIGHT;
break;
}
}
}
BOOL COXShortcutBar::SetGroupHeaderHeight(HSHBGROUP hGroup, int nHeight)
{
ASSERT(nHeight>=0);
SHB_DESCRIPTOR descriptor;
descriptor.nMask=SHBIF_HDRHEIGHT;
descriptor.nHeaderHeight=nHeight;
return SetGroupDescriptor(hGroup,&descriptor);
}
///////////////////////////////////////////////////////////////////////////////
HSHBGROUP COXShortcutBar::InsertGroup(const LPSHB_GROUPINFO pGroupInfo)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(pGroupInfo);
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_INSERTGROUP;
nmshb.lParam=(LPARAM)pGroupInfo;
if(SendSHBNotification(&nmshb))
{
return NULL;
}
// verify specified structure
if(!VerifyGroupInfo(pGroupInfo))
{
return NULL;
}
// request unique handle for new group
HSHBGROUP hGroup=GetUniqueGroupHandle();
if(hGroup==NULL)
{
return NULL;
}
LPSHB_GROUPINFO pSavedGroupInfo;
try
{
pSavedGroupInfo=new SHB_GROUPINFO;
}
catch (CMemoryException* pException)
{
UNREFERENCED_PARAMETER(pException);
TRACE(_T("COXShortcutBar::InsertGroup: failed to allocate memory for SHB_GROUPINFO"));
return NULL;
}
ASSERT(pSavedGroupInfo!=NULL);
// Save supplied group info. Note that the third parameter is set to TRUE,
// which means that pGroupInfo will be completely copied to pSavedGroupInfo
if(!CopyGroupInfo(pSavedGroupInfo,pGroupInfo,SHB_CPYINFO_GET|SHB_CPYINFO_COPY))
{
delete pSavedGroupInfo;
return NULL;
}
// check if we have to reorder existing groups
BOOL bNeedSorting=FALSE;
if(pSavedGroupInfo->nMask&SHBIF_ORDER)
{
switch(pSavedGroupInfo->nOrder)
{
case SHBI_FIRST:
{
UpdateHeaderOrder(0,-1,1);
pSavedGroupInfo->nOrder=0;
break;
}
case SHBI_LAST:
{
pSavedGroupInfo->nOrder=PtrToInt(GetGroupCount());
break;
}
case SHBI_SORT:
{
pSavedGroupInfo->nOrder=PtrToInt(GetGroupCount());
bNeedSorting=TRUE;
break;
}
default:
{
UpdateHeaderOrder(pSavedGroupInfo->nOrder,-1,1);
pSavedGroupInfo->nOrder=0;
break;
}
}
}
else
{
pSavedGroupInfo->nMask|=SHBIF_ORDER;
pSavedGroupInfo->nOrder=PtrToInt(GetGroupCount());
}
m_mapHandleToInfo.SetAt(hGroup,pSavedGroupInfo);
// if we inserted group using SHBI_SORT constant then we have to resort all groups
if(bNeedSorting)
{
if(!SortGroups(1))
{
VERIFY(DeleteGroup(hGroup));
return FALSE;
}
}
if((pSavedGroupInfo->nMask&SHBIF_CHILDWND)==0)
{
COXSHBListCtrl* pListCtrl=NULL;
try
{
pListCtrl=NewSHBListCtrl();
}
catch (CMemoryException* pException)
{
UNREFERENCED_PARAMETER(pException);
TRACE(_T("COXShortcutBar::InsertGroup: failed to allocate memory for COXSHBListCtrl"));
VERIFY(DeleteGroup(hGroup));
return NULL;
}
m_mapHandleToListCtrl.SetAt(hGroup,pListCtrl);
// if child window wasn't specified then we have to create default one -
// COXSHBListCtrl
if(!CreateListControl(hGroup))
{
VERIFY(DeleteGroup(hGroup));
return NULL;
}
}
else
{
// send message to child window about aknowledging it and set group to it
ASSERT(pSavedGroupInfo->hwndChild);
::SendMessage(pSavedGroupInfo->hwndChild,SHBM_SETSHBGROUP,
(WPARAM)0,(LPARAM)hGroup);
}
// reposition groups
CalculateBoundRects();
return hGroup;
}
HSHBGROUP COXShortcutBar::InsertGroup(LPCTSTR pszText,
int nOrder,
int nImage,
int nImageExpanded,
LPARAM lParam,
int nView,
const LPSHB_DESCRIPTOR pDescriptor,
HWND hwndChild)
{
SHB_GROUPINFO shbGroup;
// label text
if(pszText!=NULL)
{
CString sText(pszText);
shbGroup.nMask|=SHBIF_TEXT;
shbGroup.nTextMax=sText.GetLength();
shbGroup.pszText=(LPTSTR)pszText;
}
// order of insertion
if(nOrder!=-1)
{
shbGroup.nMask|=SHBIF_ORDER;
shbGroup.nOrder=nOrder;
}
// label image
if(nImage!=-1)
{
shbGroup.nMask|=SHBIF_IMAGE;
shbGroup.nImage=nImage;
}
// label image (expanded)
if(nImage!=-1)
{
shbGroup.nMask|=SHBIF_IMAGEEXPANDED;
shbGroup.nImageExpanded=nImageExpanded;
}
// user defined data
if(lParam!=NULL)
{
shbGroup.nMask|=SHBIF_PARAM;
shbGroup.lParam=lParam;
}
// view type
if(nView!=-1)
{
shbGroup.nMask|=SHBIF_VIEW;
shbGroup.nView=nView;
}
// group description data
if(pDescriptor!=NULL)
{
shbGroup.nMask|=SHBIF_DESCRIPTOR;
shbGroup.pDescriptor=pDescriptor;
}
// child window
if(hwndChild!=NULL)
{
shbGroup.nMask|=SHBIF_CHILDWND;
shbGroup.hwndChild=hwndChild;
}
return InsertGroup(&shbGroup);
}
BOOL COXShortcutBar::DeleteGroup(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_DELETEGROUP;
nmshb.hGroup=hGroup;
if(SendSHBNotification(&nmshb))
{
return FALSE;
}
LPSHB_GROUPINFO pSavedGroupInfo;
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
{
return FALSE;
}
ASSERT(pSavedGroupInfo!=NULL);
int nOrder=GetGroupOrder(hGroup);
ASSERT(nOrder!=-1);
UpdateHeaderOrder(nOrder+1,-1,-1);
// hide any associated child window
HideChildWnd(hGroup);
// notify child window that group is about to be deleted
HWND hwndChild=GetGroupChildWndHandle(hGroup);
ASSERT(hwndChild);
if(::IsWindow(hwndChild))
{
::SendMessage(hwndChild,SHBM_DELETESHBGROUP,(WPARAM)0,(LPARAM)0);
}
// delete associated group info
delete pSavedGroupInfo;
m_mapHandleToInfo.RemoveKey(hGroup);
m_mapHandleToBoundRect.RemoveKey(hGroup);
// if we deleted expanded group then we have to expand the next one
if(GetExpandedGroup()==hGroup)
{
int nGroupCount=PtrToInt(GetGroupCount());
if(nGroupCount==0)
{
// if the last group was deleted then we just clean up all info
m_hExpandedGroup=NULL;
CalculateBoundRects();
RedrawWindow();
}
else
{
// searching for next group to expand
if(nOrder==nGroupCount)
{
nOrder=0;
}
else if(nOrder>nGroupCount)
{
ASSERT(FALSE);
}
HSHBGROUP hGroup=FindGroupByOrder(nOrder);
ASSERT(hGroup);
ExpandGroup(hGroup);
}
}
else
{
// reposition groups and redraw the control
CalculateBoundRects();
RedrawBar();
}
// delete list control associated with deleted group
COXSHBListCtrl* pListCtrl=NULL;
if(m_mapHandleToListCtrl.Lookup(hGroup,pListCtrl) && pListCtrl)
{
delete pListCtrl;
m_mapHandleToListCtrl.RemoveKey(hGroup);
}
return TRUE;
}
BOOL COXShortcutBar::DeleteAllGroups()
{
ASSERT(::IsWindow(GetSafeHwnd()));
// delete all groups in cycle calling DeleteGroup function
BOOL bResult=TRUE;
HSHBGROUP hGroup=NULL;
LPSHB_GROUPINFO pGroupInfo;
POSITION pos=m_mapHandleToInfo.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToInfo.GetNextAssoc(pos,hGroup,pGroupInfo);
ASSERT(hGroup!=NULL);
ASSERT(pGroupInfo!=NULL);
bResult=DeleteGroup(hGroup) ? bResult : FALSE;
}
VERIFY(m_mapHandleToInfo.GetCount()==0);
return bResult;
}
HSHBGROUP COXShortcutBar::ExpandGroup(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
// reset autoexpand timer
if(m_nWaitForAutoExpandID!=0)
{
KillTimer(m_nWaitForAutoExpandID);
m_nWaitForAutoExpandID=0;
}
m_hSuspectAutoExpandGroup=NULL;
if(hGroup==m_hExpandedGroup)
{
return hGroup;
}
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_GROUPEXPANDING;
nmshb.hGroup=hGroup;
if(SendSHBNotification(&nmshb))
{
return m_hExpandedGroup;
}
HSHBGROUP hOldExpandedGroup=m_hExpandedGroup;
m_hExpandedGroup=hGroup;
COXShortcutBar * me = const_cast<COXShortcutBar *>(this);
COXShortcutBarSkin * skin = me->GetShortcutBarSkin();
bool bExpandCells = (skin->AnimateSelection());
// animation effect
if(bExpandCells && (GetBarStyle()&SHBS_ANIMATEEXPAND)!=0 && hOldExpandedGroup!=NULL &&
m_hExpandedGroup!=NULL && !GetChildWndRect().IsRectEmpty())
{
int nOrder=GetGroupOrder(m_hExpandedGroup);
// nOldOrder can be -1 in the case the old expanded group was just deleted
int nOldOrder=GetGroupOrder(hOldExpandedGroup);
if(nOldOrder!=-1)
{
// get the direction of animated group expanding (up or down)
BOOL bMovingUp=(nOldOrder<nOrder);
// get child window handle
HWND hOldWnd=GetGroupChildWndHandle(hOldExpandedGroup);
ASSERT(hOldWnd);
ASSERT(::IsWindow(hOldWnd));
// get child window rectangle
CRect rectOldChild=GetChildWndRect();
CRect rectToRedraw;
// animation group expanding step size (in pixels)
int nOffset=DFLT_ANIMATIONOFFSET;
// the number of steps we need to take to fully animate group expanding
int nSteps=rectOldChild.Height()/nOffset;
for(int nIndex=0; nIndex<nSteps-1; nIndex++)
{
// speed up expanding after we made it half way
if(nIndex>nSteps/2)
{
nIndex++;
nOffset=2*DFLT_ANIMATIONOFFSET;
}
// recalculate headers rectangles
rectToRedraw.left=0xffff;
rectToRedraw.top=0xffff;
rectToRedraw.right=0;
rectToRedraw.bottom=0;
for(int nGroupOrder=__min(nOldOrder,nOrder)+1;
nGroupOrder<=__max(nOldOrder,nOrder); nGroupOrder++)
{
HSHBGROUP hGroup=FindGroupByOrder(nGroupOrder);
ASSERT(hGroup);
CRect rectHeader;
VERIFY(GetGroupHeaderRect(hGroup,rectHeader));
rectToRedraw.left=__min(rectToRedraw.left,rectHeader.left);
rectToRedraw.top=__min(rectToRedraw.top,rectHeader.top);
rectToRedraw.right=__max(rectToRedraw.right,rectHeader.right);
rectToRedraw.bottom=__max(rectToRedraw.bottom,rectHeader.bottom);
rectHeader.OffsetRect(0,(bMovingUp) ? -nOffset : nOffset);
rectToRedraw.top=__min(rectToRedraw.top,rectHeader.top);
rectToRedraw.bottom=__max(rectToRedraw.bottom,rectHeader.bottom);
m_mapHandleToBoundRect.SetAt(hGroup,rectHeader);
}
// recalculate child window coordinates
if(bMovingUp)
{
rectOldChild.bottom-=nOffset;
}
else
{
rectOldChild.top+=nOffset;
}
// set expanded child window rectangle to updated one
m_rectChildWnd=rectOldChild;
// resize child window
::MoveWindow(hOldWnd,rectOldChild.left,rectOldChild.top,
rectOldChild.Width(),rectOldChild.Height(),FALSE);
// redraw shortcut bar
RedrawWindow(rectToRedraw);
::Sleep(DFLT_ANIMATIONDELAY/nSteps);
}
}
}
// reposition groups
CalculateBoundRects();
// hide child window of previous expanded group
HideChildWnd(hOldExpandedGroup);
RedrawWindow();
// show child window of newly appointed expanded group
ShowChildWnd(m_hExpandedGroup);
// notify parent
// fill structure for notification
nmshb.hdr.code=SHBN_GROUPEXPANDED;
nmshb.hGroup=hGroup;
SendSHBNotification(&nmshb);
return hOldExpandedGroup;
}
HSHBGROUP COXShortcutBar::SetDropTargetGroup(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
HSHBGROUP hOldDropHighlightGroup=m_hDropHilightGroup;
m_hDropHilightGroup=hGroup;
return hOldDropHighlightGroup;
}
HSHBGROUP COXShortcutBar::SetDragGroup(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
if(m_hDragGroup==hGroup)
return m_hDragGroup;
HSHBGROUP hOldDragGroup=m_hDragGroup;
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_BEGINDRAGHEADER;
nmshb.hGroup=hGroup;
nmshb.lParam=(LPARAM)&m_ptDragImage;
SendSHBNotification(&nmshb);
m_hDragGroup=hGroup;
return hOldDragGroup;
}
COXSHBEdit* COXShortcutBar::EditGroupHeader(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
ASSERT(::IsWindow(m_edit.GetSafeHwnd()));
// check if we can edit headers
if((GetBarStyle()&SHBS_EDITHEADERS)==0)
{
TRACE(_T("COXShortcutBar::EditGroupHeader: cannot edit header - SHBS_EDITHEADERS style wasn't set"));
return NULL;
}
// stop editing any group if any is undergoing
if(m_hEditGroup!=NULL)
{
m_edit.FinishEdit(TRUE);
m_hEditGroup=NULL;
}
// get text
CString sText=GetGroupText(hGroup);
// fill structure for notification
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_BEGINHEADEREDIT;
nmshb.hGroup=hGroup;
nmshb.lParam=(LPARAM)((LPCTSTR)sText);
if(SendSHBNotification(&nmshb))
{
return NULL;
}
CRect rectClient;
GetClientRect(rectClient);
CRect rectHeader;
if(!GetGroupHeaderRect(hGroup,rectHeader))
{
TRACE(_T("COXShortcutBar::EditGroupHeader: failed to get header rectangle"));
return NULL;
}
if(rectHeader.IsRectEmpty())
{
TRACE(_T("COXShortcutBar::EditGroupHeader: header rect is empty"));
return NULL;
}
CRect rectIntersect;
rectIntersect.IntersectRect(rectClient,rectHeader);
if(rectIntersect!=rectHeader)
{
TRACE(_T("COXShortcutBar::EditGroupHeader: failed to edit - header rectangle is not entirely visible"));
return NULL;
}
// get font to be used in COXSHBEdit control
LPLOGFONT pLF=GetGroupHeaderTextFont(hGroup);
ASSERT(pLF);
CFont font;
VERIFY(font.CreateFontIndirect(pLF));
// fill SHBE_DISPLAY structure to specify COXSHBEdit control options
SHBE_DISPLAY shbed;
shbed.nMask=SHBEIF_TEXT|SHBEIF_RECTDISPLAY|SHBEIF_STYLE|
SHBEIF_SELRANGE|SHBEIF_FONT;
shbed.lpText=sText;
shbed.rectDisplay=rectHeader;
shbed.dwStyle=WS_BORDER|ES_AUTOHSCROLL|ES_LEFT;
shbed.ptSelRange=CPoint(0,-1);
shbed.pFont=&font;
if(!m_edit.StartEdit(&shbed))
{
TRACE(_T("COXShortcutBar::EditGroupHeader: COXSHBEdit::StartEdit failed"));
return NULL;
}
m_hEditGroup=hGroup;
return &m_edit;
}
HSHBGROUP COXShortcutBar::HitTest(CPoint pt, UINT* pFlags) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
*pFlags=SHB_NOWHERE;
HSHBGROUP hGroup=NULL;
// first of all check if point is within child window rect
if(!m_rectChildWnd.IsRectEmpty() && m_rectChildWnd.PtInRect(pt))
{
hGroup=GetExpandedGroup();
ASSERT(hGroup);
*pFlags=SHB_ONCHILD;
}
else
{
// check if point is on some of headers
CRect rect;
POSITION pos=m_mapHandleToBoundRect.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToBoundRect.GetNextAssoc(pos,hGroup,rect);
ASSERT(hGroup!=NULL);
if(rect.PtInRect(pt))
{
*pFlags=SHB_ONHEADER;
break;
}
else
{
hGroup=NULL;
}
}
}
return hGroup;
}
CImageList* COXShortcutBar::CreateGroupDragImage(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
m_bCreatingDragImage=TRUE;
// IMPORTANT //
// caller of this function have to eventually destroy the image list
//
CImageList* m_pDragImageList=new CImageList;
CRect rectHeader;
VERIFY(GetGroupHeaderRect(hGroup,&rectHeader));
m_pDragImageList->Create(rectHeader.Width(),rectHeader.Height(),ILC_COLOR,0,1);
CClientDC dcClient(this);
CDC dc;
VERIFY(dc.CreateCompatibleDC(&dcClient));
CBitmap bitmap;
VERIFY(bitmap.CreateCompatibleBitmap(&dcClient,rectHeader.Width(),
rectHeader.Height()));
CBitmap* pOldBitmap=dc.SelectObject(&bitmap);
rectHeader-=rectHeader.TopLeft();
// use header drawing routine to get drag image
//
DRAWITEMSTRUCT dis;
dis.CtlType=0;
dis.CtlID=GetDlgCtrlID();
dis.itemID=(UINT)PtrToUint(hGroup);
dis.itemAction=ODA_DRAWENTIRE;
dis.itemState=ODS_DEFAULT;
dis.hwndItem=GetSafeHwnd();
dis.hDC=dc;
dis.rcItem=rectHeader;
dis.itemData=(DWORD)PtrToUlong(hGroup);
DrawHeader(&dis);
if(pOldBitmap)
dc.SelectObject(pOldBitmap);
VERIFY(m_pDragImageList->Add(&bitmap,(CBitmap*)NULL)!=-1);
m_bCreatingDragImage=FALSE;
return m_pDragImageList;
}
BOOL COXShortcutBar::SortGroups(int nSortOrder)
{
// use CompareHeaders function to sort groups in alphabetical order
return SortGroupsCB(CompareHeaders,(LPARAM)this,nSortOrder);
}
BOOL COXShortcutBar::SortGroupsCB(PFNSHBCOMPARE lpfnCompare,
LPARAM lParamSort, int nSortOrder)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(lpfnCompare);
ASSERT(nSortOrder==0 || nSortOrder==1 || nSortOrder==-1);
m_nSortOrder=nSortOrder;
int nCount=PtrToInt(GetGroupCount());
if(GetGroupCount()<2 || nSortOrder==0)
{
return TRUE;
}
HSHBGROUP hGroup1;
HSHBGROUP hGroup2;
BOOL bNotDone=TRUE;
while(bNotDone)
{
bNotDone=FALSE;
// loop through all groups
for(int nIndex=0; nIndex<nCount-1; nIndex++)
{
hGroup1=FindGroupByOrder(nIndex);
hGroup2=FindGroupByOrder(nIndex+1);
ASSERT(hGroup1!=NULL && hGroup2!=NULL);
int nResult=nSortOrder*
lpfnCompare((LPARAM)hGroup1,(LPARAM)hGroup2,lParamSort);
if(nResult>0)
{
// actually we swap items in this function
SetGroupOrder(hGroup1,nIndex+1);
bNotDone=TRUE;
}
}
}
return TRUE;
}
// functions to work with group list controls (defined only if programmer didn't set
// hwndChild member of SHB_GROUPINFO structure)
//
CImageList* COXShortcutBar::SetLCImageList(HSHBGROUP hGroup,
CImageList* pImageList,
int nImageList)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::SetLCImageList: list control wasn't created"));
return NULL;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->SetImageList(pImageList,nImageList);
}
CImageList* COXShortcutBar::GetLCImageList(HSHBGROUP hGroup, int nImageList) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::GetLCImageList: list control wasn't created"));
return NULL;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->GetImageList(nImageList);
}
BOOL COXShortcutBar::GetLCItem(HSHBGROUP hGroup, LV_ITEM* pItem) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
ASSERT(pItem);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::GetLCItem: list control wasn't created"));
return FALSE;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->GetItem(pItem);
}
int COXShortcutBar::GetLCItemCount(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::GetLCItemCount: list control wasn't created"));
return FALSE;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->GetItemCount();
}
BOOL COXShortcutBar::SetLCItem(HSHBGROUP hGroup, const LV_ITEM* pItem)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
ASSERT(pItem);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::SetLCItem: list control wasn't created"));
return FALSE;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->SetItem(pItem);
}
BOOL COXShortcutBar::SetLCItem(HSHBGROUP hGroup, int nItem, int nSubItem,
UINT nMask, LPCTSTR lpszItem, int nImage,
UINT nState, UINT nStateMask, LPARAM lParam)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::SetLCItem: list control wasn't created"));
return FALSE;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->SetItem(nItem,nSubItem,nMask,lpszItem,nImage,
nState,nStateMask,lParam);
}
int COXShortcutBar::InsertLCItem(HSHBGROUP hGroup, const LV_ITEM* pItem)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
ASSERT(pItem);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::InsertLCItem: list control wasn't created"));
return -1;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->InsertItem(pItem);
}
int COXShortcutBar::InsertLCItem(HSHBGROUP hGroup, UINT nMask, int nItem,
LPCTSTR lpszItem, UINT nState, UINT nStateMask,
int nImage, LPARAM lParam)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::InsertLCItem: list control wasn't created"));
return -1;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
return pListCtrl->InsertItem(
nMask,nItem,lpszItem,nState,nStateMask,nImage,lParam);
}
BOOL COXShortcutBar::DeleteLCItem(HSHBGROUP hGroup, int nItem)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::InsertLCItem: list control wasn't created"));
return FALSE;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
ASSERT(nItem>=0 && nItem<pListCtrl->GetItemCount());
return pListCtrl->DeleteItem(nItem);
}
COXSHBEdit* COXShortcutBar::EditLCItem(HSHBGROUP hGroup, int nItem)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
// check if we are allowed to edit items
if((GetBarStyle()&SHBS_EDITITEMS)==0)
{
TRACE(_T("COXShortcutBar::EditLCItem: cannot edit item - SHBS_EDITITEMS style wasn't set"));
return NULL;
}
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::EditLCItem: list control wasn't created"));
return NULL;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
ASSERT(nItem>=0 && nItem<pListCtrl->GetItemCount());
return pListCtrl->EditLabel(nItem);
}
BOOL COXShortcutBar::ScrollExpandedLC(CSize size)
{
ASSERT(::IsWindow(GetSafeHwnd()));
// get expanded group
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup==NULL)
return FALSE;
HWND hWnd=GetGroupChildWnd(hGroup);
if(hWnd==NULL)
{
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
ASSERT(pListCtrl);
return pListCtrl->Scroll(size);
}
TRACE(_T("COXShortcutBar::ScrollExpanded: child window is not COXSHBListCtrl\n"));
return FALSE;
}
int COXShortcutBar::SortLCItems(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl==NULL)
{
TRACE(_T("COXShortcutBar::SortLCItems: list control wasn't created\n"));
return -1;
}
ASSERT(GetGroupChildWnd(hGroup)==NULL);
ASSERT_VALID(pListCtrl);
// Sort all items in ascending aphabetical order using an STL set
typedef std::set<LVITEM*, LVITEM_less> ItemSet;
ItemSet setItems;
int iCount = pListCtrl->GetItemCount();
for (int i = 0; i < iCount; i++)
{
LVITEM* pLVI = new LVITEM();
::memset(pLVI, 0, sizeof(LVITEM));
pLVI->iItem = i;
pLVI->mask = LVIF_IMAGE | LVIF_INDENT | LVIF_PARAM | LVIF_STATE | LVIF_TEXT;
pLVI->pszText = new TCHAR[256];
pLVI->cchTextMax = 256;
pListCtrl->GetItem(pLVI);
setItems.insert(pLVI);
}
// Remove all items from the list control
pListCtrl->DeleteAllItems();
// Put the items back in the list control
int iIndex = 0;
for (ItemSet::iterator it = setItems.begin(); it != setItems.end(); ++it)
{
(*it)->iItem = iIndex++;
pListCtrl->InsertItem(*it);
delete [] (*it)->pszText;
delete *it;
}
return 0;
}
////////////////////////////////////////////////////////////////////
// Set of verification functions that check different parameters on consistent
////////////////////////////////////////////////////////////////////
BOOL COXShortcutBar::VerifyBarStyle(DWORD dwBarStyle) const
{
if(dwBarStyle & ~(SHBS_EDITHEADERS|SHBS_EDITITEMS|SHBS_INFOTIP|
SHBS_DISABLEDRAGDROPITEM|SHBS_NOSCROLL|SHBS_BOLDEXPANDEDGROUP|
SHBS_UNDERLINEHOTITEM|SHBS_SHOWACTIVEALWAYS|
SHBS_DISABLEDRAGDROPHEADER|SHBS_DRAWHEADERDRAGIMAGE|
SHBS_DRAWITEMDRAGIMAGE|SHBS_AUTOSCROLL|
SHBS_ANIMATEEXPAND|SHBS_AUTOEXPAND|SHBS_FLATGROUPBUTTON))
{
TRACE(_T("COXShortcutBar::VerifyBarStyle: unspecified Shortcut Bar style was used\n"));
return FALSE;
}
return TRUE;
}
BOOL COXShortcutBar::VerifyWindowStyle(DWORD dwStyle) const
{
if((dwStyle & WS_CHILD)==0)
{
TRACE(_T("COXShortcutBar::VerifyWindowStyle: WS_CHILD style must be specified\n"));
return FALSE;
}
return TRUE;
}
BOOL COXShortcutBar::VerifyImage(int nImage) const
{
if(!m_pImageList)
{
TRACE(_T("COXShortcutBar::VerifyImage: image list wasn't set"));
return FALSE;
}
// image index has to be in the range of possible values
if(nImage<0 || nImage>=m_pImageList->GetImageCount())
{
TRACE(_T("COXShortcutBar::VerifyImage: image number %d is out of range: 0 ... %d\n"),
nImage,m_pImageList->GetImageCount());
return FALSE;
}
return TRUE;
}
BOOL COXShortcutBar::VerifyView(int nView) const
{
// only two types of view at the moment available
if(nView&~(SHB_LARGEICON|SHB_SMALLICON))
{
TRACE(_T("COXShortcutBar::VerifyView: unknown view specified"));
return FALSE;
}
return TRUE;
}
BOOL COXShortcutBar::VerifyOrder(int nOrder) const
{
if((nOrder!=SHBI_FIRST && nOrder!=SHBI_LAST && nOrder!=SHBI_SORT) &&
(nOrder<0 || nOrder>=GetGroupCount()))
{
TRACE(_T("COXShortcutBar::VerifyOrder: order number %d is out of range: 0 ... %d\n"),
nOrder,GetGroupCount());
return FALSE;
}
return TRUE;
}
BOOL COXShortcutBar::VerifyDescriptor(LPSHB_DESCRIPTOR pDescriptor) const
{
UNREFERENCED_PARAMETER(pDescriptor);
ASSERT(pDescriptor);
return TRUE;
}
BOOL COXShortcutBar::VerifyChildWnd(HWND hwndChild) const
{
if(!::IsWindow(hwndChild))
{
TRACE(_T("COXShortcutBar::VerifyChildWnd: window wasn't created\n"));
return FALSE;
}
DWORD dwStyle=::GetWindowLongPtr(hwndChild,GWL_STYLE);
if((dwStyle&WS_CHILD)==0)
{
TRACE(_T("COXShortcutBar::VerifyChildWnd: WS_CHILD style must be specified\n"));
return FALSE;
}
HWND hwndParent=::GetParent(hwndChild);
if(hwndParent!=GetSafeHwnd())
{
TRACE(_T("COXShortcutBar::VerifyChildWnd: child window parent window is not <this>\n"));
return FALSE;
}
return TRUE;
}
BOOL COXShortcutBar::VerifyMask(UINT nMask) const
{
if(nMask&~(SHBIF_TEXT|SHBIF_IMAGE|SHBIF_IMAGEEXPANDED|SHBIF_PARAM|
SHBIF_ORDER|SHBIF_VIEW|SHBIF_DESCRIPTOR|SHBIF_CHILDWND))
{
TRACE(_T("COXShortcutBar::VerifyMask: unknown mask specified"));
return FALSE;
}
return TRUE;
}
BOOL COXShortcutBar::VerifyGroupInfo(LPSHB_GROUPINFO pGroupInfo) const
{
if(!VerifyMask(pGroupInfo->nMask))
return FALSE;
if(pGroupInfo->nMask&SHBIF_IMAGE && !VerifyImage(pGroupInfo->nImage))
return FALSE;
if(pGroupInfo->nMask&SHBIF_IMAGEEXPANDED &&
!VerifyImage(pGroupInfo->nImageExpanded))
return FALSE;
if(pGroupInfo->nMask&SHBIF_ORDER && !VerifyOrder(pGroupInfo->nOrder))
return FALSE;
if(pGroupInfo->nMask&SHBIF_VIEW && !VerifyView(pGroupInfo->nView))
return FALSE;
if(pGroupInfo->nMask&SHBIF_DESCRIPTOR &&
!VerifyDescriptor(pGroupInfo->pDescriptor))
return FALSE;
if(pGroupInfo->nMask&SHBIF_CHILDWND && !VerifyChildWnd(pGroupInfo->hwndChild))
return FALSE;
return TRUE;
}
HSHBGROUP COXShortcutBar::GetUniqueGroupHandle()
{
// we just keep track of all created groups and just increment the number
// of created groups to get a unique handle
m_nLastHandle++;
return (HSHBGROUP)m_nLastHandle;
}
BOOL COXShortcutBar::CopyGroupInfo(LPSHB_GROUPINFO pDest,
const LPSHB_GROUPINFO pSource,
int nCopyFlag/* = SHB_CPYINFO_SET*/)
{
ASSERT(pDest);
ASSERT(pSource);
// only these flags can be set
ASSERT((nCopyFlag&~(SHB_CPYINFO_COPY|SHB_CPYINFO_GET|SHB_CPYINFO_SET))==0);
// these two flags cannot be set simultenuosly
ASSERT((nCopyFlag&SHB_CPYINFO_SET)==0 || (nCopyFlag&SHB_CPYINFO_GET)==0);
// verify dest if we are going to get info from source
if((nCopyFlag&SHB_CPYINFO_GET)!=0)
VERIFY(VerifyGroupInfo(pDest));
// check if we copy source to dest with removing all existing dest contents
if((nCopyFlag&SHB_CPYINFO_COPY)!=0)
{
// delete text if it was dynamically allocated
if(pDest->IsDynCreated() && pDest->pszText!=NULL)
{
delete[] pDest->pszText;
pDest->pszText=NULL;
pDest->DynCreated(FALSE);
}
ZeroMemory(pDest,sizeof(SHB_GROUPINFO));
}
// define the group which mask will be used to copy information
LPSHB_GROUPINFO pMainGroup=(((nCopyFlag&SHB_CPYINFO_SET)!=0 ||
(nCopyFlag&SHB_CPYINFO_COPY)!=0) ? pSource : pDest);
// define whether we are going to get or set information
BOOL bGetInfo=((nCopyFlag&SHB_CPYINFO_GET)!=0 ? TRUE : FALSE);
// set header text
if(pMainGroup->nMask&SHBIF_TEXT)
{
// delete any text that was previously dynamically allocated
if(pDest->IsDynCreated() && pDest->pszText!=NULL)
{
delete[] pDest->pszText;
pDest->pszText=NULL;
pDest->DynCreated(FALSE);
}
// copy text
if(pSource->pszText!=NULL && pSource->nTextMax>0)
{
try
{
pDest->pszText=new TCHAR[pSource->nTextMax + 1];
}
catch (CMemoryException* pException)
{
UNREFERENCED_PARAMETER(pException);
TRACE(_T("COXShortcutBar::CopyGroupInfo: failed to allocate memory for text"));
pDest->pszText=NULL;
return FALSE;
}
ASSERT(pDest->pszText);
pDest->DynCreated();
UTBStr::tcsncpy(pDest->pszText, pSource->nTextMax + 1, pSource->pszText, pSource->nTextMax);
pDest->nTextMax=pSource->nTextMax;
}
pDest->nMask|=SHBIF_TEXT;
}
// set header image
if(pMainGroup->nMask&SHBIF_IMAGE)
{
if(pSource->nImage>=0 && !VerifyImage(pSource->nImage))
return FALSE;
// check if property is to set/remove
if(pSource->nImage<0)
{
pDest->nImage=-1;
pDest->nMask&=~SHBIF_IMAGE;
}
else
{
pDest->nImage=pSource->nImage;
pDest->nMask|=SHBIF_IMAGE;
}
}
// set header expanded image
if(pMainGroup->nMask&SHBIF_IMAGEEXPANDED)
{
if(pSource->nImageExpanded>=0 && !VerifyImage(pSource->nImageExpanded))
return FALSE;
// check if property is to set/remove
if(pSource->nImageExpanded<0)
{
pDest->nImageExpanded=-1;
pDest->nMask&=~SHBIF_IMAGEEXPANDED;
}
else
{
pDest->nImageExpanded=pSource->nImageExpanded;
pDest->nMask|=SHBIF_IMAGEEXPANDED;
}
}
// set user specific data
if(pMainGroup->nMask&SHBIF_PARAM)
{
pDest->lParam=pSource->lParam;
pDest->nMask|=SHBIF_PARAM;
}
// set order
if(pMainGroup->nMask&SHBIF_ORDER)
{
if(!VerifyOrder(pSource->nOrder))
return FALSE;
// reorder groups if infromation is to be set
if(!bGetInfo)
{
int nOldOrder=pDest->nOrder;
if(nOldOrder!=pSource->nOrder)
{
HSHBGROUP hSwapGroup=FindGroupByOrder(pSource->nOrder);
ASSERT(hSwapGroup!=NULL);
LPSHB_GROUPINFO pSwapSavedGroupInfo;
VERIFY(m_mapHandleToInfo.Lookup(hSwapGroup,pSwapSavedGroupInfo));
ASSERT(pSwapSavedGroupInfo!=NULL);
pSwapSavedGroupInfo->nMask|=SHBIF_ORDER;
pSwapSavedGroupInfo->nOrder=nOldOrder;
}
}
pDest->nOrder=pSource->nOrder;
pDest->nMask|=SHBIF_ORDER;
}
// set view
if(pMainGroup->nMask&SHBIF_VIEW )
{
if(!VerifyView(pSource->nView))
return FALSE;
pDest->nView=pSource->nView;
pDest->nMask|=SHBIF_VIEW;
}
// child window
if(pMainGroup->nMask&SHBIF_CHILDWND)
{
// check if property is to set/remove
if(pSource->hwndChild==NULL)
{
pDest->nMask&=~SHBIF_CHILDWND;
pDest->hwndChild=pSource->hwndChild;
}
else
{
// verify child window
if(!VerifyChildWnd(pSource->hwndChild))
return FALSE;
pDest->nMask|=SHBIF_CHILDWND;
pDest->hwndChild=pSource->hwndChild;
}
}
// set descriptor
if(pMainGroup->nMask&SHBIF_DESCRIPTOR)
{
// check if property is to set/remove
if(pSource->pDescriptor!=NULL)
{
int nDescriptorCopyFlag=nCopyFlag&~SHB_CPYINFO_COPY;
if(pDest->pDescriptor==NULL)
{
// create descriptor if haven't been created yet
pDest->pDescriptor=AddDescriptor();
nDescriptorCopyFlag|=SHB_CPYINFO_COPY;
}
ASSERT(pDest->pDescriptor);
// copy sorce descriptor to dest decriptor
if(!CopyDescriptor(pDest->pDescriptor,pSource->pDescriptor,
nDescriptorCopyFlag))
return FALSE;
pDest->nMask|=SHBIF_DESCRIPTOR;
}
else
{
// remove descriptor
if(pDest->pDescriptor!=NULL)
{
// try to find group by descriptor
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_DESCRIPTOR;
shbGroup.pDescriptor=pDest->pDescriptor;
HSHBGROUP hFindGroup=FindGroup(&shbGroup);
// if find any
if(hFindGroup==NULL)
{
// v9.3 - update 03 - 64-bit - switch param decl - TD
#ifdef _WIN64
INT_PTR nOrder;
#else
int nOrder;
#endif
UNREFERENCED_PARAMETER(nOrder);
// double check that descriptor was created using AddDescriptor
ASSERT(m_mapDescriptors.Lookup(pDest->pDescriptor,nOrder));
delete pDest->pDescriptor;
m_mapDescriptors.RemoveKey(pDest->pDescriptor);
}
}
pDest->pDescriptor=NULL;
pDest->nMask&=~SHBIF_DESCRIPTOR;
}
}
return TRUE;
}
BOOL COXShortcutBar::CopyDescriptor(LPSHB_DESCRIPTOR pDest,
const LPSHB_DESCRIPTOR pSource,
int nCopyFlag/* = SHB_CPYINFO_SET*/) const
{
ASSERT(pDest);
ASSERT(pSource);
// only these flags can be set
ASSERT((nCopyFlag&~(SHB_CPYINFO_COPY|SHB_CPYINFO_GET|SHB_CPYINFO_SET))==0);
// these two flags cannot be set simultenuosly
ASSERT((nCopyFlag&SHB_CPYINFO_SET)==0 || (nCopyFlag&SHB_CPYINFO_GET)==0);
// verify source and if needed dest descriptors
VERIFY(VerifyDescriptor(pSource));
if((nCopyFlag&SHB_CPYINFO_GET)!=0)
VERIFY(VerifyDescriptor(pDest));
// clean up the dest if SHB_CPYINFO_COPY flag is set
if((nCopyFlag&SHB_CPYINFO_COPY)!=0)
ZeroMemory(pDest,sizeof(SHB_DESCRIPTOR));
// define descriptor which mask will be used to copy information
LPSHB_DESCRIPTOR pMainDescriptor=(((nCopyFlag&SHB_CPYINFO_SET)!=0 ||
(nCopyFlag&SHB_CPYINFO_COPY)!=0) ? pSource : pDest);
if(pMainDescriptor->nMask&SHBIF_CLRBACK)
{
pDest->clrBackground=pSource->clrBackground;
pDest->nMask|=SHBIF_CLRBACK;
}
if(pMainDescriptor->nMask&SHBIF_CLRTEXT)
{
pDest->clrText=pSource->clrText;
pDest->nMask|=SHBIF_CLRTEXT;
}
if(pMainDescriptor->nMask&SHBIF_HDRCLRBACK)
{
pDest->clrHeaderBackground=pSource->clrHeaderBackground;
pDest->nMask|=SHBIF_HDRCLRBACK;
}
if(pMainDescriptor->nMask&SHBIF_HDRCLRTEXT)
{
pDest->clrHeaderText=pSource->clrHeaderText;
pDest->nMask|=SHBIF_HDRCLRTEXT;
}
if(pMainDescriptor->nMask&SHBIF_HDRTEXTFMT)
{
pDest->nHeaderTextFormat=pSource->nHeaderTextFormat;
pDest->nMask|=SHBIF_HDRTEXTFMT;
}
if(pMainDescriptor->nMask&SHBIF_HDRHEIGHT)
{
pDest->nHeaderHeight=pSource->nHeaderHeight;
pDest->nMask|=SHBIF_HDRHEIGHT;
}
if(pMainDescriptor->nMask&SHBIF_FONT)
{
VERIFY(CopyLogFont(&pDest->lfText,&pSource->lfText));
pDest->nMask|=SHBIF_FONT;
}
if(pMainDescriptor->nMask&SHBIF_HDRFONT)
{
VERIFY(CopyLogFont(&pDest->lfHeader,&pSource->lfHeader));
pDest->nMask|=SHBIF_HDRFONT;
}
return TRUE;
}
BOOL COXShortcutBar::CopyLogFont(LPLOGFONT pDest, const LPLOGFONT pSource) const
{
ASSERT(pDest);
ASSERT(pSource);
// copy all elements of LOGFONT structure
pDest->lfHeight=pSource->lfHeight;
pDest->lfWidth=pSource->lfWidth;
pDest->lfEscapement=pSource->lfEscapement;
pDest->lfOrientation=pSource->lfOrientation;
pDest->lfWeight=pSource->lfWeight;
pDest->lfItalic=pSource->lfItalic;
pDest->lfUnderline=pSource->lfUnderline;
pDest->lfStrikeOut=pSource->lfStrikeOut;
pDest->lfCharSet=pSource->lfCharSet;
pDest->lfOutPrecision=pSource->lfOutPrecision;
pDest->lfClipPrecision=pSource->lfClipPrecision;
pDest->lfQuality=pSource->lfQuality;
pDest->lfPitchAndFamily=pSource->lfPitchAndFamily;
UTBStr::tcsncpy(pDest->lfFaceName, LF_FACESIZE, pSource->lfFaceName,LF_FACESIZE);
return TRUE;
}
BOOL COXShortcutBar::CreateEditControl()
{
ASSERT(::IsWindow(GetSafeHwnd()));
if(::IsWindow(m_edit.GetSafeHwnd()))
{
return TRUE;
}
// make sure it's invisible from the beginning
CRect rect(0,0,0,0);
BOOL bResult=m_edit.Create(WS_BORDER,rect,this,SHB_IDCEDIT);
return bResult;
}
BOOL COXShortcutBar::CreateListControl(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
ASSERT(hGroup);
LPSHB_GROUPINFO pSavedGroupInfo;
// group has to be created at the moment
if(!m_mapHandleToInfo.Lookup(hGroup,pSavedGroupInfo))
return FALSE;
ASSERT(pSavedGroupInfo!=NULL);
// double check group info
ASSERT(VerifyGroupInfo(pSavedGroupInfo));
// if list control already exist then destroy it
COXSHBListCtrl* pListCtrl=NULL;
m_mapHandleToListCtrl.Lookup(hGroup,pListCtrl);
if(pListCtrl)
pListCtrl->DestroyWindow();
// default styles that are compatible with default shortcut bar styles
DWORD dwStyle=LVS_SINGLESEL|LVS_SHAREIMAGELISTS|LVS_NOSCROLL|LVS_ICON;
// create initially invisible COXSHBListCtrl
CRect rect(0,0,0,0);
if(pListCtrl->Create(dwStyle,rect,this,(UINT)PtrToUint(hGroup)))
{
// notify list control that we aknowledge it as child window
// and send as lParam the handle of the corresponding group
pListCtrl->SendMessage(SHBM_SETSHBGROUP,(WPARAM)0,(LPARAM)hGroup);
return TRUE;
}
else
return FALSE;
}
COXSHBListCtrl* COXShortcutBar::NewSHBListCtrl()
{
return (new COXSHBListCtrl());
}
void COXShortcutBar::UpdateHeaderOrder(int nFirst, int nLast, int nMargin)
{
// if nLast==-1 then we loop till the last group
if(nLast==-1)
nLast=PtrToInt(GetGroupCount()-1);
// scan through all groups and update order of them correspondingly
HSHBGROUP hGroup;
LPSHB_GROUPINFO pGroupInfo;
POSITION pos=m_mapHandleToInfo.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToInfo.GetNextAssoc(pos,hGroup,pGroupInfo);
ASSERT(hGroup!=NULL);
ASSERT(pGroupInfo!=NULL);
if(pGroupInfo->nOrder>=nFirst && pGroupInfo->nOrder<=nLast)
pGroupInfo->nOrder+=nMargin;
}
}
HSHBGROUP COXShortcutBar::FindGroup(const LPSHB_GROUPINFO pGroupInfo) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
// scan through all groups and check if pGroupInfo is subset of one of them
HSHBGROUP hGroup;
LPSHB_GROUPINFO pSavedGroupInfo;
POSITION pos=m_mapHandleToInfo.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToInfo.GetNextAssoc(pos,hGroup,pSavedGroupInfo);
ASSERT(hGroup!=NULL);
ASSERT(pSavedGroupInfo!=NULL);
// check if pSavedGroupInfo contains pGroupInfo as subset
if(CompareGroups(pGroupInfo,pSavedGroupInfo))
return hGroup;
}
return NULL;
}
HSHBGROUP COXShortcutBar::FindGroupByOrder(int nOrder) const
{
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_ORDER;
shbGroup.nOrder=nOrder;
return FindGroup(&shbGroup);
}
HSHBGROUP COXShortcutBar::FindGroupByParam(LPARAM lParam) const
{
SHB_GROUPINFO shbGroup;
shbGroup.nMask=SHBIF_PARAM;
shbGroup.lParam=lParam;
return FindGroup(&shbGroup);
}
HSHBGROUP COXShortcutBar::FindGroupByTitle(LPCTSTR lpszTitle) const
{
SHB_GROUPINFO shbGroup;
shbGroup.pszText=(LPTSTR)lpszTitle;
shbGroup.nTextMax=lstrlen(lpszTitle);
shbGroup.nMask=SHBIF_TEXT;
return FindGroup(&shbGroup);
}
// returns TRUE if all of elements from pGroup are the same in pGroupCompareTo
BOOL COXShortcutBar::CompareGroups(const LPSHB_GROUPINFO pGroup,
const LPSHB_GROUPINFO pGroupCompareTo) const
{
ASSERT(pGroup);
ASSERT(pGroupCompareTo);
// verify both groups
if(!VerifyGroupInfo(pGroup) || !VerifyGroupInfo(pGroupCompareTo))
return FALSE;
// pGroup should be a subset of pGroupCompareTo
if((pGroup->nMask&~pGroupCompareTo->nMask)!=0)
return FALSE;
// text
if(pGroup->nMask&SHBIF_TEXT)
if(_tcsncmp(pGroup->pszText,pGroupCompareTo->pszText,pGroup->nTextMax)!=0)
return FALSE;
// image
if(pGroup->nMask&SHBIF_IMAGE)
if(pGroup->nImage!=pGroupCompareTo->nImage)
return FALSE;
// image expanded
if(pGroup->nMask&SHBIF_IMAGEEXPANDED)
if(pGroup->nImageExpanded!=pGroupCompareTo->nImageExpanded)
return FALSE;
// lParam
if(pGroup->nMask&SHBIF_PARAM)
if(pGroup->lParam!=pGroupCompareTo->lParam)
return FALSE;
// order
if(pGroup->nMask&SHBIF_ORDER)
if(pGroup->nOrder!=pGroupCompareTo->nOrder)
return FALSE;
// view
if(pGroup->nMask&SHBIF_VIEW)
if(pGroup->nView!=pGroupCompareTo->nView)
return FALSE;
// descriptor - we check only pointers to SHB_DESCRIPTOR structures if they are the same
if(pGroup->nMask&SHBIF_DESCRIPTOR)
if(pGroup->pDescriptor!=pGroupCompareTo->pDescriptor)
return FALSE;
// child window
if(pGroup->nMask&SHBIF_CHILDWND)
if(pGroup->hwndChild!=pGroupCompareTo->hwndChild)
return FALSE;
return TRUE;
}
void COXShortcutBar::CalculateBoundRects()
{
ASSERT(::IsWindow(GetSafeHwnd()));
// clean up map of all bound rectangles
m_rectChildWnd.SetRectEmpty();
m_mapHandleToBoundRect.RemoveAll();
CRect rect;
GetClientRect(rect);
int nBottom=rect.bottom;
int nCount=PtrToInt(GetGroupCount());
if(nCount==0)
return;
COXShortcutBar * me = const_cast<COXShortcutBar *>(this);
COXShortcutBarSkin * skin = me->GetShortcutBarSkin();
bool bExpandCells = (skin->AnimateSelection());
// loop through all groups by their order
CRect rectOld;
HSHBGROUP hGroup;
SHB_GROUPINFO shbGroup;
for(int nIndex=0; nIndex<nCount; nIndex++)
{
hGroup=FindGroupByOrder(nIndex);
VERIFY(hGroup!=NULL);
// double check that everything alright with group info integrity
ASSERT(GetGroupInfo(hGroup,&shbGroup,TRUE));
ASSERT(VerifyGroupInfo(&shbGroup));
// just add the height of the group
rect.bottom=rect.top+GetGroupHeaderHeight(hGroup);
m_mapHandleToBoundRect.SetAt(hGroup,rect);
// don't forget about margin between groups
rect.top=rect.bottom+m_nGroupMargin;
}
// if there is space left to display child window then try to define
// the coordinates of its rectangle
if(rect.bottom<nBottom || bExpandCells)
{
// we display only child window of expanded group
hGroup=GetExpandedGroup();
if(hGroup!=NULL)
{
CRect rectExpanded;
VERIFY(m_mapHandleToBoundRect.Lookup(hGroup,rectExpanded));
m_rectChildWnd=rectExpanded;
m_rectChildWnd.top= bExpandCells ? m_rectChildWnd.bottom : ( (skin->AnimateSelection()) ? 0 : DFLT_TOPHDRHEIGHT2003);
m_rectChildWnd.bottom+=nBottom-rect.bottom - (bExpandCells ? ( (skin->AnimateSelection()) ? 0 : DFLT_TOPHDRHEIGHT2003 ) : m_rectChildWnd.bottom);
// deflate by margins
m_rectChildWnd.DeflateRect(m_rectChildWndMargins);
if(m_rectChildWnd.top>=m_rectChildWnd.bottom ||
m_rectChildWnd.left>=m_rectChildWnd.right)
m_rectChildWnd.SetRectEmpty();
// update coordinates of header rectangles of all groups that are placed
// to the bottom of shortcut bar of expanded group
UpdateBoundRects((bExpandCells ? rectExpanded.bottom+m_nGroupMargin : 0),nBottom-rect.bottom);
}
}
}
void COXShortcutBar::UpdateBoundRects(int nStartFrom, int nMargin)
{
ASSERT(::IsWindow(GetSafeHwnd()));
VERIFY(nMargin>=0);
CPoint ptMargin(0,nMargin);
// check shortcut bar integrity
ASSERT(m_mapHandleToBoundRect.GetCount()==m_mapHandleToInfo.GetCount());
// scan through all groups
HSHBGROUP hGroup;
CRect rect;
POSITION pos=m_mapHandleToBoundRect.GetStartPosition();
while(pos!=NULL)
{
m_mapHandleToBoundRect.GetNextAssoc(pos,hGroup,rect);
ASSERT(hGroup!=NULL);
// update those header rectangles that are placed down to the bottom of
// nStartFrom coordinate
if(rect.top>=nStartFrom)
{
rect+=ptMargin;
m_mapHandleToBoundRect.SetAt(hGroup,rect);
}
}
}
void COXShortcutBar::HideChildWnd(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
if(hGroup==NULL)
return;
// check if the group is already deleted
LPSHB_GROUPINFO lpshb;
if(!m_mapHandleToInfo.Lookup(hGroup,lpshb))
return;
// get handle of any child window associated with any group (whether it is
// COXSHBListCtrl window or application defined window)
HWND hWnd=GetGroupChildWndHandle(hGroup);
ASSERT(hWnd);
// just hide it
if(::IsWindow(hWnd))
::ShowWindow(hWnd,SW_HIDE);
}
void COXShortcutBar::ShowChildWnd(HSHBGROUP hGroup, BOOL bRedraw/* = TRUE*/)
{
ASSERT(::IsWindow(GetSafeHwnd()));
if(hGroup==NULL)
return;
// get handle of any child window associated with any group (whether it is
// COXSHBListCtrl window or application defined window)
HWND hWnd=GetGroupChildWndHandle(hGroup);
ASSERT(hWnd);
// window has to exist at the moment
ASSERT(::IsWindow(hWnd));
// check if there is any space where we can display child window
// of expanded group
if(!m_rectChildWnd.IsRectEmpty())
{
CRect rectWindow;
::GetWindowRect(hWnd,rectWindow);
// probably resize it
::MoveWindow(hWnd,m_rectChildWnd.left,m_rectChildWnd.top,
m_rectChildWnd.Width(),m_rectChildWnd.Height(),FALSE);
// redraw if specified
if(bRedraw)
::RedrawWindow(hWnd,NULL,NULL,RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);
// and show it
::ShowWindow(hWnd,SW_SHOW);
}
else
// there is no space to display it
::ShowWindow(hWnd,SW_HIDE);
}
void COXShortcutBar::FillBackground(CDC* pDC)
{
ASSERT(::IsWindow(GetSafeHwnd()));
// get background color of expanded group
COLORREF clrBackground;
HSHBGROUP hGroup=GetExpandedGroup();
if(hGroup!=NULL)
{
clrBackground=GetGroupBkColor(hGroup);
VERIFY(clrBackground!=ID_COLOR_NONE);
}
else
clrBackground = GetShortcutBarSkin()->GetBackgroundColor(this);
CBrush brush(clrBackground);
// optimize filling of background by excluding from client rectangle
// all group headers rect and child window rectangle of expanded group
CRect rect;
GetClientRect(rect);
int iSavedDC = pDC->SaveDC();
// exclude header's rectangles
POSITION pos=m_mapHandleToBoundRect.GetStartPosition();
while(pos!=NULL)
{
CRect rectExclude;
m_mapHandleToBoundRect.GetNextAssoc(pos,hGroup,rectExclude);
ASSERT(hGroup!=NULL);
pDC->ExcludeClipRect(rectExclude);
}
// exclude child window's rectangle
if(!m_rectChildWnd.IsRectEmpty())
pDC->ExcludeClipRect(m_rectChildWnd);
COXShortcutBar * me = const_cast<COXShortcutBar *>(this);
COXShortcutBarSkin * skin = me->GetShortcutBarSkin();
skin->DrawTopHeader(this, pDC);
// fill the rest of background
hGroup = GetExpandedGroup();
if (hGroup != NULL)
{
if (HasGroupBkColor(hGroup))
skin->FillBackground(pDC, rect, this, TRUE, clrBackground);
else
skin->FillBackground(pDC, rect, this);
}
else
skin->FillBackground(pDC, rect, this);
pDC->RestoreDC(iSavedDC);
}
LRESULT COXShortcutBar::SendSHBNotification(LPNMSHORTCUTBAR pNMSHB)
{
ASSERT(::IsWindow(GetSafeHwnd()));
// send standard shortcut bar notification to its parent using
// NMSHORTCUTBAR structure
// notify parent
CWnd* pParentWnd=GetOwner();
if(pParentWnd)
{
// fill notification structure
pNMSHB->hdr.hwndFrom=GetSafeHwnd();
pNMSHB->hdr.idFrom=GetDlgCtrlID();
return (pParentWnd->SendMessage(
WM_NOTIFY,(WPARAM)GetDlgCtrlID(),(LPARAM)pNMSHB));
}
else
{
return (LRESULT)0;
}
}
BOOL COXShortcutBar::GetGroupHeaderRect(HSHBGROUP hGroup, LPRECT lpRect) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
CRect rect;
if(!m_mapHandleToBoundRect.Lookup(hGroup,rect))
{
TRACE(_T("COXShortcutBar::GetGroupHeaderRect: bound rect not found"));
return FALSE;
}
lpRect->left=rect.left;
lpRect->right=rect.right;
lpRect->top=rect.top;
lpRect->bottom=rect.bottom;
return TRUE;
}
BOOL COXShortcutBar::UpdateHeader(HSHBGROUP hGroup)
{
ASSERT(::IsWindow(GetSafeHwnd()));
// redraw header of specified group
//
if(hGroup==NULL)
{
return FALSE;
}
CRect rectHeader;
VERIFY(GetGroupHeaderRect(hGroup,rectHeader));
RedrawWindow(rectHeader);
return TRUE;
}
HWND COXShortcutBar::GetGroupChildWndHandle(HSHBGROUP hGroup) const
{
ASSERT(::IsWindow(GetSafeHwnd()));
// Get window's handle of any child window associated with specified group.
// COXSHBListCtrl or any application defined window have to be set to every group
// in any shortcut bar control
ASSERT(hGroup);
// first check for application defined child window
HWND hWnd=GetGroupChildWnd(hGroup);
if(hWnd==NULL)
{
// after that look for COXSHBListCtrl
COXSHBListCtrl* pListCtrl=GetGroupListCtrl(hGroup);
if(pListCtrl!=NULL)
{
hWnd=pListCtrl->GetSafeHwnd();
}
}
return (hWnd);
}
int COXShortcutBar::SetGroupMargin(int nGroupMargin)
{
int nOldGroupMargin=m_nGroupMargin;
if(m_nGroupMargin!=nGroupMargin)
{
m_nGroupMargin=nGroupMargin;
if(::IsWindow(GetSafeHwnd()))
{
// reposition groups
CalculateBoundRects();
// notify all childrens about changing in properties of their
// parent shortcut bar
SendMessageToDescendants(
SHBM_SHBINFOCHANGED,(WPARAM)0,(LPARAM)SHBIF_GROUPMARGIN);
}
}
return nOldGroupMargin;
}
CRect COXShortcutBar::SetChildWndMargins(CRect rectChildWndMargins)
{
CRect rectOldChildWndMargins=m_rectChildWndMargins;
if(m_rectChildWndMargins!=rectChildWndMargins)
{
m_rectChildWndMargins=rectChildWndMargins;
if(::IsWindow(GetSafeHwnd()))
{
// reposition groups
CalculateBoundRects();
// notify all childrens about changing in properties of their
// parent shortcut bar
SendMessageToDescendants(
SHBM_SHBINFOCHANGED,(WPARAM)0,(LPARAM)SHBIF_CHILDMARGINS);
}
}
return rectOldChildWndMargins;
}
CSize COXShortcutBar::SetBarMinSize(CSize sizeMin)
{
CSize sizeOldMin=m_sizeMin;
m_sizeMin=sizeMin;
return sizeOldMin;
}
CSize COXShortcutBar::SetScrollButtonSize(CSize sizeScrollButton)
{
CSize sizeOldScrollButton=m_sizeScrollButton;
if(m_sizeScrollButton!=sizeScrollButton)
{
m_sizeScrollButton=sizeScrollButton;
if(::IsWindow(GetSafeHwnd()))
{
// notify all childrens about changing in properties of their
// parent shortcut bar
SendMessageToDescendants(
SHBM_SHBINFOCHANGED,(WPARAM)0,(LPARAM)SHBIF_SCRLBTNSIZE);
}
}
return sizeOldScrollButton;
}
UINT COXShortcutBar::SetScrollingDelay(UINT nScrollingDelay)
{
UINT nOldScrollingDelay=m_nScrollingDelay;
if(m_nScrollingDelay!=nScrollingDelay)
{
m_nScrollingDelay=nScrollingDelay;
if(::IsWindow(GetSafeHwnd()))
{
// notify all childrens about changing in properties of their
// parent shortcut bar
SendMessageToDescendants(
SHBM_SHBINFOCHANGED,(WPARAM)0,(LPARAM)SHBIF_SCRLDELAY);
}
}
return nOldScrollingDelay;
}
UINT COXShortcutBar::SetAutoScrollingDelay(UINT nAutoScrollingDelay)
{
UINT nOldAutoScrollingDelay=m_nAutoScrollingDelay;
if(m_nAutoScrollingDelay!=nAutoScrollingDelay)
{
m_nAutoScrollingDelay=nAutoScrollingDelay;
// notify all childrens about changing in properties of their
// parent shortcut bar
if(::IsWindow(GetSafeHwnd()))
{
SendMessageToDescendants(
SHBM_SHBINFOCHANGED,(WPARAM)0,(LPARAM)SHBIF_AUTOSCRLDELAY);
}
}
return nOldAutoScrollingDelay;
}
UINT COXShortcutBar::SetAutoExpandDelay(UINT nAutoExpandDelay)
{
UINT nOldAutoExpandDelay=m_nAutoExpandDelay;
if(m_nAutoExpandDelay!=nAutoExpandDelay)
{
m_nAutoExpandDelay=nAutoExpandDelay;
if(::IsWindow(GetSafeHwnd()))
{
// notify all childrens about change in properties of their
// parent shortcut bar
SendMessageToDescendants(
SHBM_SHBINFOCHANGED,(WPARAM)0,(LPARAM)SHBIF_AUTOEXPANDDELAY);
}
}
return nOldAutoExpandDelay;
}
BOOL COXShortcutBar::InitShortcutBar()
{
ASSERT(::IsWindow(GetSafeHwnd()));
// create edit control used to edit header text
if(!CreateEditControl())
{
TRACE(_T("COXShortcutBar::InitShortcutBar: failed to create edit control"));
return FALSE;
}
// tooltips must be always enabled
EnableToolTips(TRUE);
// set timer for checking which group the mouse cursor is over
m_nCheckMouseIsOverGroupID=SetTimer(
ID_CHECKMOUSEISOVERGROUP,DFLT_CHECKMOUSEISOVERGROUP,NULL);
ASSERT(m_nCheckMouseIsOverGroupID!=0);
// register OLE Drag'n'Drop
COleDropTarget* pOleDropTarget=GetDropTarget();
ASSERT(pOleDropTarget!=NULL);
if(!pOleDropTarget->Register(this))
{
TRACE(_T("COXShortcutBar::InitShortcutBar: failed to register the shortcut bar with COleDropTarget\n"));
TRACE(_T("COXShortcutBar: you've probably forgot to initialize OLE libraries using AfxOleInit function\n"));
}
return TRUE;
}
COleDropTarget* COXShortcutBar::GetDropTarget()
{
// notify parent to give it a chance to provide application specific
// COleDropTarget
NMSHORTCUTBAR nmshb;
nmshb.hdr.code=SHBN_GETDROPTARGET;
nmshb.lParam=(LPARAM)NULL;
COleDropTarget* pOleDropTarget=NULL;
// check if parent want to set its own drop target object
if(SendSHBNotification(&nmshb) && nmshb.lParam!=NULL)
pOleDropTarget=(COleDropTarget*)nmshb.lParam;
else
pOleDropTarget=(COleDropTarget*)&m_oleDropTarget;
ASSERT(pOleDropTarget!=NULL);
return pOleDropTarget;
}
void COXShortcutBar::SetMouseIsOverGroup(HSHBGROUP hGroup)
{
// reset handle to the group that is positioned under mouse cursor
if(m_hLastMouseIsOverGroup!=hGroup)
{
BOOL bFlat=((GetBarStyle() & SHBS_FLATGROUPBUTTON)==SHBS_FLATGROUPBUTTON);
HSHBGROUP hOldMouseIsOverGroup=m_hLastMouseIsOverGroup;
m_hLastMouseIsOverGroup=hGroup;
if(bFlat)
{
UpdateHeader(hOldMouseIsOverGroup);
UpdateHeader(m_hLastMouseIsOverGroup);
}
}
}
COXShortcutBarSkin* COXShortcutBar::GetShortcutBarSkin()
{
// Check if the app is derived from COXSkinnedApp
COXSkinnedApp* pSkinnedApp = DYNAMIC_DOWNCAST(COXSkinnedApp, AfxGetApp());
if (pSkinnedApp != NULL && pSkinnedApp->GetCurrentSkin() != NULL)
return pSkinnedApp->GetCurrentSkin()->GetShortcutBarSkin();
else
{
// Create a classic skin for this class if not created already
if (m_pShortcutBarSkin == NULL)
m_pShortcutBarSkin = new COXShortcutBarSkinClassic();
return m_pShortcutBarSkin;
}
}
int CALLBACK COXShortcutBar::CompareHeaders(LPARAM lParam1, LPARAM lParam2,
LPARAM lParamSort)
{
#if defined (_WINDLL)
#if defined (_AFXDLL)
AFX_MANAGE_STATE(AfxGetAppModuleState());
#else
AFX_MANAGE_STATE(AfxGetStaticModuleState());
#endif
#endif
// lParamSort is pointer to shortcut bar control
COXShortcutBar* pShortcutBar=(COXShortcutBar*)lParamSort;
ASSERT(pShortcutBar);
// while lParam1 and lParam2 are handles of compared groups
HSHBGROUP hGroup1=(HSHBGROUP)lParam1;
HSHBGROUP hGroup2=(HSHBGROUP)lParam2;
ASSERT(hGroup1 && hGroup2);
// get the text of groups
CString sText1=pShortcutBar->GetGroupText(hGroup1);
CString sText2=pShortcutBar->GetGroupText(hGroup2);
// just use alphabetical, nocase compare function to compare group headers text
return sText1.CompareNoCase(sText2);
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
COLORREF UpdateColor(COLORREF clr, int nOffset)
{
ASSERT(abs(nOffset)<256);
int rValue=GetRValue(clr)+nOffset;
int gValue=GetGValue(clr)+nOffset;
int bValue=GetRValue(clr)+nOffset;
if(nOffset>0)
{
rValue=rValue>255 ? 255 : rValue;
gValue=gValue>255 ? 255 : gValue;
bValue=bValue>255 ? 255 : bValue;
}
else
{
rValue=rValue<0 ? 0 : rValue;
gValue=gValue<0 ? 0 : gValue;
bValue=bValue<0 ? 0 : bValue;
}
return RGB(rValue,gValue,bValue);
}
COLORREF InvertColor(COLORREF clr)
{
return RGB(255-GetRValue(clr),255-GetGValue(clr),255-GetBValue(clr));
}
BOOL IsColorCloseTo(COLORREF clr,COLORREF clrCompareTo,UINT nMaxMargin)
{
UINT nMargin=(abs(GetRValue(clr)-GetRValue(clrCompareTo))+
abs(GetGValue(clr)-GetGValue(clrCompareTo))+
abs(GetBValue(clr)-GetBValue(clrCompareTo)))/3;
return (nMaxMargin>=nMargin);
}
void* CopyImageFromIL(CImageList* pil, int nImage, DWORD& nImageSize)
{
ASSERT(pil!=NULL);
ASSERT(nImage>=0 && nImage<pil->GetImageCount());
IMAGEINFO imageInfo;
VERIFY(pil->GetImageInfo(nImage,&imageInfo));
CRect rect=imageInfo.rcImage;
ASSERT(!rect.IsRectEmpty());
CImageList il;
VERIFY(il.Create(rect.Width(),rect.Height(),ILC_MASK,1,0));
HICON hIcon=pil->ExtractIcon(nImage);
ASSERT(hIcon!=NULL);
VERIFY(il.Add(hIcon)!=-1);
VERIFY(::DestroyIcon(hIcon));
CMemFile memFile;
CArchive ar(&memFile,CArchive::store);
VERIFY(il.Write(&ar));
ar.Close();
nImageSize = (DWORD) memFile.GetLength();
void* pBuffer=malloc(nImageSize);
ASSERT(pBuffer!=NULL);
BYTE* buf=memFile.Detach();
memcpy(pBuffer,(void*)buf,nImageSize);
ASSERT(pBuffer!=NULL);
free(buf);
return pBuffer;
}
int CopyImageToIL(CImageList* pil, void* pBuffer, DWORD nBufferLength)
{
/// ASSERT(pil!=NULL && pil->GetImageCount()>0);
ASSERT(pil!=NULL);
ASSERT(pBuffer!=NULL && nBufferLength>0);
CMemFile memFile((BYTE*)pBuffer,(UINT)nBufferLength);
CArchive ar(&memFile,CArchive::load);
CImageList il;
VERIFY(il.Read(&ar));
ar.Close();
ASSERT(il.GetImageCount()==1);
HICON hIcon=il.ExtractIcon(0);
ASSERT(hIcon!=NULL);
if(pil->GetSafeHandle()==NULL)
{
IMAGEINFO imageInfo;
VERIFY(il.GetImageInfo(0,&imageInfo));
CRect rect=imageInfo.rcImage;
ASSERT(!rect.IsRectEmpty());
VERIFY(pil->Create(rect.Width(),rect.Height(),ILC_MASK,1,0));
}
int nImageIndex=pil->Add(hIcon);
VERIFY(::DestroyIcon(hIcon));
return nImageIndex;
}
| mit |
smarter-solutions/google-play-scraper | src/GooglePlayScraper/Exception/HtmlImportException.php | 508 | <?php
/*
* This file is part of the GooglePlayScraper package.
*
* (c) Smarter Solutions <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SmarterSolutions\PhpTools\GooglePlayScraper\Exception;
/**
* This exception is thrown when can not import html from a given url.
*
* @author Jerry Anselmi <[email protected]>
*/
class HtmlImportException extends \RuntimeException
{
}
| mit |
jarhart/rattler | lib/rattler/compiler/parser_generator/predicate_propogating.rb | 682 | require 'rattler/compiler/parser_generator'
module Rattler::Compiler::ParserGenerator
# @private
module PredicatePropogating #:nodoc:
def gen_assert(parser, scope = ParserScope.empty)
propogate_gen parser.child, :assert, scope
end
def gen_disallow(parser, scope = ParserScope.empty)
propogate_gen parser.child, :disallow, scope
end
def gen_intermediate_assert(parser, scope = ParserScope.empty)
propogate_gen parser.child, :intermediate_assert, scope
end
def gen_intermediate_disallow(parser, scope = ParserScope.empty)
propogate_gen parser.child, :intermediate_disallow, scope
end
end
end
| mit |
mholt/json-to-go | json-to-go.js | 10952 | /*
JSON-to-Go
by Matt Holt
https://github.com/mholt/json-to-go
A simple utility to translate JSON into a Go type definition.
*/
function jsonToGo(json, typename, flatten = true, example = false)
{
let data;
let scope;
let go = "";
let tabs = 0;
const seen = {};
const stack = [];
let accumulator = "";
let innerTabs = 0;
let parent = "";
try
{
data = JSON.parse(json.replace(/:(\s*\d*)\.0/g, ":$1.1")); // hack that forces floats to stay as floats
scope = data;
}
catch (e)
{
return {
go: "",
error: e.message
};
}
typename = format(typename || "AutoGenerated");
append(`type ${typename} `);
parseScope(scope);
return {
go: flatten
? go += accumulator
: go
};
function parseScope(scope, depth = 0)
{
if (typeof scope === "object" && scope !== null)
{
if (Array.isArray(scope))
{
let sliceType;
const scopeLength = scope.length;
for (let i = 0; i < scopeLength; i++)
{
const thisType = goType(scope[i]);
if (!sliceType)
sliceType = thisType;
else if (sliceType != thisType)
{
sliceType = mostSpecificPossibleGoType(thisType, sliceType);
if (sliceType == "interface{}")
break;
}
}
const slice = flatten && ["struct", "slice"].includes(sliceType)
? `[]${parent}`
: `[]`;
if (flatten && depth >= 2)
appender(slice);
else
append(slice)
if (sliceType == "struct") {
const allFields = {};
// for each field counts how many times appears
for (let i = 0; i < scopeLength; i++)
{
const keys = Object.keys(scope[i])
for (let k in keys)
{
let keyname = keys[k];
if (!(keyname in allFields)) {
allFields[keyname] = {
value: scope[i][keyname],
count: 0
}
}
else {
const existingValue = allFields[keyname].value;
const currentValue = scope[i][keyname];
if (compareObjects(existingValue, currentValue)) {
const comparisonResult = compareObjectKeys(
Object.keys(currentValue),
Object.keys(existingValue)
)
if (!comparisonResult) {
keyname = `${keyname}_${uuidv4()}`;
allFields[keyname] = {
value: currentValue,
count: 0
};
}
}
}
allFields[keyname].count++;
}
}
// create a common struct with all fields found in the current array
// omitempty dict indicates if a field is optional
const keys = Object.keys(allFields), struct = {}, omitempty = {};
for (let k in keys)
{
const keyname = keys[k], elem = allFields[keyname];
struct[keyname] = elem.value;
omitempty[keyname] = elem.count != scopeLength;
}
parseStruct(depth + 1, innerTabs, struct, omitempty); // finally parse the struct !!
}
else if (sliceType == "slice") {
parseScope(scope[0], depth)
}
else {
if (flatten && depth >= 2) {
appender(sliceType || "interface{}");
} else {
append(sliceType || "interface{}");
}
}
}
else
{
if (flatten) {
if (depth >= 2){
appender(parent)
}
else {
append(parent)
}
}
parseStruct(depth + 1, innerTabs, scope);
}
}
else {
if (flatten && depth >= 2){
appender(goType(scope));
}
else {
append(goType(scope));
}
}
}
function parseStruct(depth, innerTabs, scope, omitempty)
{
if (flatten) {
stack.push(
depth >= 2
? "\n"
: ""
)
}
const seenTypeNames = [];
if (flatten && depth >= 2)
{
const parentType = `type ${parent}`;
const scopeKeys = formatScopeKeys(Object.keys(scope));
// this can only handle two duplicate items
// future improvement will handle the case where there could
// three or more duplicate keys with different values
if (parent in seen && compareObjectKeys(scopeKeys, seen[parent])) {
stack.pop();
return
}
seen[parent] = scopeKeys;
appender(`${parentType} struct {\n`);
++innerTabs;
const keys = Object.keys(scope);
for (let i in keys)
{
const keyname = getOriginalName(keys[i]);
indenter(innerTabs)
const typename = uniqueTypeName(format(keyname), seenTypeNames)
seenTypeNames.push(typename)
appender(typename+" ");
parent = typename
parseScope(scope[keys[i]], depth);
appender(' `json:"'+keyname);
if (omitempty && omitempty[keys[i]] === true)
{
appender(',omitempty');
}
appender('"`\n');
}
indenter(--innerTabs);
appender("}");
}
else
{
append("struct {\n");
++tabs;
const keys = Object.keys(scope);
for (let i in keys)
{
const keyname = getOriginalName(keys[i]);
indent(tabs);
const typename = uniqueTypeName(format(keyname), seenTypeNames)
seenTypeNames.push(typename)
append(typename+" ");
parent = typename
parseScope(scope[keys[i]], depth);
append(' `json:"'+keyname);
if (omitempty && omitempty[keys[i]] === true)
{
append(',omitempty');
}
if (example && scope[keys[i]] !== "" && typeof scope[keys[i]] !== "object")
{
append('" example:"'+scope[keys[i]])
}
append('"`\n');
}
indent(--tabs);
append("}");
}
if (flatten)
accumulator += stack.pop();
}
function indent(tabs)
{
for (let i = 0; i < tabs; i++)
go += '\t';
}
function append(str)
{
go += str;
}
function indenter(tabs)
{
for (let i = 0; i < tabs; i++)
stack[stack.length - 1] += '\t';
}
function appender(str)
{
stack[stack.length - 1] += str;
}
// Generate a unique name to avoid duplicate struct field names.
// This function appends a number at the end of the field name.
function uniqueTypeName(name, seen) {
if (seen.indexOf(name) === -1) {
return name;
}
let i = 0;
while (true) {
let newName = name + i.toString();
if (seen.indexOf(newName) === -1) {
return newName;
}
i++;
}
}
// Sanitizes and formats a string to make an appropriate identifier in Go
function format(str)
{
str = formatNumber(str);
let sanitized = toProperCase(str).replace(/[^a-z0-9]/ig, "")
if (!sanitized) {
return "NAMING_FAILED";
}
// After sanitizing the remaining characters can start with a number.
// Run the sanitized string again trough formatNumber to make sure the identifier is Num[0-9] or Zero_... instead of 1.
return formatNumber(sanitized)
}
// Adds a prefix to a number to make an appropriate identifier in Go
function formatNumber(str) {
if (!str)
return "";
else if (str.match(/^\d+$/))
str = "Num" + str;
else if (str.charAt(0).match(/\d/))
{
const numbers = {'0': "Zero_", '1': "One_", '2': "Two_", '3': "Three_",
'4': "Four_", '5': "Five_", '6': "Six_", '7': "Seven_",
'8': "Eight_", '9': "Nine_"};
str = numbers[str.charAt(0)] + str.substr(1);
}
return str;
}
// Determines the most appropriate Go type
function goType(val)
{
if (val === null)
return "interface{}";
switch (typeof val)
{
case "string":
if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val))
return "time.Time";
else
return "string";
case "number":
if (val % 1 === 0)
{
if (val > -2147483648 && val < 2147483647)
return "int";
else
return "int64";
}
else
return "float64";
case "boolean":
return "bool";
case "object":
if (Array.isArray(val))
return "slice";
return "struct";
default:
return "interface{}";
}
}
// Given two types, returns the more specific of the two
function mostSpecificPossibleGoType(typ1, typ2)
{
if (typ1.substr(0, 5) == "float"
&& typ2.substr(0, 3) == "int")
return typ1;
else if (typ1.substr(0, 3) == "int"
&& typ2.substr(0, 5) == "float")
return typ2;
else
return "interface{}";
}
// Proper cases a string according to Go conventions
function toProperCase(str)
{
// ensure that the SCREAMING_SNAKE_CASE is converted to snake_case
if (str.match(/^[_A-Z0-9]+$/)) {
str = str.toLowerCase();
}
// https://github.com/golang/lint/blob/5614ed5bae6fb75893070bdc0996a68765fdd275/lint.go#L771-L810
const commonInitialisms = [
"ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP",
"HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA",
"SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "UID", "UUID",
"URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS"
];
return str.replace(/(^|[^a-zA-Z])([a-z]+)/g, function(unused, sep, frag)
{
if (commonInitialisms.indexOf(frag.toUpperCase()) >= 0)
return sep + frag.toUpperCase();
else
return sep + frag[0].toUpperCase() + frag.substr(1).toLowerCase();
}).replace(/([A-Z])([a-z]+)/g, function(unused, sep, frag)
{
if (commonInitialisms.indexOf(sep + frag.toUpperCase()) >= 0)
return (sep + frag).toUpperCase();
else
return sep + frag;
});
}
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function getOriginalName(unique) {
const reLiteralUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const uuidLength = 36;
if (unique.length >= uuidLength) {
const tail = unique.substr(-uuidLength);
if (reLiteralUUID.test(tail)) {
return unique.slice(0, -1 * (uuidLength + 1))
}
}
return unique
}
function compareObjects(objectA, objectB) {
const object = "[object Object]";
return Object.prototype.toString.call(objectA) === object
&& Object.prototype.toString.call(objectB) === object;
}
function compareObjectKeys(itemAKeys, itemBKeys) {
const lengthA = itemAKeys.length;
const lengthB = itemBKeys.length;
// nothing to compare, probably identical
if (lengthA == 0 && lengthB == 0)
return true;
// duh
if (lengthA != lengthB)
return false;
for (let item of itemAKeys) {
if (!itemBKeys.includes(item))
return false;
}
return true;
}
function formatScopeKeys(keys) {
for (let i in keys) {
keys[i] = format(keys[i]);
}
return keys
}
}
if (typeof module != 'undefined') {
if (!module.parent) {
if (process.argv.length > 2 && process.argv[2] === '-big') {
bufs = []
process.stdin.on('data', function(buf) {
bufs.push(buf)
})
process.stdin.on('end', function() {
const json = Buffer.concat(bufs).toString('utf8')
console.log(jsonToGo(json).go)
})
} else {
process.stdin.on('data', function(buf) {
const json = buf.toString('utf8')
console.log(jsonToGo(json).go)
})
}
} else {
module.exports = jsonToGo
}
}
| mit |
SumOfUs/Champaign | public/service-worker.js | 86 | // for push engage
importScripts("https://sumofus.pushengage.com/service-worker.js");
| mit |
depippo/pitchfork-reviews | lib/pitchfork_reviews.rb | 184 | require 'open-uri'
require 'nokogiri'
require 'pry'
require "pitchfork_reviews/version"
require "pitchfork_reviews/cli"
require "pitchfork_reviews/album"
module PitchforkReviews
end
| mit |
stylelint/stylelint | lib/utils/__tests__/isValidHex.test.js | 685 | 'use strict';
const isValidHex = require('../isValidHex');
it('isValidHex', () => {
expect(isValidHex('#333')).toBeTruthy();
expect(isValidHex('#a3b')).toBeTruthy();
expect(isValidHex('#333a')).toBeTruthy();
expect(isValidHex('#333afe')).toBeTruthy();
expect(isValidHex('#333afeaa')).toBeTruthy();
expect(isValidHex('a')).toBeFalsy();
expect(isValidHex('aaa')).toBeFalsy();
expect(isValidHex('$aaa')).toBeFalsy();
expect(isValidHex('@aaa')).toBeFalsy();
expect(isValidHex('var(aaa)')).toBeFalsy();
expect(isValidHex('#z1')).toBeFalsy();
expect(isValidHex('#00000')).toBeFalsy();
expect(isValidHex('#000000000')).toBeFalsy();
expect(isValidHex('#33z')).toBeFalsy();
});
| mit |
xrtgavin/leetcode | leetcode/reverse-words-in-a-string/solution.go | 359 | func reverseWords(s string) string {
words := strings.Split(s, " ")
n := len(words)
j := 0
for i := 0; i < n; i++ {
if words[i] != "" {
words[j] = words[i]
j++
}
}
for i := 0; i < j/2; i++ {
words[i], words[j-1-i] = words[j-1-i], words[i]
}
return strings.Join(words[:j], " ")
}
| mit |
olenberg/simple_blog | spec/features/log_in_spec.rb | 690 | require 'rails_helper'
feature 'User log in', %q{
In order to be able to write articles and comments
As an authenticated user
I want to be able to log in
} do
given(:user) { create(:user) }
scenario 'Registered user try to log in' do
log_in(user)
expect(page).to have_content 'Logged in successfully.'
expect(current_path).to eq root_path
end
scenario 'Non-registered use try to log in' do
visit new_user_session_path
fill_in 'Email', with: '[email protected]'
fill_in 'Password', with: '12345678'
click_button 'Log in'
expect(page).to have_content 'Invalid email or password.'
expect(current_path).to eq new_user_session_path
end
end
| mit |
talkingscott/foodlog | testdb.js | 562 | 'use strict';
// We implement a promise-like pattern using events
const EventEmitter = require('events');
const items = [];
function addItem(item) {
let emitter = new EventEmitter();
process.nextTick(function () {
item.id = items.length;
items.push(item);
emitter.emit('done', item);
});
return emitter;
}
function getItems(maxCount) {
let emitter = new EventEmitter();
process.nextTick(function () {
emitter.emit('done', items.slice(-maxCount));
});
return emitter;
}
exports.addItem = addItem;
exports.getItems = getItems;
| mit |
debatanu-thakur/music-search | src/app/features/appContentDisplay/appContentDisplay.controller.js | 299 | /**
* @name appContentDisplay.controller
* @description
* This is the controller for the appContentDisplay component
*/
class AppContentDisplayController {
/**
* Initializes the appContentDisplay component
*/
constructor() {
'ngInject';
}
}
export default AppContentDisplayController;
| mit |
Krzysztof-Cieslak/vscode | src/vs/editor/contrib/parameterHints/parameterHintsWidget.ts | 11894 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { domEvent, stop } from 'vs/base/browser/event';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { Event } from 'vs/base/common/event';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import 'vs/css!./parameterHints';
import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { IConfigurationChangedEvent } from 'vs/editor/common/config/editorOptions';
import * as modes from 'vs/editor/common/modes';
import { IModeService } from 'vs/editor/common/services/modeService';
import { MarkdownRenderer } from 'vs/editor/contrib/markdown/markdownRenderer';
import { Context } from 'vs/editor/contrib/parameterHints/provideSignatureHelp';
import * as nls from 'vs/nls';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorHoverBackground, editorHoverBorder, textCodeBlockBackground, textLinkForeground } from 'vs/platform/theme/common/colorRegistry';
import { HIGH_CONTRAST, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ParameterHintsModel, TriggerContext } from 'vs/editor/contrib/parameterHints/parameterHintsModel';
const $ = dom.$;
export class ParameterHintsWidget implements IContentWidget, IDisposable {
private static readonly ID = 'editor.widget.parameterHintsWidget';
private readonly markdownRenderer: MarkdownRenderer;
private renderDisposeables: IDisposable[];
private model: ParameterHintsModel | null;
private readonly keyVisible: IContextKey<boolean>;
private readonly keyMultipleSignatures: IContextKey<boolean>;
private element: HTMLElement;
private signature: HTMLElement;
private docs: HTMLElement;
private overloads: HTMLElement;
private visible: boolean;
private announcedLabel: string | null;
private scrollbar: DomScrollableElement;
private disposables: IDisposable[];
// Editor.IContentWidget.allowEditorOverflow
allowEditorOverflow = true;
constructor(
private readonly editor: ICodeEditor,
@IContextKeyService contextKeyService: IContextKeyService,
@IOpenerService openerService: IOpenerService,
@IModeService modeService: IModeService,
) {
this.markdownRenderer = new MarkdownRenderer(editor, modeService, openerService);
this.model = new ParameterHintsModel(editor);
this.keyVisible = Context.Visible.bindTo(contextKeyService);
this.keyMultipleSignatures = Context.MultipleSignatures.bindTo(contextKeyService);
this.visible = false;
this.disposables = [];
this.disposables.push(this.model.onChangedHints(newParameterHints => {
if (newParameterHints) {
this.show();
this.render(newParameterHints);
} else {
this.hide();
}
}));
}
private createParamaterHintDOMNodes() {
this.element = $('.editor-widget.parameter-hints-widget');
const wrapper = dom.append(this.element, $('.wrapper'));
wrapper.tabIndex = -1;
const buttons = dom.append(wrapper, $('.buttons'));
const previous = dom.append(buttons, $('.button.previous'));
const next = dom.append(buttons, $('.button.next'));
const onPreviousClick = stop(domEvent(previous, 'click'));
onPreviousClick(this.previous, this, this.disposables);
const onNextClick = stop(domEvent(next, 'click'));
onNextClick(this.next, this, this.disposables);
this.overloads = dom.append(wrapper, $('.overloads'));
const body = $('.body');
this.scrollbar = new DomScrollableElement(body, {});
this.disposables.push(this.scrollbar);
wrapper.appendChild(this.scrollbar.getDomNode());
this.signature = dom.append(body, $('.signature'));
this.docs = dom.append(body, $('.docs'));
this.editor.addContentWidget(this);
this.hide();
this.element.style.userSelect = 'text';
this.disposables.push(this.editor.onDidChangeCursorSelection(e => {
if (this.visible) {
this.editor.layoutContentWidget(this);
}
}));
const updateFont = () => {
const fontInfo = this.editor.getConfiguration().fontInfo;
this.element.style.fontSize = `${fontInfo.fontSize}px`;
};
updateFont();
Event.chain<IConfigurationChangedEvent>(this.editor.onDidChangeConfiguration.bind(this.editor))
.filter(e => e.fontInfo)
.on(updateFont, null, this.disposables);
this.disposables.push(this.editor.onDidLayoutChange(e => this.updateMaxHeight()));
this.updateMaxHeight();
}
private show(): void {
if (!this.model || this.visible) {
return;
}
if (!this.element) {
this.createParamaterHintDOMNodes();
}
this.keyVisible.set(true);
this.visible = true;
setTimeout(() => dom.addClass(this.element, 'visible'), 100);
this.editor.layoutContentWidget(this);
}
private hide(): void {
if (!this.model || !this.visible) {
return;
}
if (!this.element) {
this.createParamaterHintDOMNodes();
}
this.keyVisible.reset();
this.visible = false;
this.announcedLabel = null;
dom.removeClass(this.element, 'visible');
this.editor.layoutContentWidget(this);
}
getPosition(): IContentWidgetPosition | null {
if (this.visible) {
return {
position: this.editor.getPosition(),
preference: [ContentWidgetPositionPreference.ABOVE, ContentWidgetPositionPreference.BELOW]
};
}
return null;
}
private render(hints: modes.SignatureHelp): void {
const multiple = hints.signatures.length > 1;
dom.toggleClass(this.element, 'multiple', multiple);
this.keyMultipleSignatures.set(multiple);
this.signature.innerHTML = '';
this.docs.innerHTML = '';
const signature = hints.signatures[hints.activeSignature];
if (!signature) {
return;
}
const code = dom.append(this.signature, $('.code'));
const hasParameters = signature.parameters.length > 0;
const fontInfo = this.editor.getConfiguration().fontInfo;
code.style.fontSize = `${fontInfo.fontSize}px`;
code.style.fontFamily = fontInfo.fontFamily;
if (!hasParameters) {
const label = dom.append(code, $('span'));
label.textContent = signature.label;
} else {
this.renderParameters(code, signature, hints.activeParameter);
}
dispose(this.renderDisposeables);
this.renderDisposeables = [];
const activeParameter = signature.parameters[hints.activeParameter];
if (activeParameter && activeParameter.documentation) {
const documentation = $('span.documentation');
if (typeof activeParameter.documentation === 'string') {
documentation.textContent = activeParameter.documentation;
} else {
const renderedContents = this.markdownRenderer.render(activeParameter.documentation);
dom.addClass(renderedContents.element, 'markdown-docs');
this.renderDisposeables.push(renderedContents);
documentation.appendChild(renderedContents.element);
}
dom.append(this.docs, $('p', {}, documentation));
}
dom.toggleClass(this.signature, 'has-docs', !!signature.documentation);
if (signature.documentation === undefined) { /** no op */ }
else if (typeof signature.documentation === 'string') {
dom.append(this.docs, $('p', {}, signature.documentation));
} else {
const renderedContents = this.markdownRenderer.render(signature.documentation);
dom.addClass(renderedContents.element, 'markdown-docs');
this.renderDisposeables.push(renderedContents);
dom.append(this.docs, renderedContents.element);
}
let currentOverload = String(hints.activeSignature + 1);
if (hints.signatures.length < 10) {
currentOverload += `/${hints.signatures.length}`;
}
this.overloads.textContent = currentOverload;
if (activeParameter) {
const labelToAnnounce = this.getParameterLabel(signature, hints.activeParameter);
// Select method gets called on every user type while parameter hints are visible.
// We do not want to spam the user with same announcements, so we only announce if the current parameter changed.
if (this.announcedLabel !== labelToAnnounce) {
aria.alert(nls.localize('hint', "{0}, hint", labelToAnnounce));
this.announcedLabel = labelToAnnounce;
}
}
this.editor.layoutContentWidget(this);
this.scrollbar.scanDomNode();
}
private renderParameters(parent: HTMLElement, signature: modes.SignatureInformation, currentParameter: number): void {
const [start, end] = this.getParameterLabelOffsets(signature, currentParameter);
const beforeSpan = document.createElement('span');
beforeSpan.textContent = signature.label.substring(0, start);
const paramSpan = document.createElement('span');
paramSpan.textContent = signature.label.substring(start, end);
paramSpan.className = 'parameter active';
const afterSpan = document.createElement('span');
afterSpan.textContent = signature.label.substring(end);
dom.append(parent, beforeSpan, paramSpan, afterSpan);
}
private getParameterLabel(signature: modes.SignatureInformation, paramIdx: number): string {
const param = signature.parameters[paramIdx];
if (typeof param.label === 'string') {
return param.label;
} else {
return signature.label.substring(param.label[0], param.label[1]);
}
}
private getParameterLabelOffsets(signature: modes.SignatureInformation, paramIdx: number): [number, number] {
const param = signature.parameters[paramIdx];
if (!param) {
return [0, 0];
} else if (Array.isArray(param.label)) {
return param.label;
} else {
const idx = signature.label.lastIndexOf(param.label);
return idx >= 0
? [idx, idx + param.label.length]
: [0, 0];
}
}
next(): void {
if (this.model) {
this.editor.focus();
this.model.next();
}
}
previous(): void {
if (this.model) {
this.editor.focus();
this.model.previous();
}
}
cancel(): void {
if (this.model) {
this.model.cancel();
}
}
getDomNode(): HTMLElement {
return this.element;
}
getId(): string {
return ParameterHintsWidget.ID;
}
trigger(context: TriggerContext): void {
if (this.model) {
this.model.trigger(context, 0);
}
}
private updateMaxHeight(): void {
const height = Math.max(this.editor.getLayoutInfo().height / 4, 250);
this.element.style.maxHeight = `${height}px`;
}
dispose(): void {
this.disposables = dispose(this.disposables);
this.renderDisposeables = dispose(this.renderDisposeables);
if (this.model) {
this.model.dispose();
this.model = null;
}
}
}
registerThemingParticipant((theme, collector) => {
const border = theme.getColor(editorHoverBorder);
if (border) {
const borderWidth = theme.type === HIGH_CONTRAST ? 2 : 1;
collector.addRule(`.monaco-editor .parameter-hints-widget { border: ${borderWidth}px solid ${border}; }`);
collector.addRule(`.monaco-editor .parameter-hints-widget.multiple .body { border-left: 1px solid ${border.transparent(0.5)}; }`);
collector.addRule(`.monaco-editor .parameter-hints-widget .signature.has-docs { border-bottom: 1px solid ${border.transparent(0.5)}; }`);
}
const background = theme.getColor(editorHoverBackground);
if (background) {
collector.addRule(`.monaco-editor .parameter-hints-widget { background-color: ${background}; }`);
}
const link = theme.getColor(textLinkForeground);
if (link) {
collector.addRule(`.monaco-editor .parameter-hints-widget a { color: ${link}; }`);
}
const codeBackground = theme.getColor(textCodeBlockBackground);
if (codeBackground) {
collector.addRule(`.monaco-editor .parameter-hints-widget code { background-color: ${codeBackground}; }`);
}
});
| mit |
arsouza/Aritter | src/Infra.Crosscutting/Validations/Rules/GreatherThanRule.cs | 2249 | using System;
using System.Linq.Expressions;
namespace Ritter.Infra.Crosscutting.Validations.Rules
{
public sealed class GreatherThanRule<TValidable, TProp> : PropertyRule<TValidable, TProp>
where TValidable : class
{
private readonly TProp value;
public GreatherThanRule(Expression<Func<TValidable, TProp>> expression, TProp value) : this(expression, value, null) { }
public GreatherThanRule(Expression<Func<TValidable, TProp>> expression, TProp value, string message) : base(expression, message)
{
Ensure.Argument.NotNull(value, nameof(value));
this.value = value;
}
public override bool IsValid(TValidable entity)
{
TProp value = Compile(entity);
if (value is IComparable<TProp> genericComparable)
{
return genericComparable.CompareTo(this.value) > 0;
}
if (value is IComparable comparable)
{
return comparable.CompareTo(this.value) > 0;
}
throw new ArgumentException($"{typeof(TProp).FullName} does not implement IComparable.");
}
}
public sealed class LessThanRule<TValidable, TProp> : PropertyRule<TValidable, TProp>
where TValidable : class
{
private readonly TProp value;
public LessThanRule(Expression<Func<TValidable, TProp>> expression, TProp value) : this(expression, value, null) { }
public LessThanRule(Expression<Func<TValidable, TProp>> expression, TProp value, string message) : base(expression, message)
{
Ensure.Argument.NotNull(value, nameof(value));
this.value = value;
}
public override bool IsValid(TValidable entity)
{
TProp value = Compile(entity);
if (value is IComparable<TProp> genericComparable)
{
return genericComparable.CompareTo(this.value) < 0;
}
if (value is IComparable comparable)
{
return comparable.CompareTo(this.value) < 0;
}
throw new ArgumentException($"{typeof(TProp).FullName} does not implement IComparable.");
}
}
}
| mit |
mxenabled/mx-react-components | docs/components/BarChartDocs.js | 6801 | // eslint-disable react/jsx-indent rule added for proper <Markdown /> formatting
/* eslint-disable react/jsx-indent */
const React = require('react');
const d3 = require('d3');
const moment = require('moment');
const Markdown = require('components/Markdown');
const { Link } = require('react-router');
const { BarChart, BarTimeXAxis, Styles } = require('mx-react-components');
const margins = {
top: 50,
right: 20,
bottom: 40,
left: 20
};
const width = 500 - margins.right - margins.left;
const height = 300 - margins.top - margins.bottom;
const chartData = [];
for (let i = 0; i < 12; i++) {
const date = moment().add(i, 'M');
chartData.push({
label: date.unix(),
value: Math.round(Math.random() * (10000 - -10000) + -10000)
});
}
chartData[4].value = 0;
class BarChartDocs extends React.Component {
state = {
buttonIsActive: false,
spinnerIsActive: false
};
_handleButtonClick = () => {
this.setState({
buttonIsActive: !this.state.buttonIsActive
});
};
_handleSpinnerClick = () => {
this.setState({
spinnerIsActive: !this.state.spinnerIsActive
});
};
render () {
const styles = this.styles();
const ticks = chartData.map(d => {
return d.label;
});
const xAxisScale = d3.scale.ordinal()
.domain(ticks)
.rangeRoundBands([0, width], 0.2);
const xAxis = (
<BarTimeXAxis
tickValues={ticks}
timeAxisFormat='MMM'
transform={`translate(${margins.left},${height + margins.top + margins.bottom / 2})`}
xScaleFunction={xAxisScale}
/>
);
return (
<div>
<h1>
BarChart
<label>A D3 bar chart that supports labels for the bars and tooltips.</label>
</h1>
<h3 style={styles.demoHeader}>Demo</h3>
<BarChart
animateOnHover={true}
data={chartData}
margin={margins}
minBarHeight={1}
style={styles.chart}
threshold={Math.round(Math.random() * 10000)}
xAxis={xAxis}
/>
<h3>Usage</h3>
<h5>animateOnHover <label>Boolean</label></h5>
<p>Default: `false`</p>
<p>If true, individual bars will animate on hover.</p>
<h5>barRadius <label>Number</label></h5>
<p>Default: 3</p>
<p>Radius for the bar applied to the top for positive and bottom for negative values.</p>
<h5>data<label>Array</label></h5>
<p>An array of objects that label and value properties. Each object represents a bar. Optionally allows a color property to override the default color of the bar. Example:</p>
<Markdown lang='js'>
{`
[{
label: 'label', //optional - Anything that can be parsed by d3 as an axis value.
color: '#E3E6E7', //string - hexcode or rgb
value: 10 //number - required, value of bar, determines bar size
}]
`}
</Markdown>
<h5>height <label>Number</label></h5>
<p>Default: 300</p>
<p>Height in pixels of the SVG that renders the bars.</p>
<h5>initialSelectedData <label>Object</label></h5>
<p>Used to set initial selected bar of the graph. If not provided, defaults to no selected bar.</p>
<h5>margin <label>Object</label></h5>
<p>Object containing the desired padding on the SVG to account for axis labels and tooltips.</p>
<p>Default:</p>
<Markdown lang='js'>
{`
{
top: 20,
right: 20,
bottom: 40,
left: 20
}
`}
</Markdown>
<h5>minBarHeight <label>Number</label></h5>
<p>Default: 0</p>
<p>The minimum height for a bar if the value of the data is 0.</p>
<p>NOTE: If minBarHeight is less than barRadius, the radius will be changed to equal the minBarHeight for the bar.</p>
<h5>onClick <label>Function</label></h5>
<p>Callback function that will run when a bar is clicked. Provided the data values from the bar clicked.</p>
<h5>onHover <label>Function</label></h5>
<p>Callback function that will run when a bar is hovered over. Provided the data values from the bar hovered over.</p>
<h5>showTooltips <label>Boolean</label></h5>
<p>Default: `true`</p>
<p>Shows tooltips on BarChart when set to `true`.</p>
<h5>style <label>Object</label></h5>
<p>A object that allows you to override the internal styles</p>
<p>Available keys: </p>
<Markdown>
{`
bar,
positiveBarHover,
negativeBarHover,
positiveBarClicked,
negativeBarClicked,
threshold,
tooltipContainer,
tooltipText
`}
</Markdown>
<h5>theme <label>Object</label></h5>
<p>Customize the component's look. See <Link to='/components/theme'>Theme</Link> for more information.</p>
<h5>threshold <label>Number</label></h5>
<p>A value used to render an optional threshold line.</p>
<h5>tooltipFormat <label>Function</label></h5>
<p>A function that is called to format the value being displayed in the tooltip.</p>
<h5>width <label>Number</label></h5>
<p>Default: 500</p>
<p>Width of the SVG; bars will determine their individual width accordingly.</p>
<h5>xAxis<label>Element</label></h5>
<p>An element representing the xAxis. You are in charge of transforming to the correct location.</p>
<h5>yAxis<label>Element</label></h5>
<p>An element representing the yAxis. You are in charge of transforming to the correct location.</p>
<h3>Example</h3>
<Markdown lang='js'>
{`
const margins = {
top: 50,
right: 20,
bottom: 40,
left: 20
};
const width = 500 - margins.right - margins.left;
const height = 300 - margins.top - margins.bottom;
const data = [{label: 1485470502878, value:, 1337}, {...}];
const threshold = 2000;
const ticks = data.map(d => {
return d.label;
});
const xAxisScale = d3.scale.ordinal()
.domain(ticks)
.rangeRoundBands([0, width], 0.2);
const xAxis = (
<BarTimeXAxis
tickValues={ticks}
timeAxisFormat='MMM'
transform={'translate(${margins.left},${height + margins.top + margins.bottom / 2})'}
xScaleFunction={xAxisScale}
/>
);
return (
<BarChart
data={data}
margin={margins}
minBarHeight={1}
threshold={threshold}
xAxis={xAxis}
/>
);
`}
</Markdown>
</div>
);
}
styles = () => {
return {
demoHeader: {
marginBottom: 20
},
chart: {
positiveBarClicked: {
fill: Styles.Colors.SUCCESS
}
}
};
};
}
module.exports = BarChartDocs;
| mit |
mooso/BlueCoffee | Tests/Microsoft.Experimental.Azure.Cassandra.Tests/CassandraNodeRunnerTest.cs | 1331 | using Microsoft.Experimental.Azure.CommonTestUtilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Experimental.Azure.Cassandra.Tests
{
[TestClass]
public class CassandraNodeRunnerTest
{
[TestMethod]
[Ignore]
public void EndToEndTest()
{
var tempDirectory = @"C:\CassandraTestOutput";
if (Directory.Exists(tempDirectory))
{
Directory.Delete(tempDirectory, recursive: true);
}
var config = new CassandraConfig(
clusterName: "Test cluster",
clusterNodes: new[] { "127.0.0.1" },
dataDirectories: new[] { Path.Combine(tempDirectory, "D1"), Path.Combine(tempDirectory, "D2") },
commitLogDirectory: Path.Combine(tempDirectory, "commitlog"),
savedCachesDirectory: Path.Combine(tempDirectory, "savedcaches"));
var runner = new CassandraNodeRunner(
resourceFileDirectory: ResourcePaths.CassandraResourcesPath,
jarsDirectory: Path.Combine(tempDirectory, "jars"),
javaHome: @"C:\Program Files\Java\jdk1.7.0_21",
logsDirctory: Path.Combine(tempDirectory, "logs"),
configDirectory: Path.Combine(tempDirectory, "conf"),
config: config);
runner.Setup();
runner.Run(runContinuous: false);
}
}
}
| mit |
ignaciocases/hermeneumatics | node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/Function2$mcJJI$sp.js | 1140 | ScalaJS.is.scala_Function2$mcJJI$sp = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_Function2$mcJJI$sp)))
});
ScalaJS.as.scala_Function2$mcJJI$sp = (function(obj) {
if ((ScalaJS.is.scala_Function2$mcJJI$sp(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.Function2$mcJJI$sp")
}
});
ScalaJS.isArrayOf.scala_Function2$mcJJI$sp = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_Function2$mcJJI$sp)))
});
ScalaJS.asArrayOf.scala_Function2$mcJJI$sp = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_Function2$mcJJI$sp(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.Function2$mcJJI$sp;", depth)
}
});
ScalaJS.data.scala_Function2$mcJJI$sp = new ScalaJS.ClassTypeData({
scala_Function2$mcJJI$sp: 0
}, true, "scala.Function2$mcJJI$sp", undefined, {
scala_Function2$mcJJI$sp: 1,
scala_Function2: 1,
java_lang_Object: 1
});
//@ sourceMappingURL=Function2$mcJJI$sp.js.map
| mit |
bhurivaj/cm | application/controllers/HR/Overtime.php | 2267 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Overtime extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library('time');
$this->load->model('HR/HR_Overtime_model','HR_ot_m');
$this->load->model('HR/HR_Emp_model','HR_Emp_m');
}
public function index()
{
if(!$this->ion_auth->logged_in()){
$_SESSION['error_msg'] = 'คุณยังไม่ได้รับสิทธิ์ในส่วนนี้';
$this->session->mark_as_flash('error_msg');
redirect('/login');
}else{
$data['title'] = 'บันทึกลงล่วงเวลา';
$data['table'] = 'Y';
$data['result'] = $this->HR_ot_m->getAll();
$this->load->view('parts/head',$data);
$this->load->view('HR/HR_Overtime_list',$data);
$this->load->view('parts/footer');
}
}
public function data()
{
$data['title'] = 'รายการล่วงเวลา';
$data['execute'] = '
<li><a class="button hollow warning" href="'.site_url('/HR/Overtime').'">กลับ</a></li>
<li><a class="button hollow" href="'.site_url('/HR/Overtime/create').'">พิมพ์รายงาน</a></li>';
if($this->input->post('ot_desc') == null){
$sort = $this->uri->segment(4);
$data['get_group'] = $this->HR_ot_m->get_group($sort);
}
$data['mask'] = '<script language="javascript" src="'.asset_url().'js/js_mask_helper.js'.'""></script>';
$this->load->view('parts/head',$data);
$this->load->view('HR/HR_Overtime_form',$data);
$this->load->view('parts/footer');
$this->load->view('scripts/ot_script');
}
public function sort_get()
{
$sort = $this->input->get('sort');
$data['table'] = $this->HR_ot_m->get_each($sort);
$this->load->view('HR/HR_Overtime_table',$data);
}
public function add_ot()
{
$data = array(
'ot_desc' => $this->input->post('ot_desc'),
'ot_type' => $this->input->post('ot_type'),
'pnch_in' => $this->input->post('pnch_in'),
'pnch_out' => $this->input->post('pnch_out'),
'emp_id' => $this->input->post('emp_id')
);
$this->HR_ot_m->add_ot($data);
}
public function del_ot()
{
$ot_id = $this->input->post('ot_id');
$this->HR_ot_m->del_ot($ot_id);
}
} | mit |
lonfen1108/Coding-Android-master | app/src/main/java/net/coding/program/common/comment/BaseCommentHolder.java | 2504 | package net.coding.program.common.comment;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import net.coding.program.R;
import net.coding.program.common.Global;
import net.coding.program.common.ImageLoadTool;
import net.coding.program.model.BaseComment;
import net.coding.program.model.Commit;
/**
* Created by chaochen on 14-10-27.
*/
public class BaseCommentHolder {
protected ImageView icon;
protected TextView name;
protected TextView time;
protected View layout;
protected Html.ImageGetter imageGetter;
protected ImageLoadTool imageLoadTool;
protected String globalKey = "";
public BaseCommentHolder(View convertView, View.OnClickListener onClickComment, Html.ImageGetter imageGetter, ImageLoadTool imageLoadTool, View.OnClickListener clickUser) {
layout = convertView.findViewById(R.id.Commentlayout);
layout.setOnClickListener(onClickComment);
icon = (ImageView) convertView.findViewById(R.id.icon);
icon.setOnClickListener(clickUser);
name = (TextView) convertView.findViewById(R.id.name);
time = (TextView) convertView.findViewById(R.id.time);
this.imageLoadTool = imageLoadTool;
this.imageGetter = imageGetter;
}
public BaseCommentHolder(View convertView, BaseCommentParam param) {
this(convertView, param.onClickComment, param.imageGetter, param.imageLoadTool, param.clickUser);
}
public void setContent(Object param) {
if (param instanceof BaseComment) {
BaseComment comment = (BaseComment) param;
String nameString = comment.owner.name;
long timeParam = comment.created_at;
String iconUri = comment.owner.avatar;
imageLoadTool.loadImage(icon, iconUri);
icon.setTag(comment.owner.global_key);
name.setText(nameString);
time.setText(Global.dayToNow(timeParam));
layout.setTag(comment);
} else if (param instanceof Commit) {
Commit commit = (Commit) param;
String nameString = commit.getName();
long timeParam = commit.getCommitTime();
String iconUri = commit.getIcon();
imageLoadTool.loadImage(icon, iconUri);
icon.setTag(commit.getGlobalKey());
name.setText(nameString);
time.setText(Global.dayToNow(timeParam));
layout.setTag(commit);
}
}
}
| mit |
leecade/fe | src/dev/index.js | 77 | // export devServer from './devServer'
export mockServer from './mockServer'
| mit |
mayth/parasol | spec/controllers/admin/posts_controller_spec.rb | 4497 | require 'rails_helper'
RSpec.describe Admin::PostsController, type: :controller do
let(:admin) { create(:admin) }
describe 'GET index' do
it 'assigns all posts as @posts' do
sign_in admin
post = create(:post)
get :index
expect(assigns(:posts)).to eq [post]
end
end
describe 'GET show' do
it 'assigns the requested post as @post' do
sign_in admin
post = create(:post)
get :show, id: post.to_param
expect(assigns(:post)).to eq post
end
end
describe 'GET new' do
it 'assigns a new post as @post' do
sign_in admin
get :new
expect(assigns(:post)).to be_a_new Post
end
end
describe 'GET edit' do
it 'assigns the requested post as @post' do
sign_in admin
post = create(:post)
get :edit, id: post.to_param
expect(assigns(:post)).to eq post
end
end
describe 'POST create' do
describe 'with valid params' do
it 'creates a new Post' do
sign_in admin
expect { post :create, post: attributes_for(:post) }
.to change(Post, :count).by(1)
end
it 'assigns a newly created post as @post' do
sign_in admin
post :create, post: attributes_for(:post)
expect(assigns(:post)).to be_a Post
expect(assigns(:post)).to be_persisted
end
it 'redirects to the created post' do
sign_in admin
post :create, post: attributes_for(:post)
expect(response).to redirect_to(admin_post_url(Post.last))
end
end
describe 'with invalid params' do
it 'assigns a newly created but unsaved post as @post' do
sign_in admin
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Post).to receive(:save).and_return(false)
post :create, post: { 'title' => '' }
expect(assigns(:post)).to be_a_new Post
end
it 're-renders the "new" template' do
sign_in admin
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Post).to receive(:save).and_return(false)
post :create, post: { 'title' => '' }
expect(response).to render_template('new')
end
end
end
describe 'PUT update' do
describe 'with valid params' do
it 'updates the requested post' do
sign_in admin
post = create(:post)
# Assuming there are no other posts in the database, this
# specifies that the Post created on the previous line
# receives the :update_attributes message with whatever params are
# submitted in the request.
expect_any_instance_of(Post)
.to receive(:update).with('title' => 'New Title')
put :update, id: post.to_param, post: { 'title' => 'New Title' }
end
it 'assigns the requested post as @post' do
sign_in admin
post = create(:post)
put :update, id: post.to_param, post: attributes_for(:post)
expect(assigns(:post)).to eq post
end
it 'redirects to the post' do
sign_in admin
post = create(:post)
put :update, id: post.to_param, post: attributes_for(:post)
expect(response).to redirect_to(admin_post_url(post))
end
end
describe 'with invalid params' do
it 'assigns the post as @post' do
sign_in admin
post = create(:post)
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Post).to receive(:save).and_return(false)
put :update, id: post.to_param, post: { 'title' => '' }
expect(assigns(:post)).to eq post
end
it 're-renders the "edit" template' do
sign_in admin
post = create(:post)
# Trigger the behavior that occurs when invalid params are submitted
allow_any_instance_of(Post).to receive(:save).and_return(false)
put :update, id: post.to_param, post: { 'title' => '' }
expect(response).to render_template('edit')
end
end
end
describe 'DELETE destroy' do
it 'destroys the requested post' do
sign_in admin
post = create(:post)
expect { delete :destroy, id: post.to_param }
.to change(Post, :count).by(-1)
end
it 'redirects to the posts list' do
sign_in admin
post = create(:post)
delete :destroy, id: post.to_param
expect(response).to redirect_to(admin_posts_url)
end
end
end
| mit |
dakom/basic-site-api | lib/utils/mathextra/mathextra.go | 777 | package mathextra
import (
"math"
"strconv"
)
const LARGEST_BIT uint64 = 1 << (64 - 1)
func Round(num float64) int64 {
return int64(num + math.Copysign(0.5, num))
}
func ToFixed(num float64, precision int) float64 {
output := math.Pow(10, float64(precision))
return float64(Round(num*output)) / output
}
func GetRoundedPercentageAsString(total float64, partial float64) string {
return strconv.FormatInt(Round((partial / total * 100)), 10)
}
func MaxInt64(a int64, b int64) int64 {
if a > b {
return a
}
return b
}
func MaxUInt64(a uint64, b uint64) uint64 {
if a > b {
return a
}
return b
}
func MinInt64(a int64, b int64) int64 {
if a < b {
return a
}
return b
}
func MinUInt64(a uint64, b uint64) uint64 {
if a < b {
return a
}
return b
}
| mit |
dudulab/Astrology_winphone | Astrology/Converter.cs | 663 | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace Astrology
{
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToBoolean(value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(Visibility.Visible);
}
}
}
| mit |
Webb-2/Kollosidan | functions.php | 302 | <?php
// Theme Support
add_theme_support('post-thumbnails');
add_theme_support('menus');
// Add Actions
add_action( 'init', 'register_my_menus' );
//Register the custom menus
function register_my_menus() {
register_nav_menus(
array(
'primary-menu' => __( 'Primary Menu' )
));
}
?> | mit |
dima117/devcon-demo | Todo/Bem/libs/bem-components/common.blocks/spin/spin.tests/gemini.bemjson.js | 696 | ({
block : 'page',
title : 'bem-components: spin',
mods : { theme : 'islands' },
head : [
{ elem : 'css', url : 'gemini.css' }
],
content : [
{ tag : 'h2', content : 'islands' },
['xs', 's', 'm', 'l', 'xl'].map(function(size){
return {
tag : 'p',
content : [
size,
{ tag : 'br' },
{
block : 'spin',
mods : { paused : true, theme : 'islands', visible : true, size : size },
cls : 'islands-' + size
}
]
}
})
]
});
| mit |
devdigital/endeavour | Source/Endeavour.Desktop/Views/OpportunitySearchView.xaml.cs | 685 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Endeavour.Desktop.Views
{
/// <summary>
/// Interaction logic for OpportunitySearchView.xaml
/// </summary>
public partial class OpportunitySearchView : UserControl
{
public OpportunitySearchView()
{
InitializeComponent();
}
}
}
| mit |
MrSoya/soya2d | src/core/Assets.js | 2168 | /**
* 资源类提供了用于获取指定类型资源的服务。这是一个内部类,无法在外部实例化。
* 每个game有且只有一个assets属性,通过该属性可以获取资源。
* ```
* game.assets.sound('bgm').play();
* ```
* @class Assets
*
*/
function Assets(){
this.__assets = {
image:{},
sound:{},
imageFont:{},
atlas:{},
text:{},
xml:{},
json:{}
};
};
Assets.prototype = {
/**
* 获取一个图像资源
* @method image
* @param {String} key 加载资源时指定的key
* @return {HTMLImageElement}
*/
image:function(key){
return this.__assets.image[key];
},
/**
* 获取一个声音资源。
* 如果没有装载声音模块,该方法永远不会返回有效值
* @method sound
* @param {String} key 加载资源时指定的key
* @return {soya2d.Sound}
*/
sound:function(key){
return this.__assets.sound[key];
},
/**
* 获取一个图像文字资源
* @method imageFont
* @param {String} key 加载资源时指定的key
* @return {soya2d.ImageFont}
*/
imageFont:function(key){
return this.__assets.imageFont[key];
},
/**
* 获取一个图像集资源
* @method atlas
* @param {String} key 加载资源时指定的key
* @return {soya2d.Atlas}
*/
atlas:function(key){
return this.__assets.atlas[key];
},
/**
* 获取一个文本资源
* @method text
* @param {String} key 加载资源时指定的key
* @return {String}
*/
text:function(key){
return this.__assets.text[key];
},
/**
* 获取一个xml资源
* @method xml
* @param {String} key 加载资源时指定的key
* @return {Document}
*/
xml:function(key){
return this.__assets.xml[key];
},
/**
* 获取一个json资源
* @method json
* @param {String} key 加载资源时指定的key
* @return {Object}
*/
json:function(key){
return this.__assets.json[key];
}
}
| mit |
davidmarkclements/react-functional | src/index.js | 1514 | import createReactClass from 'create-react-class';
export default function (component, opts = {}) {
if (!component) {
throw new Error(`
[createReactClass(component)] stateless needs a component
`)
}
component = (component instanceof Function) ?
{render: component, ...component} :
component
if (!('render' in component)) {
throw new Error(`
[createReactClass(component)] No render function found.
"component" should be a render function or contain a render function.
`)
}
component = {...component, ...opts}
const {render} = component
const displayName = render.name
const methods = [
'componentWillMount',
'componentDidMount',
'componentWillReceiveProps',
'shouldComponentUpdate',
'componentWillUpdate',
'componentDidUpdate',
'componentWillUnmount'
]
const properties = [
'propTypes',
'defaultProps',
'getDefaultProps',
'displayName'
]
const spec = {
displayName,
render: function () { return render(this.props, this) },
...properties.reduce((o, p) => {
if (!(p in component)) return o
o[p] = component[p]
return o
}, {}),
...methods.reduce((o, m) => {
if (!(m in component)) return o
o[m] = function(input) {
if (!this) throw Error('NO CONTEXT')
const {props, refs} = this
return component[m](...[props, input, refs, this].filter(Boolean))
}
return o
}, {})
}
return createReactClass(spec);
}
| mit |
anomalylabs/users-module | src/User/Register/RegisterFormBuilder.php | 2548 | <?php namespace Anomaly\UsersModule\User\Register;
use Anomaly\Streams\Platform\Ui\Form\FormBuilder;
use Anomaly\UsersModule\User\Register\Command\AssociateActivationRoles;
use Anomaly\UsersModule\User\UserModel;
use Anomaly\UsersModule\User\Validation\ValidatePassword;
/**
* Class RegisterFormBuilder
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
*/
class RegisterFormBuilder extends FormBuilder
{
/**
* The form roles.
*
* @var array
*/
protected $roles = [
'user',
];
/**
* The form model.
*
* @var string
*/
protected $model = UserModel::class;
/**
* The form fields.
*
* @var array
*/
protected $fields = [
'display_name' => [
'instructions' => false,
],
'username' => [
'instructions' => false,
],
'email' => [
'instructions' => false,
],
'password' => [
'instructions' => false,
'rules' => [
'valid_password',
],
'validators' => [
'valid_password' => [
'message' => false,
'handler' => ValidatePassword::class,
],
],
],
];
/**
* The form actions.
*
* @var array
*/
protected $actions = [
'blue' => [
'text' => 'anomaly.module.users::button.register',
],
];
/**
* The form options.
*
* @var array
*/
protected $options = [
'redirect' => '/',
'success_message' => 'anomaly.module.users::success.user_registered',
'pending_message' => 'anomaly.module.users::message.pending_admin_activation',
'confirm_message' => 'anomaly.module.users::message.pending_email_activation',
'activated_message' => 'anomaly.module.users::message.account_activated',
];
/**
* Fired after the form is saved.
*/
public function onSaved()
{
$this->dispatch(new AssociateActivationRoles($this));
}
/**
* Get the roles.
*
* @return array
*/
public function getRoles()
{
return $this->roles;
}
/**
* Set roles.
*
* @param $roles
* @return $this
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
}
| mit |
lift-project/lift | src/test/rodinia/Kmeans.scala | 6254 | package rodinia
import ir.ast._
import ir.{ArrayTypeWSWC, TupleType}
import lift.arithmetic.SizeVar
import opencl.executor._
import opencl.ir._
import opencl.ir.pattern._
import org.junit.Assert._
import org.junit.Test
object Kmeans extends TestWithExecutor {
val P = SizeVar("P") // number of points
val C = SizeVar("C") // number of clusters
val F = SizeVar("F") // number of features
val featuresType = ArrayTypeWSWC(ArrayTypeWSWC(Float, P), F)
val clustersType = ArrayTypeWSWC(ArrayTypeWSWC(Float, F), C)
val update = UserFun("update", Array("dist", "pair"),
"{ return dist + (pair._0 - pair._1) * (pair._0 - pair._1); }",
Seq(Float, TupleType(Float, Float)), Float)
val update2 = UserFun("update", Array("dist", "pair0", "pair1"),
"{ return dist + (pair0 - pair1) * (pair0 - pair1); }",
Seq(Float, Float, Float), Float)
val test = UserFun("test", Array("dist", "tuple"),
"{" +
"float min_dist = tuple._0;" +
"int i = tuple._1;" +
"int index = tuple._2;" +
"if (dist < min_dist) {" +
" Tuple t = {dist, i + 1, i};" +
" return t;" +
"} else {" +
" Tuple t = {min_dist, i + 1, index};" +
" return t;" +
"}" +
"}",
Seq(Float, TupleType(Float, Int, Int)), TupleType(Float, Int, Int))
val select = UserFun("select_", Array("tuple"),
"{ return tuple._2; }",
Seq(TupleType(Float, Int, Int)), Int)
def calculateMembership(points: Array[(Float, Float)], centres: Array[(Float, Float, Int)]): Array[Int] = {
points.map(x => {
centres
.map(c => ((x._1 - c._1) * (x._1 - c._1) + (x._2 - c._2) * (x._2 - c._2), c._3))
.reduce((p1, p2) => if (p1._1 < p2._1) p1 else p2)
._2
})
}
def calculateMembership(points: Array[Array[Float]], centres: Array[Array[Float]]): Array[Int] = {
points.map(x => {
centres.zipWithIndex
.map(c => ((c._1,x).zipped.map((p1, p2) => (p1-p2)*(p1-p2)).sum, c._2))
.reduce((p1, p2) => if (p1._1 < p2._1) p1 else p2)
._2
})
}
}
class Kmeans {
import rodinia.Kmeans._
@Test def kMeansMembership2Dim(): Unit = {
val inputSize = 512
val k = 16
val pointsX = Array.fill(inputSize)(util.Random.nextFloat())
val pointsY = Array.fill(inputSize)(util.Random.nextFloat())
val centresX = Array.fill(k)(util.Random.nextFloat())
val centresY = Array.fill(k)(util.Random.nextFloat())
val indices = Array.range(0, k)
val distance = UserFun("dist", Array("x", "y", "a", "b", "id"), "{ Tuple t = {(x - a) * (x - a) + (y - b) * (y - b), id}; return t; }", Seq(Float, Float, Float, Float, Int), TupleType(Float, Int))
val minimum = UserFun("minimum", Array("x", "y"), "{ return x._0 < y._0 ? x : y; }", Seq(TupleType(Float, Int), TupleType(Float, Int)), TupleType(Float, Int))
val getSecond = UserFun("getSecond", "x", "{ return x._1; }", TupleType(Float, Int), Int)
val points = pointsX zip pointsY
val centres = (centresX, centresY, indices).zipped.toArray
val gold = calculateMembership(points, centres)
val N = SizeVar("N")
val K = SizeVar("K")
val function = fun(
ArrayTypeWSWC(Float, N),
ArrayTypeWSWC(Float, N),
ArrayTypeWSWC(Float, K),
ArrayTypeWSWC(Float, K),
ArrayTypeWSWC(Int, K),
(x, y, a, b, i) => {
MapGlb(fun(xy => {
toGlobal(MapSeq(idI)) o
MapSeq(getSecond) o
ReduceSeq(minimum, (scala.Float.MaxValue, -1)) o
MapSeq(fun(ab => {
distance(Get(xy, 0), Get(xy, 1), Get(ab, 0), Get(ab, 1), Get(ab, 2))
})) $ Zip(a, b, i)
})) $ Zip(x, y)
}
)
val (output, _) = Execute(inputSize)[Array[Int]](function, pointsX, pointsY, centresX, centresY, indices)
assertArrayEquals(gold, output)
}
@Test
def kMeans(): Unit = {
val numPoints = 1024
val numClusters = 5
val numFeatures = 34
val points = Array.fill(numPoints, numFeatures)(util.Random.nextFloat())
val clusters = Array.fill(numClusters, numFeatures)(util.Random.nextFloat())
val gold = calculateMembership(points, clusters)
val kMeans = fun(
featuresType, clustersType,
(features, clusters) => {
features :>> Transpose() :>> MapGlb( \( feature => {
clusters :>> ReduceSeq( \( (tuple, cluster) => {
val dist = Zip(feature, cluster) :>> ReduceSeq(update, 0.0f )
Zip(dist, tuple) :>> MapSeq(test)
}), Value("{3.40282347e+38, 0, 0}", ArrayTypeWSWC(TupleType(Float, Int, Int), 1)) ) :>>
toGlobal(MapSeq(MapSeq(select)))
}) )
})
val (output, _) = Execute(numPoints)[Array[Int]](kMeans, points.transpose, clusters)
assertArrayEquals(gold, output)
}
@Test
def kMeansLocalMemory(): Unit = {
val numPoints = 1024
val numClusters = 5
val numFeatures = 8
val points = Array.fill(numPoints, numFeatures)(util.Random.nextFloat())
val clusters = Array.fill(numClusters, numFeatures)(util.Random.nextFloat())
val gold = calculateMembership(points, clusters)
val splitFactor = 128
val kMeans = fun(
featuresType, clustersType,
(features, clusters) => {
features :>> Transpose() :>> Split(splitFactor) :>> MapWrg(\( featuresChunk =>
clusters :>> toLocal(MapLcl(MapSeq(id))) :>> Let(localClusters =>
MapLcl( \( feature => {
localClusters :>> ReduceSeq( \( (tuple, cluster) => {
val dist = Zip(feature, cluster) :>> ReduceSeq(\((acc, b) => update2(acc, Get(b, 0), Get(b,1))), 0.0f )
Zip(dist, tuple) :>> MapSeq(test)
}), Value("{3.40282347e+38, 0, 0}", ArrayTypeWSWC(TupleType(Float, Int, Int), 1)) ) :>>
toGlobal(MapSeq(MapSeq(select)))
})) $ featuresChunk
)
)) :>> Join()
})
val (output, _) = Execute(numPoints)[Array[Int]](kMeans, points.transpose, clusters)
assertArrayEquals(gold, output)
}
@Test
def kMeans_swap(): Unit = {
val kMeans_swap = fun(
featuresType,
features => {
features :>> MapGlb(MapSeq(id)) :>> TransposeW()
})
val code = Compile(kMeans_swap)
println(code)
}
}
| mit |
bschneier/credit-cards-front-end | src/shared/constants.js | 923 | export default {
AUTHENTICATION_HEADER: 'credit-cards-authentication',
HTTP_METHODS: {
DELETE: 'DELETE',
GET: 'GET',
POST: 'POST',
PUT: 'PUT'
},
HTTP_STATUS_CODES: {
OK: 200,
INVALID_REQUEST: 400,
INVALID_AUTHENTICATION: 401,
NOT_AUTHORIZED: 403,
ERROR: 500
},
LOCAL_STORAGE: {
SESSION_KEY: 'credit-card-rewards-session',
REMEMBER_ME_KEY: 'credit-card-rewards-remember-me'
},
NAV_BAR: {
KEYS: {
SHOP: 1,
DEALS: 2,
CREDIT_CARDS: 3,
MERCHANTS: 4,
PROFILE: 5,
LOGOUT: 6
},
KEY_TO_PATH_MAP: new Map([
[1, '/shop'],
[2, '/deals'],
[3, '/credit-cards'],
[4, '/merchants'],
[5, '/profile']
]),
PATH_TO_KEY_MAP: new Map([
['shop', 1],
['deals', 2],
['credit-cards', 3],
['merchants', 4],
['profile', 5]
])
},
PUB_SUB: {
LOGOUT: 'LOGOUT'
}
}; | mit |
wavefancy/Exome-Java | BIDMC/src/shortestPath/edu/princeton/cs/algs4/DijkstraUndirectedSP.java | 10330 | /******************************************************************************
* Compilation: javac DijkstraUndirectedSP.java
* Execution: java DijkstraUndirectedSP input.txt s
* Dependencies: EdgeWeightedGraph.java IndexMinPQ.java Stack.java Edge.java
* Data files: http://algs4.cs.princeton.edu/43mst/tinyEWG.txt
* http://algs4.cs.princeton.edu/43mst/mediumEWG.txt
* http://algs4.cs.princeton.edu/43mst/largeEWG.txt
*
* Dijkstra's algorithm. Computes the shortest path tree.
* Assumes all weights are nonnegative.
*
* % java DijkstraUndirectedSP tinyEWG.txt 6
* 6 to 0 (0.58) 6-0 0.58000
* 6 to 1 (0.76) 6-2 0.40000 1-2 0.36000
* 6 to 2 (0.40) 6-2 0.40000
* 6 to 3 (0.52) 3-6 0.52000
* 6 to 4 (0.93) 6-4 0.93000
* 6 to 5 (1.02) 6-2 0.40000 2-7 0.34000 5-7 0.28000
* 6 to 6 (0.00)
* 6 to 7 (0.74) 6-2 0.40000 2-7 0.34000
*
* % java DijkstraUndirectedSP mediumEWG.txt 0
* 0 to 0 (0.00)
* 0 to 1 (0.71) 0-44 0.06471 44-93 0.06793 ... 1-107 0.07484
* 0 to 2 (0.65) 0-44 0.06471 44-231 0.10384 ... 2-42 0.11456
* 0 to 3 (0.46) 0-97 0.07705 97-248 0.08598 ... 3-45 0.11902
* ...
*
* % java DijkstraUndirectedSP largeEWG.txt 0
* 0 to 0 (0.00)
* 0 to 1 (0.78) 0-460790 0.00190 460790-696678 0.00173 ... 1-826350 0.00191
* 0 to 2 (0.61) 0-15786 0.00130 15786-53370 0.00113 ... 2-793420 0.00040
* 0 to 3 (0.31) 0-460790 0.00190 460790-752483 0.00194 ... 3-698373 0.00172
*
******************************************************************************/
package shortestPath.edu.princeton.cs.algs4;
/**
* The {@code DijkstraUndirectedSP} class represents a data type for solving
* the single-source shortest paths problem in edge-weighted graphs
* where the edge weights are nonnegative.
* <p>
* This implementation uses Dijkstra's algorithm with a binary heap.
* The constructor takes time proportional to <em>E</em> log <em>V</em>,
* where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
* Afterwards, the {@code distTo()} and {@code hasPathTo()} methods take
* constant time and the {@code pathTo()} method takes time proportional to the
* number of edges in the shortest path returned.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* See {@link DijkstraSP} for a version on edge-weighted digraphs.
*
* @author Robert Sedgewick
* @author Kevin Wayne
* @author Nate Liu
*/
public class DijkstraUndirectedSP {
private double[] distTo; // distTo[v] = distance of shortest s->v path
private Edge[] edgeTo; // edgeTo[v] = last edge on shortest s->v path
private IndexMinPQ<Double> pq; // priority queue of vertices
/**
* Computes a shortest-paths tree from the source vertex {@code s} to every
* other vertex in the edge-weighted graph {@code G}.
*
* @param G the edge-weighted digraph
* @param s the source vertex
* @throws IllegalArgumentException if an edge weight is negative
* @throws IllegalArgumentException unless {@code 0 <= s < V}
*/
public DijkstraUndirectedSP(EdgeWeightedGraph G, int s) {
for (Edge e : G.edges()) {
if (e.weight() < 0)
throw new IllegalArgumentException("edge " + e + " has negative weight");
}
distTo = new double[G.V()];
edgeTo = new Edge[G.V()];
validateVertex(s);
for (int v = 0; v < G.V(); v++)
distTo[v] = Double.POSITIVE_INFINITY;
distTo[s] = 0.0;
// relax vertices in order of distance from s
pq = new IndexMinPQ<Double>(G.V());
pq.insert(s, distTo[s]);
while (!pq.isEmpty()) {
int v = pq.delMin();
for (Edge e : G.adj(v))
relax(e, v);
}
// check optimality conditions
assert check(G, s);
}
// relax edge e and update pq if changed
private void relax(Edge e, int v) {
int w = e.other(v);
if (distTo[w] > distTo[v] + e.weight()) {
distTo[w] = distTo[v] + e.weight();
edgeTo[w] = e;
if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);
else pq.insert(w, distTo[w]);
}
}
/**
* Returns the length of a shortest path between the source vertex {@code s} and
* vertex {@code v}.
*
* @param v the destination vertex
* @return the length of a shortest path between the source vertex {@code s} and
* the vertex {@code v}; {@code Double.POSITIVE_INFINITY} if no such path
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public double distTo(int v) {
validateVertex(v);
return distTo[v];
}
/**
* Returns true if there is a path between the source vertex {@code s} and
* vertex {@code v}.
*
* @param v the destination vertex
* @return {@code true} if there is a path between the source vertex
* {@code s} to vertex {@code v}; {@code false} otherwise
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public boolean hasPathTo(int v) {
validateVertex(v);
return distTo[v] < Double.POSITIVE_INFINITY;
}
/**
* Returns a shortest path between the source vertex {@code s} and vertex {@code v}.
*
* @param v the destination vertex
* @return a shortest path between the source vertex {@code s} and vertex {@code v};
* {@code null} if no such path
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public Iterable<Edge> pathTo(int v) {
validateVertex(v);
if (!hasPathTo(v)) return null;
Stack<Edge> path = new Stack<Edge>();
int x = v;
for (Edge e = edgeTo[v]; e != null; e = edgeTo[x]) {
path.push(e);
x = e.other(x);
}
return path;
}
// check optimality conditions:
// (i) for all edges e = v-w: distTo[w] <= distTo[v] + e.weight()
// (ii) for all edge e = v-w on the SPT: distTo[w] == distTo[v] + e.weight()
private boolean check(EdgeWeightedGraph G, int s) {
// check that edge weights are nonnegative
for (Edge e : G.edges()) {
if (e.weight() < 0) {
System.err.println("negative edge weight detected");
return false;
}
}
// check that distTo[v] and edgeTo[v] are consistent
if (distTo[s] != 0.0 || edgeTo[s] != null) {
System.err.println("distTo[s] and edgeTo[s] inconsistent");
return false;
}
for (int v = 0; v < G.V(); v++) {
if (v == s) continue;
if (edgeTo[v] == null && distTo[v] != Double.POSITIVE_INFINITY) {
System.err.println("distTo[] and edgeTo[] inconsistent");
return false;
}
}
// check that all edges e = v-w satisfy distTo[w] <= distTo[v] + e.weight()
for (int v = 0; v < G.V(); v++) {
for (Edge e : G.adj(v)) {
int w = e.other(v);
if (distTo[v] + e.weight() < distTo[w]) {
System.err.println("edge " + e + " not relaxed");
return false;
}
}
}
// check that all edges e = v-w on SPT satisfy distTo[w] == distTo[v] + e.weight()
for (int w = 0; w < G.V(); w++) {
if (edgeTo[w] == null) continue;
Edge e = edgeTo[w];
if (w != e.either() && w != e.other(e.either())) return false;
int v = e.other(w);
if (distTo[v] + e.weight() != distTo[w]) {
System.err.println("edge " + e + " on shortest path not tight");
return false;
}
}
return true;
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertex(int v) {
int V = distTo.length;
if (v < 0 || v >= V)
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
/**
* Unit tests the {@code DijkstraUndirectedSP} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
In in = new In(args[0]);
EdgeWeightedGraph G = new EdgeWeightedGraph(in);
int s = Integer.parseInt(args[1]);
// compute shortest paths
DijkstraUndirectedSP sp = new DijkstraUndirectedSP(G, s);
// print shortest path
for (int t = 0; t < G.V(); t++) {
if (sp.hasPathTo(t)) {
StdOut.printf("%d to %d (%.2f) ", s, t, sp.distTo(t));
for (Edge e : sp.pathTo(t)) {
StdOut.print(e + " ");
}
StdOut.println();
}
else {
StdOut.printf("%d to %d no path\n", s, t);
}
}
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar 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.
*
* algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
| mit |
georobGWJ/coco-app-back | app/controllers/applications_controller.rb | 167 | class ApplicationsController < ApplicationController
skip_before_action :authenticate
def index
end
def new
end
def create
end
def show
end
end
| mit |
lianvervoort/game | game/gameapp/whiteboard.js | 224 |
var connect = function connect (io) {
io.on('connection', function (socket) {
socket.on('drawing', (data) => socket.broadcast.emit('drawing', data)
)
;
})
};
exports.connect = connect; | mit |
smischke/helix-toolkit | Source/HelixToolkit.UWP/Model/ExampleCube3D.cs | 11444 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExampleCube3D.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace HelixToolkit.UWP
{
using System;
using System.Diagnostics;
using System.IO;
using HelixToolkit.UWP.CommonDX;
public class ExampleCube3D : Element3D
{
private global::SharpDX.Direct3D11.Buffer constantBuffer;
private global::SharpDX.Direct3D11.InputLayout layout;
private global::SharpDX.Direct3D11.VertexBufferBinding vertexBufferBinding;
private Stopwatch clock;
private global::SharpDX.Direct3D11.VertexShader vertexShader;
private global::SharpDX.Direct3D11.PixelShader pixelShader;
public ExampleCube3D()
{
this.Scale = 1.0f;
this.ShowCube = true;
this.EnableClear = true;
this.RotationSpeed = 1;
}
public bool EnableClear { get; set; }
public bool ShowCube { get; set; }
public double Scale { get; set; }
public double RotationSpeed { get; set; }
public override void Render(TargetBase render)
{
base.Render(render);
var context = render.DeviceManager.ContextDirect3D;
var width = render.RenderTargetSize.Width;
var height = render.RenderTargetSize.Height;
// Prepare matrices
var view = global::SharpDX.Matrix.LookAtLH(new global::SharpDX.Vector3(0, 0, -5), new global::SharpDX.Vector3(0, 0, 0), global::SharpDX.Vector3.UnitY);
var proj = global::SharpDX.Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, (float)(width / height), 0.1f, 100.0f);
var viewProj = global::SharpDX.Matrix.Multiply(view, proj);
var time = (float)(this.clock.ElapsedMilliseconds / 1000.0);
// Set targets (This is mandatory in the loop)
context.OutputMerger.SetTargets(render.DepthStencilView, render.RenderTargetView);
// Clear the views
context.ClearDepthStencilView(render.DepthStencilView, global::SharpDX.Direct3D11.DepthStencilClearFlags.Depth, 1.0f, 0);
if (this.EnableClear)
{
context.ClearRenderTargetView(render.RenderTargetView, global::SharpDX.Color.LightGray);
}
if (this.ShowCube)
{
// Calculate WorldViewProj
var worldViewProj = global::SharpDX.Matrix.Scaling((float)this.Scale) * global::SharpDX.Matrix.RotationX((float)this.RotationSpeed * time)
* global::SharpDX.Matrix.RotationY((float)this.RotationSpeed * time * 2.0f) * global::SharpDX.Matrix.RotationZ((float)this.RotationSpeed * time * .7f)
* viewProj;
worldViewProj.Transpose();
// Setup the pipeline
context.InputAssembler.SetVertexBuffers(0, this.vertexBufferBinding);
context.InputAssembler.InputLayout = this.layout;
context.InputAssembler.PrimitiveTopology = global::SharpDX.Direct3D.PrimitiveTopology.TriangleList;
context.VertexShader.SetConstantBuffer(0, this.constantBuffer);
context.VertexShader.Set(this.vertexShader);
context.PixelShader.Set(this.pixelShader);
// Update Constant Buffer
context.UpdateSubresource(ref worldViewProj, this.constantBuffer, 0);
// Draw the cube
context.Draw(36, 0);
}
}
public override void Initialize(DeviceManager deviceManager)
{
base.Initialize(deviceManager);
// Remove previous buffer
if (this.constantBuffer != null)
{
this.constantBuffer.Dispose();
}
// RemoveAndDispose(ref constantBuffer);
// Setup local variables
var d3dDevice = deviceManager.DeviceDirect3D;
var d3dContext = deviceManager.ContextDirect3D;
var path = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "HelixToolkit.UWP");
// Loads vertex shader bytecode
var vertexShaderByteCode = global::SharpDX.IO.NativeFile.ReadAllBytes(path + "\\MiniCube_VS.fxo");
this.vertexShader = new global::SharpDX.Direct3D11.VertexShader(d3dDevice, vertexShaderByteCode);
// Loads pixel shader bytecode
this.pixelShader = new global::SharpDX.Direct3D11.PixelShader(d3dDevice, global::SharpDX.IO.NativeFile.ReadAllBytes(path + "\\MiniCube_PS.fxo"));
// Layout from VertexShader input signature
this.layout = new global::SharpDX.Direct3D11.InputLayout(
d3dDevice,
vertexShaderByteCode,
new[]
{
new global::SharpDX.Direct3D11.InputElement("POSITION", 0, global::SharpDX.DXGI.Format.R32G32B32A32_Float, 0, 0),
new global::SharpDX.Direct3D11.InputElement("COLOR", 0, global::SharpDX.DXGI.Format.R32G32B32A32_Float, 16, 0)
});
// Instantiate Vertex buffer from vertex data
var vertices = global::SharpDX.Direct3D11.Buffer.Create(
d3dDevice,
global::SharpDX.Direct3D11.BindFlags.VertexBuffer,
new[]
{
new global::SharpDX.Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front
new global::SharpDX.Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK
new global::SharpDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top
new global::SharpDX.Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom
new global::SharpDX.Vector4(1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 1.0f, 0.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left
new global::SharpDX.Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(1.0f, 0.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right
new global::SharpDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, -1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, -1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, -1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 1.0f, 1.0f),
new global::SharpDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f), new global::SharpDX.Vector4(0.0f, 1.0f, 1.0f, 1.0f),
});
this.vertexBufferBinding = new global::SharpDX.Direct3D11.VertexBufferBinding(vertices, global::SharpDX.Utilities.SizeOf<global::SharpDX.Vector4>() * 2, 0);
// Create Constant Buffer
this.constantBuffer = new global::SharpDX.Direct3D11.Buffer(
d3dDevice,
global::SharpDX.Utilities.SizeOf< global::SharpDX.Matrix>(),
global::SharpDX.Direct3D11.ResourceUsage.Default,
global::SharpDX.Direct3D11.BindFlags.ConstantBuffer,
global::SharpDX.Direct3D11.CpuAccessFlags.None,
global::SharpDX.Direct3D11.ResourceOptionFlags.None,
0);
this.clock = new Stopwatch();
this.clock.Start();
}
}
} | mit |
dticln/CaCln | app/plugins/sources/imanager/configs/env/development/variables.php | 50 | <?php
define('ENV_IM_SECRET_KEY', 'change_it');
?> | mit |
nomoreserious/FlowSimulation | FlowSimulation.Test/MainWindow.xaml.cs | 7186 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Drawing;
using System.IO;
using FlowSimulation.Enviroment;
using FlowSimulation.Enviroment.IO;
using FlowSimulation.Helpers.Timer;
using FlowSimulation.Contracts.Services;
using System.Windows.Threading;
using FlowSimulation.Contracts.Agents;
namespace FlowSimulation.Test
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//PortTest pt = new PortTest();
//ExportToPng(new Uri(@"C:\saved.png", UriKind.Absolute), pt.svg2985);
Paint();
}
public void ExportToPng(Uri path, Canvas surface)
{
if (path == null)
return;
// Save current canvas transform
Transform transform = surface.LayoutTransform;
// reset current transform (in case it is scaled or rotated)
surface.LayoutTransform = null;
// Get the size of canvas
System.Windows.Size size = new System.Windows.Size(surface.Width, surface.Height);
// Measure and arrange the surface
// VERY IMPORTANT
surface.Measure(size);
surface.Arrange(new Rect(size));
// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
new RenderTargetBitmap(
(int)size.Width,
(int)size.Height,
96d,
96d,
PixelFormats.Pbgra32);
renderBitmap.Render(surface);
// Create a file stream for saving image
using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
{
// Use png encoder for our data
PngBitmapEncoder encoder = new PngBitmapEncoder();
// push the rendered bitmap to it
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
// save the data to the stream
encoder.Save(outStream);
}
// Restore previously saved layout
surface.LayoutTransform = transform;
}
Bitmap BaseBmp;
Map map;
public void Paint()
{
MapReader reader = new MapReader(@"test.svg");
HighResolutionTime.Start();
if (reader.Read())
{
map = reader.GetMap(new Dictionary<string,byte>());
}
Console.WriteLine("Чтение карты: " + HighResolutionTime.GetTime());
BaseBmp = map.GetLayerMask(0);
Graphics g = Graphics.FromImage(BaseBmp);
foreach (var node in map._patensyGraph.Vertices)
{
g.FillRectangle(System.Drawing.Brushes.Red, node.SourceWP.X, node.SourceWP.Y, node.SourceWP.PointWidth, node.SourceWP.PointHeight);
g.FillRectangle(System.Drawing.Brushes.Red, node.TargetWP.X, node.TargetWP.Y, node.TargetWP.PointWidth, node.TargetWP.PointHeight);
}
foreach (var edge in map._patensyGraph.Edges)
{
g.DrawLine(System.Drawing.Pens.Green, edge.Source.SourceWP.Center, edge.Target.SourceWP.Center);
}
Agents.Human.HumanManager mng = new Agents.Human.HumanManager();
//agent = mng.GetInstance(map, null, new System.Windows.Media.Media3D.Size3D(0.5, 0.3, 2.0), 1.4, 1.0, 1.0);
//agent.Initialize(new System.Drawing.Point(10, 3), new List<WayPoint> { new WayPoint(300, 10), new WayPoint(154, 550), new WayPoint(630, 130) });
g.FillEllipse(System.Drawing.Brushes.Orange, 300, 10, 5, 5);
g.FillEllipse(System.Drawing.Brushes.Orange, 154, 550, 5, 5);
g.FillEllipse(System.Drawing.Brushes.Orange, 630, 130, 5, 5);
SetMapImage(BaseBmp);
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(10);
timer.Tick+=new EventHandler(timer_Tick);
timer.Start();
}
AgentBase agent;
void timer_Tick(object sender, EventArgs e)
{
agent.DoStep(50);
PaintPanel.Children.Clear();
PaintPanel.Children.Add(agent.GetAgentShape());
PaintPanel.InvalidateVisual();
}
private void SetMapImage(Bitmap bmp)
{
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
image.BeginInit();
image.StreamSource = ms;
image.EndInit();
PaintPanel.Width = bmp.Width;
PaintPanel.Height = bmp.Height;
PaintPanel.Background = new ImageBrush(image);
}
System.Drawing.Point from = new System.Drawing.Point(-1, -1), to = new System.Drawing.Point(-1, -1);
private void PaintPanel_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
to = new System.Drawing.Point((int)e.GetPosition((IInputElement)e.OriginalSource).X, (int)e.GetPosition((IInputElement)e.OriginalSource).Y);
}
else if (e.LeftButton == MouseButtonState.Pressed)
{
from = new System.Drawing.Point((int)e.GetPosition((IInputElement)e.OriginalSource).X, (int)e.GetPosition((IInputElement)e.OriginalSource).Y);
}
if (to != new System.Drawing.Point(-1, -1) && to != from)
{
//HighResolutionTime.Start();
var route = map.GetRoute(from, to);
//Console.WriteLine("Построение маршрута: " + HighResolutionTime.GetTime());
if (route != null)
{
var bitmap = (Bitmap)BaseBmp.Clone();
HighResolutionTime.Start();
for (int i = 0; i < route.Count - 1; i++)
{
var path = map.GetWay(route[i], route[i + 1]);
if (path == null)
continue;
foreach (var point in path)
{
bitmap.SetPixel(point.X - 1, point.Y - 1, System.Drawing.Color.Blue);
}
}
Console.WriteLine("Построение всех путей: " + HighResolutionTime.GetTime());
SetMapImage(bitmap);
}
}
}
}
}
| mit |
gonetcats/betaseries-api-redux-sdk | lib/modules/shows/actions/doFetchShowEpisodes.js | 1040 | import constants from '../constants';
import ApiFetch from '../../../utils/fetch/ApiFetch';
/**
* Retrieve episodes of the show
*
* **Dispatch**: `FETCH_SHOW_EPISODES`
*
* @alias module:Shows.doFetchShowEpisodes
* @category actions
*
* @example
* BetaSeries.getAction('shows', 'doFetchShowEpisodes')({ showId: 1275, season: 1 });
*
* @param {Object} [obj] Accept the following:
* @param {Number} [obj.showId] Show ID
* @param {Number} [obj.season] Season number (optional)
* @param {Number} [obj.episode] Episode Number (optional)
* @param {Bool} [obj.subtitles] Displays subtitles and information (optional)
*
* @returns {Promise}
*/
const doFetchShowEpisodes = ({ showId, ...props }) =>
dispatch =>
ApiFetch.get('shows/episodes', { id: showId, ...props }).then(response =>
dispatch({
type: constants.FETCH_SHOW_EPISODES,
payload: {
...props,
showId,
episodes: response.episodes
}
}));
export default doFetchShowEpisodes;
| mit |
anthill-platform/anthill-exec | anthill/exec/model/session.py | 6421 | from tornado.gen import with_timeout, TimeoutError
# noinspection PyUnresolvedReferences
from v8py import JSException, JSPromise, Context, new, JavaScriptTerminated
from anthill.common.access import InternalError
from anthill.common.validate import validate
from . util import APIError, PromiseContext, JavascriptCallHandler, JavascriptExecutionError, JSFuture
import datetime
import sys
import logging
class JavascriptSessionError(Exception):
def __init__(self, code, message):
self.code = code
self.message = message
def __str__(self):
return str(self.code) + ": " + self.message
class JavascriptSession(object):
CALL_BLACKLIST = ["release"]
def __init__(self, build, instance, env, log, debug, cache, promise_type):
self.build = build
self.instance = instance
self.cache = cache
self.env = env
self.log = log
self.debug = debug
self.promise_type = promise_type
async def call_internal_method(self, method_name, args, call_timeout=10):
method = getattr(self.instance, method_name, None)
if not method:
return
context = self.build.context
handler = JavascriptCallHandler(self.cache, self.env, context,
debug=self.debug, promise_type=self.promise_type)
if self.log:
handler.log = self.log
PromiseContext.current = handler
try:
future = context.async_call(method, (args,), JSFuture)
except JSException as e:
value = e.value
if hasattr(value, "code"):
if hasattr(value, "stack"):
raise JavascriptExecutionError(value.code, value.message, stack=str(value.stack))
else:
raise JavascriptExecutionError(value.code, value.message)
if hasattr(e, "stack"):
raise JavascriptExecutionError(500, str(e), stack=str(e.stack))
raise JavascriptExecutionError(500, str(e))
except APIError as e:
raise JavascriptExecutionError(e.code, e.message)
except InternalError as e:
raise JavascriptExecutionError(
e.code, "Internal error: " + e.body)
except JavaScriptTerminated:
raise JavascriptExecutionError(
408, "Evaluation process timeout: function shouldn't be "
"blocking and should rely on async methods instead.")
except Exception as e:
raise JavascriptExecutionError(500, str(e))
if future.done():
return future.result()
try:
result = await with_timeout(datetime.timedelta(seconds=call_timeout), future)
except TimeoutError:
raise APIError(408, "Total function '{0}' call timeout ({1})".format(
method_name, call_timeout))
else:
return result
@validate(method_name="str_name", args="json_dict")
async def call(self, method_name, args, call_timeout=10):
if method_name.startswith("_"):
raise JavascriptSessionError(404, "No such method: " + str(method_name))
if method_name in JavascriptSession.CALL_BLACKLIST:
raise JavascriptSessionError(404, "No such method: " + str(method_name))
if not hasattr(self.instance, method_name):
raise JavascriptSessionError(404, "No such method: " + str(method_name))
method = getattr(self.instance, method_name)
context = self.build.context
handler = JavascriptCallHandler(self.cache, self.env, context,
debug=self.debug, promise_type=self.promise_type)
if self.log:
handler.log = self.log
PromiseContext.current = handler
try:
future = context.async_call(method, (args,), JSFuture)
except JSException as e:
value = e.value
if hasattr(value, "code"):
if hasattr(value, "stack"):
raise JavascriptExecutionError(value.code, value.message, stack=str(value.stack))
else:
raise JavascriptExecutionError(value.code, value.message)
if hasattr(e, "stack"):
raise JavascriptExecutionError(500, str(e), stack=str(e.stack))
raise JavascriptExecutionError(500, str(e))
except APIError as e:
raise JavascriptExecutionError(e.code, e.message)
except InternalError as e:
raise JavascriptExecutionError(
e.code, "Internal error: " + e.body)
except JavaScriptTerminated:
raise JavascriptExecutionError(
408, "Evaluation process timeout: function shouldn't be "
"blocking and should rely on async methods instead.")
except Exception as e:
raise JavascriptExecutionError(500, str(e))
if future.done():
return future.result()
try:
result = await with_timeout(datetime.timedelta(seconds=call_timeout), future)
except TimeoutError:
raise APIError(408, "Total function '{0}' call timeout ({1})".format(
method_name, call_timeout))
else:
return result
@validate(value="str")
async def eval(self, value):
handler = JavascriptCallHandler(self.cache, self.env, self.build.context)
PromiseContext.current = handler
try:
result = self.build.context.eval(str(value))
except JSException as e:
raise APIError(500, e.message)
except JavaScriptTerminated:
raise APIError(408, "Evaluation process timeout: function shouldn't be blocking and "
"should rely on async methods instead.")
except InternalError as e:
raise APIError(e.code, "Internal error: " + e.body)
except APIError:
raise
except Exception as e:
raise APIError(500, e)
return result
async def release(self, code=1006, reason="Closed normally"):
await self.call_internal_method("released", {
"code": code,
"reason": reason
})
if self.build:
await self.build.session_released(self)
self.debug = None
self.instance = None
| mit |
lukkos/vCard | web/bundles_/lukkosvcard/js/person/modalController.js | 1765 | angular.module('vcard').controller('ModalInstanceCtrl', function ($scope,Restangular, FlashFactory, $modalInstance, person) {
if(person)
{
$scope.lukkos_vcardbundle_person = person;
console.log($scope.lukkos_vcardbundle_person)
}
$scope.submit = function (formValues) {
var person = Restangular.restangularizeElement(null,formValues,'api/vcards');
if(undefined == person.id)
{
person.post().then(function(data) {
$scope.errors = data.errors;
$scope.flash = data.flash;
if(data.errors.length == 0)
$modalInstance.close($scope.flash);
//console.log($scope.errors);
}, function() {
console.log("There was an error saving");
});
}
else
{
person.put().then(function(data) {
$scope.errors = data.errors;
$scope.flash = data.flash;
if(data.errors.length == 0)
$modalInstance.close($scope.flash);
//console.log($scope.errors);
}, function() {
console.log("There was an error saving");
});
}
//$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.remove = function (formValues) {
var person = Restangular.restangularizeElement(null,formValues,'api/vcards');
person.remove().then(function(data){
$scope.errors = data.errors;
$scope.flash = data.flash;
if(data.errors.length == 0)
$modalInstance.close($scope.flash);
});
};
}); | mit |
ashutoshrishi/slate | packages/slate-react/test/rendering/fixtures/custom-block.js | 647 | /** @jsx h */
import React from 'react'
import h from '../../helpers/h'
function Code(props) {
return React.createElement(
'pre',
props.attributes,
React.createElement('code', {}, props.children)
)
}
export const props = {
renderNode(p) {
switch (p.node.type) {
case 'code':
return Code(p)
}
},
}
export const value = (
<value>
<document>
<code>word</code>
</document>
</value>
)
export const output = `
<div data-slate-editor="true" contenteditable="true" role="textbox">
<pre>
<code>
<span>
<span>word</span>
</span>
</code>
</pre>
</div>
`.trim()
| mit |
PasaiakoUdala/zerbikat | src/Zerbikat/BackendBundle/Controller/FitxafamiliaController.php | 9524 | <?php
namespace Zerbikat\BackendBundle\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Zerbikat\BackendBundle\Entity\Fitxafamilia;
use Zerbikat\BackendBundle\Form\FitxafamiliaType;
/**
* Fitxafamilia controller.
*
* @Route("/fitxafamilia")
*/
class FitxafamiliaController extends Controller
{
/**
* Fitxa-Familiak ordena duen ikusi.
*
* @Route("/api/fitxafamiliakordenadauka/{id}/{fitxa_id}/{familia_id}", name="api_fitxafamiliahasorden")
* @Method("GET")
*/
public function fitxafamiliahasordenAction ( $id, $fitxa_id, $familia_id )
{
$em = $this->getDoctrine()->getManager();
$fitxafamilia = $em->getRepository( 'BackendBundle:Fitxafamilia' )->find( $id );
if ( $fitxafamilia ) {
$resp = array ('ordena' => $fitxafamilia->getOrdena());
} else {
$query = $em->createQuery(
'
SELECT MAX(f.ordena) as ordena
FROM BackendBundle:Fitxafamilia f
WHERE f.familia = :familia_id AND f.fitxa = :fitxa
'
);
$query->setParameter( 'familia_id', $familia_id );
$query->setParameter( 'fitxa', $fitxafamilia->getFitxa()->getId() );
$resp = $query->getSingleResult();
}
return New JsonResponse( $resp );
}
/**
* Fitxa-Familiak datooren ordena eman.
*
* @Route("/api/fitxafamilianextorden/{fitxa_id}/{familia_id}", name="api_fitxafamilianextorden")
* @Method("GET")
*/
public function fitxafamilianextordenAction ( $fitxa_id, $familia_id )
{
$em = $this->getDoctrine()->getManager();
// 1-. Badagoen begiratu
$fitxafamilia = $em->getRepository( 'BackendBundle:Fitxafamilia' )->findOneBy(
array ('fitxa' => $fitxa_id, 'familia' => $familia_id)
);
if ($fitxafamilia) {
return new JsonResponse(array('ordena'=>-1));
}
$query = $em->createQuery(
'
SELECT MAX(f.ordena) as ordena
FROM BackendBundle:Fitxafamilia f
WHERE f.familia = :familia_id
'
);
// $query->setParameter( 'fitxa_id', $fitxa_id );
$query->setParameter( 'familia_id', $familia_id );
$resp = $query->getSingleResult();
return New JsonResponse( $resp );
}
/**
* Lists all Fitxafamilia entities.
*
* @Route("/", name="fitxafamilia_index")
* @Method("GET")
*/
public function indexAction ()
{
$em = $this->getDoctrine()->getManager();
$fitxafamilias = $em->getRepository( 'BackendBundle:Fitxafamilia' )->findAll();
return $this->render(
'fitxafamilia/index.html.twig',
array (
'fitxafamilias' => $fitxafamilias,
)
);
}
/**
* Creates a new Fitxafamilia entity.
*
* @Route("/newfromfitxa", name="fitxafamilia_newfromfitxa")
* @Method({"GET", "POST"})
*/
public function newfromfitxaAction ( Request $request )
{
$fitxafamilium = new Fitxafamilia();
$fitxafamilium->setUdala( $this->getUser()->getUdala() );
$form = $this->createForm( 'Zerbikat\BackendBundle\Form\FitxafamiliaType', $fitxafamilium );
$form->handleRequest( $request );
if ( $form->isSubmitted() && $form->isValid() ) {
$em = $this->getDoctrine()->getManager();
$em->persist( $fitxafamilium );
$em->flush();
return $this->redirect(
$this->generateUrl(
'fitxa_edit',
array ('id' => $fitxafamilium->getFitxa()->getId())
).'#gehituFamilia'
);
}
return $this->render(
'fitxafamilia/new.html.twig',
array (
'fitxafamilium' => $fitxafamilium,
'form' => $form->createView(),
)
);
}
/**
* Creates a new Fitxafamilia entity.
*
* @Route("/new", name="fitxafamilia_new")
* @Method({"GET", "POST"})
*/
public function newAction ( Request $request )
{
$fitxafamilium = new Fitxafamilia();
$fitxafamilium->setUdala( $this->getUser()->getUdala() );
$form = $this->createForm( 'Zerbikat\BackendBundle\Form\FitxafamiliaType', $fitxafamilium );
$form->handleRequest( $request );
if ( $form->isSubmitted() && $form->isValid() ) {
$em = $this->getDoctrine()->getManager();
$em->persist( $fitxafamilium );
$em->flush();
return $this->redirectToRoute( 'fitxafamilia_show', array ('id' => $fitxafamilium->getId()) );
}
return $this->render(
'fitxafamilia/new.html.twig',
array (
'fitxafamilium' => $fitxafamilium,
'form' => $form->createView(),
)
);
}
/**
* Finds and displays a Fitxafamilia entity.
*
* @Route("/{id}", name="fitxafamilia_show")
* @Method("GET")
*/
public function showAction ( Fitxafamilia $fitxafamilium )
{
$deleteForm = $this->createDeleteForm( $fitxafamilium );
return $this->render(
'fitxafamilia/show.html.twig',
array (
'fitxafamilium' => $fitxafamilium,
'delete_form' => $deleteForm->createView(),
)
);
}
/**
* Displays a form to edit an existing Fitxafamilia entity.
*
* @Route("/{id}/edit", name="fitxafamilia_edit")
* @Method({"GET", "POST"})
*/
public function editAction ( Request $request, Fitxafamilia $fitxafamilium )
{
$deleteForm = $this->createDeleteForm( $fitxafamilium );
$editForm = $this->createForm(
'Zerbikat\BackendBundle\Form\FitxafamiliaType',
$fitxafamilium,
[
'action' => $this->generateUrl(
'fitxafamilia_edit',
array ('id' => $fitxafamilium->getFitxa()->getId())
),
'method' => "POST",
]
);
$editForm->handleRequest( $request );
if ( $editForm->isSubmitted() && $editForm->isValid() ) {
$em = $this->getDoctrine()->getManager();
$em->persist( $fitxafamilium );
$em->flush();
return $this->redirect(
$this->generateUrl(
'fitxa_edit',
array ('id' => $fitxafamilium->getFitxa()->getId())
).'#gehituFamilia'
);
}
return $this->render(
'fitxafamilia/edit.html.twig',
array (
'fitxafamilium' => $fitxafamilium,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
)
);
}
/**
* Deletes a Fitxafamilia entity.
*
* @Route("/{id}", name="fitxafamilia_delete")
* @Method("DELETE")
*/
public function deleteAction ( Request $request, Fitxafamilia $fitxafamilium )
{
if($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$em->remove( $fitxafamilium );
$em->flush();
return New JsonResponse(array('result' => 'ok'));
}
$form = $this->createDeleteForm( $fitxafamilium );
$form->handleRequest( $request );
if ( $form->isSubmitted() && $form->isValid() ) {
$em = $this->getDoctrine()->getManager();
$em->remove( $fitxafamilium );
$em->flush();
}
return $this->redirectToRoute( 'fitxafamilia_index' );
}
/**
* Creates a form to delete a Fitxafamilia entity.
*
* @param Fitxafamilia $fitxafamilium The Fitxafamilia entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm ( Fitxafamilia $fitxafamilium )
{
return $this->createFormBuilder()
->setAction( $this->generateUrl( 'fitxafamilia_delete', array ('id' => $fitxafamilium->getId()) ) )
->setMethod( 'DELETE' )
->getForm();
}
}
| mit |
DarthJonathan/arcon | assets/elfinder/js/elFinder.js | 185045 | "use strict";
/**
* @class elFinder - file manager for web
*
* @author Dmitry (dio) Levashov
**/
var elFinder = function(node, opts) {
//this.time('load');
var self = this,
/**
* Node on which elfinder creating
*
* @type jQuery
**/
node = $(node),
/**
* Store node contents.
*
* @see this.destroy
* @type jQuery
**/
prevContent = $('<div/>').append(node.contents()),
/**
* Store node inline styles
*
* @see this.destroy
* @type String
**/
prevStyle = node.attr('style'),
/**
* Instance ID. Required to get/set cookie
*
* @type String
**/
id = node.attr('id') || '',
/**
* Events namespace
*
* @type String
**/
namespace = 'elfinder-' + (id ? id : Math.random().toString().substr(2, 7)),
/**
* Mousedown event
*
* @type String
**/
mousedown = 'mousedown.'+namespace,
/**
* Keydown event
*
* @type String
**/
keydown = 'keydown.'+namespace,
/**
* Keypress event
*
* @type String
**/
keypress = 'keypress.'+namespace,
/**
* Is shortcuts/commands enabled
*
* @type Boolean
**/
enabled = true,
/**
* Store enabled value before ajax requiest
*
* @type Boolean
**/
prevEnabled = true,
/**
* List of build-in events which mapped into methods with same names
*
* @type Array
**/
events = ['enable', 'disable', 'load', 'open', 'reload', 'select', 'add', 'remove', 'change', 'dblclick', 'getfile', 'lockfiles', 'unlockfiles', 'selectfiles', 'unselectfiles', 'dragstart', 'dragstop', 'search', 'searchend', 'viewchange'],
/**
* Rules to validate data from backend
*
* @type Object
**/
rules = {},
/**
* Current working directory hash
*
* @type String
**/
cwd = '',
/**
* Current working directory options
*
* @type Object
**/
cwdOptions = {
path : '',
url : '',
tmbUrl : '',
disabled : [],
separator : '/',
archives : [],
extract : [],
copyOverwrite : true,
uploadOverwrite : true,
uploadMaxSize : 0,
jpgQuality : 100,
tmbCrop : false,
tmb : false // old API
},
/**
* Files/dirs cache
*
* @type Object
**/
files = {},
/**
* Selected files hashes
*
* @type Array
**/
selected = [],
/**
* Events listeners
*
* @type Object
**/
listeners = {},
/**
* Shortcuts
*
* @type Object
**/
shortcuts = {},
/**
* Buffer for copied files
*
* @type Array
**/
clipboard = [],
/**
* Copied/cuted files hashes
* Prevent from remove its from cache.
* Required for dispaly correct files names in error messages
*
* @type Array
**/
remember = [],
/**
* Queue for 'open' requests
*
* @type Array
**/
queue = [],
/**
* Queue for only cwd requests e.g. `tmb`
*
* @type Array
**/
cwdQueue = [],
/**
* Commands prototype
*
* @type Object
**/
base = new self.command(self),
/**
* elFinder node width
*
* @type String
* @default "auto"
**/
width = 'auto',
/**
* elFinder node height
*
* @type Number
* @default 400
**/
height = 400,
/**
* elfinder path for sound played on remove
* @type String
* @default ./sounds/
**/
soundPath = './sounds/',
beeper = $(document.createElement('audio')).hide().appendTo('body')[0],
syncInterval,
autoSyncStop = 0,
uiCmdMapPrev = '',
open = function(data) {
// NOTES: Do not touch data object
var volumeid, contextmenu, emptyDirs = {}, stayDirs = {},
rmClass, hashes, calc, gc, collapsed, prevcwd;
if (self.api >= 2.1) {
self.commandMap = (data.options.uiCmdMap && Object.keys(data.options.uiCmdMap).length)? data.options.uiCmdMap : {};
// support volume driver option `uiCmdMap`
if (uiCmdMapPrev !== JSON.stringify(self.commandMap)) {
uiCmdMapPrev = JSON.stringify(self.commandMap);
if (Object.keys(self.commandMap).length) {
// for contextmenu
contextmenu = self.getUI('contextmenu');
if (!contextmenu.data('cmdMaps')) {
contextmenu.data('cmdMaps', {});
}
volumeid = data.cwd? data.cwd.volumeid : null;
if (volumeid && !contextmenu.data('cmdMaps')[volumeid]) {
contextmenu.data('cmdMaps')[volumeid] = self.commandMap;
}
}
}
} else {
self.options.sync = 0;
}
if (data.init) {
// init - reset cache
files = {};
} else {
// remove only files from prev cwd
// and collapsed directory (included 100+ directories) to empty for perfomance tune in DnD
prevcwd = cwd;
rmClass = 'elfinder-subtree-loaded ' + self.res('class', 'navexpand');
collapsed = self.res('class', 'navcollapse');
hashes = Object.keys(files);
calc = function(n, i) {
if (!files[i]) {
return true;
}
var isDir = (files[i].mime === 'directory'),
phash = files[i].phash,
pnav;
if (
(!isDir
|| emptyDirs[phash]
|| (!stayDirs[phash]
&& $('#'+self.navHash2Id(files[i].hash)).is(':hidden')
&& $('#'+self.navHash2Id(phash)).next('.elfinder-navbar-subtree').children().length > 100
)
)
&& (isDir || phash !== cwd)
&& $.inArray(i, remember) === -1
) {
if (isDir && !emptyDirs[phash]) {
emptyDirs[phash] = true;
$('#'+self.navHash2Id(phash))
.removeClass(rmClass)
.next('.elfinder-navbar-subtree').empty();
}
delete files[i];
} else if (isDir) {
stayDirs[phash] = true;
}
};
gc = function() {
if (hashes.length) {
$.each(hashes.splice(0, 100), calc);
if (hashes.length) {
setTimeout(gc, 20);
}
}
};
self.trigger('filesgc').one('filesgc', function() {
hashes = [];
});
self.one('opendone', function() {
if (prevcwd !== cwd) {
if (! node.data('lazycnt')) {
gc();
} else {
self.one('lazydone', gc);
}
}
});
}
self.sorters = [];
cwd = data.cwd.hash;
cache(data.files);
if (!files[cwd]) {
cache([data.cwd]);
}
self.lastDir(cwd);
self.autoSync();
},
/**
* Store info about files/dirs in "files" object.
*
* @param Array files
* @return void
**/
cache = function(data) {
var defsorter = { name: true, perm: true, date: true, size: true, kind: true },
sorterChk = (self.sorters.length === 0),
l = data.length,
f, i;
for (i = 0; i < l; i++) {
f = data[i];
if (f.name && f.hash && f.mime) {
if (sorterChk && f.phash === cwd) {
$.each(self.sortRules, function(key) {
if (defsorter[key] || typeof f[key] !== 'undefined' || (key === 'mode' && typeof f.perm !== 'undefined')) {
self.sorters.push(key);
}
});
sorterChk = false;
}
// make or update of leaf roots cache
if (f.isroot && f.phash) {
if (! self.leafRoots[f.phash]) {
self.leafRoots[f.phash] = [ f.hash ];
} else {
if ($.inArray(f.hash, self.leafRoots[f.phash]) === -1) {
self.leafRoots[f.phash].push(f.hash);
}
}
if (files[f.phash]) {
if (! files[f.phash].dirs) {
files[f.phash].dirs = 1;
}
if (f.ts && (files[f.phash].ts || 0) < f.ts) {
files[f.phash].ts = f.ts;
}
}
}
files[f.hash] = f;
}
}
},
/**
* Exec shortcut
*
* @param jQuery.Event keydown/keypress event
* @return void
*/
execShortcut = function(e) {
var code = e.keyCode,
ctrlKey = !!(e.ctrlKey || e.metaKey),
ddm;
if (enabled) {
$.each(shortcuts, function(i, shortcut) {
if (shortcut.type == e.type
&& shortcut.keyCode == code
&& shortcut.shiftKey == e.shiftKey
&& shortcut.ctrlKey == ctrlKey
&& shortcut.altKey == e.altKey) {
e.preventDefault();
e.stopPropagation();
shortcut.callback(e, self);
self.debug('shortcut-exec', i+' : '+shortcut.description);
}
});
// prevent tab out of elfinder
if (code == $.ui.keyCode.TAB && !$(e.target).is(':input')) {
e.preventDefault();
}
// cancel any actions by [Esc] key
if (e.type === 'keydown' && code == $.ui.keyCode.ESCAPE) {
// copy or cut
if (! node.find('.ui-widget:visible').length) {
self.clipboard().length && self.clipboard([]);
}
// dragging
if ($.ui.ddmanager) {
ddm = $.ui.ddmanager.current;
ddm && ddm.helper && ddm.cancel();
}
// button menus
node.find('.ui-widget.elfinder-button-menu').hide();
}
}
},
date = new Date(),
utc,
i18n,
inFrame = (window.parent !== window),
parentIframe = (function() {
var pifm, ifms;
if (inFrame) {
try {
ifms = $('iframe', window.parent.document);
if (ifms.length) {
$.each(ifms, function(i, ifm) {
if (ifm.contentWindow === window) {
pifm = $(ifm);
return false;
}
});
}
} catch(e) {}
}
return pifm;
})();
;
/**
* Protocol version
*
* @type String
**/
this.api = null;
/**
* elFinder use new api
*
* @type Boolean
**/
this.newAPI = false;
/**
* elFinder use old api
*
* @type Boolean
**/
this.oldAPI = false;
/**
* Net drivers names
*
* @type Array
**/
this.netDrivers = [];
/**
* Configuration options
*
* @type Object
**/
this.options = $.extend(true, {}, this._options, opts||{});
// auto load required CSS
if (this.options.cssAutoLoad) {
(function(fm) {
var myTag = $('head > script[src$="js/elfinder.min.js"],script[src$="js/elfinder.full.js"]:first'),
baseUrl, hide, fi, cnt;
if (myTag.length) {
// hide elFinder node while css loading
hide = $('<style>.elfinder{visibility:hidden;overflow:hidden}</style>');
$('head').append(hide);
baseUrl = myTag.attr('src').replace(/js\/[^\/]+$/, '');
fm.loadCss([baseUrl+'css/elfinder.min.css', baseUrl+'css/theme.css']);
// additional CSS files
if ($.isArray(fm.options.cssAutoLoad)) {
fm.loadCss(fm.options.cssAutoLoad);
}
// check css loaded and remove hide
cnt = 1000; // timeout 10 secs
fi = setInterval(function() {
if (--cnt > 0 && node.css('visibility') !== 'hidden') {
clearInterval(fi);
hide.remove();
fm.trigger('cssloaded');
}
}, 10);
} else {
fm.options.cssAutoLoad = false;
}
})(this);
}
/**
* Volume option to set the properties of the root Stat
*
* @type Array
*/
this.optionProperties = ['icon', 'csscls', 'tmbUrl', 'uiCmdMap', 'netkey'];
if (opts.ui) {
this.options.ui = opts.ui;
}
if (opts.commands) {
this.options.commands = opts.commands;
}
if (opts.uiOptions && opts.uiOptions.toolbar) {
this.options.uiOptions.toolbar = opts.uiOptions.toolbar;
}
if (opts.uiOptions && opts.uiOptions.cwd && opts.uiOptions.cwd.listView && opts.uiOptions.cwd.listView.columns) {
this.options.uiOptions.cwd.listView.columns = opts.uiOptions.cwd.listView.columns;
}
if (opts.uiOptions && opts.uiOptions.cwd && opts.uiOptions.cwd.listView && opts.uiOptions.cwd.listView.columnsCustomName) {
this.options.uiOptions.cwd.listView.columnsCustomName = opts.uiOptions.cwd.listView.columnsCustomName;
}
if (! inFrame && ! this.options.enableAlways && $('body').children().length === 2) { // only node and beeper
this.options.enableAlways = true;
}
/**
* Is elFinder over CORS
*
* @type Boolean
**/
this.isCORS = false;
// configure for CORS
(function(){
var parseUrl = document.createElement('a'),
parseUploadUrl;
parseUrl.href = opts.url;
if (opts.urlUpload && (opts.urlUpload !== opts.url)) {
parseUploadUrl = document.createElement('a');
parseUploadUrl.href = opts.urlUpload;
}
if (window.location.host !== parseUrl.host || (parseUploadUrl && (window.location.host !== parseUploadUrl.host))) {
self.isCORS = true;
if (!$.isPlainObject(self.options.customHeaders)) {
self.options.customHeaders = {};
}
if (!$.isPlainObject(self.options.xhrFields)) {
self.options.xhrFields = {};
}
self.options.requestType = 'post';
self.options.customHeaders['X-Requested-With'] = 'XMLHttpRequest';
self.options.xhrFields['withCredentials'] = true;
}
})();
$.extend(this.options.contextmenu, opts.contextmenu);
/**
* Ajax request type
*
* @type String
* @default "get"
**/
this.requestType = /^(get|post)$/i.test(this.options.requestType) ? this.options.requestType.toLowerCase() : 'get';
/**
* Any data to send across every ajax request
*
* @type Object
* @default {}
**/
this.customData = $.isPlainObject(this.options.customData) ? this.options.customData : {};
/**
* Any custom headers to send across every ajax request
*
* @type Object
* @default {}
*/
this.customHeaders = $.isPlainObject(this.options.customHeaders) ? this.options.customHeaders : {};
/**
* Any custom xhrFields to send across every ajax request
*
* @type Object
* @default {}
*/
this.xhrFields = $.isPlainObject(this.options.xhrFields) ? this.options.xhrFields : {};
/**
* command names for into queue for only cwd requests
* these commands aborts before `open` request
*
* @type Array
* @default ['tmb']
*/
this.abortCmdsOnOpen = this.options.abortCmdsOnOpen || ['tmb'];
/**
* ID. Required to create unique cookie name
*
* @type String
**/
this.id = id;
/**
* ui.nav id prefix
*
* @type String
*/
this.navPrefix = 'nav' + (elFinder.prototype.uniqueid? elFinder.prototype.uniqueid : '') + '-';
/**
* ui.cwd id prefix
*
* @type String
*/
this.cwdPrefix = elFinder.prototype.uniqueid? ('cwd' + elFinder.prototype.uniqueid + '-') : '';
// Increment elFinder.prototype.uniqueid
++elFinder.prototype.uniqueid;
/**
* URL to upload files
*
* @type String
**/
this.uploadURL = opts.urlUpload || opts.url;
/**
* Events namespace
*
* @type String
**/
this.namespace = namespace;
/**
* Interface language
*
* @type String
* @default "en"
**/
this.lang = this.i18[this.options.lang] && this.i18[this.options.lang].messages ? this.options.lang : 'en';
i18n = this.lang == 'en'
? this.i18['en']
: $.extend(true, {}, this.i18['en'], this.i18[this.lang]);
/**
* Interface direction
*
* @type String
* @default "ltr"
**/
this.direction = i18n.direction;
/**
* i18 messages
*
* @type Object
**/
this.messages = i18n.messages;
/**
* Date/time format
*
* @type String
* @default "m.d.Y"
**/
this.dateFormat = this.options.dateFormat || i18n.dateFormat;
/**
* Date format like "Yesterday 10:20:12"
*
* @type String
* @default "{day} {time}"
**/
this.fancyFormat = this.options.fancyDateFormat || i18n.fancyDateFormat;
/**
* Today timestamp
*
* @type Number
**/
this.today = (new Date(date.getFullYear(), date.getMonth(), date.getDate())).getTime()/1000;
/**
* Yesterday timestamp
*
* @type Number
**/
this.yesterday = this.today - 86400;
utc = this.options.UTCDate ? 'UTC' : '';
this.getHours = 'get'+utc+'Hours';
this.getMinutes = 'get'+utc+'Minutes';
this.getSeconds = 'get'+utc+'Seconds';
this.getDate = 'get'+utc+'Date';
this.getDay = 'get'+utc+'Day';
this.getMonth = 'get'+utc+'Month';
this.getFullYear = 'get'+utc+'FullYear';
/**
* Css classes
*
* @type String
**/
this.cssClass = 'ui-helper-reset ui-helper-clearfix ui-widget ui-widget-content ui-corner-all elfinder elfinder-'
+(this.direction == 'rtl' ? 'rtl' : 'ltr')
+(this.UA.Touch? (' elfinder-touch' + (this.options.resizable ? ' touch-punch' : '')) : '')
+(this.UA.Mobile? ' elfinder-mobile' : '')
+' '+this.options.cssClass;
/**
* elFinder node z-index (auto detect on elFinder load)
*
* @type null | Number
**/
this.zIndex;
/**
* Current search status
*
* @type Object
*/
this.searchStatus = {
state : 0, // 0: search ended, 1: search started, 2: in search result
query : '',
target : '',
mime : '',
mixed : false, // in multi volumes search
ininc : false // in incremental search
};
/**
* Method to store/fetch data
*
* @type Function
**/
this.storage = (function() {
try {
if ('localStorage' in window && window['localStorage'] !== null) {
if (self.UA.Safari) {
// check for Mac/iOS safari private browsing mode
window.localStorage.setItem('elfstoragecheck', 1);
window.localStorage.removeItem('elfstoragecheck');
}
return self.localStorage;
} else {
return self.cookie;
}
} catch (e) {
return self.cookie;
}
})();
this.viewType = this.storage('view') || this.options.defaultView || 'icons';
this.sortType = this.storage('sortType') || this.options.sortType || 'name';
this.sortOrder = this.storage('sortOrder') || this.options.sortOrder || 'asc';
this.sortStickFolders = this.storage('sortStickFolders');
if (this.sortStickFolders === null) {
this.sortStickFolders = !!this.options.sortStickFolders;
} else {
this.sortStickFolders = !!this.sortStickFolders
}
this.sortAlsoTreeview = this.storage('sortAlsoTreeview');
if (this.sortAlsoTreeview === null) {
this.sortAlsoTreeview = !!this.options.sortAlsoTreeview;
} else {
this.sortAlsoTreeview = !!this.sortAlsoTreeview
}
this.sortRules = $.extend(true, {}, this._sortRules, this.options.sortRules);
$.each(this.sortRules, function(name, method) {
if (typeof method != 'function') {
delete self.sortRules[name];
}
});
this.compare = $.proxy(this.compare, this);
/**
* Delay in ms before open notification dialog
*
* @type Number
* @default 500
**/
this.notifyDelay = this.options.notifyDelay > 0 ? parseInt(this.options.notifyDelay) : 500;
/**
* Dragging UI Helper object
*
* @type jQuery | null
**/
this.draggingUiHelper = null;
// draggable closure
(function() {
var ltr, wzRect, wzBottom, nodeStyle,
keyEvt = keydown + 'draggable' + ' keyup.' + namespace + 'draggable';
/**
* Base draggable options
*
* @type Object
**/
self.draggable = {
appendTo : node,
addClasses : false,
distance : 4,
revert : true,
refreshPositions : false,
cursor : 'crosshair',
cursorAt : {left : 50, top : 47},
scroll : false,
start : function(e, ui) {
var helper = ui.helper,
targets = $.map(helper.data('files')||[], function(h) { return h || null ;}),
locked = false,
cnt, h;
// fix node size
nodeStyle = node.attr('style');
node.width(node.width()).height(node.height());
// set var for drag()
ltr = (self.direction === 'ltr');
wzRect = self.getUI('workzone').data('rectangle');
wzBottom = wzRect.top + wzRect.height;
self.draggingUiHelper = helper;
cnt = targets.length;
while (cnt--) {
h = targets[cnt];
if (files[h].locked) {
locked = true;
helper.data('locked', true);
break;
}
}
!locked && self.trigger('lockfiles', {files : targets});
helper.data('autoScrTm', setInterval(function() {
if (helper.data('autoScr')) {
self.autoScroll[helper.data('autoScr')](helper.data('autoScrVal'));
}
}, 50));
},
drag : function(e, ui) {
var helper = ui.helper,
autoUp;
if ((autoUp = wzRect.top > e.pageY) || wzBottom < e.pageY) {
if (wzRect.cwdEdge > e.pageX) {
helper.data('autoScr', (ltr? 'navbar' : 'cwd') + (autoUp? 'Up' : 'Down'));
} else {
helper.data('autoScr', (ltr? 'cwd' : 'navbar') + (autoUp? 'Up' : 'Down'));
}
helper.data('autoScrVal', Math.pow((autoUp? wzRect.top - e.pageY : e.pageY - wzBottom), 1.3));
} else {
if (helper.data('autoScr')) {
helper.data('refreshPositions', 1).data('autoScr', null);
}
}
if (helper.data('refreshPositions') && $(this).elfUiWidgetInstance('draggable')) {
if (helper.data('refreshPositions') > 0) {
$(this).draggable('option', { refreshPositions : true, elfRefresh : true });
helper.data('refreshPositions', -1);
} else {
$(this).draggable('option', { refreshPositions : false, elfRefresh : false });
helper.data('refreshPositions', null);
}
}
},
stop : function(e, ui) {
var helper = ui.helper,
files;
$(document).off(keyEvt);
$(this).elfUiWidgetInstance('draggable') && $(this).draggable('option', { refreshPositions : false });
self.draggingUiHelper = null;
self.trigger('focus').trigger('dragstop');
if (! helper.data('droped')) {
files = $.map(helper.data('files')||[], function(h) { return h || null ;});
self.trigger('unlockfiles', {files : files});
self.trigger('selectfiles', {files : files});
}
self.enable();
// restore node style
node.attr('style', nodeStyle);
helper.data('autoScrTm') && clearInterval(helper.data('autoScrTm'));
},
helper : function(e, ui) {
var element = this.id ? $(this) : $(this).parents('[id]:first'),
helper = $('<div class="elfinder-drag-helper"><span class="elfinder-drag-helper-icon-status"/></div>'),
icon = function(f) {
var mime = f.mime, i, tmb = self.tmb(f);
i = '<div class="elfinder-cwd-icon '+self.mime2class(mime)+' ui-corner-all"/>';
if (tmb) {
i = $(i).addClass(tmb.className).css('background-image', "url('"+tmb.url+"')").get(0).outerHTML;
}
return i;
},
hashes, l, ctr;
self.draggingUiHelper && self.draggingUiHelper.stop(true, true);
self.trigger('dragstart', {target : element[0], originalEvent : e});
hashes = element.hasClass(self.res('class', 'cwdfile'))
? self.selected()
: [self.navId2Hash(element.attr('id'))];
helper.append(icon(files[hashes[0]])).data('files', hashes).data('locked', false).data('droped', false).data('namespace', namespace).data('dropover', 0);
if ((l = hashes.length) > 1) {
helper.append(icon(files[hashes[l-1]]) + '<span class="elfinder-drag-num">'+l+'</span>');
}
$(document).on(keyEvt, function(e){
var chk = (e.shiftKey||e.ctrlKey||e.metaKey);
if (ctr !== chk) {
ctr = chk;
if (helper.is(':visible') && helper.data('dropover') && ! helper.data('droped')) {
helper.toggleClass('elfinder-drag-helper-plus', helper.data('locked')? true : ctr);
self.trigger(ctr? 'unlockfiles' : 'lockfiles', {files : hashes, helper: helper});
}
}
});
return helper;
}
};
})();
/**
* Base droppable options
*
* @type Object
**/
this.droppable = {
greedy : true,
tolerance : 'pointer',
accept : '.elfinder-cwd-file-wrapper,.elfinder-navbar-dir,.elfinder-cwd-file,.elfinder-cwd-filename',
hoverClass : this.res('class', 'adroppable'),
classes : { // Deprecated hoverClass jQueryUI>=1.12.0
'ui-droppable-hover': this.res('class', 'adroppable')
},
autoDisable: true, // elFinder original, see jquery.elfinder.js
drop : function(e, ui) {
var dst = $(this),
targets = $.map(ui.helper.data('files')||[], function(h) { return h || null }),
result = [],
dups = [],
faults = [],
isCopy = ui.helper.hasClass('elfinder-drag-helper-plus'),
c = 'class',
cnt, hash, i, h;
if (typeof e.button === 'undefined' || ui.helper.data('namespace') !== namespace || ! self.insideWorkzone(e.pageX, e.pageY)) {
return false;
}
if (dst.hasClass(self.res(c, 'cwdfile'))) {
hash = self.cwdId2Hash(dst.attr('id'));
} else if (dst.hasClass(self.res(c, 'navdir'))) {
hash = self.navId2Hash(dst.attr('id'));
} else {
hash = cwd;
}
cnt = targets.length;
while (cnt--) {
h = targets[cnt];
// ignore drop into itself or in own location
if (h != hash && files[h].phash != hash) {
result.push(h);
} else {
((isCopy && h !== hash && files[hash].write)? dups : faults).push(h);
}
}
if (faults.length) {
return false;
}
ui.helper.data('droped', true);
if (dups.length) {
ui.helper.hide();
self.exec('duplicate', dups);
}
if (result.length) {
ui.helper.hide();
self.clipboard(result, !isCopy);
self.exec('paste', hash, void 0, hash).always(function(){
self.clipboard([]);
self.trigger('unlockfiles', {files : targets});
});
self.trigger('drop', {files : targets});
}
}
};
/**
* Return true if filemanager is active
*
* @return Boolean
**/
this.enabled = function() {
return enabled && this.visible();
};
/**
* Return true if filemanager is visible
*
* @return Boolean
**/
this.visible = function() {
return node[0].elfinder && node.is(':visible');
};
/**
* Return file is root?
*
* @param Object target file object
* @return Boolean
*/
this.isRoot = function(file) {
return (file.isroot || ! file.phash)? true : false;
}
/**
* Return root dir hash for current working directory
*
* @param String target hash
* @param Boolean include fake parent (optional)
* @return String
*/
this.root = function(hash, fake) {
hash = hash || cwd;
var dir, i;
if (! fake) {
$.each(self.roots, function(id, rhash) {
if (hash.indexOf(id) === 0) {
dir = rhash;
return false;
}
});
if (dir) {
return dir;
}
}
dir = files[hash];
while (dir && dir.phash && (fake || ! dir.isroot)) {
dir = files[dir.phash]
}
if (dir) {
return dir.hash;
}
while (i in files && files.hasOwnProperty(i)) {
dir = files[i]
if (!dir.phash && !dir.mime == 'directory' && dir.read) {
return dir.hash;
}
}
return '';
};
/**
* Return current working directory info
*
* @return Object
*/
this.cwd = function() {
return files[cwd] || {};
};
/**
* Return required cwd option
*
* @param String option name
* @param String target hash (optional)
* @return mixed
*/
this.option = function(name, target) {
var res;
target = target || cwd;
if (self.optionsByHashes[target] && typeof self.optionsByHashes[target][name] !== 'undefined') {
return self.optionsByHashes[target][name];
}
if (cwd !== target) {
res = '';
$.each(self.volOptions, function(id, opt) {
if (target.indexOf(id) === 0) {
res = opt[name] || '';
return false;
}
});
return res;
} else {
return cwdOptions[name] || '';
}
};
/**
* Return disabled commands by each folder
*
* @param Array target hashes
* @return Array
*/
this.getDisabledCmds = function(targets) {
var disabled = [];
if (! $.isArray(targets)) {
targets = [ targets ];
}
$.each(targets, function(i, h) {
var disCmds = self.option('disabled', h);
if (disCmds) {
$.each(disCmds, function(i, cmd) {
if ($.inArray(cmd, disabled) === -1) {
disabled.push(cmd);
}
});
}
});
return disabled;
}
/**
* Return file data from current dir or tree by it's hash
*
* @param String file hash
* @return Object
*/
this.file = function(hash) {
return hash? files[hash] : void(0);
};
/**
* Return all cached files
*
* @return Array
*/
this.files = function() {
return $.extend(true, {}, files);
};
/**
* Return list of file parents hashes include file hash
*
* @param String file hash
* @return Array
*/
this.parents = function(hash) {
var parents = [],
dir;
while ((dir = this.file(hash))) {
parents.unshift(dir.hash);
hash = dir.phash;
}
return parents;
};
this.path2array = function(hash, i18) {
var file,
path = [];
while (hash) {
if ((file = files[hash]) && file.hash) {
path.unshift(i18 && file.i18 ? file.i18 : file.name);
hash = file.isroot? null : file.phash;
} else {
path = [];
break;
}
}
return path;
};
/**
* Return file path or Get path async with jQuery.Deferred
*
* @param Object file
* @param Boolean i18
* @param Object asyncOpt
* @return String|jQuery.Deferred
*/
this.path = function(hash, i18, asyncOpt) {
var path = files[hash] && files[hash].path
? files[hash].path
: this.path2array(hash, i18).join(cwdOptions.separator);
if (! asyncOpt || ! files[hash]) {
return path;
} else {
asyncOpt = $.extend({notify: {type : 'parents', cnt : 1, hideCnt : true}}, asyncOpt);
var dfd = $.Deferred(),
notify = asyncOpt.notify,
noreq = false,
req = function() {
self.request({
data : {cmd : 'parents', target : files[hash].phash},
notify : notify,
preventFail : true
})
.done(done)
.fail(function() {
dfd.reject();
});
},
done = function() {
self.one('parentsdone', function() {
path = self.path(hash, i18);
if (path === '' && noreq) {
//retry with request
noreq = false;
req();
} else {
if (notify) {
clearTimeout(ntftm);
notify.cnt = -(parseInt(notify.cnt || 0));
self.notify(notify);
}
dfd.resolve(path);
}
});
},
ntftm;
if (path) {
return dfd.resolve(path);
} else {
if (self.ui['tree']) {
// try as no request
if (notify) {
ntftm = setTimeout(function() {
self.notify(notify);
}, self.notifyDelay);
}
noreq = true;
done(true);
} else {
req();
}
return dfd;
}
}
};
/**
* Return file url if set
*
* @param String file hash
* @return String
*/
this.url = function(hash) {
var file = files[hash],
baseUrl;
if (!file || !file.read) {
return '';
}
if (file.url == '1') {
this.request({
data : {cmd : 'url', target : hash},
preventFail : true,
options: {async: false}
})
.done(function(data) {
file.url = data.url || '';
})
.fail(function() {
file.url = '';
});
}
if (file.url) {
return file.url;
}
baseUrl = (file.hash.indexOf(self.cwd().volumeid) === 0)? cwdOptions.url : this.option('url', file.hash);
if (baseUrl) {
return baseUrl + $.map(this.path2array(hash), function(n) { return encodeURIComponent(n); }).slice(1).join('/')
}
var params = $.extend({}, this.customData, {
cmd: 'file',
target: file.hash
});
if (this.oldAPI) {
params.cmd = 'open';
params.current = file.phash;
}
return this.options.url + (this.options.url.indexOf('?') === -1 ? '?' : '&') + $.param(params, true);
};
/**
* Return file url for open in elFinder
*
* @param String file hash
* @param Boolean for download link
* @return String
*/
this.openUrl = function(hash, download) {
var file = files[hash],
url = '';
if (!file || !file.read) {
return '';
}
if (!download) {
if (file.url) {
if (file.url != 1) {
return file.url;
}
} else if (cwdOptions.url && file.hash.indexOf(self.cwd().volumeid) === 0) {
return cwdOptions.url + $.map(this.path2array(hash), function(n) { return encodeURIComponent(n); }).slice(1).join('/');
}
}
url = this.options.url;
url = url + (url.indexOf('?') === -1 ? '?' : '&')
+ (this.oldAPI ? 'cmd=open¤t='+file.phash : 'cmd=file')
+ '&target=' + file.hash;
if (download) {
url += '&download=1';
}
$.each(this.options.customData, function(key, val) {
url += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(val);
});
return url;
};
/**
* Return thumbnail url
*
* @param Object file object
* @return String
*/
this.tmb = function(file) {
var tmbUrl, tmbCrop,
cls = 'elfinder-cwd-bgurl',
url = '';
if ($.isPlainObject(file)) {
if (self.searchStatus.state && file.hash.indexOf(self.cwd().volumeid) !== 0) {
tmbUrl = self.option('tmbUrl', file.hash);
tmbCrop = self.option('tmbCrop', file.hash);
} else {
tmbUrl = cwdOptions['tmbUrl'];
tmbCrop = cwdOptions['tmbCrop'];
}
if (tmbCrop) {
cls += ' elfinder-cwd-bgurl-crop';
}
if (tmbUrl === 'self' && file.mime.indexOf('image/') === 0) {
url = self.openUrl(file.hash);
cls += ' elfinder-cwd-bgself';
} else if ((self.oldAPI || tmbUrl) && file && file.tmb && file.tmb != 1) {
url = tmbUrl + file.tmb;
}
if (url) {
return { url: url, className: cls };
}
}
return false;
};
/**
* Return selected files hashes
*
* @return Array
**/
this.selected = function() {
return selected.slice(0);
};
/**
* Return selected files info
*
* @return Array
*/
this.selectedFiles = function() {
return $.map(selected, function(hash) { return files[hash] ? $.extend({}, files[hash]) : null });
};
/**
* Return true if file with required name existsin required folder
*
* @param String file name
* @param String parent folder hash
* @return Boolean
*/
this.fileByName = function(name, phash) {
var hash;
for (hash in files) {
if (files.hasOwnProperty(hash) && files[hash].phash == phash && files[hash].name == name) {
return files[hash];
}
}
};
/**
* Valid data for required command based on rules
*
* @param String command name
* @param Object cammand's data
* @return Boolean
*/
this.validResponse = function(cmd, data) {
return data.error || this.rules[this.rules[cmd] ? cmd : 'defaults'](data);
};
/**
* Return bytes from ini formated size
*
* @param String ini formated size
* @return Integer
*/
this.returnBytes = function(val) {
var last;
if (isNaN(val)) {
if (! val) {
val = '';
}
// for ex. 1mb, 1KB
val = val.replace(/b$/i, '');
last = val.charAt(val.length - 1).toLowerCase();
val = val.replace(/[tgmk]$/i, '');
if (last == 't') {
val = val * 1024 * 1024 * 1024 * 1024;
} else if (last == 'g') {
val = val * 1024 * 1024 * 1024;
} else if (last == 'm') {
val = val * 1024 * 1024;
} else if (last == 'k') {
val = val * 1024;
}
val = isNaN(val)? 0 : parseInt(val);
} else {
val = parseInt(val);
if (val < 1) val = 0;
}
return val;
};
/**
* Proccess ajax request.
* Fired events :
* @todo
* @example
* @todo
* @return $.Deferred
*/
this.request = function(opts) {
var self = this,
o = this.options,
dfrd = $.Deferred(),
// request data
data = $.extend({}, o.customData, {mimes : o.onlyMimes}, opts.data || opts),
// command name
cmd = data.cmd,
isOpen = (cmd === 'open'),
// call default fail callback (display error dialog) ?
deffail = !(opts.preventDefault || opts.preventFail),
// call default success callback ?
defdone = !(opts.preventDefault || opts.preventDone),
// options for notify dialog
notify = $.extend({}, opts.notify),
// make cancel button
cancel = !!opts.cancel,
// do not normalize data - return as is
raw = !!opts.raw,
// sync files on request fail
syncOnFail = opts.syncOnFail,
// use lazy()
lazy = !!opts.lazy,
// prepare function before done()
prepare = opts.prepare,
// open notify dialog timeout
timeout,
// request options
options = $.extend({
url : o.url,
async : true,
type : this.requestType,
dataType : 'json',
cache : false,
// timeout : 100,
data : data,
headers : this.customHeaders,
xhrFields: this.xhrFields
}, opts.options || {}),
/**
* Default success handler.
* Call default data handlers and fire event with command name.
*
* @param Object normalized response data
* @return void
**/
done = function(data) {
data.warning && self.error(data.warning);
isOpen && open(data);
self.lazy(function() {
// fire some event to update cache/ui
data.removed && data.removed.length && self.remove(data);
data.added && data.added.length && self.add(data);
data.changed && data.changed.length && self.change(data);
}).then(function() {
// fire event with command name
return self.lazy(function() {
self.trigger(cmd, data);
});
}).then(function() {
// fire event with command name + 'done'
return self.lazy(function() {
self.trigger(cmd + 'done');
});
}).then(function() {
// force update content
data.sync && self.sync();
});
},
/**
* Request error handler. Reject dfrd with correct error message.
*
* @param jqxhr request object
* @param String request status
* @return void
**/
error = function(xhr, status) {
var error, data;
switch (status) {
case 'abort':
error = xhr.quiet ? '' : ['errConnect', 'errAbort'];
break;
case 'timeout':
error = ['errConnect', 'errTimeout'];
break;
case 'parsererror':
error = ['errResponse', 'errDataNotJSON'];
if (xhr.responseText) {
self.debug('backend-debug', { debug: {phpErrors: [ xhr.responseText] }});
if (! cwd) {
xhr.responseText && error.push(xhr.responseText);
}
}
break;
default:
if (xhr.responseText) {
// check responseText, Is that JSON?
try {
data = JSON.parse(xhr.responseText);
if (data && data.error) {
error = data.error;
}
} catch(e) {}
}
if (! error) {
if (xhr.status == 403) {
error = ['errConnect', 'errAccess', 'HTTP error ' + xhr.status];
} else if (xhr.status == 404) {
error = ['errConnect', 'errNotFound', 'HTTP error ' + xhr.status];
} else {
if (xhr.status == 414 && options.type === 'get') {
// retry by POST method
options.type = 'post';
dfrd.xhr = xhr = self.transport.send(options).fail(error).done(success);
return;
}
error = xhr.quiet ? '' : ['errConnect', 'HTTP error ' + xhr.status];
}
}
}
self.trigger(cmd + 'done');
dfrd.reject(error, xhr, status);
},
/**
* Request success handler. Valid response data and reject/resolve dfrd.
*
* @param Object response data
* @param String request status
* @return void
**/
success = function(response) {
// Set currrent request command name
self.currentReqCmd = cmd;
if (raw) {
response && response.debug && self.debug('backend-debug', response);
return dfrd.resolve(response);
}
if (!response) {
return dfrd.reject(['errResponse', 'errDataEmpty'], xhr, response);
} else if (!$.isPlainObject(response)) {
return dfrd.reject(['errResponse', 'errDataNotJSON'], xhr, response);
} else if (response.error) {
return dfrd.reject(response.error, xhr, response);
} else if (!self.validResponse(cmd, response)) {
return dfrd.reject('errResponse', xhr, response);
}
var resolve = function() {
var pushLeafRoots = function(name) {
if (self.leafRoots[data.target] && response[name]) {
$.each(self.leafRoots[data.target], function(i, h) {
var root;
if (root = self.file(h)) {
response[name].push(root);
}
});
}
};
if (isOpen) {
pushLeafRoots('files');
} else if (cmd === 'tree') {
pushLeafRoots('tree');
}
response = self.normalize(response);
if (!self.api) {
self.api = response.api || 1;
if (self.api == '2.0' && typeof response.options.uploadMaxSize !== 'undefined') {
self.api = '2.1';
}
self.newAPI = self.api >= 2;
self.oldAPI = !self.newAPI;
}
if (response.options) {
cwdOptions = $.extend({}, cwdOptions, response.options);
}
if (response.netDrivers) {
self.netDrivers = response.netDrivers;
}
if (response.maxTargets) {
self.maxTargets = response.maxTargets;
}
if (isOpen && !!data.init) {
self.uplMaxSize = self.returnBytes(response.uplMaxSize);
self.uplMaxFile = !!response.uplMaxFile? parseInt(response.uplMaxFile) : 20;
}
if (typeof prepare === 'function') {
prepare(response);
}
dfrd.resolve(response);
response.debug && self.debug('backend-debug', response);
};
lazy? self.lazy(resolve) : resolve();
},
xhr, _xhr,
abort = function(e){
self.trigger(cmd + 'done');
if (e.type == 'autosync') {
if (e.data.action != 'stop') return;
} else if (e.type != 'unload' && e.type != 'destroy' && e.type != 'openxhrabort') {
if (!e.data.added || !e.data.added.length) {
return;
}
}
if (xhr.state() == 'pending') {
xhr.quiet = true;
xhr.abort();
if (e.type != 'unload' && e.type != 'destroy') {
self.autoSync();
}
}
},
request = function() {
dfrd.fail(function(error, xhr, response) {
self.trigger(cmd + 'fail', response);
if (error) {
deffail ? self.error(error) : self.debug('error', self.i18n(error));
}
syncOnFail && self.sync();
})
if (!cmd) {
syncOnFail = false;
return dfrd.reject('errCmdReq');
}
if (self.maxTargets && data.targets && data.targets.length > self.maxTargets) {
syncOnFail = false;
return dfrd.reject(['errMaxTargets', self.maxTargets]);
}
defdone && dfrd.done(done);
if (notify.type && notify.cnt) {
if (cancel) {
notify.cancel = dfrd;
}
timeout = setTimeout(function() {
self.notify(notify);
dfrd.always(function() {
notify.cnt = -(parseInt(notify.cnt)||0);
self.notify(notify);
})
}, self.notifyDelay)
dfrd.always(function() {
clearTimeout(timeout);
});
}
// quiet abort not completed "open" requests
if (isOpen) {
while ((_xhr = queue.pop())) {
if (_xhr.state() == 'pending') {
_xhr.quiet = true;
_xhr.abort();
}
}
if (cwd !== data.target) {
while ((_xhr = cwdQueue.pop())) {
if (_xhr.state() == 'pending') {
_xhr.quiet = true;
_xhr.abort();
}
}
}
}
// trigger abort autoSync for commands to add the item
if ($.inArray(cmd, (self.cmdsToAdd + ' autosync').split(' ')) !== -1) {
if (cmd !== 'autosync') {
self.autoSync('stop');
dfrd.always(function() {
self.autoSync();
});
}
self.trigger('openxhrabort');
}
delete options.preventFail
dfrd.xhr = xhr = self.transport.send(options).fail(error).done(success);
if (isOpen || (data.compare && cmd === 'info')) {
// add autoSync xhr into queue
queue.unshift(xhr);
// bind abort()
data.compare && self.bind(self.cmdsToAdd + ' autosync openxhrabort', abort);
dfrd.always(function() {
var ndx = $.inArray(xhr, queue);
data.compare && self.unbind(self.cmdsToAdd + ' autosync openxhrabort', abort);
ndx !== -1 && queue.splice(ndx, 1);
});
} else if ($.inArray(cmd, self.abortCmdsOnOpen) !== -1) {
// add "open" xhr, only cwd xhr into queue
cwdQueue.unshift(xhr);
dfrd.always(function() {
var ndx = $.inArray(xhr, cwdQueue);
ndx !== -1 && cwdQueue.splice(ndx, 1);
});
}
// abort pending xhr on window unload or elFinder destroy
self.bind('unload destroy', abort);
dfrd.always(function() {
self.unbind('unload destroy', abort);
});
return dfrd;
},
bindData = {opts: opts, result: true};
// trigger "request.cmd" that callback be able to cancel request by substituting "false" for "event.data.result"
self.trigger('request.' + cmd, bindData, true);
if (! bindData.result) {
self.trigger(cmd + 'done');
return dfrd.reject();
} else if (typeof bindData.result === 'object' && bindData.result.promise) {
bindData.result
.done(request)
.fail(function() {
self.trigger(cmd + 'done');
dfrd.reject();
});
return dfrd;
}
// do request
return request();
};
/**
* Compare current files cache with new files and return diff
*
* @param Array new files
* @param String target folder hash
* @param Array exclude properties to compare
* @return Object
*/
this.diff = function(incoming, onlydir, excludeProps) {
var raw = {},
added = [],
removed = [],
changed = [],
isChanged = function(hash) {
var l = changed.length;
while (l--) {
if (changed[l].hash == hash) {
return true;
}
}
};
$.each(incoming, function(i, f) {
raw[f.hash] = f;
});
// find removed
$.each(files, function(hash, f) {
if (! raw[hash] && (! onlydir || f.phash === onlydir)) {
removed.push(hash);
}
});
// compare files
$.each(raw, function(hash, file) {
var origin = files[hash];
if (!origin) {
added.push(file);
} else {
$.each(file, function(prop) {
if (! excludeProps || $.inArray(prop, excludeProps) === -1) {
if (file[prop] !== origin[prop]) {
changed.push(file)
return false;
}
}
});
}
});
// parents of removed dirs mark as changed (required for tree correct work)
$.each(removed, function(i, hash) {
var file = files[hash],
phash = file.phash;
if (phash
&& file.mime == 'directory'
&& $.inArray(phash, removed) === -1
&& raw[phash]
&& !isChanged(phash)) {
changed.push(raw[phash]);
}
});
return {
added : added,
removed : removed,
changed : changed
};
};
/**
* Sync content
*
* @return jQuery.Deferred
*/
this.sync = function(onlydir, polling) {
this.autoSync('stop');
var self = this,
compare = function(){
var c = '', cnt = 0, mtime = 0;
if (onlydir && polling) {
$.each(files, function(h, f) {
if (f.phash && f.phash === onlydir) {
++cnt;
mtime = Math.max(mtime, f.ts);
}
c = cnt+':'+mtime;
});
}
return c;
},
comp = compare(),
dfrd = $.Deferred().done(function() { self.trigger('sync'); }),
opts = [this.request({
data : {cmd : 'open', reload : 1, target : cwd, tree : (! onlydir && this.ui.tree) ? 1 : 0, compare : comp},
preventDefault : true
})],
exParents = function() {
var parents = [],
curRoot = self.file(self.root(cwd)),
curId = curRoot? curRoot.volumeid : null,
phash = self.cwd().phash,
isroot,pdir;
while(phash) {
if (pdir = self.file(phash)) {
if (phash.indexOf(curId) !== 0) {
if (! self.isRoot(pdir)) {
parents.push( {target: phash, cmd: 'tree'} );
}
parents.push( {target: phash, cmd: 'parents'} );
curRoot = self.file(self.root(phash));
curId = curRoot? curRoot.volumeid : null;
}
phash = pdir.phash;
} else {
phash = null;
}
}
return parents;
};
if (! onlydir && self.api >= 2) {
(cwd !== this.root()) && opts.push(this.request({
data : {cmd : 'parents', target : cwd},
preventDefault : true
}));
$.each(exParents(), function(i, data) {
opts.push(self.request({
data : {cmd : data.cmd, target : data.target},
preventDefault : true
}));
});
}
$.when.apply($, opts)
.fail(function(error, xhr) {
if (! polling || $.inArray('errOpen', error) !== -1) {
dfrd.reject(error);
error && self.request({
data : {cmd : 'open', target : (self.lastDir('') || self.root()), tree : 1, init : 1},
notify : {type : 'open', cnt : 1, hideCnt : true}
});
} else {
dfrd.reject((error && xhr.status != 0)? error : void 0);
}
})
.done(function(odata) {
var pdata, argLen, i;
if (odata.cwd.compare) {
if (comp === odata.cwd.compare) {
return dfrd.reject();
}
}
// for 2nd and more requests
pdata = {tree : []};
// results marge of 2nd and more requests
argLen = arguments.length;
if (argLen > 1) {
for(i = 1; i < argLen; i++) {
if (arguments[i].tree && arguments[i].tree.length) {
pdata.tree.push.apply(pdata.tree, arguments[i].tree);
}
}
}
if (self.api < 2.1) {
if (! pdata.tree) {
pdata.tree = [];
}
pdata.tree.push(odata.cwd);
}
// data normalize
odata = self.normalize(odata);
pdata = self.normalize(pdata);
var diff = self.diff(odata.files.concat(pdata && pdata.tree ? pdata.tree : []), onlydir);
diff.added.push(odata.cwd);
diff.removed.length && self.remove(diff);
diff.added.length && self.add(diff);
diff.changed.length && self.change(diff);
return dfrd.resolve(diff);
})
.always(function() {
self.autoSync();
});
return dfrd;
};
this.upload = function(files) {
return this.transport.upload(files, this);
};
/**
* Attach listener to events
* To bind to multiply events at once, separate events names by space
*
* @param String event(s) name(s)
* @param Object event handler
* @return elFinder
*/
this.bind = function(event, callback) {
var i;
if (typeof(callback) == 'function') {
event = ('' + event).toLowerCase().split(/\s+/);
for (i = 0; i < event.length; i++) {
if (listeners[event[i]] === void(0)) {
listeners[event[i]] = [];
}
listeners[event[i]].push(callback);
}
}
return this;
};
/**
* Remove event listener if exists
* To un-bind to multiply events at once, separate events names by space
*
* @param String event(s) name(s)
* @param Function callback
* @return elFinder
*/
this.unbind = function(event, callback) {
var i, l, ci;
event = ('' + event).toLowerCase().split(/\s+/);
for (i = 0; i < event.length; i++) {
l = listeners[event[i]] || [];
ci = $.inArray(callback, l);
ci > -1 && l.splice(ci, 1);
}
callback = null
return this;
};
/**
* Fire event - send notification to all event listeners
*
* @param String event type
* @param Object data to send across event
* @param Boolean allow modify data (call by reference of data)
* @return elFinder
*/
this.trigger = function(event, data, allowModify) {
var event = event.toLowerCase(),
isopen = (event === 'open'),
handlers = listeners[event] || [], i, l, jst;
this.debug('event-'+event, data);
if (isopen && !allowModify) {
// for performance tuning
jst = JSON.stringify(data);
}
if (l = handlers.length) {
event = $.Event(event);
if (allowModify) {
event.data = data;
}
for (i = 0; i < l; i++) {
if (! handlers[i]) {
// probably un-binded this handler
continue;
}
// only callback has argument
if (handlers[i].length) {
if (!allowModify) {
// to avoid data modifications. remember about "sharing" passing arguments in js :)
event.data = isopen? JSON.parse(jst) : $.extend(true, {}, data);
}
}
try {
if (handlers[i](event, this) === false
|| event.isDefaultPrevented()) {
this.debug('event-stoped', event.type);
break;
}
} catch (ex) {
window.console && window.console.log && window.console.log(ex);
}
}
}
return this;
};
/**
* Get event listeners
*
* @param String event type
* @return Array listed event functions
*/
this.getListeners = function(event) {
return event? listeners[event.toLowerCase()] : listeners;
};
/**
* Bind keybord shortcut to keydown event
*
* @example
* elfinder.shortcut({
* pattern : 'ctrl+a',
* description : 'Select all files',
* callback : function(e) { ... },
* keypress : true|false (bind to keypress instead of keydown)
* })
*
* @param Object shortcut config
* @return elFinder
*/
this.shortcut = function(s) {
var patterns, pattern, code, i, parts;
if (this.options.allowShortcuts && s.pattern && $.isFunction(s.callback)) {
patterns = s.pattern.toUpperCase().split(/\s+/);
for (i= 0; i < patterns.length; i++) {
pattern = patterns[i]
parts = pattern.split('+');
code = (code = parts.pop()).length == 1
? code > 0 ? code : code.charCodeAt(0)
: (code > 0 ? code : $.ui.keyCode[code]);
if (code && !shortcuts[pattern]) {
shortcuts[pattern] = {
keyCode : code,
altKey : $.inArray('ALT', parts) != -1,
ctrlKey : $.inArray('CTRL', parts) != -1,
shiftKey : $.inArray('SHIFT', parts) != -1,
type : s.type || 'keydown',
callback : s.callback,
description : s.description,
pattern : pattern
};
}
}
}
return this;
};
/**
* Registered shortcuts
*
* @type Object
**/
this.shortcuts = function() {
var ret = [];
$.each(shortcuts, function(i, s) {
ret.push([s.pattern, self.i18n(s.description)]);
});
return ret;
};
/**
* Get/set clipboard content.
* Return new clipboard content.
*
* @example
* this.clipboard([]) - clean clipboard
* this.clipboard([{...}, {...}], true) - put 2 files in clipboard and mark it as cutted
*
* @param Array new files hashes
* @param Boolean cut files?
* @return Array
*/
this.clipboard = function(hashes, cut) {
var map = function() { return $.map(clipboard, function(f) { return f.hash }); };
if (hashes !== void(0)) {
clipboard.length && this.trigger('unlockfiles', {files : map()});
remember = [];
clipboard = $.map(hashes||[], function(hash) {
var file = files[hash];
if (file) {
remember.push(hash);
return {
hash : hash,
phash : file.phash,
name : file.name,
mime : file.mime,
read : file.read,
locked : file.locked,
cut : !!cut
}
}
return null;
});
this.trigger('changeclipboard', {clipboard : clipboard.slice(0, clipboard.length)});
cut && this.trigger('lockfiles', {files : map()});
}
// return copy of clipboard instead of refrence
return clipboard.slice(0, clipboard.length);
};
/**
* Return true if command enabled
*
* @param String command name
* @param String|void hash for check of own volume's disabled cmds
* @return Boolean
*/
this.isCommandEnabled = function(name, dstHash) {
var disabled,
cvid = self.cwd().volumeid || '';
if (dstHash && (! cvid || dstHash.indexOf(cvid) !== 0)) {
disabled = self.option('disabled', dstHash);
if (! disabled) {
disabled = [];
}
} else {
disabled = cwdOptions.disabled;
}
return this._commands[name] ? $.inArray(name, disabled) === -1 : false;
};
/**
* Exec command and return result;
*
* @param String command name
* @param String|Array usualy files hashes
* @param String|Array command options
* @param String|void hash for enabled check of own volume's disabled cmds
* @return $.Deferred
*/
this.exec = function(cmd, files, opts, dstHash) {
if (cmd === 'open') {
if (this.searchStatus.state || this.searchStatus.ininc) {
this.trigger('searchend', { noupdate: true });
}
this.autoSync('stop');
}
return this._commands[cmd] && this.isCommandEnabled(cmd, dstHash)
? this._commands[cmd].exec(files, opts)
: $.Deferred().reject('No such command');
};
/**
* Create and return dialog.
*
* @param String|DOMElement dialog content
* @param Object dialog options
* @return jQuery
*/
this.dialog = function(content, options) {
var dialog = $('<div/>').append(content).appendTo(node).elfinderdialog(options, this),
dnode = dialog.closest('.ui-dialog'),
resize = function(){
! dialog.data('draged') && dialog.is(':visible') && dialog.elfinderdialog('posInit');
};
if (dnode.length) {
self.bind('resize', resize);
dnode.on('remove', function() {
self.unbind('resize', resize);
});
}
return dialog;
};
/**
* Create and return toast.
*
* @param Object toast options - see ui/toast.js
* @return jQuery
*/
this.toast = function(options) {
return $('<div class="ui-front"/>').appendTo(this.ui.toast).elfindertoast(options || {}, this);
};
/**
* Return UI widget or node
*
* @param String ui name
* @return jQuery
*/
this.getUI = function(ui) {
return this.ui[ui] || node;
};
/**
* Return elFinder.command instance or instances array
*
* @param String command name
* @return Object | Array
*/
this.getCommand = function(name) {
return name === void(0) ? this._commands : this._commands[name];
};
/**
* Resize elfinder node
*
* @param String|Number width
* @param Number height
* @return void
*/
this.resize = function(w, h) {
node.css('width', w).height(h).trigger('resize');
this.trigger('resize', {width : node.width(), height : node.height()});
};
/**
* Restore elfinder node size
*
* @return elFinder
*/
this.restoreSize = function() {
this.resize(width, height);
};
this.show = function() {
node.show();
this.enable().trigger('show');
};
this.hide = function() {
if (this.options.enableAlways) {
prevEnabled = enabled;
enabled = false;
}
this.disable().trigger('hide');
node.hide();
};
/**
* Lazy execution function
*
* @param Object function
* @param Number delay
* @param Object options
* @return Object jQuery.Deferred
*/
this.lazy = function(func, delay, opts) {
var busy = function(state) {
var cnt = node.data('lazycnt'),
repaint;
if (state) {
repaint = node.data('lazyrepaint')? false : opts.repaint;
if (! cnt) {
node.data('lazycnt', 1)
.addClass('elfinder-processing');
} else {
node.data('lazycnt', ++cnt);
}
if (repaint) {
node.data('lazyrepaint', true).css('display'); // force repaint
}
} else {
if (cnt && cnt > 1) {
node.data('lazycnt', --cnt);
} else {
repaint = node.data('lazyrepaint');
node.data('lazycnt', 0)
.removeData('lazyrepaint')
.removeClass('elfinder-processing');
repaint && node.css('display'); // force repaint;
self.trigger('lazydone');
}
}
},
dfd = $.Deferred();
delay = delay || 0;
opts = opts || {};
busy(true);
setTimeout(function() {
dfd.resolve(func.call(dfd));
busy(false);
}, delay);
return dfd;
}
/**
* Destroy this elFinder instance
*
* @return void
**/
this.destroy = function() {
if (node && node[0].elfinder) {
this.options.syncStart = false;
this.autoSync('forcestop');
this.trigger('destroy').disable();
clipboard = [];
selected = [];
listeners = {};
shortcuts = {};
$(window).off('.' + namespace);
$(document).off('.' + namespace);
self.trigger = function(){}
node.off();
node.removeData();
node.empty();
node[0].elfinder = null;
$(beeper).remove();
node.append(prevContent.contents()).removeClass(this.cssClass).attr('style', prevStyle);
}
};
/**
* Start or stop auto sync
*
* @param String|Bool stop
* @return void
*/
this.autoSync = function(mode) {
var sync;
if (self.options.sync >= 1000) {
if (syncInterval) {
clearTimeout(syncInterval);
syncInterval = null;
self.trigger('autosync', {action : 'stop'});
}
if (mode === 'stop') {
++autoSyncStop;
} else {
autoSyncStop = Math.max(0, --autoSyncStop);
}
if (autoSyncStop || mode === 'forcestop' || ! self.options.syncStart) {
return;
}
// run interval sync
sync = function(start){
var timeout;
if (cwdOptions.syncMinMs && (start || syncInterval)) {
start && self.trigger('autosync', {action : 'start'});
timeout = Math.max(self.options.sync, cwdOptions.syncMinMs);
syncInterval && clearTimeout(syncInterval);
syncInterval = setTimeout(function() {
var dosync = true, hash = cwd, cts;
if (cwdOptions.syncChkAsTs && (cts = files[hash].ts)) {
self.request({
data : {cmd : 'info', targets : [hash], compare : cts, reload : 1},
preventDefault : true
})
.done(function(data){
var ts;
dosync = true;
if (data.compare) {
ts = data.compare;
if (ts == cts) {
dosync = false;
}
}
if (dosync) {
self.sync(hash).always(function(){
if (ts) {
// update ts for cache clear etc.
files[hash].ts = ts;
}
sync();
});
} else {
sync();
}
})
.fail(function(error, xhr){
if (error && xhr.status != 0) {
self.error(error);
if ($.inArray('errOpen', error) !== -1) {
self.request({
data : {cmd : 'open', target : (self.lastDir('') || self.root()), tree : 1, init : 1},
notify : {type : 'open', cnt : 1, hideCnt : true}
});
}
} else {
syncInterval = setTimeout(function() {
sync();
}, timeout);
}
});
} else {
self.sync(cwd, true).always(function(){
sync();
});
}
}, timeout);
}
};
sync(true);
}
};
/**
* Return bool is inside work zone of specific point
*
* @param Number event.pageX
* @param Number event.pageY
* @return Bool
*/
this.insideWorkzone = function(x, y, margin) {
var rectangle = this.getUI('workzone').data('rectangle');
margin = margin || 1;
if (x < rectangle.left + margin
|| x > rectangle.left + rectangle.width + margin
|| y < rectangle.top + margin
|| y > rectangle.top + rectangle.height + margin) {
return false;
}
return true;
};
/**
* Target ui node move to last of children of elFinder node fot to show front
*
* @param Object target Target jQuery node object
*/
this.toFront = function(target) {
var lastnode = node.children(':last');
target = $(target);
if (lastnode.get(0) !== target.get(0)) {
lastnode.after(target);
}
};
/**
* Return css object for maximize
*
* @return Object
*/
this.getMaximizeCss = function() {
return {
width : '100%',
height : '100%',
margin : 0,
padding : 0,
top : 0,
left : 0,
display : 'block',
position: 'fixed',
zIndex : Math.max(self.zIndex? (self.zIndex + 1) : 0 , 1000)
};
};
// Closure for togglefullscreen
(function() {
// check is in iframe
if (inFrame && self.UA.Fullscreen) {
self.UA.Fullscreen = false;
if (parentIframe && typeof parentIframe.attr('allowfullscreen') !== 'undefined') {
self.UA.Fullscreen = true;
}
}
var orgStyle, bodyOvf, resizeTm, fullElm, exitFull, toFull,
cls = 'elfinder-fullscreen',
clsN = 'elfinder-fullscreen-native',
checkDialog = function() {
var t = 0,
l = 0;
$.each(node.children('.ui-dialog,.ui-draggable'), function(i, d) {
var $d = $(d),
pos = $d.position();
if (pos.top < 0) {
$d.css('top', t);
t += 20;
}
if (pos.left < 0) {
$d.css('left', l);
l += 20;
}
});
},
funcObj = self.UA.Fullscreen? {
// native full screen mode
fullElm: function() {
return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || null;
},
exitFull: function() {
if (document.exitFullscreen) {
return document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
return document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
return document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
return document.msExitFullscreen();
}
},
toFull: function(elem) {
if (elem.requestFullscreen) {
return elem.requestFullscreen();
} else if (elem.webkitRequestFullscreen) {
return elem.webkitRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
return elem.mozRequestFullScreen();
} else if (elem.msRequestFullscreen) {
return elem.msRequestFullscreen();
}
return false;
}
} : {
// node element maximize mode
fullElm: function() {
var full;
if (node.hasClass(cls)) {
return node.get(0);
} else {
full = node.find('.' + cls);
if (full.length) {
return full.get(0);
}
}
return null;
},
exitFull: function() {
var elm;
$(window).off('resize.' + namespace, resize);
if (bodyOvf !== void(0)) {
$('body').css('overflow', bodyOvf);
}
bodyOvf = void(0);
if (orgStyle) {
elm = orgStyle.elm;
restoreStyle(elm);
$(elm).trigger('resize', {fullscreen: 'off'});
}
$(window).trigger('resize');
},
toFull: function(elem) {
bodyOvf = $('body').css('overflow') || '';
$('body').css('overflow', 'hidden');
$(elem).css(self.getMaximizeCss())
.addClass(cls)
.trigger('resize', {fullscreen: 'on'});
checkDialog();
$(window).on('resize.' + namespace, resize).trigger('resize');
return true;
}
},
restoreStyle = function(elem) {
if (orgStyle && orgStyle.elm == elem) {
$(elem).removeClass(cls + ' ' + clsN).attr('style', orgStyle.style);
orgStyle = null;
}
},
resize = function(e) {
var elm;
if (e.target === window) {
resizeTm && clearTimeout(resizeTm);
resizeTm = setTimeout(function() {
if (elm = funcObj.fullElm()) {
$(elm).trigger('resize', {fullscreen: 'on'});
}
}, 100);
}
};
$(document).on('fullscreenchange.' + namespace + ' webkitfullscreenchange.' + namespace + ' mozfullscreenchange.' + namespace + ' MSFullscreenChange.' + namespace, function(e){
if (self.UA.Fullscreen) {
var elm = funcObj.fullElm(),
win = $(window);
resizeTm && clearTimeout(resizeTm);
if (elm === null) {
win.off('resize.' + namespace, resize);
if (orgStyle) {
elm = orgStyle.elm;
restoreStyle(elm);
$(elm).trigger('resize', {fullscreen: 'off'});
}
} else {
$(elm).addClass(cls + ' ' + clsN)
.attr('style', 'width:100%; height:100%; margin:0; padding:0;')
.trigger('resize', {fullscreen: 'on'});
win.on('resize.' + namespace, resize);
checkDialog();
}
win.trigger('resize');
}
});
/**
* Toggle Full Scrren Mode
*
* @param Object target
* @param Bool full
* @return Object | Null DOM node object of current full scrren
*/
self.toggleFullscreen = function(target, full) {
var elm = $(target).get(0),
curElm = null;
curElm = funcObj.fullElm();
if (curElm) {
if (curElm == elm) {
if (full === true) {
return curElm;
}
} else {
if (full === false) {
return curElm;
}
}
funcObj.exitFull();
return null;
} else {
if (full === false) {
return null;
}
}
orgStyle = {elm: elm, style: $(elm).attr('style')};
if (funcObj.toFull(elm) !== false) {
return elm;
} else {
orgStyle = null;
return null;
}
};
})();
// Closure for toggleMaximize
(function(){
var cls = 'elfinder-maximized',
resizeTm,
resize = function(e) {
if (e.target === window && e.data && e.data.elm) {
var elm = e.data.elm;
resizeTm && clearTimeout(resizeTm);
resizeTm = setTimeout(function() {
elm.trigger('resize', {maximize: 'on'});
}, 100);
}
},
exitMax = function(elm) {
$(window).off('resize.' + namespace, resize);
$('body').css('overflow', elm.data('bodyOvf'));
elm.removeClass(cls)
.attr('style', elm.data('orgStyle'))
.removeData('bodyOvf')
.removeData('orgStyle');
elm.trigger('resize', {maximize: 'off'});
},
toMax = function(elm) {
elm.data('bodyOvf', $('body').css('overflow') || '')
.data('orgStyle', elm.attr('style'))
.addClass(cls)
.css(self.getMaximizeCss());
$('body').css('overflow', 'hidden');
$(window).on('resize.' + namespace, {elm: elm}, resize).trigger('resize');
};
/**
* Toggle Maximize target node
*
* @param Object target
* @param Bool max
* @return void
*/
self.toggleMaximize = function(target, max) {
var elm = $(target),
maximized = elm.hasClass(cls);
if (maximized) {
if (max === true) {
return;
}
exitMax(elm);
} else {
if (max === false) {
return;
}
toMax(elm);
}
};
})();
/************* init stuffs ****************/
// check jquery ui
if (!($.fn.selectable && $.fn.draggable && $.fn.droppable)) {
return alert(this.i18n('errJqui'));
}
// check node
if (!node.length) {
return alert(this.i18n('errNode'));
}
// check connector url
if (!this.options.url) {
return alert(this.i18n('errURL'));
}
$.extend($.ui.keyCode, {
'F1' : 112,
'F2' : 113,
'F3' : 114,
'F4' : 115,
'F5' : 116,
'F6' : 117,
'F7' : 118,
'F8' : 119,
'F9' : 120,
'F10' : 121,
'F11' : 122,
'F12' : 123,
'CONTEXTMENU' : 93
});
this.dragUpload = false;
this.xhrUpload = (typeof XMLHttpRequestUpload != 'undefined' || typeof XMLHttpRequestEventTarget != 'undefined') && typeof File != 'undefined' && typeof FormData != 'undefined';
// configure transport object
this.transport = {};
if (typeof(this.options.transport) == 'object') {
this.transport = this.options.transport;
if (typeof(this.transport.init) == 'function') {
this.transport.init(this)
}
}
if (typeof(this.transport.send) != 'function') {
this.transport.send = function(opts) { return $.ajax(opts); }
}
if (this.transport.upload == 'iframe') {
this.transport.upload = $.proxy(this.uploads.iframe, this);
} else if (typeof(this.transport.upload) == 'function') {
this.dragUpload = !!this.options.dragUploadAllow;
} else if (this.xhrUpload && !!this.options.dragUploadAllow) {
this.transport.upload = $.proxy(this.uploads.xhr, this);
this.dragUpload = true;
} else {
this.transport.upload = $.proxy(this.uploads.iframe, this);
}
/**
* Decoding 'raw' string converted to unicode
*
* @param String str
* @return String
*/
this.decodeRawString = $.isFunction(this.options.rawStringDecoder)? this.options.rawStringDecoder : function(str) {
var charCodes = function(str) {
var i, len, arr;
for (i=0,len=str.length,arr=[]; i<len; i++) {
arr.push(str.charCodeAt(i));
}
return arr;
},
scalarValues = function(arr) {
var scalars = [], i, len, c;
if (typeof arr === 'string') {arr = charCodes(arr);}
for (i=0,len=arr.length; c=arr[i],i<len; i++) {
if (c >= 0xd800 && c <= 0xdbff) {
scalars.push((c & 1023) + 64 << 10 | arr[++i] & 1023);
} else {
scalars.push(c);
}
}
return scalars;
},
decodeUTF8 = function(arr) {
var i, len, c, str, char = String.fromCharCode;
for (i=0,len=arr.length,str=""; c=arr[i],i<len; i++) {
if (c <= 0x7f) {
str += char(c);
} else if (c <= 0xdf && c >= 0xc2) {
str += char((c&31)<<6 | arr[++i]&63);
} else if (c <= 0xef && c >= 0xe0) {
str += char((c&15)<<12 | (arr[++i]&63)<<6 | arr[++i]&63);
} else if (c <= 0xf7 && c >= 0xf0) {
str += char(
0xd800 | ((c&7)<<8 | (arr[++i]&63)<<2 | arr[++i]>>>4&3) - 64,
0xdc00 | (arr[i++]&15)<<6 | arr[i]&63
);
} else {
str += char(0xfffd);
}
}
return str;
};
return decodeUTF8(scalarValues(str));
};
/**
* Alias for this.trigger('error', {error : 'message'})
*
* @param String error message
* @return elFinder
**/
this.error = function() {
var arg = arguments[0],
opts = arguments[1] || null;
return arguments.length == 1 && typeof(arg) == 'function'
? self.bind('error', arg)
: (arg === true? this : self.trigger('error', {error : arg, opts : opts}));
};
// create bind/trigger aliases for build-in events
$.each(events, function(i, name) {
self[name] = function() {
var arg = arguments[0];
return arguments.length == 1 && typeof(arg) == 'function'
? self.bind(name, arg)
: self.trigger(name, $.isPlainObject(arg) ? arg : {});
}
});
// bind core event handlers
this
.enable(function() {
if (!enabled && self.visible() && self.ui.overlay.is(':hidden') && ! node.children('.elfinder-dialog').find('.'+self.res('class', 'editing')).length) {
enabled = true;
document.activeElement && document.activeElement.blur();
node.removeClass('elfinder-disabled');
}
})
.disable(function() {
prevEnabled = enabled;
enabled = false;
node.addClass('elfinder-disabled');
})
.open(function() {
selected = [];
})
.select(function(e) {
var cnt = 0,
unselects = [];
selected = $.map(e.data.selected || e.data.value|| [], function(hash) {
if (unselects.length || (self.maxTargets && ++cnt > self.maxTargets)) {
unselects.push(hash);
return null;
} else {
return files[hash] ? hash : null;
}
});
if (unselects.length) {
self.trigger('unselectfiles', {files: unselects, inselect: true});
self.toast({mode: 'warning', msg: self.i18n(['errMaxTargets', self.maxTargets])});
}
})
.error(function(e) {
var opts = {
cssClass : 'elfinder-dialog-error',
title : self.i18n(self.i18n('error')),
resizable : false,
destroyOnClose : true,
buttons : {}
};
opts.buttons[self.i18n(self.i18n('btnClose'))] = function() { $(this).elfinderdialog('close'); };
if (e.data.opts && $.isPlainObject(e.data.opts)) {
$.extend(opts, e.data.opts);
}
self.dialog('<span class="elfinder-dialog-icon elfinder-dialog-icon-error"/>'+self.i18n(e.data.error), opts);
})
.bind('tree parents', function(e) {
cache(e.data.tree || []);
})
.bind('tmb', function(e) {
$.each(e.data.images||[], function(hash, tmb) {
if (files[hash]) {
files[hash].tmb = tmb;
}
})
})
.add(function(e) {
cache(e.data.added || []);
})
.change(function(e) {
$.each(e.data.changed||[], function(i, file) {
var hash = file.hash;
if (files[hash]) {
$.each(['locked', 'hidden', 'width', 'height'], function(i, v){
if (files[hash][v] && !file[v]) {
delete files[hash][v];
}
});
}
files[hash] = files[hash] ? $.extend(files[hash], file) : file;
});
})
.remove(function(e) {
var removed = e.data.removed||[],
l = removed.length,
roots = {},
rm = function(hash) {
var file = files[hash], i;
if (file) {
if (file.mime === 'directory') {
if (roots[hash]) {
delete self.roots[roots[hash]];
}
$.each(files, function(h, f) {
f.phash == hash && rm(h);
});
}
delete files[hash];
}
};
$.each(self.roots, function(k, v) {
roots[v] = k;
});
while (l--) {
rm(removed[l]);
}
})
.bind('searchstart', function(e) {
$.extend(self.searchStatus, e.data);
self.searchStatus.state = 1;
})
.bind('search', function(e) {
self.searchStatus.state = 2;
cache(e.data.files || []);
})
.bind('searchend', function() {
self.searchStatus.state = 0;
self.searchStatus.mixed = false;
})
;
// We listen and emit a sound on delete according to option
if (true === this.options.sound) {
this.bind('rm', function(e) {
var play = beeper.canPlayType && beeper.canPlayType('audio/wav; codecs="1"');
play && play != '' && play != 'no' && $(beeper).html('<source src="' + soundPath + 'rm.wav" type="audio/wav">')[0].play()
});
}
// bind external event handlers
$.each(this.options.handlers, function(event, callback) {
self.bind(event, callback);
});
/**
* History object. Store visited folders
*
* @type Object
**/
this.history = new this.history(this);
// in getFileCallback set - change default actions on double click/enter/ctrl+enter
if (this.commands.getfile) {
if (typeof(this.options.getFileCallback) == 'function') {
this.bind('dblclick', function(e) {
e.preventDefault();
self.exec('getfile').fail(function() {
self.exec('open');
});
});
this.shortcut({
pattern : 'enter',
description : this.i18n('cmdgetfile'),
callback : function() { self.exec('getfile').fail(function() { self.exec(self.OS == 'mac' ? 'rename' : 'open') }) }
})
.shortcut({
pattern : 'ctrl+enter',
description : this.i18n(this.OS == 'mac' ? 'cmdrename' : 'cmdopen'),
callback : function() { self.exec(self.OS == 'mac' ? 'rename' : 'open') }
});
} else {
this.options.getFileCallback = null;
}
}
/**
* Root hashed
*
* @type Object
*/
this.roots = {};
/**
* leaf roots
*
* @type Object
*/
this.leafRoots = {};
/**
* Loaded commands
*
* @type Object
**/
this._commands = {};
if (!$.isArray(this.options.commands)) {
this.options.commands = [];
}
if ($.inArray('*', this.options.commands) !== -1) {
this.options.commands = Object.keys(this.commands);
}
// load commands
$.each(this.commands, function(name, cmd) {
var proto = $.extend({}, cmd.prototype),
extendsCmd, opts;
if ($.isFunction(cmd) && !self._commands[name] && (cmd.prototype.forceLoad || $.inArray(name, self.options.commands) !== -1)) {
extendsCmd = cmd.prototype.extendsCmd || '';
if (extendsCmd) {
if ($.isFunction(self.commands[extendsCmd])) {
cmd.prototype = $.extend({}, base, new self.commands[extendsCmd](), cmd.prototype);
} else {
return true;
}
} else {
cmd.prototype = $.extend({}, base, cmd.prototype);
}
self._commands[name] = new cmd();
cmd.prototype = proto;
opts = self.options.commandsOptions[name] || {};
if (extendsCmd && self.options.commandsOptions[extendsCmd]) {
opts = $.extend(true, {}, self.options.commandsOptions[extendsCmd], opts);
}
self._commands[name].setup(name, opts);
// setup linked commands
if (self._commands[name].linkedCmds.length) {
$.each(self._commands[name].linkedCmds, function(i, n) {
var lcmd = self.commands[n];
if ($.isFunction(lcmd) && !self._commands[n]) {
lcmd.prototype = base;
self._commands[n] = new lcmd();
self._commands[n].setup(n, self.options.commandsOptions[n]||{});
}
});
}
}
});
/**
* UI command map of cwd volume ( That volume driver option `uiCmdMap` )
*
* @type Object
**/
this.commandMap = {};
/**
* cwd options of each volume
* key: volumeid
* val: options object
*
* @type Object
*/
this.volOptions = {};
/**
* cwd options of each folder/file
* key: hash
* val: options object
*
* @type Object
*/
this.optionsByHashes = {};
// prepare node
node.addClass(this.cssClass)
.on(mousedown, function() {
!enabled && self.enable();
});
/**
* UI nodes
*
* @type Object
**/
this.ui = {
// container for nav panel and current folder container
workzone : $('<div/>').appendTo(node).elfinderworkzone(this),
// container for folders tree / places
navbar : $('<div/>').appendTo(node).elfindernavbar(this, this.options.uiOptions.navbar || {}),
// contextmenu
contextmenu : $('<div/>').appendTo(node).elfindercontextmenu(this),
// overlay
overlay : $('<div/>').appendTo(node).elfinderoverlay({
show : function() { self.disable(); },
hide : function() { prevEnabled && self.enable(); }
}),
// current folder container
cwd : $('<div/>').appendTo(node).elfindercwd(this, this.options.uiOptions.cwd || {}),
// notification dialog window
notify : this.dialog('', {
cssClass : 'elfinder-dialog-notify',
position : this.options.notifyDialog.position,
absolute : true,
resizable : false,
autoOpen : false,
closeOnEscape : false,
title : ' ',
width : parseInt(this.options.notifyDialog.width)
}),
statusbar : $('<div class="ui-widget-header ui-helper-clearfix ui-corner-bottom elfinder-statusbar"/>').hide().appendTo(node),
toast : $('<div class="elfinder-toast"/>').appendTo(node),
bottomtray : $('<div class="elfinder-bottomtray">').appendTo(node)
};
/**
* UI Auto Hide Functions
* Each auto hide function mast be call to `fm.trigger('uiautohide')` at end of process
*
* @type Array
**/
this.uiAutoHide = [];
// trigger `uiautohide`
this.one('open', function() {
if (self.uiAutoHide.length) {
setTimeout(function() {
self.trigger('uiautohide');
}, 500);
}
});
// Auto Hide Functions sequential processing start
this.bind('uiautohide', function() {
if (self.uiAutoHide.length) {
self.uiAutoHide.shift()();
}
});
// load required ui
$.each(this.options.ui || [], function(i, ui) {
var name = 'elfinder'+ui,
opts = self.options.uiOptions[ui] || {};
if (!self.ui[ui] && $.fn[name]) {
// regist to self.ui before make instance
self.ui[ui] = $('<'+(opts.tag || 'div')+'/>').appendTo(node);
self.ui[ui][name](self, opts);
}
});
// store instance in node
node[0].elfinder = this;
// make node resizable
this.options.resizable
&& $.fn.resizable
&& node.resizable({
resize : function(e, ui) {
self.resize(ui.size.width, ui.size.height);
},
handles : 'se',
minWidth : 300,
minHeight : 200
});
if (this.options.width) {
width = this.options.width;
}
if (this.options.height) {
height = parseInt(this.options.height);
}
if (this.options.soundPath) {
soundPath = this.options.soundPath.replace(/\/+$/, '') + '/';
}
// update size
self.resize(width, height);
// attach events to document
$(document)
// disable elfinder on click outside elfinder
.on('click.'+namespace, function(e) { enabled && ! self.options.enableAlways && !$(e.target).closest(node).length && self.disable(); })
// exec shortcuts
.on(keydown+' '+keypress, execShortcut);
// attach events to window
self.options.useBrowserHistory && $(window)
.on('popstate.' + namespace, function(ev) {
var target = ev.originalEvent.state && ev.originalEvent.state.thash;
target && !$.isEmptyObject(self.files()) && self.request({
data : {cmd : 'open', target : target, onhistory : 1},
notify : {type : 'open', cnt : 1, hideCnt : true},
syncOnFail : true
});
});
(function(){
var tm;
$(window).on('resize.' + namespace, function(e){
if (e.target === this) {
tm && clearTimeout(tm);
tm = setTimeout(function() {
self.trigger('resize', {width : node.width(), height : node.height()});
}, 100);
}
})
.on('beforeunload.' + namespace,function(e){
var msg, cnt;
if (node.is(':visible')) {
if (self.ui.notify.children().length && $.inArray('hasNotifyDialog', self.options.windowCloseConfirm) !== -1) {
msg = self.i18n('ntfsmth');
} else if (node.find('.'+self.res('class', 'editing')).length && $.inArray('editingFile', self.options.windowCloseConfirm) !== -1) {
msg = self.i18n('editingFile');
} else if ((cnt = Object.keys(self.selected()).length) && $.inArray('hasSelectedItem', self.options.windowCloseConfirm) !== -1) {
msg = self.i18n('hasSelected', ''+cnt);
} else if ((cnt = Object.keys(self.clipboard()).length) && $.inArray('hasClipboardData', self.options.windowCloseConfirm) !== -1) {
msg = self.i18n('hasClipboard', ''+cnt);
}
if (msg) {
e.returnValue = msg;
return msg;
}
}
self.trigger('unload');
});
})();
// bind window onmessage for CORS
$(window).on('message.' + namespace, function(e){
var res = e.originalEvent || null,
obj, data;
if (res && self.uploadURL.indexOf(res.origin) === 0) {
try {
obj = JSON.parse(res.data);
data = obj.data || null;
if (data) {
if (data.error) {
if (obj.bind) {
self.trigger(obj.bind+'fail', data);
}
self.error(data.error);
} else {
data.warning && self.error(data.warning);
data.removed && data.removed.length && self.remove(data);
data.added && data.added.length && self.add(data);
data.changed && data.changed.length && self.change(data);
if (obj.bind) {
self.trigger(obj.bind, data);
self.trigger(obj.bind+'done');
}
data.sync && self.sync();
}
}
} catch (e) {
self.sync();
}
}
});
// elFinder enable always
if (self.options.enableAlways) {
$(window).on('focus.' + namespace, function(e){
(e.target === this) && self.enable();
});
if (inFrame) {
$(window.top).on('focus.' + namespace, function() {
if (self.enable() && (! parentIframe || parentIframe.is(':visible'))) {
setTimeout(function() {
$(window).focus();
}, 10);
}
});
}
} else if (inFrame) {
$(window).on('blur.' + namespace, function(e){
enabled && e.target === this && self.disable();
});
}
(function() {
var navbar = self.getUI('navbar'),
cwd = self.getUI('cwd').parent();
self.autoScroll = {
navbarUp : function(v) {
navbar.scrollTop(Math.max(0, navbar.scrollTop() - v));
},
navbarDown : function(v) {
navbar.scrollTop(navbar.scrollTop() + v);
},
cwdUp : function(v) {
cwd.scrollTop(Math.max(0, cwd.scrollTop() - v));
},
cwdDown : function(v) {
cwd.scrollTop(cwd.scrollTop() + v);
}
};
})();
if (self.dragUpload) {
// add event listener for HTML5 DnD upload
(function() {
var isin = function(e) {
return (e.target.nodeName !== 'TEXTAREA' && e.target.nodeName !== 'INPUT' && $(e.target).closest('div.ui-dialog-content').length === 0);
},
ent = 'native-drag-enter',
disable = 'native-drag-disable',
c = 'class',
navdir = self.res(c, 'navdir'),
droppable = self.res(c, 'droppable'),
dropover = self.res(c, 'adroppable'),
arrow = self.res(c, 'navarrow'),
clDropActive = self.res(c, 'adroppable'),
wz = self.getUI('workzone'),
ltr = (self.direction === 'ltr'),
clearTm = function() {
autoScrTm && clearTimeout(autoScrTm);
autoScrTm = null;
},
wzRect, autoScrFn, autoScrTm;
node.on('dragenter', function(e) {
clearTm();
if (isin(e)) {
e.preventDefault();
e.stopPropagation();
wzRect = wz.data('rectangle');
}
})
.on('dragleave', function(e) {
clearTm();
if (isin(e)) {
e.preventDefault();
e.stopPropagation();
}
})
.on('dragover', function(e) {
var autoUp;
if (isin(e)) {
e.preventDefault();
e.stopPropagation();
e.originalEvent.dataTransfer.dropEffect = 'none';
if (! autoScrTm) {
autoScrTm = setTimeout(function() {
var wzBottom = wzRect.top + wzRect.height,
fn;
if ((autoUp = e.pageY < wzRect.top) || e.pageY > wzBottom ) {
if (wzRect.cwdEdge > e.pageX) {
fn = (ltr? 'navbar' : 'cwd') + (autoUp? 'Up' : 'Down');
} else {
fn = (ltr? 'cwd' : 'navbar') + (autoUp? 'Up' : 'Down');
}
self.autoScroll[fn](Math.pow((autoUp? wzRect.top - e.pageY : e.pageY - wzBottom), 1.3));
}
autoScrTm = null;
}, 20);
}
} else {
clearTm();
}
})
.on('drop', function(e) {
clearTm();
if (isin(e)) {
e.stopPropagation();
e.preventDefault();
}
});
node.on('dragenter', '.native-droppable', function(e){
if (e.originalEvent.dataTransfer) {
var $elm = $(e.currentTarget),
id = e.currentTarget.id || null,
cwd = null,
elfFrom;
if (!id) { // target is cwd
cwd = self.cwd();
$elm.data(disable, false);
try {
$.each(e.originalEvent.dataTransfer.types, function(i, v){
if (v.substr(0, 13) === 'elfinderfrom:') {
elfFrom = v.substr(13).toLowerCase();
}
});
} catch(e) {}
}
if (!cwd || (cwd.write && (!elfFrom || elfFrom !== (window.location.href + cwd.hash).toLowerCase()))) {
e.preventDefault();
e.stopPropagation();
$elm.data(ent, true);
$elm.addClass(clDropActive);
} else {
$elm.data(disable, true);
}
}
})
.on('dragleave', '.native-droppable', function(e){
if (e.originalEvent.dataTransfer) {
var $elm = $(e.currentTarget);
e.preventDefault();
e.stopPropagation();
if ($elm.data(ent)) {
$elm.data(ent, false);
} else {
$elm.removeClass(clDropActive);
}
}
})
.on('dragover', '.native-droppable', function(e){
if (e.originalEvent.dataTransfer) {
var $elm = $(e.currentTarget);
e.preventDefault();
e.stopPropagation();
e.originalEvent.dataTransfer.dropEffect = $elm.data(disable)? 'none' : 'copy';
$elm.data(ent, false);
}
})
.on('drop', '.native-droppable', function(e){
if (e.originalEvent && e.originalEvent.dataTransfer) {
var $elm = $(e.currentTarget)
id;
e.preventDefault();
e.stopPropagation();
$elm.removeClass(clDropActive);
if (e.currentTarget.id) {
id = $elm.hasClass(navdir)? self.navId2Hash(e.currentTarget.id) : self.cwdId2Hash(e.currentTarget.id);
} else {
id = self.cwd().hash;
}
e.originalEvent._target = id;
self.exec('upload', {dropEvt: e.originalEvent, target: id}, void 0, id);
}
});
})();
}
// Swipe on the touch devices to show/hide of toolbar or navbar
if (self.UA.Touch) {
(function() {
var lastX, lastY, nodeOffset, nodeWidth, nodeTop, navbarW, toolbarH,
navbar = self.getUI('navbar'),
toolbar = self.getUI('toolbar'),
moveOn = function(e) {
e.preventDefault();
},
moveOff = function() {
$(document).off('touchmove', moveOn);
},
handleW, handleH = 50;
node.on('touchstart touchmove touchend', function(e) {
if (e.type === 'touchend') {
lastX = false;
lastY = false;
moveOff();
return;
}
var touches = e.originalEvent.touches || [{}],
x = touches[0].pageX || null,
y = touches[0].pageY || null,
ltr = (self.direction === 'ltr'),
navbarMode, treeWidth, swipeX, moveX, toolbarT, mode;
if (x === null || y === null || (e.type === 'touchstart' && touches.length > 1)) {
return;
}
if (e.type === 'touchstart') {
nodeOffset = node.offset();
nodeWidth = node.width();
if (navbar) {
lastX = false;
if (navbar.is(':hidden')) {
if (! handleW) {
handleW = Math.max(50, nodeWidth / 10)
}
if ((ltr? (x - nodeOffset.left) : (nodeWidth + nodeOffset.left - x)) < handleW) {
lastX = x;
}
} else {
navbarW = navbar.width();
treeWidth = Math.max.apply(Math, $.map(navbar.children('.elfinder-tree'), function(c){return $(c).width();}));
if (ltr) {
swipeX = (x < nodeOffset.left + navbarW && treeWidth - navbar.scrollLeft() - 5 <= navbarW);
} else {
swipeX = (x > nodeOffset.left + nodeWidth - navbarW && treeWidth + navbar.scrollLeft() - 5 <= navbarW);
}
if (swipeX) {
handleW = Math.max(50, nodeWidth / 10);
lastX = x;
} else {
lastX = false;
}
}
}
if (toolbar) {
toolbarH = toolbar.height();
nodeTop = nodeOffset.top;
if (y - nodeTop < (toolbar.is(':hidden')? handleH : (toolbarH + 30))) {
lastY = y;
$(document).on('touchmove.' + namespace, moveOn);
setTimeout(function() {
moveOff();
}, 500);
} else {
lastY = false;
}
}
} else {
if (navbar && lastX !== false) {
navbarMode = (ltr? (lastX > x) : (lastX < x))? 'navhide' : 'navshow';
moveX = Math.abs(lastX - x);
if (navbarMode === 'navhide' && moveX > navbarW * .6
|| (moveX > (navbarMode === 'navhide'? navbarW / 3 : 45)
&& (navbarMode === 'navshow'
|| (ltr? x < nodeOffset.left + 20 : x > nodeOffset.left + nodeWidth - 20)
))
) {
self.getUI('navbar').trigger(navbarMode, {handleW: handleW});
lastX = false;
}
}
if (toolbar && lastY !== false ) {
toolbarT = toolbar.offset().top;
if (Math.abs(lastY - y) > Math.min(45, toolbarH / 3)) {
mode = (lastY > y)? 'slideUp' : 'slideDown';
if (mode === 'slideDown' || toolbarT + 20 > y) {
if (toolbar.is(mode === 'slideDown' ? ':hidden' : ':visible')) {
toolbar.stop(true, true).trigger('toggle', {duration: 100, handleH: handleH});
moveOff();
}
lastY = false;
}
}
}
}
});
})();
}
// return focus to the window on click (elFInder in the frame)
if (inFrame) {
node.on('click', function(e) {
$(window).focus();
});
}
// elFinder to enable by mouse over
if (this.options.enableByMouseOver) {
node.on('mouseenter', function(e) {
(inFrame) && $(window).focus();
! self.enabled() && self.enable();
});
}
// trigger event cssloaded if cddAutoLoad disabled
if (! this.options.cssAutoLoad) {
this.trigger('cssloaded');
}
// send initial request and start to pray >_<
this.trigger('init')
.request({
data : {cmd : 'open', target : self.startDir(), init : 1, tree : this.ui.tree ? 1 : 0},
preventDone : true,
notify : {type : 'open', cnt : 1, hideCnt : true},
freeze : true
})
.fail(function() {
self.trigger('fail').disable().lastDir('');
listeners = {};
shortcuts = {};
$(document).add(node).off('.'+namespace);
self.trigger = function() { };
})
.done(function(data) {
// detect elFinder node z-index
var ni = node.css('z-index');
if (ni && ni !== 'auto' && ni !== 'inherit') {
self.zIndex = ni;
} else {
node.parents().each(function(i, n) {
var z = $(n).css('z-index');
if (z !== 'auto' && z !== 'inherit' && (z = parseInt(z))) {
self.zIndex = z;
return false;
}
});
}
self.load().debug('api', self.api);
// update ui's size after init
node.trigger('resize');
// initial open
open(data);
self.trigger('open', data);
if (inFrame && self.options.enableAlways) {
$(window).focus();
}
});
// self.timeEnd('load');
};
//register elFinder to global scope
if (typeof toGlobal === 'undefined' || toGlobal) {
window.elFinder = elFinder;
}
/**
* Prototype
*
* @type Object
*/
elFinder.prototype = {
uniqueid : 0,
res : function(type, id) {
return this.resources[type] && this.resources[type][id];
},
/**
* User os. Required to bind native shortcuts for open/rename
*
* @type String
**/
OS : navigator.userAgent.indexOf('Mac') !== -1 ? 'mac' : navigator.userAgent.indexOf('Win') !== -1 ? 'win' : 'other',
/**
* User browser UA.
* jQuery.browser: version deprecated: 1.3, removed: 1.9
*
* @type Object
**/
UA : (function(){
var webkit = !document.uniqueID && !window.opera && !window.sidebar && window.localStorage && 'WebkitAppearance' in document.documentElement.style;
return {
// Browser IE <= IE 6
ltIE6 : typeof window.addEventListener == "undefined" && typeof document.documentElement.style.maxHeight == "undefined",
// Browser IE <= IE 7
ltIE7 : typeof window.addEventListener == "undefined" && typeof document.querySelectorAll == "undefined",
// Browser IE <= IE 8
ltIE8 : typeof window.addEventListener == "undefined" && typeof document.getElementsByClassName == "undefined",
IE : document.uniqueID,
Firefox : window.sidebar,
Opera : window.opera,
Webkit : webkit,
Chrome : webkit && window.chrome,
Safari : webkit && !window.chrome,
Mobile : typeof window.orientation != "undefined",
Touch : typeof window.ontouchstart != "undefined",
iOS : navigator.platform.match(/^iP(?:[ao]d|hone)/),
Fullscreen : (typeof (document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen) !== 'undefined')
};
})(),
/**
* Current request command
*
* @type String
*/
currentReqCmd : '',
/**
* Internationalization object
*
* @type Object
*/
i18 : {
en : {
translator : '',
language : 'English',
direction : 'ltr',
dateFormat : 'd.m.Y H:i',
fancyDateFormat : '$1 H:i',
messages : {}
},
months : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsShort : ['msJan', 'msFeb', 'msMar', 'msApr', 'msMay', 'msJun', 'msJul', 'msAug', 'msSep', 'msOct', 'msNov', 'msDec'],
days : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
daysShort : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
},
/**
* File mimetype to kind mapping
*
* @type Object
*/
kinds : {
'unknown' : 'Unknown',
'directory' : 'Folder',
'symlink' : 'Alias',
'symlink-broken' : 'AliasBroken',
'application/x-empty' : 'TextPlain',
'application/postscript' : 'Postscript',
'application/vnd.ms-office' : 'MsOffice',
'application/msword' : 'MsWord',
'application/vnd.ms-word' : 'MsWord',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : 'MsWord',
'application/vnd.ms-word.document.macroEnabled.12' : 'MsWord',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template' : 'MsWord',
'application/vnd.ms-word.template.macroEnabled.12' : 'MsWord',
'application/vnd.ms-excel' : 'MsExcel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : 'MsExcel',
'application/vnd.ms-excel.sheet.macroEnabled.12' : 'MsExcel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.template' : 'MsExcel',
'application/vnd.ms-excel.template.macroEnabled.12' : 'MsExcel',
'application/vnd.ms-excel.sheet.binary.macroEnabled.12' : 'MsExcel',
'application/vnd.ms-excel.addin.macroEnabled.12' : 'MsExcel',
'application/vnd.ms-powerpoint' : 'MsPP',
'application/vnd.openxmlformats-officedocument.presentationml.presentation' : 'MsPP',
'application/vnd.ms-powerpoint.presentation.macroEnabled.12' : 'MsPP',
'application/vnd.openxmlformats-officedocument.presentationml.slideshow' : 'MsPP',
'application/vnd.ms-powerpoint.slideshow.macroEnabled.12' : 'MsPP',
'application/vnd.openxmlformats-officedocument.presentationml.template' : 'MsPP',
'application/vnd.ms-powerpoint.template.macroEnabled.12' : 'MsPP',
'application/vnd.ms-powerpoint.addin.macroEnabled.12' : 'MsPP',
'application/vnd.openxmlformats-officedocument.presentationml.slide' : 'MsPP',
'application/vnd.ms-powerpoint.slide.macroEnabled.12' : 'MsPP',
'application/pdf' : 'PDF',
'application/xml' : 'XML',
'application/vnd.oasis.opendocument.text' : 'OO',
'application/vnd.oasis.opendocument.text-template' : 'OO',
'application/vnd.oasis.opendocument.text-web' : 'OO',
'application/vnd.oasis.opendocument.text-master' : 'OO',
'application/vnd.oasis.opendocument.graphics' : 'OO',
'application/vnd.oasis.opendocument.graphics-template' : 'OO',
'application/vnd.oasis.opendocument.presentation' : 'OO',
'application/vnd.oasis.opendocument.presentation-template' : 'OO',
'application/vnd.oasis.opendocument.spreadsheet' : 'OO',
'application/vnd.oasis.opendocument.spreadsheet-template' : 'OO',
'application/vnd.oasis.opendocument.chart' : 'OO',
'application/vnd.oasis.opendocument.formula' : 'OO',
'application/vnd.oasis.opendocument.database' : 'OO',
'application/vnd.oasis.opendocument.image' : 'OO',
'application/vnd.openofficeorg.extension' : 'OO',
'application/x-shockwave-flash' : 'AppFlash',
'application/flash-video' : 'Flash video',
'application/x-bittorrent' : 'Torrent',
'application/javascript' : 'JS',
'application/rtf' : 'RTF',
'application/rtfd' : 'RTF',
'application/x-font-ttf' : 'TTF',
'application/x-font-otf' : 'OTF',
'application/x-rpm' : 'RPM',
'application/x-web-config' : 'TextPlain',
'application/xhtml+xml' : 'HTML',
'application/docbook+xml' : 'DOCBOOK',
'application/x-awk' : 'AWK',
'application/x-gzip' : 'GZIP',
'application/x-bzip2' : 'BZIP',
'application/x-xz' : 'XZ',
'application/zip' : 'ZIP',
'application/x-zip' : 'ZIP',
'application/x-rar' : 'RAR',
'application/x-tar' : 'TAR',
'application/x-7z-compressed' : '7z',
'application/x-jar' : 'JAR',
'text/plain' : 'TextPlain',
'text/x-php' : 'PHP',
'text/html' : 'HTML',
'text/javascript' : 'JS',
'text/css' : 'CSS',
'text/rtf' : 'RTF',
'text/rtfd' : 'RTF',
'text/x-c' : 'C',
'text/x-csrc' : 'C',
'text/x-chdr' : 'CHeader',
'text/x-c++' : 'CPP',
'text/x-c++src' : 'CPP',
'text/x-c++hdr' : 'CPPHeader',
'text/x-shellscript' : 'Shell',
'application/x-csh' : 'Shell',
'text/x-python' : 'Python',
'text/x-java' : 'Java',
'text/x-java-source' : 'Java',
'text/x-ruby' : 'Ruby',
'text/x-perl' : 'Perl',
'text/x-sql' : 'SQL',
'text/xml' : 'XML',
'text/x-comma-separated-values' : 'CSV',
'text/x-markdown' : 'Markdown',
'image/x-ms-bmp' : 'BMP',
'image/jpeg' : 'JPEG',
'image/gif' : 'GIF',
'image/png' : 'PNG',
'image/tiff' : 'TIFF',
'image/x-targa' : 'TGA',
'image/vnd.adobe.photoshop' : 'PSD',
'image/xbm' : 'XBITMAP',
'image/pxm' : 'PXM',
'audio/mpeg' : 'AudioMPEG',
'audio/midi' : 'AudioMIDI',
'audio/ogg' : 'AudioOGG',
'audio/mp4' : 'AudioMPEG4',
'audio/x-m4a' : 'AudioMPEG4',
'audio/wav' : 'AudioWAV',
'audio/x-mp3-playlist' : 'AudioPlaylist',
'video/x-dv' : 'VideoDV',
'video/mp4' : 'VideoMPEG4',
'video/mpeg' : 'VideoMPEG',
'video/x-msvideo' : 'VideoAVI',
'video/quicktime' : 'VideoMOV',
'video/x-ms-wmv' : 'VideoWM',
'video/x-flv' : 'VideoFlash',
'video/x-matroska' : 'VideoMKV',
'video/ogg' : 'VideoOGG'
},
/**
* Ajax request data validation rules
*
* @type Object
*/
rules : {
defaults : function(data) {
if (!data
|| (data.added && !$.isArray(data.added))
|| (data.removed && !$.isArray(data.removed))
|| (data.changed && !$.isArray(data.changed))) {
return false;
}
return true;
},
open : function(data) { return data && data.cwd && data.files && $.isPlainObject(data.cwd) && $.isArray(data.files); },
tree : function(data) { return data && data.tree && $.isArray(data.tree); },
parents : function(data) { return data && data.tree && $.isArray(data.tree); },
tmb : function(data) { return data && data.images && ($.isPlainObject(data.images) || $.isArray(data.images)); },
upload : function(data) { return data && ($.isPlainObject(data.added) || $.isArray(data.added));},
search : function(data) { return data && data.files && $.isArray(data.files)}
},
/**
* Commands costructors
*
* @type Object
*/
commands : {},
/**
* Commands to add the item (space delimited)
*
* @type String
*/
cmdsToAdd : 'archive duplicate extract mkdir mkfile paste rm upload',
parseUploadData : function(text) {
var data;
if (!$.trim(text)) {
return {error : ['errResponse', 'errDataEmpty']};
}
try {
data = JSON.parse(text);
} catch (e) {
return {error : ['errResponse', 'errDataNotJSON']};
}
if (!this.validResponse('upload', data)) {
return {error : ['errResponse']};
}
data = this.normalize(data);
data.removed = $.merge((data.removed || []), $.map(data.added||[], function(f) { return f.hash; }));
return data;
},
iframeCnt : 0,
uploads : {
// xhr muiti uploading flag
xhrUploading: false,
// check file/dir exists
checkExists: function(files, target, fm) {
var dfrd = $.Deferred(),
names, name,
cancel = function() {
var i = files.length;
while (--i > -1) {
files[i]._remove = true;
}
},
check = function() {
var renames = [], hashes = {}, existed = [], exists = [], i, c;
var confirm = function(ndx) {
var last = ndx == exists.length-1,
opts = {
title : fm.i18n('cmdupload'),
text : ['errExists', exists[ndx].name, 'confirmRepl'],
all : !last,
accept : {
label : 'btnYes',
callback : function(all) {
!last && !all
? confirm(++ndx)
: dfrd.resolve(renames, hashes);
}
},
reject : {
label : 'btnNo',
callback : function(all) {
var i;
if (all) {
i = exists.length;
while (ndx < i--) {
files[exists[i].i]._remove = true;
}
} else {
files[exists[ndx].i]._remove = true;
}
!last && !all
? confirm(++ndx)
: dfrd.resolve(renames, hashes);
}
},
cancel : {
label : 'btnCancel',
callback : function() {
cancel();
dfrd.resolve(renames, hashes);
}
},
buttons : [
{
label : 'btnBackup',
callback : function(all) {
var i;
if (all) {
i = exists.length;
while (ndx < i--) {
renames.push(exists[i].name);
}
} else {
renames.push(exists[ndx].name);
}
!last && !all
? confirm(++ndx)
: dfrd.resolve(renames, hashes);
}
}
]
};
if (fm.iframeCnt > 0) {
delete opts.reject;
}
fm.confirm(opts);
};
if (! fm.file(target).read) {
// for dropbox type
dfrd.resolve([]);
return;
}
names = $.map(files, function(file, i) { return file.name? {i: i, name: file.name} : null ;});
name = $.map(names, function(item) { return item.name;});
fm.request({
data : {cmd : 'ls', target : target, intersect : name},
notify : {type : 'preupload', cnt : 1, hideCnt : true},
preventFail : true
})
.done(function(data) {
var existedArr, cwdItems;
if (data) {
if (data.error) {
cancel();
} else {
if (fm.options.overwriteUploadConfirm && ! fm.UA.iOS && fm.option('uploadOverwrite', target)) {
if (data.list) {
if ($.isArray(data.list)) {
existed = data.list || [];
} else {
existedArr = [];
existed = $.map(data.list, function(n) {
if (typeof n === 'string') {
return n;
} else {
// support to >=2.1.11 plugin Normalizer, Sanitizer
existedArr = existedArr.concat(n);
return null;
}
});
if (existedArr.length) {
existed = existed.concat(existedArr);
}
hashes = data.list;
}
exists = $.map(names, function(name){
return $.inArray(name.name, existed) !== -1 ? name : null ;
});
if (existed.length && target == fm.cwd().hash) {
cwdItems = $.map(fm.files(), function(file) { return (file.phash == target) ? file.name : null; } );
if ($.map(existed, function(n) {
return $.inArray(n, cwdItems) === -1? true : null;
}).length){
fm.sync();
}
}
}
}
}
}
if (exists.length > 0) {
confirm(0);
} else {
dfrd.resolve([]);
}
})
.fail(function(error) {
cancel();
dfrd.resolve([]);
error && fm.error(error);
});
};
if (fm.api >= 2.1 && typeof files[0] == 'object') {
check();
return dfrd;
} else {
return dfrd.resolve([]);
}
},
// check droped contents
checkFile : function(data, fm, target) {
if (!!data.checked || data.type == 'files') {
return data.files;
} else if (data.type == 'data') {
var dfrd = $.Deferred(),
files = [],
paths = [],
dirctorys = [],
entries = [],
processing = 0,
items,
mkdirs = [],
readEntries = function(dirReader) {
var toArray = function(list) {
return Array.prototype.slice.call(list || []);
};
},
doScan = function(items) {
var dirReader, entry, length,
entries = [],
toArray = function(list) {
return Array.prototype.slice.call(list || [], 0);
},
excludes = fm.options.folderUploadExclude[fm.OS] || null;
length = items.length;
for (var i = 0; i < length; i++) {
entry = items[i];
if (entry) {
if (entry.isFile) {
processing++;
entry.file(function (file) {
if (! excludes || ! file.name.match(excludes)) {
paths.push(entry.fullPath || '');
files.push(file);
}
processing--;
});
} else if (entry.isDirectory) {
if (fm.api >= 2.1) {
processing++;
mkdirs.push(entry.fullPath);
dirReader = entry.createReader();
var entries = [];
// Call the reader.readEntries() until no more results are returned.
var readEntries = function() {
dirReader.readEntries (function(results) {
if (!results.length) {
for (var i = 0; i < entries.length; i++) {
doScan([entries[i]]);
}
processing--;
} else {
entries = entries.concat(toArray(results));
readEntries();
}
}, function(){
processing--;
});
};
readEntries(); // Start reading dirs.
}
}
}
}
};
items = $.map(data.files.items, function(item){
return item.getAsEntry? item.getAsEntry() : item.webkitGetAsEntry();
});
if (items.length > 0) {
fm.uploads.checkExists(items, target, fm).done(function(renames, hashes){
var notifyto, dfds = [];
if (fm.options.overwriteUploadConfirm && ! fm.UA.iOS && fm.option('uploadOverwrite', target)) {
items = $.map(items, function(item){
var i, bak, hash, dfd, hi;
if (item.isDirectory) {
i = $.inArray(item.name, renames);
if (i !== -1) {
renames.splice(i, 1);
bak = fm.uniqueName(item.name + fm.options.backupSuffix , null, '');
$.each(hashes, function(h, name) {
if (item.name == name) {
hash = h;
return false;
}
});
if (! hash) {
hash = fm.fileByName(item.name, target).hash;
}
fm.lockfiles({files : [hash]});
dfd = fm.request({
data : {cmd : 'rename', target : hash, name : bak},
notify : {type : 'rename', cnt : 1}
})
.fail(function(error) {
item._remove = true;
fm.sync();
})
.always(function() {
fm.unlockfiles({files : [hash]})
});
dfds.push(dfd);
}
}
return !item._remove? item : null;
});
}
$.when.apply($, dfds).done(function(){
if (items.length > 0) {
notifyto = setTimeout(function() {
fm.notify({type : 'readdir', cnt : 1, hideCnt: true});
}, fm.options.notifyDelay);
doScan(items);
setTimeout(function wait() {
if (processing > 0) {
setTimeout(wait, 10);
} else {
notifyto && clearTimeout(notifyto);
fm.notify({type : 'readdir', cnt : -1});
dfrd.resolve([files, paths, renames, hashes, mkdirs]);
}
}, 10);
} else {
dfrd.reject();
}
});
});
return dfrd.promise();
} else {
return dfrd.reject();
}
} else {
var ret = [];
var check = [];
var str = data.files[0];
if (data.type == 'html') {
var tmp = $("<html/>").append($.parseHTML(str.replace(/ src=/ig, ' _elfsrc='))),
atag;
$('img[_elfsrc]', tmp).each(function(){
var url, purl,
self = $(this),
pa = self.closest('a');
if (pa && pa.attr('href') && pa.attr('href').match(/\.(?:jpe?g|gif|bmp|png)/i)) {
purl = pa.attr('href');
}
url = self.attr('_elfsrc');
if (url) {
if (purl) {
$.inArray(purl, ret) == -1 && ret.push(purl);
$.inArray(url, check) == -1 && check.push(url);
} else {
$.inArray(url, ret) == -1 && ret.push(url);
}
}
});
atag = $('a[href]', tmp);
atag.each(function(){
var loc,
parseUrl = function(url) {
var a = document.createElement('a');
a.href = url;
return a;
};
if ($(this).text()) {
loc = parseUrl($(this).attr('href'));
if (loc.href && (atag.length === 1 || ! loc.pathname.match(/(?:\.html?|\/[^\/.]*)$/i))) {
if ($.inArray(loc.href, ret) == -1 && $.inArray(loc.href, check) == -1) ret.push(loc.href);
}
}
});
} else {
var regex, m, url;
regex = /(http[^<>"{}|\\^\[\]`\s]+)/ig;
while (m = regex.exec(str)) {
url = m[1].replace(/&/g, '&');
if ($.inArray(url, ret) == -1) ret.push(url);
}
}
return ret;
}
},
// upload transport using XMLHttpRequest
xhr : function(data, fm) {
var self = fm ? fm : this,
node = self.getUI(),
xhr = new XMLHttpRequest(),
notifyto = null, notifyto2 = null,
dataChecked = data.checked,
isDataType = (data.isDataType || data.type == 'data'),
target = (data.target || self.cwd().hash),
dropEvt = (data.dropEvt || null),
chunkEnable = (self.option('uploadMaxConn', target) != -1),
multiMax = Math.min(5, Math.max(1, self.option('uploadMaxConn', target))),
retryWait = 10000, // 10 sec
retryMax = 30, // 10 sec * 30 = 300 secs (Max 5 mins)
retry = 0,
dfrd = $.Deferred()
.fail(function(error) {
if (self.uploads.xhrUploading) {
setTimeout(function() { self.sync(); }, 5000);
var file = files.length? (isDataType? files[0][0] : files[0]) : {};
if (file._cid) {
formData = new FormData();
files = [{_chunkfail: true}];
formData.append('chunk', file._chunk);
formData.append('cid' , file._cid);
isDataType = false;
send(files);
}
}
self.uploads.xhrUploading = false;
files = null;
error && self.error(error);
})
.done(function(data) {
xhr = null;
self.uploads.xhrUploading = false;
files = null;
if (data) {
self.currentReqCmd = 'upload';
data.warning && self.error(data.warning);
data.removed && self.remove(data);
data.added && self.add(data);
data.changed && self.change(data);
self.trigger('upload', data);
self.trigger('uploaddone');
data.sync && self.sync();
data.debug && fm.debug('backend-debug', data);
}
})
.always(function() {
// unregist fnAbort function
node.off('uploadabort', fnAbort);
$(window).off('unload', fnAbort);
notifyto && clearTimeout(notifyto);
notifyto2 && clearTimeout(notifyto2);
dataChecked && !data.multiupload && checkNotify() && self.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0});
chunkMerge && notifyElm.children('.elfinder-notify-chunkmerge').length && self.notify({type : 'chunkmerge', cnt : -1});
}),
formData = new FormData(),
files = data.input ? data.input.files : self.uploads.checkFile(data, self, target),
cnt = data.checked? (isDataType? files[0].length : files.length) : files.length,
loaded = 0,
prev = 0,
filesize = 0,
notify = false,
notifyElm = self.ui.notify,
cancelBtn = true,
abort = false,
checkNotify = function() {
return notify = (notify || notifyElm.children('.elfinder-notify-upload').length);
},
fnAbort = function() {
abort = true;
if (xhr) {
xhr.quiet = true;
xhr.abort();
}
if (checkNotify()) {
self.notify({type : 'upload', cnt : notifyElm.children('.elfinder-notify-upload').data('cnt') * -1, progress : 0, size : 0});
}
},
cancelToggle = function(show) {
notifyElm.children('.elfinder-notify-upload').children('.elfinder-notify-cancel')[show? 'show':'hide']();
},
startNotify = function(size) {
if (!size) size = filesize;
return setTimeout(function() {
notify = true;
self.notify({type : 'upload', cnt : cnt, progress : loaded - prev, size : size,
cancel: function() {
node.trigger('uploadabort');
dfrd.resolve();
}
});
prev = loaded;
if (data.multiupload) {
cancelBtn && cancelToggle(true);
} else {
cancelToggle(cancelBtn && loaded < size);
}
}, self.options.notifyDelay);
},
doRetry = function() {
if (retry++ <= retryMax) {
if (checkNotify() && prev) {
self.notify({type : 'upload', cnt : 0, progress : 0, size : prev});
}
xhr.quiet = true;
xhr.abort();
prev = loaded = 0;
setTimeout(function() {
if (! abort) {
xhr.open('POST', self.uploadURL, true);
xhr.send(formData);
}
}, retryWait);
} else {
node.trigger('uploadabort');
dfrd.reject(['errAbort', 'errTimeout']);
}
},
renames = (data.renames || null),
hashes = (data.hashes || null),
chunkMerge = false;
// regist fnAbort function
node.one('uploadabort', fnAbort);
$(window).one('unload.' + fm.namespace, fnAbort);
!chunkMerge && (prev = loaded);
if (!isDataType && !cnt) {
return dfrd.reject(['errUploadNoFiles']);
}
xhr.addEventListener('error', function() {
if (xhr.status == 0) {
if (abort) {
dfrd.reject();
} else {
// ff bug while send zero sized file
// for safari - send directory
if (!isDataType && data.files && $.map(data.files, function(f){return ! f.type && f.size === (self.UA.Safari? 1802 : 0)? f : null;}).length) {
errors.push('errFolderUpload');
dfrd.reject(['errAbort', 'errFolderUpload']);
} else if (data.input && $.map(data.input.files, function(f){return ! f.type && f.size === (self.UA.Safari? 1802 : 0)? f : null;}).length) {
dfrd.reject(['errUploadNoFiles']);
} else {
doRetry();
}
}
} else {
node.trigger('uploadabort');
dfrd.reject('errConnect');
}
}, false);
xhr.addEventListener('load', function(e) {
var status = xhr.status, res, curr = 0, error = '';
if (status >= 400) {
if (status > 500) {
error = 'errResponse';
} else {
error = 'errConnect';
}
} else {
if (!xhr.responseText) {
error = ['errResponse', 'errDataEmpty'];
}
}
if (error) {
node.trigger('uploadabort');
var file = isDataType? files[0][0] : files[0];
return dfrd.reject(file._cid? null : error);
}
loaded = filesize;
if (checkNotify() && (curr = loaded - prev)) {
self.notify({type : 'upload', cnt : 0, progress : curr, size : 0});
}
res = self.parseUploadData(xhr.responseText);
// chunked upload commit
if (res._chunkmerged) {
formData = new FormData();
var _file = [{_chunkmerged: res._chunkmerged, _name: res._name, _mtime: res._mtime}];
chunkMerge = true;
node.off('uploadabort', fnAbort);
notifyto2 = setTimeout(function() {
self.notify({type : 'chunkmerge', cnt : 1});
}, self.options.notifyDelay);
isDataType? send(_file, files[1]) : send(_file);
return;
}
res._multiupload = data.multiupload? true : false;
if (res.error) {
self.trigger('uploadfail', res);
if (res._chunkfailure || res._multiupload) {
abort = true;
self.uploads.xhrUploading = false;
notifyto && clearTimeout(notifyto);
if (notifyElm.children('.elfinder-notify-upload').length) {
self.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0});
dfrd.reject(res.error);
} else {
// for multi connection
dfrd.reject();
}
} else {
dfrd.reject(res.error);
}
} else {
dfrd.resolve(res);
}
}, false);
xhr.upload.addEventListener('loadstart', function(e) {
if (!chunkMerge && e.lengthComputable) {
loaded = e.loaded;
retry && (loaded = 0);
filesize = e.total;
if (!loaded) {
loaded = parseInt(filesize * 0.05);
}
if (checkNotify()) {
self.notify({type : 'upload', cnt : 0, progress : loaded - prev, size : data.multiupload? 0 : filesize});
prev = loaded;
}
}
}, false);
xhr.upload.addEventListener('progress', function(e) {
var curr;
if (e.lengthComputable && !chunkMerge && xhr.readyState < 2) {
loaded = e.loaded;
// to avoid strange bug in safari (not in chrome) with drag&drop.
// bug: macos finder opened in any folder,
// reset safari cache (option+command+e), reload elfinder page,
// drop file from finder
// on first attempt request starts (progress callback called ones) but never ends.
// any next drop - successfull.
if (!data.checked && loaded > 0 && !notifyto) {
notifyto = startNotify(xhr._totalSize - loaded);
}
if (!filesize) {
filesize = e.total;
if (!loaded) {
loaded = parseInt(filesize * 0.05);
}
}
curr = loaded - prev;
if (checkNotify() && (curr/e.total) >= 0.05) {
self.notify({type : 'upload', cnt : 0, progress : curr, size : 0});
prev = loaded;
}
if (! data.multiupload && loaded >= filesize) {
cancelBtn = false;
cancelToggle(false);
}
}
}, false);
var send = function(files, paths){
var size = 0,
fcnt = 1,
sfiles = [],
c = 0,
total = cnt,
maxFileSize,
totalSize = 0,
chunked = [],
chunkID = new Date().getTime().toString().substr(-9), // for take care of the 32bit backend system
BYTES_PER_CHUNK = Math.min((fm.uplMaxSize? fm.uplMaxSize : 2097152) - 8190, fm.options.uploadMaxChunkSize), // uplMaxSize margin 8kb or options.uploadMaxChunkSize
blobSlice = chunkEnable? false : '',
blobSize, blobMtime, i, start, end, chunks, blob, chunk, added, done, last, failChunk,
multi = function(files, num){
var sfiles = [], cid, sfilesLen = 0, cancelChk;
if (!abort) {
while(files.length && sfiles.length < num) {
sfiles.push(files.shift());
}
sfilesLen = sfiles.length;
if (sfilesLen) {
cancelChk = sfilesLen;
for (var i=0; i < sfilesLen; i++) {
if (abort) {
break;
}
cid = isDataType? (sfiles[i][0][0]._cid || null) : (sfiles[i][0]._cid || null);
if (!!failChunk[cid]) {
last--;
continue;
}
fm.exec('upload', {
type: data.type,
isDataType: isDataType,
files: sfiles[i],
checked: true,
target: target,
dropEvt: dropEvt,
renames: renames,
hashes: hashes,
multiupload: true}, void 0, target)
.fail(function(error) {
if (error && error === 'No such command') {
abort = true;
fm.error(['errUpload', 'errPerm']);
}
if (cid) {
failChunk[cid] = true;
}
})
.always(function(e) {
if (e && e.added) added = $.merge(added, e.added);
if (last <= ++done) {
fm.trigger('multiupload', {added: added});
notifyto && clearTimeout(notifyto);
if (checkNotify()) {
self.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0});
}
}
if (files.length) {
multi(files, 1); // Next one
} else {
if (--cancelChk <= 1) {
cancelBtn = false;
cancelToggle(false);
}
}
});
}
}
}
if (sfiles.length < 1 || abort) {
if (abort) {
notifyto && clearTimeout(notifyto);
if (cid) {
failChunk[cid] = true;
}
dfrd.reject();
} else {
dfrd.resolve();
self.uploads.xhrUploading = false;
}
}
},
check = function(){
if (!self.uploads.xhrUploading) {
self.uploads.xhrUploading = true;
multi(sfiles, multiMax); // Max connection: 3
} else {
setTimeout(function(){ check(); }, 100);
}
};
if (! dataChecked && (isDataType || data.type == 'files')) {
if (! (maxFileSize = fm.option('uploadMaxSize', target))) {
maxFileSize = 0;
}
for (i=0; i < files.length; i++) {
try {
blob = files[i];
blobSize = blob.size;
if (blobSlice === false) {
blobSlice = '';
if (self.api >= 2.1) {
if ('slice' in blob) {
blobSlice = 'slice';
} else if ('mozSlice' in blob) {
blobSlice = 'mozSlice';
} else if ('webkitSlice' in blob) {
blobSlice = 'webkitSlice';
}
}
}
} catch(e) {
cnt--;
total--;
continue;
}
// file size check
if ((maxFileSize && blobSize > maxFileSize) || (!blobSlice && fm.uplMaxSize && blobSize > fm.uplMaxSize)) {
self.error(self.i18n('errUploadFile', blob.name) + ' ' + self.i18n('errUploadFileSize'));
cnt--;
total--;
continue;
}
// file mime check
if (blob.type && ! self.uploadMimeCheck(blob.type, target)) {
self.error(self.i18n('errUploadFile', blob.name) + ' ' + self.i18n('errUploadMime') + ' (' + self.escape(blob.type) + ')');
cnt--;
total--;
continue;
}
if (blobSlice && blobSize > BYTES_PER_CHUNK) {
start = 0;
end = BYTES_PER_CHUNK;
chunks = -1;
total = Math.floor(blobSize / BYTES_PER_CHUNK);
blobMtime = blob.lastModified? Math.round(blob.lastModified/1000) : 0;
totalSize += blobSize;
chunked[chunkID] = 0;
while(start <= blobSize) {
chunk = blob[blobSlice](start, end);
chunk._chunk = blob.name + '.' + (++chunks) + '_' + total + '.part';
chunk._cid = chunkID;
chunk._range = start + ',' + chunk.size + ',' + blobSize;
chunk._mtime = blobMtime;
chunked[chunkID]++;
if (size) {
c++;
}
if (typeof sfiles[c] == 'undefined') {
sfiles[c] = [];
if (isDataType) {
sfiles[c][0] = [];
sfiles[c][1] = [];
}
}
size = BYTES_PER_CHUNK;
fcnt = 1;
if (isDataType) {
sfiles[c][0].push(chunk);
sfiles[c][1].push(paths[i]);
} else {
sfiles[c].push(chunk);
}
start = end;
end = start + BYTES_PER_CHUNK;
}
if (chunk == null) {
self.error(self.i18n('errUploadFile', blob.name) + ' ' + self.i18n('errUploadFileSize'));
cnt--;
total--;
} else {
total += chunks;
size = 0;
fcnt = 1;
c++;
}
continue;
}
if ((fm.uplMaxSize && size + blobSize >= fm.uplMaxSize) || fcnt > fm.uplMaxFile) {
size = 0;
fcnt = 1;
c++;
}
if (typeof sfiles[c] == 'undefined') {
sfiles[c] = [];
if (isDataType) {
sfiles[c][0] = [];
sfiles[c][1] = [];
}
}
if (isDataType) {
sfiles[c][0].push(blob);
sfiles[c][1].push(paths[i]);
} else {
sfiles[c].push(blob);
}
size += blobSize;
totalSize += blobSize;
fcnt++;
}
if (sfiles.length == 0) {
// no data
data.checked = true;
return false;
}
if (sfiles.length > 1) {
// multi upload
notifyto = startNotify(totalSize);
added = [];
done = 0;
last = sfiles.length;
failChunk = [];
check();
return true;
}
// single upload
if (isDataType) {
files = sfiles[0][0];
paths = sfiles[0][1];
} else {
files = sfiles[0];
}
}
if (!dataChecked) {
if (!fm.UA.Safari || !data.files) {
notifyto = startNotify(totalSize);
} else {
xhr._totalSize = totalSize;
}
}
dataChecked = true;
if (! files.length) {
dfrd.reject(['errUploadNoFiles']);
}
xhr.open('POST', self.uploadURL, true);
// set request headers
if (fm.customHeaders) {
$.each(fm.customHeaders, function(key) {
xhr.setRequestHeader(key, this);
});
}
// set xhrFields
if (fm.xhrFields) {
$.each(fm.xhrFields, function(key) {
if (key in xhr) {
xhr[key] = this;
}
});
}
formData.append('cmd', 'upload');
formData.append(self.newAPI ? 'target' : 'current', target);
if (renames && renames.length) {
$.each(renames, function(i, v) {
formData.append('renames[]', v);
});
formData.append('suffix', fm.options.backupSuffix);
}
if (hashes) {
$.each(hashes, function(i, v) {
formData.append('hashes['+ i +']', v);
});
}
$.each(self.options.customData, function(key, val) {
formData.append(key, val);
});
$.each(self.options.onlyMimes, function(i, mime) {
formData.append('mimes['+i+']', mime);
});
$.each(files, function(i, file) {
if (file._chunkmerged) {
formData.append('chunk', file._chunkmerged);
formData.append('upload[]', file._name);
formData.append('mtime[]', file._mtime);
} else {
if (file._chunkfail) {
formData.append('upload[]', 'chunkfail');
formData.append('mimes', 'chunkfail');
} else {
formData.append('upload[]', file);
}
if (file._chunk) {
formData.append('chunk', file._chunk);
formData.append('cid' , file._cid);
formData.append('range', file._range);
formData.append('mtime[]', file._mtime);
} else {
formData.append('mtime[]', file.lastModified? Math.round(file.lastModified/1000) : 0);
}
}
if (fm.UA.iOS) {
formData.append('overwrite', 0);
}
});
if (isDataType) {
$.each(paths, function(i, path) {
formData.append('upload_path[]', path);
});
}
// send int value that which meta key was pressed when dropped as `dropWith`
if (dropEvt) {
formData.append('dropWith', parseInt(
(dropEvt.altKey ? '1' : '0')+
(dropEvt.ctrlKey ? '1' : '0')+
(dropEvt.metaKey ? '1' : '0')+
(dropEvt.shiftKey? '1' : '0'), 2));
}
xhr.send(formData);
return true;
};
if (! isDataType) {
if (files.length > 0) {
if (renames == null) {
var mkdirs = [],
paths = [],
excludes = fm.options.folderUploadExclude[fm.OS] || null;
$.each(files, function(i, file) {
var relPath = file.webkitRelativePath || file.relativePath || '';
if (! relPath) {
return false;
}
if (excludes && file.name.match(excludes)) {
file._remove = true;
relPath = void(0);
} else {
relPath = relPath.replace(/\/[^\/]*$/, '');
if (relPath && $.inArray(relPath, mkdirs) === -1) {
mkdirs.push(relPath);
}
}
paths.push(relPath);
});
fm.getUI().find('div.elfinder-upload-dialog-wrapper').elfinderdialog('close');
renames = [];
hashes = {};
if (mkdirs.length) {
(function() {
var checkDirs = $.map(mkdirs, function(name) { return name.indexOf('/') === -1 ? {name: name} : null;}),
cancelDirs = [];
fm.uploads.checkExists(checkDirs, target, fm).done(
function(res, res2) {
var dfds = [], dfd, bak, hash;
if (fm.options.overwriteUploadConfirm && ! fm.UA.iOS && fm.option('uploadOverwrite', target)) {
cancelDirs = $.map(checkDirs, function(dir) { return dir._remove? dir.name : null ;} );
checkDirs = $.map(checkDirs, function(dir) { return !dir._remove? dir : null ;} );
}
if (cancelDirs.length) {
$.each(paths.concat(), function(i, path) {
if ($.inArray(path, cancelDirs) === 0) {
files[i]._remove = true;
delete paths[i];
}
});
}
files = $.map(files, function(file) { return file._remove? null : file; });
paths = $.map(paths, function(path) { return path === void 0 ? null : path; });
if (checkDirs.length) {
dfd = $.Deferred();
if (res.length) {
$.each(res, function(i, existName) {
// backup
bak = fm.uniqueName(existName + fm.options.backupSuffix , null, '');
$.each(res2, function(h, name) {
if (res[0] == name) {
hash = h;
return false;
}
});
if (! hash) {
hash = fm.fileByName(res[0], target).hash;
}
fm.lockfiles({files : [hash]});
dfds.push(
fm.request({
data : {cmd : 'rename', target : hash, name : bak},
notify : {type : 'rename', cnt : 1}
})
.fail(function(error) {
dfrd.reject(error);
fm.sync();
})
.always(function() {
fm.unlockfiles({files : [hash]})
})
);
});
} else {
dfds.push(null);
}
$.when.apply($, dfds).done(function() {
// ensure directories
fm.request({
data : {cmd : 'mkdir', target : target, dirs : mkdirs},
notify : {type : 'mkdir', cnt : mkdirs.length}
})
.fail(function(error) {
error = error || ['errUnknown'];
if (error[0] === 'errCmdParams') {
multiMax = 1;
} else {
multiMax = 0;
dfrd.reject(error);
}
})
.done(function(data) {
if (data.hashes) {
paths = $.map(paths.concat(), function(p) {
if (p === '') {
return target;
} else {
return data.hashes['/' + p];
}
});
}
})
.always(function(data) {
if (multiMax) {
isDataType = true;
if (! send(files, paths)) {
dfrd.reject();
}
}
});
});
} else {
dfrd.reject();
}
}
);
})();
} else {
fm.uploads.checkExists(files, target, fm).done(
function(res, res2){
if (fm.options.overwriteUploadConfirm && ! fm.UA.iOS && fm.option('uploadOverwrite', target)) {
renames = res;
hashes = res2;
files = $.map(files, function(file){return !file._remove? file : null ;});
}
cnt = files.length;
if (cnt > 0) {
if (! send(files)) {
dfrd.reject();
}
} else {
dfrd.reject();
}
}
);
}
} else {
if (! send(files)) {
dfrd.reject();
}
}
} else {
dfrd.reject();
}
} else {
if (dataChecked) {
send(files[0], files[1]);
} else {
files.done(function(result) { // result: [files, paths, renames, hashes, mkdirs]
renames = [];
cnt = result[0].length;
if (cnt) {
if (result[4] && result[4].length) {
// ensure directories
fm.request({
data : {cmd : 'mkdir', target : target, dirs : result[4]},
notify : {type : 'mkdir', cnt : result[4].length}
})
.fail(function(error) {
error = error || ['errUnknown'];
if (error[0] === 'errCmdParams') {
multiMax = 1;
} else {
multiMax = 0;
dfrd.reject(error);
}
})
.done(function(data) {
if (data.hashes) {
result[1] = $.map(result[1], function(p) {
p = p.replace(/\/[^\/]*$/, '');
if (p === '') {
return target;
} else {
return data.hashes[p];
}
});
}
})
.always(function(data) {
if (multiMax) {
renames = result[2];
hashes = result[3];
send(result[0], result[1]);
}
});
return;
} else {
result[1] = $.map(result[1], function() { return target; });
}
renames = result[2];
hashes = result[3];
send(result[0], result[1]);
} else {
dfrd.reject(['errUploadNoFiles']);
}
}).fail(function(){
dfrd.reject();
});
}
}
return dfrd;
},
// upload transport using iframe
iframe : function(data, fm) {
var self = fm ? fm : this,
input = data.input? data.input : false,
files = !input ? self.uploads.checkFile(data, self) : false,
dfrd = $.Deferred()
.fail(function(error) {
error && self.error(error);
}),
name = 'iframe-'+fm.namespace+(++self.iframeCnt),
form = $('<form action="'+self.uploadURL+'" method="post" enctype="multipart/form-data" encoding="multipart/form-data" target="'+name+'" style="display:none"><input type="hidden" name="cmd" value="upload" /></form>'),
msie = this.UA.IE,
// clear timeouts, close notification dialog, remove form/iframe
onload = function() {
abortto && clearTimeout(abortto);
notifyto && clearTimeout(notifyto);
notify && self.notify({type : 'upload', cnt : -cnt});
setTimeout(function() {
msie && $('<iframe src="javascript:false;"/>').appendTo(form);
form.remove();
iframe.remove();
}, 100);
},
iframe = $('<iframe src="'+(msie ? 'javascript:false;' : 'about:blank')+'" name="'+name+'" style="position:absolute;left:-1000px;top:-1000px" />')
.on('load', function() {
iframe.off('load')
.on('load', function() {
onload();
// data will be processed in callback response or window onmessage
dfrd.resolve();
});
// notify dialog
notifyto = setTimeout(function() {
notify = true;
self.notify({type : 'upload', cnt : cnt});
}, self.options.notifyDelay);
// emulate abort on timeout
if (self.options.iframeTimeout > 0) {
abortto = setTimeout(function() {
onload();
dfrd.reject([errors.connect, errors.timeout]);
}, self.options.iframeTimeout);
}
form.submit();
}),
target = (data.target || self.cwd().hash),
names = [],
dfds = [],
renames = [],
hashes = {},
cnt, notify, notifyto, abortto;
if (files && files.length) {
$.each(files, function(i, val) {
form.append('<input type="hidden" name="upload[]" value="'+val+'"/>');
});
cnt = 1;
} else if (input && $(input).is(':file') && $(input).val()) {
if (fm.options.overwriteUploadConfirm && ! fm.UA.iOS && fm.option('uploadOverwrite', target)) {
names = input.files? input.files : [{ name: $(input).val().replace(/^(?:.+[\\\/])?([^\\\/]+)$/, '$1') }];
//names = $.map(names, function(file){return file.name? { name: file.name } : null ;});
dfds.push(self.uploads.checkExists(names, target, self).done(
function(res, res2){
renames = res;
hashes = res2;
cnt = $.map(names, function(file){return !file._remove? file : null ;}).length;
if (cnt != names.length) {
cnt = 0;
}
}
));
}
cnt = input.files ? input.files.length : 1;
form.append(input);
} else {
return dfrd.reject();
}
$.when.apply($, dfds).done(function() {
if (cnt < 1) {
return dfrd.reject();
}
form.append('<input type="hidden" name="'+(self.newAPI ? 'target' : 'current')+'" value="'+target+'"/>')
.append('<input type="hidden" name="html" value="1"/>')
.append('<input type="hidden" name="node" value="'+self.id+'"/>')
.append($(input).attr('name', 'upload[]'));
if (renames.length > 0) {
$.each(renames, function(i, rename) {
form.append('<input type="hidden" name="renames[]" value="'+self.escape(rename)+'"/>');
});
form.append('<input type="hidden" name="suffix" value="'+fm.options.backupSuffix+'"/>');
}
if (hashes) {
$.each(renames, function(i, v) {
form.append('<input type="hidden" name="['+i+']" value="'+self.escape(v)+'"/>');
});
}
$.each(self.options.onlyMimes||[], function(i, mime) {
form.append('<input type="hidden" name="mimes[]" value="'+self.escape(mime)+'"/>');
});
$.each(self.options.customData, function(key, val) {
form.append('<input type="hidden" name="'+key+'" value="'+self.escape(val)+'"/>');
});
form.appendTo('body');
iframe.appendTo('body');
});
return dfrd;
}
},
/**
* Bind callback to event(s) The callback is executed at most once per event.
* To bind to multiply events at once, separate events names by space
*
* @param String event name
* @param Function callback
* @return elFinder
*/
one : function(event, callback) {
var self = this,
h = function(e, f) {
setTimeout(function() {self.unbind(event, h);}, 3);
return callback.apply(self.getListeners(e.type), arguments);
};
return this.bind(event, h);
},
/**
* Set/get data into/from localStorage
*
* @param String key
* @param String|void value
* @return String
*/
localStorage : function(key, val) {
var s = window.localStorage,
oldkey = 'elfinder-'+key+this.id, // old key of elFinder < 2.1.6
retval, oldval,t;
// new key of elFinder >= 2.1.6
key = window.location.pathname+'-elfinder-'+key+this.id;
if (val === null) {
return s.removeItem(key);
}
if (val === void(0) && !(retval = s.getItem(key)) && (oldval = s.getItem(oldkey))) {
val = oldval;
s.removeItem(oldkey);
}
if (val !== void(0)) {
t = typeof val;
if (t !== 'string' && t !== 'number') {
val = JSON.stringify(val);
}
try {
s.setItem(key, val);
} catch (e) {
try {
s.clear();
s.setItem(key, val);
} catch (e) {
self.debug('error', e.toString());
}
}
retval = s.getItem(key);
}
if (retval && (retval.substr(0,1) === '{' || retval.substr(0,1) === '[')) {
try {
return JSON.parse(retval);
} catch(e) {}
}
return retval;
},
/**
* Get/set cookie
*
* @param String cookie name
* @param String|void cookie value
* @return String
*/
cookie : function(name, value) {
var d, o, c, i, retval, t;
name = 'elfinder-'+name+this.id;
if (value === void(0)) {
if (document.cookie && document.cookie != '') {
c = document.cookie.split(';');
name += '=';
for (i=0; i<c.length; i++) {
c[i] = $.trim(c[i]);
if (c[i].substring(0, name.length) == name) {
retval = decodeURIComponent(c[i].substring(name.length));
if (retval.substr(0,1) === '{' || retval.substr(0,1) === '[') {
try {
return JSON.parse(retval);
} catch(e) {}
}
return retval;
}
}
}
return '';
}
o = $.extend({}, this.options.cookie);
if (value === null) {
value = '';
o.expires = -1;
} else {
t = typeof value;
if (t !== 'string' && t !== 'number') {
value = JSON.stringify(value);
}
}
if (typeof(o.expires) == 'number') {
d = new Date();
d.setTime(d.getTime()+(o.expires * 86400000));
o.expires = d;
}
document.cookie = name+'='+encodeURIComponent(value)+'; expires='+o.expires.toUTCString()+(o.path ? '; path='+o.path : '')+(o.domain ? '; domain='+o.domain : '')+(o.secure ? '; secure' : '');
return value;
},
/**
* Get start directory (by location.hash or last opened directory)
*
* @return String
*/
startDir : function() {
var locHash = window.location.hash;
if (locHash && locHash.match(/^#elf_/)) {
return locHash.replace(/^#elf_/, '');
} else if (this.options.startPathHash) {
return this.options.startPathHash;
} else {
return this.lastDir();
}
},
/**
* Get/set last opened directory
*
* @param String|undefined dir hash
* @return String
*/
lastDir : function(hash) {
return this.options.rememberLastDir ? this.storage('lastdir', hash) : '';
},
/**
* Node for escape html entities in texts
*
* @type jQuery
*/
_node : $('<span/>'),
/**
* Replace not html-safe symbols to html entities
*
* @param String text to escape
* @return String
*/
escape : function(name) {
return this._node.text(name).html().replace(/"/g, '"').replace(/'/g, ''');
},
/**
* Cleanup ajax data.
* For old api convert data into new api format
*
* @param String command name
* @param Object data from backend
* @return Object
*/
normalize : function(data) {
var self = this,
filter = function(file) {
var vid, targetOptions;
if (file && file.hash && file.name && file.mime) {
if (file.mime == 'application/x-empty') {
file.mime = 'text/plain';
}
if (file.options) {
self.optionsByHashes[file.hash] = file.options;
}
if (! file.phash || file.mime === 'directory') {
// set options, tmbUrls for each volume
if (file.volumeid) {
vid = file.volumeid;
if (self.isRoot(file)) {
if (! self.volOptions[vid]) {
self.volOptions[vid] = {};
}
targetOptions = self.volOptions[vid];
if (file.options) {
// >= v.2.1.14 has file.options
targetOptions = $.extend(targetOptions, file.options);
}
// for compat <= v2.1.13
if (file.disabled) {
targetOptions.disabled = file.disabled;
}
if (file.tmbUrl) {
targetOptions.tmbUrl = file.tmbUrl;
}
// set immediate properties
$.each(self.optionProperties, function(i, k) {
if (targetOptions[k]) {
file[k] = targetOptions[k];
}
});
self.roots[vid] = file.hash;
}
if (prevId !== vid) {
prevId = vid;
i18nFolderName = self.option('i18nFolderName', vid);
}
}
// volume root i18n name
if (! file.i18 && self.isRoot(file)) {
name = 'volume_' + file.name,
i18 = self.i18n(false, name);
if (name !== i18) {
file.i18 = i18;
}
}
// i18nFolderName
if (i18nFolderName && ! file.i18) {
name = 'folder_' + file.name,
i18 = self.i18n(false, name);
if (name !== i18) {
file.i18 = i18;
}
}
if (self.leafRoots[file.hash]) {
// has leaf root to `dirs: 1`
if (! file.dirs) {
file.dirs = 1;
}
// set ts
$.each(self.leafRoots[file.hash], function() {
var f = self.file(this);
if (f && f.ts && (file.ts || 0) < f.ts) {
file.ts = f.ts;
}
});
}
}
return file;
}
return null;
},
name, i18, i18nFolderName, prevId;
if (data.cwd) {
if (data.cwd.volumeid && data.options && Object.keys(data.options).length) {
self.volOptions[data.cwd.volumeid] = data.options;
}
data.cwd = filter(data.cwd);
}
if (data.files) {
data.files = $.map(data.files, filter);
}
if (data.tree) {
data.tree = $.map(data.tree, filter);
}
if (data.added) {
data.added = $.map(data.added, filter);
}
if (data.changed) {
data.changed = $.map(data.changed, filter);
}
if (data.api) {
data.init = true;
}
// merge options that apply only to cwd
if (data.cwd && data.cwd.options && data.options) {
$.extend(data.options, data.cwd.options);
}
return data;
},
/**
* Update sort options
*
* @param {String} sort type
* @param {String} sort order
* @param {Boolean} show folder first
*/
setSort : function(type, order, stickFolders, alsoTreeview) {
this.storage('sortType', (this.sortType = this.sortRules[type] ? type : 'name'));
this.storage('sortOrder', (this.sortOrder = /asc|desc/.test(order) ? order : 'asc'));
this.storage('sortStickFolders', (this.sortStickFolders = !!stickFolders) ? 1 : '');
this.storage('sortAlsoTreeview', (this.sortAlsoTreeview = !!alsoTreeview) ? 1 : '');
this.trigger('sortchange');
},
_sortRules : {
name : function(file1, file2) {
return elFinder.prototype.naturalCompare(file1.i18 || file1.name, file2.i18 || file2.name);
},
size : function(file1, file2) {
var size1 = parseInt(file1.size) || 0,
size2 = parseInt(file2.size) || 0;
return size1 === size2 ? 0 : size1 > size2 ? 1 : -1;
},
kind : function(file1, file2) {
return elFinder.prototype.naturalCompare(file1.mime, file2.mime);
},
date : function(file1, file2) {
var date1 = file1.ts || file1.date,
date2 = file2.ts || file2.date;
return date1 === date2 ? 0 : date1 > date2 ? 1 : -1
},
perm : function(file1, file2) {
var val = function(file) { return (file.write? 2 : 0) + (file.read? 1 : 0); },
v1 = val(file1),
v2 = val(file2);
return v1 === v2 ? 0 : v1 > v2 ? 1 : -1
},
mode : function(file1, file2) {
var v1 = file1.mode || (file1.perm || ''),
v2 = file2.mode || (file2.perm || '');
return elFinder.prototype.naturalCompare(v1, v2);
},
owner : function(file1, file2) {
var v1 = file1.owner || '',
v2 = file2.owner || '';
return elFinder.prototype.naturalCompare(v1, v2);
},
group : function(file1, file2) {
var v1 = file1.group || '',
v2 = file2.group || '';
return elFinder.prototype.naturalCompare(v1, v2);
}
},
/**
* Valid sort rule names
*
* @type Array
*/
sorters : [],
/**
* Compare strings for natural sort
*
* @param String
* @param String
* @return Number
*/
naturalCompare : function(a, b) {
var self = elFinder.prototype.naturalCompare;
if (typeof self.loc == 'undefined') {
self.loc = (navigator.userLanguage || navigator.browserLanguage || navigator.language || 'en-US');
}
if (typeof self.sort == 'undefined') {
if ('11'.localeCompare('2', self.loc, {numeric: true}) > 0) {
// Native support
if (window.Intl && window.Intl.Collator) {
self.sort = new Intl.Collator(self.loc, {numeric: true}).compare;
} else {
self.sort = function(a, b) {
return a.localeCompare(b, self.loc, {numeric: true});
};
}
} else {
/*
* Edited for elFinder (emulates localeCompare() by numeric) by Naoki Sawada aka nao-pon
*/
/*
* Huddle/javascript-natural-sort (https://github.com/Huddle/javascript-natural-sort)
*/
/*
* Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
* Author: Jim Palmer (based on chunking idea from Dave Koelle)
* http://opensource.org/licenses/mit-license.php
*/
self.sort = function(a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
hre = /^0x[0-9a-f]+$/i,
ore = /^0/,
syre = /^[\x01\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]/, // symbol first - (Naoki Sawada)
i = function(s) { return self.sort.insensitive && (''+s).toLowerCase() || ''+s },
// convert all to strings strip whitespace
// first character is "_", it's smallest - (Naoki Sawada)
x = i(a).replace(sre, '').replace(/^_/, "\x01") || '',
y = i(b).replace(sre, '').replace(/^_/, "\x01") || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
// numeric, hex or date detection
xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null,
oFxNcL, oFyNcL,
locRes = 0;
// first try and sort Hex codes or Dates
if (yD) {
if ( xD < yD ) return -1;
else if ( xD > yD ) return 1;
}
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
// but symbol first < number - (Naoki Sawada)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
if (isNaN(oFxNcL) && (typeof oFxNcL !== 'string' || ! oFxNcL.match(syre))) {
return 1;
} else if (typeof oFyNcL !== 'string' || ! oFyNcL.match(syre)) {
return -1;
}
}
// use decimal number comparison if either value is string zero
if (parseInt(oFxNcL, 10) === 0) oFxNcL = 0;
if (parseInt(oFyNcL, 10) === 0) oFyNcL = 0;
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
// use locale sensitive sort for strings when case insensitive
// note: localeCompare interleaves uppercase with lowercase (e.g. A,a,B,b)
if (self.sort.insensitive && typeof oFxNcL === 'string' && typeof oFyNcL === 'string') {
locRes = oFxNcL.localeCompare(oFyNcL, self.loc);
if (locRes !== 0) return locRes;
}
if (oFxNcL < oFyNcL) return -1;
if (oFxNcL > oFyNcL) return 1;
}
return 0;
};
self.sort.insensitive = true;
}
}
return self.sort(a, b);
},
/**
* Compare files based on elFinder.sort
*
* @param Object file
* @param Object file
* @return Number
*/
compare : function(file1, file2) {
var self = this,
type = self.sortType,
asc = self.sortOrder == 'asc',
stick = self.sortStickFolders,
rules = self.sortRules,
sort = rules[type],
d1 = file1.mime == 'directory',
d2 = file2.mime == 'directory',
res;
if (stick) {
if (d1 && !d2) {
return -1;
} else if (!d1 && d2) {
return 1;
}
}
res = asc ? sort(file1, file2) : sort(file2, file1);
return type !== 'name' && res === 0
? res = asc ? rules.name(file1, file2) : rules.name(file2, file1)
: res;
},
/**
* Sort files based on config
*
* @param Array files
* @return Array
*/
sortFiles : function(files) {
return files.sort(this.compare);
},
/**
* Open notification dialog
* and append/update message for required notification type.
*
* @param Object options
* @example
* this.notify({
* type : 'copy',
* msg : 'Copy files', // not required for known types @see this.notifyType
* cnt : 3,
* hideCnt : false, // true for not show count
* progress : 10, // progress bar percents (use cnt : 0 to update progress bar)
* cancel : callback // callback function for cancel button
* })
* @return elFinder
*/
notify : function(opts) {
var type = opts.type,
msg = this.i18n((typeof opts.msg !== 'undefined')? opts.msg : (this.messages['ntf'+type] ? 'ntf'+type : 'ntfsmth')),
ndialog = this.ui.notify,
notify = ndialog.children('.elfinder-notify-'+type),
button = notify.children('div.elfinder-notify-cancel').children('button'),
ntpl = '<div class="elfinder-notify elfinder-notify-{type}"><span class="elfinder-dialog-icon elfinder-dialog-icon-{type}"/><span class="elfinder-notify-msg">{msg}</span> <span class="elfinder-notify-cnt"/><div class="elfinder-notify-progressbar"><div class="elfinder-notify-progress"/></div><div class="elfinder-notify-cancel"/></div>',
delta = opts.cnt,
size = (typeof opts.size != 'undefined')? parseInt(opts.size) : null,
progress = (typeof opts.progress != 'undefined' && opts.progress >= 0) ? opts.progress : null,
cancel = opts.cancel,
clhover = 'ui-state-hover',
close = function() {
notify._esc && $(document).off('keydown', notify._esc);
notify.remove();
!ndialog.children().length && ndialog.elfinderdialog('close');
},
cnt, total, prc;
if (!type) {
return this;
}
if (!notify.length) {
notify = $(ntpl.replace(/\{type\}/g, type).replace(/\{msg\}/g, msg))
.appendTo(ndialog)
.data('cnt', 0);
if (progress != null) {
notify.data({progress : 0, total : 0});
}
if (cancel) {
button = $('<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"><span class="ui-button-text">'+this.i18n('btnCancel')+'</span></button>')
.hover(function(e) {
$(this).toggleClass(clhover, e.type == 'mouseenter');
});
notify.children('div.elfinder-notify-cancel').append(button);
}
} else if (typeof opts.msg !== 'undefined') {
notify.children('span.elfinder-notify-msg').html(msg);
}
cnt = delta + parseInt(notify.data('cnt'));
if (cnt > 0) {
if (cancel && button.length) {
if ($.isFunction(cancel) || (typeof cancel === 'object' && cancel.promise)) {
notify._esc = function(e) {
if (e.type == 'keydown' && e.keyCode != $.ui.keyCode.ESCAPE) {
return;
}
e.preventDefault();
e.stopPropagation();
close();
if (cancel.promise) {
if (cancel.xhr) {
cancel.xhr.quiet = true;
cancel.xhr.abort();
}
cancel.reject();
} else {
cancel(e);
}
};
button.on('click', function(e) {
notify._esc(e);
});
$(document).on('keydown.' + this.namespace, notify._esc);
}
}
!opts.hideCnt && notify.children('.elfinder-notify-cnt').text('('+cnt+')');
ndialog.is(':hidden') && ndialog.elfinderdialog('open', this);
notify.data('cnt', cnt);
if ((progress != null)
&& (total = notify.data('total')) >= 0
&& (prc = notify.data('progress')) >= 0) {
total += size != null? size : delta;
prc += progress;
(size == null && delta < 0) && (prc += delta * 100);
notify.data({progress : prc, total : total});
if (size != null) {
prc *= 100;
total = Math.max(1, total);
}
progress = parseInt(prc/total);
notify.find('.elfinder-notify-progress')
.animate({
width : (progress < 100 ? progress : 100)+'%'
}, 20);
}
} else {
close();
}
return this;
},
/**
* Open confirmation dialog
*
* @param Object options
* @example
* this.confirm({
* title : 'Remove files',
* text : 'Here is question text',
* accept : { // accept callback - required
* label : 'Continue',
* callback : function(applyToAll) { fm.log('Ok') }
* },
* cancel : { // cancel callback - required
* label : 'Cancel',
* callback : function() { fm.log('Cancel')}
* },
* reject : { // reject callback - optionally
* label : 'No',
* callback : function(applyToAll) { fm.log('No')}
* },
* buttons : [ // additional buttons callback - optionally
* {
* label : 'Btn1',
* callback : function(applyToAll) { fm.log('Btn1')}
* }
* ],
* all : true // display checkbox "Apply to all"
* })
* @return elFinder
*/
confirm : function(opts) {
var self = this,
complete = false,
options = {
cssClass : 'elfinder-dialog-confirm',
modal : true,
resizable : false,
title : this.i18n(opts.title || 'confirmReq'),
buttons : {},
close : function() {
!complete && opts.cancel.callback();
$(this).elfinderdialog('destroy');
}
},
apply = this.i18n('apllyAll'),
label, checkbox;
options.buttons[this.i18n(opts.accept.label)] = function() {
opts.accept.callback(!!(checkbox && checkbox.prop('checked')))
complete = true;
$(this).elfinderdialog('close');
};
if (opts.reject) {
options.buttons[this.i18n(opts.reject.label)] = function() {
opts.reject.callback(!!(checkbox && checkbox.prop('checked')))
complete = true;
$(this).elfinderdialog('close');
};
}
if (opts.buttons && opts.buttons.length > 0) {
$.each(opts.buttons, function(i, v){
options.buttons[self.i18n(v.label)] = function() {
v.callback(!!(checkbox && checkbox.prop('checked')))
complete = true;
$(this).elfinderdialog('close');
};
});
}
options.buttons[this.i18n(opts.cancel.label)] = function() {
$(this).elfinderdialog('close');
};
if (opts.all) {
options.create = function() {
var base = $('<div class="elfinder-dialog-confirm-applyall"/>');
checkbox = $('<input type="checkbox" />');
$(this).next().find('.ui-dialog-buttonset')
.prepend(base.append($('<label>'+apply+'</label>').prepend(checkbox)));
}
}
if (opts.optionsCallback && $.isFunction(opts.optionsCallback)) {
opts.optionsCallback(options);
}
return this.dialog('<span class="elfinder-dialog-icon elfinder-dialog-icon-confirm"/>' + this.i18n(opts.text), options);
},
/**
* Create unique file name in required dir
*
* @param String file name
* @param String parent dir hash
* @param String glue
* @return String
*/
uniqueName : function(prefix, phash, glue) {
var i = 0, ext = '', p, name;
prefix = this.i18n(prefix);
phash = phash || this.cwd().hash;
glue = (typeof glue === 'undefined')? ' ' : glue;
if (p = prefix.match(/^(.+)(\.[^.]+)$/)) {
ext = p[2];
prefix = p[1];
}
name = prefix+ext;
if (!this.fileByName(name, phash)) {
return name;
}
while (i < 10000) {
name = prefix + glue + (++i) + ext;
if (!this.fileByName(name, phash)) {
return name;
}
}
return prefix + Math.random() + ext;
},
/**
* Return message translated onto current language
* Allowed accept HTML element that was wrapped in jQuery object
* To be careful to XSS vulnerability of HTML element Ex. You should use `fm.escape(file.name)`
*
* @param String|Array message[s]|Object jQuery
* @return String
**/
i18n : function() {
var self = this,
messages = this.messages,
input = [],
ignore = [],
message = function(m) {
var file;
if (m.indexOf('#') === 0) {
if ((file = self.file(m.substr(1)))) {
return file.name;
}
}
return m;
},
i, j, m, escFunc, start = 0;
if (arguments.length && arguments[0] === false) {
escFunc = function(m){ return m; };
start = 1;
}
for (i = start; i< arguments.length; i++) {
m = arguments[i];
if ($.isArray(m)) {
for (j = 0; j < m.length; j++) {
if (m[j] instanceof jQuery) {
// jQuery object is HTML element
input.push(m[j]);
} else if (typeof m[j] !== 'undefined'){
input.push(message('' + m[j]));
}
}
} else if (m instanceof jQuery) {
// jQuery object is HTML element
input.push(m[j]);
} else if (typeof m !== 'undefined'){
input.push(message('' + m));
}
}
for (i = 0; i < input.length; i++) {
// dont translate placeholders
if ($.inArray(i, ignore) !== -1) {
continue;
}
m = input[i];
if (typeof m == 'string') {
// translate message
m = messages[m] || (escFunc? escFunc(m) : self.escape(m));
// replace placeholders in message
m = m.replace(/\$(\d+)/g, function(match, placeholder) {
placeholder = i + parseInt(placeholder);
if (placeholder > 0 && input[placeholder]) {
ignore.push(placeholder)
}
return escFunc? escFunc(input[placeholder]) : self.escape(input[placeholder]);
});
} else {
// get HTML from jQuery object
m = m.get(0).outerHTML;
}
input[i] = m;
}
return $.map(input, function(m, i) { return $.inArray(i, ignore) === -1 ? m : null; }).join('<br>');
},
/**
* Convert mimetype into css classes
*
* @param String file mimetype
* @return String
*/
mime2class : function(mime) {
var prefix = 'elfinder-cwd-icon-';
mime = mime.split('/');
return prefix+mime[0]+(mime[0] != 'image' && mime[1] ? ' '+prefix+mime[1].replace(/(\.|\+)/g, '-') : '');
},
/**
* Return localized kind of file
*
* @param Object|String file or file mimetype
* @return String
*/
mime2kind : function(f) {
var isObj = typeof(f) == 'object' ? true : false,
mime = isObj ? f.mime : f,
kind;
if (isObj && f.alias && mime != 'symlink-broken') {
kind = 'Alias';
} else if (this.kinds[mime]) {
if (isObj && mime === 'directory' && (! f.phash || f.isroot)) {
kind = 'Root';
} else {
kind = this.kinds[mime];
}
}
if (! kind) {
if (mime.indexOf('text') === 0) {
kind = 'Text';
} else if (mime.indexOf('image') === 0) {
kind = 'Image';
} else if (mime.indexOf('audio') === 0) {
kind = 'Audio';
} else if (mime.indexOf('video') === 0) {
kind = 'Video';
} else if (mime.indexOf('application') === 0) {
kind = 'App';
} else {
kind = mime;
}
}
return this.messages['kind'+kind] ? this.i18n('kind'+kind) : mime;
},
/**
* Return localized date
*
* @param Object file object
* @return String
*/
formatDate : function(file, ts) {
var self = this,
ts = ts || file.ts,
i18 = self.i18,
date, format, output, d, dw, m, y, h, g, i, s;
if (self.options.clientFormatDate && ts > 0) {
date = new Date(ts*1000);
h = date[self.getHours]();
g = h > 12 ? h - 12 : h;
i = date[self.getMinutes]();
s = date[self.getSeconds]();
d = date[self.getDate]();
dw = date[self.getDay]();
m = date[self.getMonth]() + 1;
y = date[self.getFullYear]();
format = ts >= this.yesterday
? this.fancyFormat
: this.dateFormat;
output = format.replace(/[a-z]/gi, function(val) {
switch (val) {
case 'd': return d > 9 ? d : '0'+d;
case 'j': return d;
case 'D': return self.i18n(i18.daysShort[dw]);
case 'l': return self.i18n(i18.days[dw]);
case 'm': return m > 9 ? m : '0'+m;
case 'n': return m;
case 'M': return self.i18n(i18.monthsShort[m-1]);
case 'F': return self.i18n(i18.months[m-1]);
case 'Y': return y;
case 'y': return (''+y).substr(2);
case 'H': return h > 9 ? h : '0'+h;
case 'G': return h;
case 'g': return g;
case 'h': return g > 9 ? g : '0'+g;
case 'a': return h >= 12 ? 'pm' : 'am';
case 'A': return h >= 12 ? 'PM' : 'AM';
case 'i': return i > 9 ? i : '0'+i;
case 's': return s > 9 ? s : '0'+s;
}
return val;
});
return ts >= this.yesterday
? output.replace('$1', this.i18n(ts >= this.today ? 'Today' : 'Yesterday'))
: output;
} else if (file.date) {
return file.date.replace(/([a-z]+)\s/i, function(a1, a2) { return self.i18n(a2)+' '; });
}
return self.i18n('dateUnknown');
},
/**
* Return css class marks file permissions
*
* @param Object file
* @return String
*/
perms2class : function(o) {
var c = '';
if (!o.read && !o.write) {
c = 'elfinder-na';
} else if (!o.read) {
c = 'elfinder-wo';
} else if (!o.write) {
c = 'elfinder-ro';
}
if (o.type) {
c += ' elfinder-' + this.escape(o.type);
}
return c;
},
/**
* Return localized string with file permissions
*
* @param Object file
* @return String
*/
formatPermissions : function(f) {
var p = [];
f.read && p.push(this.i18n('read'));
f.write && p.push(this.i18n('write'));
return p.length ? p.join(' '+this.i18n('and')+' ') : this.i18n('noaccess');
},
/**
* Return formated file size
*
* @param Number file size
* @return String
*/
formatSize : function(s) {
var n = 1, u = 'b';
if (s == 'unknown') {
return this.i18n('unknown');
}
if (s > 1073741824) {
n = 1073741824;
u = 'GB';
} else if (s > 1048576) {
n = 1048576;
u = 'MB';
} else if (s > 1024) {
n = 1024;
u = 'KB';
}
s = s/n;
return (s > 0 ? n >= 1048576 ? s.toFixed(2) : Math.round(s) : 0) +' '+u;
},
/**
* Return formated file mode by options.fileModeStyle
*
* @param String file mode
* @param String format style
* @return String
*/
formatFileMode : function(p, style) {
var i, o, s, b, sticy, suid, sgid, str, oct;
if (!style) {
style = this.options.fileModeStyle.toLowerCase();
}
p = $.trim(p);
if (p.match(/[rwxs-]{9}$/i)) {
str = p = p.substr(-9);
if (style == 'string') {
return str;;
}
oct = '';
s = 0;
for (i=0; i<7; i=i+3) {
o = p.substr(i, 3);
b = 0;
if (o.match(/[r]/i)) {
b += 4;
}
if (o.match(/[w]/i)) {
b += 2;
}
if (o.match(/[xs]/i)) {
if (o.match(/[xs]/)) {
b += 1;
}
if (o.match(/[s]/i)) {
if (i == 0) {
s += 4;
} else if (i == 3) {
s += 2;
}
}
}
oct += b.toString(8);
}
if (s) {
oct = s.toString(8) + oct;
}
} else {
p = parseInt(p, 8);
oct = p? p.toString(8) : '';
if (!p || style == 'octal') {
return oct;
}
o = p.toString(8);
s = 0;
if (o.length > 3) {
o = o.substr(-4);
s = parseInt(o.substr(0, 1), 8);
o = o.substr(1);
}
sticy = ((s & 1) == 1); // not support
sgid = ((s & 2) == 2);
suid = ((s & 4) == 4);
str = '';
for(i=0; i<3; i++) {
if ((parseInt(o.substr(i, 1), 8) & 4) == 4) {
str += 'r';
} else {
str += '-';
}
if ((parseInt(o.substr(i, 1), 8) & 2) == 2) {
str += 'w';
} else {
str += '-';
}
if ((parseInt(o.substr(i, 1), 8) & 1) == 1) {
str += ((i==0 && suid)||(i==1 && sgid))? 's' : 'x';
} else {
str += '-';
}
}
}
if (style == 'both') {
return str + ' (' + oct + ')';
} else if (style == 'string') {
return str;
} else {
return oct;
}
},
/**
* Return boolean that uploadable MIME type into target folder
*
* @param String mime MIME type
* @param String target target folder hash
* @return Bool
*/
uploadMimeCheck : function(mime, target) {
target = target || this.cwd().hash;
var res = true, // default is allow
mimeChecker = this.option('uploadMime', target),
allow,
deny,
check = function(checker) {
var ret = false;
if (typeof checker === 'string' && checker.toLowerCase() === 'all') {
ret = true;
} else if ($.isArray(checker) && checker.length) {
$.each(checker, function(i, v) {
v = v.toLowerCase();
if (v === 'all' || mime.indexOf(v) === 0) {
ret = true;
return false;
}
});
}
return ret;
};
if (mime && $.isPlainObject(mimeChecker)) {
mime = mime.toLowerCase();
allow = check(mimeChecker.allow);
deny = check(mimeChecker.deny);
if (mimeChecker.firstOrder === 'allow') {
res = false; // default is deny
if (! deny && allow === true) { // match only allow
res = true;
}
} else {
res = true; // default is allow
if (deny === true && ! allow) { // match only deny
res = false;
}
}
}
return res;
},
/**
* call chained sequence of async deferred functions
*
* @param Array tasks async functions
* @return Object jQuery.Deferred
*/
sequence : function(tasks) {
var l = tasks.length,
chain = function(task, idx) {
++idx;
if (tasks[idx]) {
return chain(task.then(tasks[idx]), idx);
} else {
return task;
}
};
if (l > 1) {
return chain(tasks[0](), 0);
} else {
return tasks[0]();
}
},
/**
* Reload contents of target URL for clear browser cache
*
* @param String url target URL
* @return Object jQuery.Deferred
*/
reloadContents : function(url) {
var dfd = $.Deferred(),
ifm;
try {
ifm = $('<iframe width="1" height="1" scrolling="no" frameborder="no" style="position:absolute; top:-1px; left:-1px" crossorigin="use-credentials">')
.attr('src', url)
.one('load', function() {
var ifm = $(this);
try {
this.contentDocument.location.reload(true);
ifm.one('load', function() {
ifm.remove();
dfd.resolve();
});
} catch(e) {
ifm.attr('src', '').attr('src', url).one('load', function() {
ifm.remove();
dfd.resolve();
});
}
})
.appendTo('body');
} catch(e) {
ifm && ifm.remove();
dfd.reject();
}
return dfd;
},
/**
* Make netmount option for OAuth2
*
* @param String protocol
* @param String name
* @param String host
* @param Boolean noOffline
*
* @return Object
*/
makeNetmountOptionOauth : function(protocol, name, host, noOffline) {
return {
vars : {},
name : name,
inputs: {
offline : $('<input type="checkbox"/>').on('change', function() {
$(this).parents('table.elfinder-netmount-tb').find('select:first').trigger('change', 'reset');
}),
host : $('<span><span class="elfinder-info-spinner"/></span><input type="hidden"/>'),
path : $('<input type="text" value="root"/>'),
user : $('<input type="hidden"/>'),
pass : $('<input type="hidden"/>')
},
select: function(fm, ev, data){
var f = this.inputs,
oline = f.offline,
f0 = $(f.host[0]),
data = data || null;
this.vars.mbtn = f.host.closest('.ui-dialog').children('.ui-dialog-buttonpane:first').find('button.elfinder-btncnt-0');
if (! f0.data('inrequest')
&& (f0.find('span.elfinder-info-spinner').length
|| data === 'reset'
|| (data === 'winfocus' && ! f0.siblings('span.elfinder-button-icon-reload').length))
)
{
if (oline.parent().children().length === 1) {
f.path.parent().prev().html(fm.i18n('folderId'));
oline.attr('title', fm.i18n('offlineAccess'));
oline.uniqueId().after($('<label/>').attr('for', oline.attr('id')).html(' '+fm.i18n('offlineAccess')));
}
f0.data('inrequest', true).empty().addClass('elfinder-info-spinner')
.parent().find('span.elfinder-button-icon').remove();
fm.request({
data : {cmd : 'netmount', protocol: protocol, host: host, user: 'init', options: {id: fm.id, offline: oline.prop('checked')? 1:0, pass: f.host[1].value}},
preventDefault : true
}).done(function(data){
f0.removeClass("elfinder-info-spinner").html(data.body.replace(/\{msg:([^}]+)\}/g, function(whole,s1){return fm.i18n(s1, host);}));
});
noOffline && oline.closest('tr').hide();
} else {
oline.closest('tr')[(noOffline || f.user.val())? 'hide':'show']();
f0.data('funcexpup') && f0.data('funcexpup')();
}
this.vars.mbtn[$(f.host[1]).val()? 'show':'hide']();
},
done: function(fm, data){
var f = this.inputs,
p = this.protocol,
f0 = $(f.host[0]),
f1 = $(f.host[1]),
expires = ' ';
noOffline && f.offline.closest('tr').hide();
if (data.mode == 'makebtn') {
f0.removeClass('elfinder-info-spinner').removeData('expires').removeData('funcexpup');
f.host.find('input').hover(function(){$(this).toggleClass('ui-state-hover');});
f1.val('');
f.path.val('root').next().remove();
f.user.val('');
f.pass.val('');
! noOffline && f.offline.closest('tr').show();
this.vars.mbtn.hide();
} else {
if (data.expires) {
expires = '()';
f0.data('expires', data.expires);
}
f0.html(host + expires).removeClass('elfinder-info-spinner');
if (data.expires) {
f0.data('funcexpup', function() {
var rem = Math.floor((f0.data('expires') - (+new Date()) / 1000) / 60);
if (rem < 3) {
f0.parent().children('.elfinder-button-icon-reload').click();
} else {
f0.text(f0.text().replace(/\(.*\)/, '('+fm.i18n(['minsLeft', rem])+')'));
setTimeout(function() {
if (f0.is(':visible')) {
f0.data('funcexpup')();
}
}, 60000);
}
});
f0.data('funcexpup')();
}
if (data.reset) {
p.trigger('change', 'reset');
return;
}
f0.parent().append($('<span class="elfinder-button-icon elfinder-button-icon-reload" title="'+fm.i18n('reAuth')+'">')
.on('click', function() {
f1.val('reauth');
p.trigger('change', 'reset');
}));
f1.val(protocol);
this.vars.mbtn.show();
if (data.folders) {
f.path.next().remove().end().after(
$('<div/>').append(
$('<select class="ui-corner-all" style="max-width:200px;">').append(
$($.map(data.folders, function(n,i){return '<option value="'+(i+'').trim()+'">'+fm.escape(n)+'</option>'}).join(''))
).on('change', function(){f.path.val($(this).val());})
)
);
}
f.user.val('done');
f.pass.val('done');
f.offline.closest('tr').hide();
}
f0.removeData('inrequest');
},
fail: function(fm, err){
$(this.inputs.host[0]).removeData('inrequest');
this.protocol.trigger('change', 'reset');
}
};
},
/**
* Find cwd's nodes from files
*
* @param Array files
* @param Object opts {firstOnly: true|false}
*/
findCwdNodes : function(files, opts) {
var self = this,
cwd = this.getUI('cwd'),
cwdHash = this.cwd().hash,
newItem = $();
opts = opts || {};
$.each(files, function(i, f) {
if (f.phash === cwdHash) {
newItem = newItem.add(cwd.find('#'+self.cwdHash2Id(f.hash)));
if (opts.firstOnly) {
return false;
}
}
});
return newItem;
},
/**
* Convert from relative URL to abstract URL based on current URL
*
* @param String URL
* @return String
*/
convAbsUrl : function(url) {
if (url.match(/^http/i)) {
return url;
}
if (url.substr(0,2) === '//') {
return window.location.protocol + url;
}
var root = window.location.protocol + '//' + window.location.host,
reg = /[^\/]+\/\.\.\//,
ret;
if (url.substr(0, 1) === '/') {
ret = root + url;
} else {
ret = root + window.location.pathname.replace(/\/[^\/]+$/, '/') + url;
}
ret = ret.replace('/./', '/');
while(reg.test(ret)) {
ret = ret.replace(reg, '');
}
return ret;
},
navHash2Id : function(hash) {
return this.navPrefix + hash;
},
navId2Hash : function(id) {
return typeof(id) == 'string' ? id.substr(this.navPrefix.length) : false;
},
cwdHash2Id : function(hash) {
return this.cwdPrefix + hash;
},
cwdId2Hash : function(id) {
return typeof(id) == 'string' ? id.substr(this.cwdPrefix.length) : false;
},
isInWindow : function(elem, nochkHide) {
if (! nochkHide && elem.is(':hidden')) {
return false;
}
var elm, rect;
if (! (elm = elem.get(0))) {
return false;
}
rect = elm.getBoundingClientRect();
return document.elementFromPoint(rect.left, rect.top)? true : false;
},
/**
* Load JavaScript files
*
* @param Array urls to load JavaScript file URLs
* @param Function callback call back function on script loaded
* @param Object opts Additional options to $.ajax OR {loadType: 'tag'} to load by script tag
* @param Object check { obj: (Object)ParentObject, name: (String)"Attribute name", timeout: (Integer)milliseconds }
* @return elFinder
*/
loadScript : function(urls, callback, opts, check) {
var defOpts = {
dataType : 'script',
cache : true
},
success = null;
if ($.isFunction(callback)) {
success = function() {
if (check) {
if (typeof check.obj[check.name] === 'undefined') {
var cnt = check.timeout? (check.timeout / 10) : 1000; // timeout 10 secs
var fi = setInterval(function() {
if (--cnt > 0 && typeof check.obj[check.name] !== 'undefined') {
clearInterval(fi);
callback();
}
}, 10);
} else {
callback();
}
} else {
callback();
}
}
}
if (opts && opts.loadType === 'tag') {
$.each(urls, function(i, url) {
$('head').append($('<script defer="defer">').attr('src', url));
});
success();
} else {
opts = $.isPlainObject(opts)? $.extend(defOpts, opts) : defOpts;
(function appendScript() {
$.ajax($.extend(opts, {
url: urls.shift(),
success: urls.length? appendScript : success
}));
})();
}
return this;
},
/**
* Load CSS files
*
* @param Array to load CSS file URLs
* @return elFinder
*/
loadCss : function(urls) {
var self = this;
if (typeof urls === 'string') {
urls = [ urls ];
}
$.each(urls, function(i, url) {
url = self.convAbsUrl(url).replace(/^https?:/i, '');
if (! $("head > link[href='+url+']").length) {
$('head').append('<link rel="stylesheet" type="text/css" href="' + url + '" />');
}
});
return this;
},
log : function(m) { window.console && window.console.log && window.console.log(m); return this; },
debug : function(type, m) {
var d = this.options.debug;
if (d == 'all' || d === true || ($.isArray(d) && $.inArray(type, d) != -1)) {
window.console && window.console.log && window.console.log('elfinder debug: ['+type+'] ['+this.id+']', m);
}
if (type === 'backend-debug') {
this.trigger('backenddebug', m);
}
return this;
},
time : function(l) { window.console && window.console.time && window.console.time(l); },
timeEnd : function(l) { window.console && window.console.timeEnd && window.console.timeEnd(l); }
};
/**
* for conpat ex. ie8...
*
* Object.keys() - JavaScript | MDN
* https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
*/
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object')
var result = []
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop)
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i])
}
}
return result
}
})()
};
| mit |
monzee/fist | fist-kt-android/src/test/java/ph/codeia/fist/ExampleUnitTest.java | 392 | package ph.codeia.fist;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
ongaeshi/mrubin | test/data/BindTouchPoint.cpp | 996 | #include "BindTouchPoint.hpp"
#include "mruby/value.h"
namespace {
mrb_value x(mrb_state *mrb, mrb_value self)
{
// return self;
return mrb_nil_value();
}
mrb_value y(mrb_state *mrb, mrb_value self)
{
// return self;
return mrb_nil_value();
}
mrb_value valid?(mrb_state *mrb, mrb_value self)
{
// return self;
return mrb_nil_value();
}
mrb_value inspect(mrb_state *mrb, mrb_value self)
{
// return self;
return mrb_nil_value();
}
}
void BindTouchPoint::Bind(mrb_state* mrb)
{
struct RClass *cc = mrb_define_class(mrb, "TouchPoint", mrb->object_class);
mrb_define_method(mrb, cc, "x" , x , MRB_ARGS_NONE());
mrb_define_method(mrb, cc, "y" , y , MRB_ARGS_NONE());
mrb_define_method(mrb, cc, "valid?" , valid? , MRB_ARGS_NONE());
mrb_define_method(mrb, cc, "inspect" , inspect , MRB_ARGS_NONE());
}
| mit |
deep0892/jitendrachatbot | packages/rocketchat-livechat/server/methods/setting.js | 266 | Meteor.methods({
'livechat:getSetting' (ids) {
return RocketChat.models.Settings.findByIds(ids).fetch();
}
});
Meteor.methods({
'livechat:setSetting' (_id, value) {
return RocketChat.models.Settings.updateValueById(_id, value);
}
}); | mit |
twilio/twilio-csharp | test/Twilio.Test/Rest/Api/V2010/Account/Call/SiprecResourceTest.cs | 6401 | /// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.Api.V2010.Account.Call;
namespace Twilio.Tests.Rest.Api.V2010.Account.Call
{
[TestFixture]
public class SiprecTest : TwilioTest
{
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Api,
"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Siprec.json",
""
);
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
SiprecResource.Create("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateNoArgsResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"call_sid\": \"CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"SRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\": null,\"status\": \"in-progress\",\"date_updated\": \"Thu, 30 Jul 2015 20:00:00 +0000\"}"
));
var response = SiprecResource.Create("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateWithArgsResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"call_sid\": \"CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"SRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\": \"myName\",\"status\": \"in-progress\",\"date_updated\": \"Thu, 30 Jul 2015 20:00:00 +0000\"}"
));
var response = SiprecResource.Create("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestUpdateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Api,
"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Siprec/SRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json",
""
);
request.AddPostParam("Status", Serialize(SiprecResource.UpdateStatusEnum.Stopped));
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
SiprecResource.Update("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "SRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", SiprecResource.UpdateStatusEnum.Stopped, client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestUpdateBySidResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"call_sid\": \"CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"SRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\": null,\"status\": \"stopped\",\"date_updated\": \"Thu, 30 Jul 2015 20:00:00 +0000\"}"
));
var response = SiprecResource.Update("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "SRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", SiprecResource.UpdateStatusEnum.Stopped, client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestUpdateByNameResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"call_sid\": \"CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"sid\": \"SRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\": \"mySiprec\",\"status\": \"stopped\",\"date_updated\": \"Thu, 30 Jul 2015 20:00:00 +0000\"}"
));
var response = SiprecResource.Update("CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "SRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", SiprecResource.UpdateStatusEnum.Stopped, client: twilioRestClient);
Assert.NotNull(response);
}
}
} | mit |
rushter/MLAlgorithms | mla/fm.py | 2594 | # coding:utf-8
import autograd.numpy as np
from autograd import elementwise_grad
from mla.base import BaseEstimator
from mla.metrics import mean_squared_error, binary_crossentropy
np.random.seed(9999)
"""
References:
Factorization Machines http://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf
"""
class BaseFM(BaseEstimator):
def __init__(
self, n_components=10, max_iter=100, init_stdev=0.1, learning_rate=0.01, reg_v=0.1, reg_w=0.5, reg_w0=0.0
):
"""Simplified factorization machines implementation using SGD optimizer."""
self.reg_w0 = reg_w0
self.reg_w = reg_w
self.reg_v = reg_v
self.n_components = n_components
self.lr = learning_rate
self.init_stdev = init_stdev
self.max_iter = max_iter
self.loss = None
self.loss_grad = None
def fit(self, X, y=None):
self._setup_input(X, y)
# bias
self.wo = 0.0
# Feature weights
self.w = np.zeros(self.n_features)
# Factor weights
self.v = np.random.normal(scale=self.init_stdev, size=(self.n_features, self.n_components))
self._train()
def _train(self):
for epoch in range(self.max_iter):
y_pred = self._predict(self.X)
loss = self.loss_grad(self.y, y_pred)
w_grad = np.dot(loss, self.X) / float(self.n_samples)
self.wo -= self.lr * (loss.mean() + 2 * self.reg_w0 * self.wo)
self.w -= self.lr * w_grad + (2 * self.reg_w * self.w)
self._factor_step(loss)
def _factor_step(self, loss):
for ix, x in enumerate(self.X):
for i in range(self.n_features):
v_grad = loss[ix] * (x.dot(self.v).dot(x[i])[0] - self.v[i] * x[i] ** 2)
self.v[i] -= self.lr * v_grad + (2 * self.reg_v * self.v[i])
def _predict(self, X=None):
linear_output = np.dot(X, self.w)
factors_output = np.sum(np.dot(X, self.v) ** 2 - np.dot(X ** 2, self.v ** 2), axis=1) / 2.0
return self.wo + linear_output + factors_output
class FMRegressor(BaseFM):
def fit(self, X, y=None):
super(FMRegressor, self).fit(X, y)
self.loss = mean_squared_error
self.loss_grad = elementwise_grad(mean_squared_error)
class FMClassifier(BaseFM):
def fit(self, X, y=None):
super(FMClassifier, self).fit(X, y)
self.loss = binary_crossentropy
self.loss_grad = elementwise_grad(binary_crossentropy)
def predict(self, X=None):
predictions = self._predict(X)
return np.sign(predictions)
| mit |
elfafa/CostShare | src/FS/CostShareBundle/Entity/User.php | 2056 | <?php
namespace FS\CostShareBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* Contact
*
* @ORM\Table(name="user")
* @ORM\Entity
*/
class User extends BaseUser {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="lastname", type="string", length=255)
*/
private $lastname;
/**
* @var string
*
* @ORM\Column(name="firstname", type="string", length=255)
*/
private $firstname;
/**
* @var \DateTime
*
* @ORM\Column(name="date_create", type="datetime")
*/
private $dateCreate;
public function __construct() {
parent::__construct();
}
/**
* Get id
*
* @return integer
*/
public function getId() {
return $this->id;
}
/**
* Set lastname
*
* @param string $lastname
* @return Contact
*/
public function setLastname($lastname) {
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* @return string
*/
public function getLastname() {
return $this->lastname;
}
/**
* Set firstname
*
* @param string $firstname
* @return Contact
*/
public function setFirstname($firstname) {
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* @return string
*/
public function getFirstname() {
return $this->firstname;
}
/**
* Set dateCreate
*
* @param \DateTime $dateCreate
* @return Contact
*/
public function setDateCreate($dateCreate) {
$this->dateCreate = $dateCreate;
return $this;
}
/**
* Get dateCreate
*
* @return \DateTime
*/
public function getDateCreate() {
return $this->dateCreate;
}
}
| mit |
watermint/toolbox | infra/api/api_request/request.go | 2719 | package api_request
import (
"encoding/json"
"github.com/google/go-querystring/query"
"github.com/watermint/toolbox/essentials/io/es_rewinder"
"github.com/watermint/toolbox/essentials/log/esl"
)
const (
ReqHeaderContentType = "Content-Type"
ReqHeaderAccept = "Accept"
ReqHeaderContentLength = "Content-Length"
ReqHeaderAuthorization = "Authorization"
ReqHeaderUserAgent = "User-Agent"
ReqHeaderDropboxApiSelectUser = "Dropbox-API-Select-User"
ReqHeaderDropboxApiSelectAdmin = "Dropbox-API-Select-Admin"
ReqHeaderDropboxApiPathRoot = "Dropbox-API-Path-Root"
ReqHeaderDropboxApiArg = "Dropbox-API-Arg"
)
type RequestData struct {
p interface{}
q interface{}
h map[string]string
c es_rewinder.ReadRewinder
}
// Convert into JSON form of param. Returns `null` string if an error occurred.
// Returns empty string when the parameter is null.
func (z RequestData) ParamJson() json.RawMessage {
l := esl.Default()
if z.p == nil {
l.Debug("Parameter is null")
return json.RawMessage{}
}
q, err := json.Marshal(z.p)
if err != nil {
l.Debug("unable to marshal param", esl.Error(err), esl.Any("p", z.p))
return json.RawMessage("null")
} else {
return q
}
}
// Returns query string like "?key=value&key2=value2". Returns empty string if an error occurred.
func (z RequestData) ParamQuery() string {
l := esl.Default()
if z.q == nil {
return ""
}
q, err := query.Values(z.q)
if err != nil {
l.Debug("unable to make query", esl.Error(err), esl.Any("q", z.q))
return ""
} else {
return "?" + q.Encode()
}
}
// Returns raw param data
func (z RequestData) Param() interface{} {
return z.p
}
// Returns raw query data
func (z RequestData) Query() interface{} {
return z.q
}
func (z RequestData) Headers() map[string]string {
if z.h == nil {
return map[string]string{}
}
return z.h
}
func (z RequestData) Content() es_rewinder.ReadRewinder {
return z.c
}
type RequestDatum func(d RequestData) RequestData
func Query(q interface{}) RequestDatum {
return func(d RequestData) RequestData {
d.q = q
return d
}
}
func Param(p interface{}) RequestDatum {
return func(d RequestData) RequestData {
d.p = p
return d
}
}
func Header(name, value string) RequestDatum {
return func(d RequestData) RequestData {
h := make(map[string]string)
for k, v := range d.h {
h[k] = v
}
h[name] = value
d.h = h
return d
}
}
func Content(c es_rewinder.ReadRewinder) RequestDatum {
return func(d RequestData) RequestData {
d.c = c
return d
}
}
// Combine datum into data
func Combine(rds []RequestDatum) RequestData {
rd := RequestData{}
for _, d := range rds {
rd = d(rd)
}
return rd
}
| mit |
kahveci/cherry-iot | node_modules/node-opcua/schemas/HistoryReadResult_schema.js | 345 |
var HistoryReadResult_Schema = {
name: "HistoryReadResult",
fields: [
{ name: "statusCode", fieldType:"StatusCode" },
{ name: "continuationPoint", fieldType:"ByteString" ,defaultValue:null},
{ name: "historyData", fieldType:"ExtensionObject"}
]
};
exports.HistoryReadResult_Schema = HistoryReadResult_Schema; | mit |
omidmogharian/enga | src/js/cas/myapi/samplesrvc.js | 443 |
class sampleSrvc {
static login(accessToken) {
this.server.accessToken = accessToken;
return this.server.call( "login",{"accessToken":accessToken})
}
static hasPermission(accessToken) {
this.server.accessToken = accessToken;
return this.server.call( "has_permission",{"accessToken":accessToken});
}
static getAllContact() {
return this.server.call( "get_all_contact",{});
}
}
export default sampleSrvc
| mit |
kagel/wayfarer | src/main/java/com/wavedroid/wayfarer/manners/Homebody.java | 772 | package com.wavedroid.wayfarer.manners;
import com.wavedroid.wayfarer.ambitions.Ambition;
import com.wavedroid.wayfarer.ambitions.Amoeba;
import com.wavedroid.wayfarer.strategies.FixedList;
import com.wavedroid.wayfarer.strategies.Strategy;
import fi.foyt.foursquare.api.entities.CompleteVenue;
/**
* Date: 26.10.13
* Time: 22:57
*
* @author dkhvatov
*/
public class Homebody implements Manner {
private FixedList strategy;
public Homebody(CompleteVenue[] homeVenuesList) {
this.strategy = new FixedList(homeVenuesList, new Ambition[]{new Amoeba()});
}
@Override
public Strategy getStrategy() {
return strategy;
}
@Override
public int getDelay() {
return 0; // check-in at home as fast as you can
}
}
| mit |
astupak/muffin-server | libs/passport/localStrategy.js | 605 | const passport = require('koa-passport');
const LocalStrategy = require('passport-local');
const User = require('../../models/user');
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
},
(email, password, done) => {
User.findOne({ email }, (err, user) => {
if (err) {
return done(err);
}
if (!user || !user.checkPassword(password)) {
return done(null, false, { message: 'Нет такого пользователя или пароль неверен.' });
}
return done(null, user);
});
}
));
| mit |
pulipulichen/ocs | lib/jquery-survey/example/survey.js | 1907 | var survey = {
title: 'signup',
name: 'signup',
pages: [
{
//name: 'generalinfo',
title: 'Signup',
elements: [
{
//name: "firstName",
type: 'text',
label: "First Name",
//placeholder: "Your First Name...",
required: true
},
{
//name: "lastName",
type: 'text',
label: "Last Name",
//placeholder: "Your Last Name...",
required: true
},
{
//name: "email",
type: 'email',
label: "Email Address",
//placeholder: "Your Email Address...",
required: true
},
{
//name: "gender",
type: 'radio',
label: "Gender",
options: [
{
//key: 'male',
value: 'Male'
},
{
//key: 'female',
value: 'Female'
}
],
required: true
},
{
type: 'section',
condition: {
from: {elem: "[name=gender]:checked"},
to: 'female'
},
elements: [
{
type: 'html',
fragment: '<p>Girls rule!</p>'
}
]
},
{
type: 'section',
condition: {
from: {elem: "[name=gender]:checked"},
to: 'male'
},
elements: [
{
type: 'html',
fragment: '<p>Guys rule!</p>'
}
]
}
],
options: [
{
type: 'nextPage',
caption: 'Signup >'
}
]
},
{
name: "thanks",
elements: [
{
type: 'handlebars',
source: '<p>{{data.firstName}}, thanks for your interest.</p>'
}
],
}
]
};
| mit |
meserovirtual/mesero | app/reservas/reservas.js | 368 | (function () {
'use strict';
var scripts = document.getElementsByTagName("script");
var currentScriptPath = scripts[scripts.length - 1].src;
angular.module('myApp.reservas', ['ngRoute'])
.controller('ReservasCtrl', ReservasCtrl);
ReservasCtrl.$inject = ['$scope'];
function ReservasCtrl($scope) {
var vm = this;
}
})(); | mit |
clooca/clooca | src/common/utils/ajax.js | 4209 | const http = require("http"),
https = require('https'),
querystring = require("querystring"),
URL = require('url');
/**
* @params options req,res
*/
function request(method, url, params, headers, callback, _dataOptions) {
var dataOptions = _dataOptions || {};
var urlObject = URL.parse(url);
var http_client = urlObject.protocol=="https:" ? https : http;
if(dataOptions.req == 'json') {
headers['Content-Type'] = 'application/json';
}else{
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
var options = {
hostname: urlObject.hostname,
port: urlObject.port,
path: urlObject.path,
method: method,
headers : headers
};
if(method == 'GET' || method == 'DELETE') {
var postItem = querystring.stringify(params);
options.path += '?'+ postItem;
http_client.get(options, process_response)
.on('error', function (e) {
callback(e);
});
}else{
var req = http_client.request(options, process_response);
req.setTimeout(5000);
req.on('timeout', function() {
if(callback) callback(new Error("timed out"), null);
req.abort();
});
req.on('error', function(err) {
if(callback) callback(err, null);
});
if(dataOptions.req == 'json') {
var postItem = JSON.stringify(params);
}else{
var postItem = querystring.stringify(params);
}
var postItem = querystring.stringify(params);
req.write(postItem);
req.end();
}
function process_response(res) {
if(callback) {
var content = "";
res.on('data', function(str) {
content += str;
});
res.on('end', function() {
responseType(dataOptions, content, callback);
});
}
}
}
function requestBrowser(method, url, params, headers, callback, _options) {
var options = _options || {};
var urlObject = URL.parse(url);
if(method == 'GET' || method == 'DELETE') {
url += '?' + querystring.stringify(params);
}
var xhr = createCORSRequest(method , url);
xhr.withCredentials = true;
xhr.onload = function() {
responseType(options, xhr.responseText, callback);
}
xhr.onerror = function() {
callback(xhr.statusText || 'unknown error');
}
if(options.req == 'json') {
xhr.setRequestHeader("Content-type", "application/json");
var params_str = JSON.stringify(params);
}else{
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var params_str = querystring.stringify(params);
}
for(header_key in headers) {
xhr.setRequestHeader(header_key, headers[header_key]);
}
if(method == 'GET' || method == 'DELETE') {
xhr.send();
}else{
xhr.send(params_str);
}
}
function post(url, params, options) {
return new Promise((resolve, reject) => {
this.request('POST', url, params, {}, function(err, data) {
if(err) {
return reject(err);
}
resolve(data);
}, options);
});
}
function get(url, qs, options) {
return new Promise((resolve, reject) => {
this.request('GET', url, qs, {}, function(err, data) {
if(err) {
return reject(err);
}
resolve(data);
}, options);
});
}
function put(url, params, options) {
return new Promise((resolve, reject) => {
this.request('PUT', url, params, {}, function(err, data) {
if(err) {
return reject(err);
}
resolve(data);
}, options);
});
}
function deleteMethod(url, qs, options) {
return new Promise((resolve, reject) => {
this.request('GET', url, qs, {}, function(err, data) {
if(err) {
return reject(err);
}
resolve(data);
}, options);
});
}
if ('browser' !== process.title) {
module.exports = {
request : request,
post: post,
get: get,
put: put,
delete: deleteMethod
}
}else{
module.exports = {
request : requestBrowser,
post: post,
get: get,
put: put,
delete: deleteMethod
}
}
function responseType(options, data, callback) {
if(options.res == 'json') {
var result = JSON.parse(data);
}else{
var result = data;
}
callback(null, result);
}
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
} | mit |
mohayonao/neume | test/scapi/operators/asin.js | 591 | import assert from "assert";
import asin from "../../../src/scapi/operators/asin";
import createNode from "../../../src/scapi/utils/createNode";
import isSCNode from "../../../src/scapi/utils/isSCNode";
describe("scapi/operators/asin(a)", () => {
it("numeric", () => {
const a = 0.5;
const node = asin(a);
assert(node === Math.asin(a));
});
it("sc.node", () => {
const a = createNode("SinOsc", "audio", [ 440, 0 ]);
const node = asin(a);
assert(isSCNode(node));
assert.deepEqual(node, {
type: "asin", rate: "audio", props: [ a ]
});
});
});
| mit |
openfact/openfact | src/main/java/org/openfact/core/keys/FailsafeRsaKeyProvider.java | 1856 | package org.openfact.core.keys;
import org.jboss.logging.Logger;
import org.keycloak.common.util.KeyUtils;
import org.keycloak.common.util.Time;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;
public class FailsafeRsaKeyProvider implements RsaKeyProvider {
private static final Logger logger = Logger.getLogger(FailsafeRsaKeyProvider.class);
private static String KID;
private static KeyPair KEY_PAIR;
private static long EXPIRES;
private KeyPair keyPair;
private String kid;
public FailsafeRsaKeyProvider() {
logger.errorv("No active keys found, using failsafe provider, please login to admin console to add keys. Clustering is not supported.");
synchronized (FailsafeRsaKeyProvider.class) {
if (EXPIRES < Time.currentTime()) {
KEY_PAIR = KeyUtils.generateRsaKeyPair(2048);
KID = KeyUtils.createKeyId(KEY_PAIR.getPublic());
EXPIRES = Time.currentTime() + 60 * 10;
if (EXPIRES > 0) {
logger.warnv("Keys expired, re-generated kid={0}", KID);
}
}
kid = KID;
keyPair = KEY_PAIR;
}
}
@Override
public String getKid() {
return kid;
}
@Override
public PrivateKey getPrivateKey() {
return keyPair.getPrivate();
}
@Override
public PublicKey getPublicKey(String kid) {
return kid.equals(this.kid) ? keyPair.getPublic() : null;
}
@Override
public X509Certificate getCertificate(String kid) {
return null;
}
@Override
public List<RsaKeyMetadata> getKeyMetadata() {
return Collections.emptyList();
}
}
| mit |
brakmic/BlockchainStore | src/app/reducers/index.ts | 25 | export * from './route';
| mit |
gsi-upm/soba | projects/GreenSOBA/model/model.py | 31929 | from mesa import Agent, Model
from mesa.time import BaseScheduler
from mesa.space import MultiGrid
from mesa.space import ContinuousSpace
from collections import defaultdict
import random
import os
import os.path
import configuration.settings
import configuration.defineOccupancy
import configuration.defineMap
from log.log import Log
from log.logsc import Logsc
from model.socialChoice import SocialChoice
from model.energy import Energy
from model.time import Time
from agents.occupant import Occupant
from agents.pc import PC
from agents.light import Light
from agents.hvac import HVAC
from space.door import Door
from space.room import Room
from space.window import Window
from space.wall import Wall
from space.thermalZone import ThermalZone
from time import time
class SOBAModel(Model):
def __init__(self, width, height, modelWay = None, seed = int(time()), nothing = 1, voting_method = False):
super().__init__(seed)
#Init configurations and defines
configuration.settings.init()
configuration.defineOccupancy.init()
configuration.defineMap.init()
#Way of working
if modelWay is None:
self.modelWay = configuration.settings.model
else:
self.modelWay = modelWay
#Mesa
self.schedule = BaseScheduler(self)
self.grid = MultiGrid(width, height, False)
self.running = True
#Control of time and energy
self.energy = Energy()
self.clock = Time()
self.voting_method = voting_method
self.sc = SocialChoice()
#Log
self.log = Log()
if self.voting_method:
self.log = Logsc()
self.roomsSchedule = []
self.agentSatisfationByStep = []
self.fangerSatisfationByStep = []
self.agentsActivityByTime = []
self.averageSatisfationByTime = []
self.totalSatisfationByTime = []
self.occupantsValues = False
if self.modelWay != 0 and os.path.isfile('../log/tmp/occupants.txt'):
self.occupantsValues = self.log.getOccupantsValues()
#Vars of control
self.complete = False
self.num_occupants = 0
self.day = self.clock.day
self.NStep = 0
self.timeToSampling = 'init' # Temperature ThermalLoads
self.placeByStateByTypeAgent = {}
self.lightsOn = []
#Create the map
self.createRooms()
self.createThermalzones()
self.setMap(width, height)
self.createDoors()
self.createWindows()
self.createWalls()
#Create agents
self.setAgents()
def consumeEnergy(self, appliance):
if isinstance(appliance, PC):
if appliance.state == 'on':
self.energy.consumeEnergyAppliance('PC',appliance.consumeOn)
elif appliance.state == 'standby':
self.energy.consumeEnergyAppliance('PC',appliance.consumeStandby)
else:
self.energy.consumeEnergyAppliance('PC',0)
elif isinstance(appliance, Light):
if appliance.state == 'on':
self.energy.consumeEnergyAppliance('Light',appliance.consume)
else:
self.energy.consumeEnergyAppliance('Light',0)
elif isinstance(appliance, HVAC):
if appliance.state == 'on':
self.energy.consumeEnergyAppliance('HVAC',appliance.consumeOn)
else:
self.energy.consumeEnergyAppliance('HVAC',0)
else:
pass
def isConected(self, pos):
nextRoom = False
for room in self.rooms:
if room.pos == pos:
nextRoom = room
if nextRoom == False:
return False
for x in range(0, width):
for y in range(0, height):
self.pos_out_of_map.append(x, y)
for room in self.rooms:
self.pos_out_of_map.remove(room.pos)
def createRooms(self):
rooms = configuration.defineMap.rooms_json
self.rooms = []
#occupantsByTypeRoom = configuration.defineMap.NumberOccupancyByTypeRoom
for room in rooms:
newRoom = 0
name = room['name']
typeRoom = room['type']
if typeRoom != 'out':
conectedTo = room.get('conectedTo')
nameThermalZone = room.get('thermalZone')
entrance = room.get('entrance')
measures = room['measures']
dx = measures['dx']
dy = measures['dy']
dh = measures['dh']
jsonWindows = room.get('windows')
newRoom = Room(name, typeRoom, conectedTo, nameThermalZone, dx, dy, dh, jsonWindows)
newRoom.entrance = entrance
else:
newRoom = Room(name, typeRoom, None, False, 0, 0, 0, {})
self.outBuilding = newRoom
self.rooms.append(newRoom)
for room1 in self.rooms:
if room1.conectedTo is not None:
for otherRooms in list(room1.conectedTo.values()):
for room2 in self.rooms:
if room2.name == otherRooms:
room1.roomsConected.append(room2)
room2.roomsConected.append(room1)
for room in self.rooms:
room.roomsConected = list(set(room.roomsConected))
sameRoom = {}
for room in self.rooms:
if sameRoom.get(room.name.split(r".")[0]) is None:
sameRoom[room.name.split(r".")[0]] = 1
else:
sameRoom[room.name.split(r".")[0]] = sameRoom[room.name.split(r".")[0]] + 1
def createThermalzones(self):
self.thermalZones = []
namesThermalZonesCreated = []
for room1 in self.rooms:
posibleThermalZone = room1.nameThermalZone
if posibleThermalZone not in namesThermalZonesCreated and posibleThermalZone != False and posibleThermalZone is not None:
namesThermalZonesCreated.append(posibleThermalZone)
rooms = []
for room2 in self.rooms:
if room2.nameThermalZone == posibleThermalZone:
rooms.append(room2)
TZ = ThermalZone(self, posibleThermalZone, rooms)
for room3 in TZ.rooms:
room3.thermalZone = TZ
self.thermalZones.append(TZ)
if self.modelWay == 2:
hoursRoomsOnOffByDay = {}
hoursRoomsOnStrings = self.log.getScheduleRooms()
hoursRoomsOn = []
for row in hoursRoomsOnStrings:
hoursRoomsOn.append([row[0], float(row[1]), float(row[2])])
for room in self.rooms:
count = 0
if room.typeRoom != 'out' and room.typeRoom != 'restroom':
hoursOneRoomOn = []
for row in hoursRoomsOn:
if row[0] == room.name:
hoursOneRoomOn.append([row[1], row[2]])
hoursOneRoomOnByDay = []
for i in range(0, 5):
hoursOneDay = []
for hour in hoursOneRoomOn:
if int(hour[0]) == i:
hoursOneDay.append(hour[1])
hoursOneRoomOnByDay.append(hoursOneDay)
hoursOnOffOneRoomByDay = []
for i in range(0 ,5):
hoursOnOffOneRoomOneDay = []
hourOn = hoursOneRoomOnByDay[i]
if len(hourOn) > 0:
auxHour = hourOn[0]
hourOnAux = hourOn[0]
for hour in hourOn:
if (auxHour != hour):
if(hour > (auxHour + configuration.settings.setOffWorthIt)):
hourOff = auxHour-0.01
pairOnOff = [int(hourOnAux*100)/100, int(hourOff*100)/100]
hoursOnOffOneRoomOneDay.append(pairOnOff)
auxHour = hour + 0.01
hourOnAux = hour
else:
auxHour = hour + 0.01
else:
auxHour = auxHour + 0.01
pairOnOffObligatory = [hourOnAux, hourOn.pop()]
hoursOnOffOneRoomOneDay.append(pairOnOffObligatory)
hoursOnOffOneRoomByDay.append(hoursOnOffOneRoomOneDay)
else:
hoursOnOffOneRoomByDay.append(False)
hoursRoomsOnOffByDay[room.name] = hoursOnOffOneRoomByDay
count = count + 1
for tz in self.thermalZones:
schedule = []
for i in range(0, 5):
scheduleByDay = []
for room in tz.rooms:
hoursByDay = hoursRoomsOnOffByDay.get(room.name)
if hoursByDay is not None and hoursByDay != False:
hoursOneDay = hoursByDay[i]
if hoursOneDay is not None and hoursOneDay != False:
for hours in hoursOneDay:
hourOn = hours[0]
hourOff = hours[1]
for pairHours in scheduleByDay:
if hourOn > pairHours[0] and pairHours[1] > hourOn:
scheduleByDay.remove([pairHours[0], pairHours[1]])
hourOn = pairHours[0]
if(hourOff < pairHours[1]):
hourOff = pairHours[1]
else:
pass
elif hourOff > pairHours[0] and pairHours[1] > hourOff:
scheduleByDay.remove([pairHours[0], pairHours[1]])
hourOff = pairHours[1]
if(hourOn > pairHours[0]):
hourOn = pairHours[0]
else:
pass
elif hourOff > pairHours[1] and pairHours[0] > hourOn:
scheduleByDay.remove([pairHours[0], pairHours[1]])
scheduleByDay.append([hourOn, hourOff])
if len(scheduleByDay) == 0:
scheduleByDay.append([False])
schedule.append(scheduleByDay)
scheduleJoined = []
for day in schedule:
if day != False:
scheduleJoined.append(sorted(day))
for day in scheduleJoined:
i = 0
if day != False:
while (len(day)>(i+1)):
if (day[i][1] + configuration.settings.setOffWorthIt) > day[i+1][0]:
day[i][1] = day[i+1][1]
day.pop(i+1)
else:
i = i+1
tz.schedule = scheduleJoined
def setMap(self, width, height):
rooms_noPos = self.rooms
rooms_using = []
rooms_used = []
for room in self.rooms:
if room.entrance is not None:
room.pos = (int(1), 2)
rooms_using.append(room)
rooms_used.append(room)
rooms_noPos.remove(room)
break
while len(rooms_noPos) > 0:
for roomC in rooms_using:
xc, yc = roomC.pos
rooms_conected = roomC.conectedTo
rooms_using.remove(roomC)
if rooms_conected is not None:
orientations = list(rooms_conected.keys())
for orientation in orientations:
if orientation == 'R':
for room in rooms_noPos:
if room.name == rooms_conected['R']:
room.pos = (int(xc + 1), yc)
rooms_noPos.remove(room)
rooms_used.append(room)
rooms_using.append(room)
elif orientation == 'U':
for room in rooms_noPos:
if room.name == rooms_conected['U']:
room.pos = (xc, int(yc + 1))
rooms_noPos.remove(room)
rooms_used.append(room)
rooms_using.append(room)
elif orientation == 'D':
for room in rooms_noPos:
if room.name == rooms_conected['D']:
room.pos = (xc, int(yc - 1))
rooms_noPos.remove(room)
rooms_used.append(room)
rooms_using.append(room)
elif orientation == 'L':
for room in rooms_noPos:
if room.name == rooms_conected['L']:
room.pos = (int(xc -1), yc)
rooms_noPos.remove(room)
rooms_used.append(room)
rooms_using.append(room)
else:
pass
self.rooms = rooms_used
def createDoors(self):
self.doors = []
for roomC in self.rooms:
roomsConected = roomC.roomsConected
for room in roomsConected:
door_created = False
same_corridor = False
if room.name != roomC.name:
for door in self.doors:
if (door.room1.name == roomC.name and door.room2.name == room.name) or (door.room2.name == roomC.name and door.room1.name == room.name):
door_created = True
if room.name.split(r".")[0] == roomC.name.split(r".")[0]:
same_corridor = True
if door_created == False and same_corridor == False:
d = Door(roomC, room)
self.doors.append(d)
room.doors.append(d)
roomC.doors.append(d)
def createWindows(self):
for room in self.rooms:
windows = []
json = room.jsonWindows
if json is None:
pass
else:
for k in json:
window = Window(k, json[k]['l1'], json[k]['l2'])
windows.append(window)
room.windows = windows
def createWalls(self):
for room in self.rooms:
if room.typeRoom != 'out':
walls = []
innerWalls = []
adjRooms = []
xr, yr = room.pos
roomA = self.getRoom((xr, yr+1))
if roomA != False:
if roomA.typeRoom != 'out':
if roomA.name.split(r".")[0] == room.name.split(r".")[0]:
pass
else:
wall = Wall(room.dx, room.dh, room, roomA)
innerWalls.append(wall)
adjRooms.append(roomA)
else:
wall = Wall(room.dx, room.dh, orientation = 'N')
walls.append(wall)
else:
wall = Wall(room.dx, room.dh, orientation = 'N')
walls.append(wall)
roomB = self.getRoom((xr, yr-1))
if roomB != False:
if roomB.typeRoom != 'out':
if roomB.name.split(r".")[0] == room.name.split(r".")[0]:
pass
else:
wall = Wall(room.dx, room.dh, room, roomB)
innerWalls.append(wall)
adjRooms.append(roomB)
else:
wall = Wall(room.dx, room.dh, orientation = 'S')
walls.append(wall)
else:
wall = Wall(room.dx, room.dh, orientation = 'S')
walls.append(wall)
roomC = self.getRoom((xr+1, yr))
if roomC != False:
if roomC.typeRoom != 'out':
if roomC.name.split(r".")[0] == room.name.split(r".")[0]:
pass
else:
wall = Wall(room.dy, room.dh, room, roomC)
innerWalls.append(wall)
adjRooms.append(roomC)
else:
wall = Wall(room.dy, room.dh, orientation = 'E')
walls.append(wall)
else:
wall = Wall(room.dy, room.dh, orientation = 'E')
walls.append(wall)
roomD = self.getRoom((xr-1, yr))
if roomD != False:
if roomD.typeRoom != 'out':
if roomD.name.split(r".")[0] == room.name.split(r".")[0]:
pass
else:
wall = Wall(room.dy, room.dh, room, roomD)
innerWalls.append(wall)
adjRooms.append(roomD)
else:
wall = Wall(room.dy, room.dh, orientation = 'W')
walls.append(wall)
else:
wall = Wall(room.dy, room.dh, orientation = 'W')
walls.append(wall)
room.walls = walls
room.innerWalls = innerWalls
room.roomsAdj = adjRooms
def setAgents(self):
# Identifications
id_offset = 1000
# Height and Width
height = self.grid.height
width = self.grid.width
# CREATE AGENTS
#Create Lightlights
self.lights = []
id_light = 0
for room in self.rooms:
if room.typeRoom != 'out' and room.light == False:
light = Light(id_light, self, room)
self.lights.append(light)
id_light = id_light + 1
room.light = light
for room2 in self.rooms:
if room.name.split(r".")[0] == room2.name.split(r".")[0]:
room2.light = light
id_hvac = id_light + id_offset
#Create HVAC
self.HVACs = []
for thermalZone in self.thermalZones:
restroom = False
for room in thermalZone.rooms:
if room.typeRoom == 'restroom':
restroom = True
if restroom == False:
hvac = HVAC(id_hvac, self, thermalZone)
thermalZone.hvac = hvac
self.HVACs.append(hvac)
id_hvac = id_hvac + 1
else:
thermalZone.hvac = False
#Create PC
'''
self.workplaces = []
id_aux = 0
for room in self.rooms:
#for i in range(0, room.PCs):
pc = PC(id_pc + id_aux, self, room)
room.PCs.append(pc)
self.workplaces.append(pc)
id_aux = id_aux + 1
'''
id_occupant = id_hvac + id_offset
id_pc = id_occupant + id_offset
self.workplaces = []
self.agents = []
# Create occupants
if self.modelWay == 0:
countPC = 0
print('Número de ocupantes: ', configuration.defineOccupancy.occupancy_json[0]['N'])
for n_type_occupants in configuration.defineOccupancy.occupancy_json:
self.placeByStateByTypeAgent[n_type_occupants['type']] = n_type_occupants['states']
n_agents_perfect = int((n_type_occupants['N'] * n_type_occupants['environment'][0]) / 100)
for i in range(0, n_agents_perfect):
rooms_with_already_pc = []
a = Occupant(id_occupant, self, n_type_occupants, 1)
self.agents.append(a)
id_occupant = 1 + id_occupant
for state_use_PCs in n_type_occupants['PCs']:
roomPC = False
name_room_with_pc = a.positionByState[state_use_PCs]
for room in self.rooms:
if room.name.split(r".")[0] == name_room_with_pc:
roomPC = room
if roomPC != False and roomPC.typeRoom != 'out':
if roomPC not in rooms_with_already_pc:
pc = PC(id_pc, self, roomPC)
id_pc = id_pc + 1
pc.owner = a
self.workplaces.append(pc)
a.PCs[state_use_PCs] = pc
pc.states_when_is_used.append(state_use_PCs)
roomPC.PCs.append(pc)
else:
for pcaux in roomPC.PCs:
if pcaux.owner == a:
a.PCs[state_use_PCs] = pcaux
pc.states_when_is_used.append(state_use_PCs)
self.schedule.add(a)
self.grid.place_agent(a, self.outBuilding.pos)
self.pushAgentRoom(a, self.outBuilding.pos)
self.num_occupants = self.num_occupants + 1
n_agents_good = int((n_type_occupants['N'] * n_type_occupants['environment'][1]) / 100)
for i in range(0, n_agents_good):
rooms_with_already_pc = []
a = Occupant(id_occupant, self, n_type_occupants, 2)
self.agents.append(a)
id_occupant = 1 + id_occupant
for state_use_PCs in n_type_occupants['PCs']:
roomPC = False
name_room_with_pc = a.positionByState[state_use_PCs]
for room in self.rooms:
if room.name.split(r".")[0] == name_room_with_pc:
roomPC = room
if roomPC != False and roomPC.typeRoom != 'out':
if roomPC not in rooms_with_already_pc:
pc = PC(id_pc, self, roomPC)
id_pc = id_pc + 1
pc.owner = a
self.workplaces.append(pc)
a.PCs[state_use_PCs] = pc
pc.states_when_is_used.append(state_use_PCs)
roomPC.PCs.append(pc)
else:
for pcaux in roomPC.PCs:
if pcaux.owner == a:
a.PCs[state_use_PCs] = pcaux
pc.states_when_is_used.append(state_use_PCs)
self.schedule.add(a)
self.grid.place_agent(a, self.outBuilding.pos)
self.pushAgentRoom(a, self.outBuilding.pos)
self.num_occupants = self.num_occupants + 1
n_agents_bad = int(n_type_occupants['N'] * n_type_occupants['environment'][2] / 100)
allAgents = n_agents_perfect + n_agents_good + n_agents_bad
if allAgents < n_type_occupants['N']:
n_agents_bad = n_type_occupants['N'] - (n_agents_perfect + n_agents_good)
for i in range(0, n_agents_bad):
rooms_with_already_pc = []
a = Occupant(id_occupant, self, n_type_occupants, 3)
self.agents.append(a)
id_occupant = 1 + id_occupant
for state_use_PCs in n_type_occupants['PCs']:
roomPC = False
name_room_with_pc = a.positionByState[state_use_PCs]
for room in self.rooms:
if room.name.split(r".")[0] == name_room_with_pc:
roomPC = room
if roomPC != False and roomPC.typeRoom != 'out':
if roomPC not in rooms_with_already_pc:
pc = PC(id_pc, self, roomPC)
id_pc = id_pc + 1
pc.owner = a
self.workplaces.append(pc)
a.PCs[state_use_PCs] = pc
pc.states_when_is_used.append(state_use_PCs)
roomPC.PCs.append(pc)
else:
for pcaux in roomPC.PCs:
if pcaux.owner == a:
a.PCs[state_use_PCs] = pcaux
pc.states_when_is_used.append(state_use_PCs)
self.schedule.add(a)
self.grid.place_agent(a, self.outBuilding.pos)
self.pushAgentRoom(a, self.outBuilding.pos)
self.num_occupants = self.num_occupants + 1
else:
for n_type_occupants in configuration.defineOccupancy.occupancy_json:
self.placeByStateByTypeAgent[n_type_occupants['type']] = n_type_occupants['states']
n_agents = n_type_occupants['N']
for i in range(0, n_agents):
rooms_with_already_pc = []
a = Occupant(id_occupant, self, n_type_occupants, '')
self.agents.append(a)
id_occupant = 1 + id_occupant
for state_use_PCs in n_type_occupants['PCs']:
roomPC = False
name_room_with_pc = a.positionByState[state_use_PCs]
for room in self.rooms:
if room.name.split(r".")[0] == name_room_with_pc:
roomPC = room
if roomPC != False and roomPC.typeRoom != 'out':
if roomPC not in rooms_with_already_pc:
pc = PC(id_pc, self, roomPC)
id_pc = id_pc + 1
pc.owner = a
self.workplaces.append(pc)
a.PCs[state_use_PCs] = pc
pc.states_when_is_used.append(state_use_PCs)
roomPC.PCs.append(pc)
else:
for pcaux in roomPC.PCs:
if pcaux.owner == a:
a.PCs[state_use_PCs] = pcaux
pc.states_when_is_used.append(state_use_PCs)
self.schedule.add(a)
self.grid.place_agent(a, self.outBuilding.pos)
self.pushAgentRoom(a, self.outBuilding.pos)
self.num_occupants = self.num_occupants + 1
#Add to schedule
for pc in self.workplaces:
self.schedule.add(pc)
for light in self.lights:
self.schedule.add(light)
for hvac in self.HVACs:
self.schedule.add(hvac)
self.schedule.add(self.clock)
def getPosState(self, name, typeA):
placeByStateByTypeAgent = self.placeByStateByTypeAgent
n = 0
for state in self.placeByStateByTypeAgent[typeA]:
if state.get('name') == name:
pos1 = state.get('position')
if isinstance(pos1, dict):
for k,v in pos1.items():
if v > 0:
placeByStateByTypeAgent[typeA][n]['position'][k] = v - 1
self.placeByStateByTypeAgent = placeByStateByTypeAgent
return k
return list(pos1.keys())[-1]
else:
return pos1
n = n +1
def thereIsClosedDoor(self, beforePos, nextPos):
oldRoom = False
newRoom = False
for room in rooms:
if room.pos == beforePos:
oldRoom = room
if room.pos == nextPos:
newRoom = room
for door in self.doors:
if (door.room1.name == oldRoom.name and door.room2.name == newRoom.name) or (door.room2.name == oldRoom.name and door.room1.name == newRoom.name):
if door.state == False:
return True
return False
def thereIsPC(self, pos):
x,y = pos
for pc in self.workplaces:
if pc.x == x and pc.y == y:
return True
return False
def thereIsOccupant(self,pos):
possible_occupant = self.grid.get_cell_list_contents([pos])
if (len(possible_occupant) > 0):
for occupant in possible_occupant:
if isinstance(occupant,Occupant):
return True
return False
def ThereIsOtherOccupantInRoom(self, room, agent):
for roomAux in self.rooms:
possible_occupant = []
if roomAux.name.split(r".")[0] == room.name.split(r".")[0]:
possible_occupant = self.grid.get_cell_list_contents(roomAux.pos)
for occupant in possible_occupant:
if isinstance(occupant, Occupant) and occupant != agent:
return True
return False
def ThereIsSomeOccupantInRoom(self, room):
for roomAux in self.rooms:
possible_occupant = []
if roomAux.name.split(r".")[0] == room.name.split(r".")[0]:
possible_occupant = self.grid.get_cell_list_contents(roomAux.pos)
for occupant in possible_occupant:
if isinstance(occupant, Occupant):
return True
return False
def thereIsOccupantInRoom(self, room, agent):
for roomAux in self.rooms:
possible_occupant = []
if roomAux.name.split(r".")[0] == room.name.split(r".")[0]:
possible_occupant = self.grid.get_cell_list_contents(roomAux.pos)
for occupant in possible_occupant:
if isinstance(occupant, Occupant) and occupant == agent:
return True
return False
def getRoom(self, pos):
for room in self.rooms:
if room.pos == pos:
return room
return False
def pushAgentRoom(self, agent, pos):
room = self.getRoom(pos)
room.agentsInRoom.append(agent)
def popAgentRoom(self, agent, pos):
room = self.getRoom(pos)
room.agentsInRoom.remove(agent)
def getLightWithRoom(self, room):
for light in self.lights:
if light.room == room:
return light
return False
def crossDoor(self, agent, room1, room2):
numb = random.randint(0, 10)
for door in self.doors:
if ((door.room1 == room1 and door.room2 == room2) or (door.room1 == room2 and door.room2 == room1)):
if agent.leftClosedDoor >= numb:
door.state = False
else:
door.state = True
def getMatrix(self,agent):
new_matrix = configuration.defineOccupancy.returnMatrix(agent, self.clock.clock)
agent.markov_matrix = new_matrix
def getTimeInState(self, agent):
matrix_time_in_state = configuration.defineOccupancy.getTimeInState(agent, self.clock.clock)
return matrix_time_in_state
def end_work(self, agent, pc):
change = configuration.defineOccupancy.environmentBehaviour(agent, self.clock.clock, 'pc')[int(agent.environment)-1]
print(change)
if change == 'off':
pc.turn_off()
elif change == 'standby':
pc.turn_standby()
else:
pass
def switchLights(self, agent, currentRoom, nextRoom):
change = configuration.defineOccupancy.environmentBehaviour(agent, self.clock.clock, 'light')[int(agent.environment)-1]
light_switch_on = nextRoom.light
if light_switch_on != False and light_switch_on.state == 'off':
light_switch_on.switch_on()
if change == 'off':
light_switch_off = currentRoom.light
if self.ThereIsOtherOccupantInRoom(currentRoom, agent) == False:
if light_switch_off != False:
light_switch_off.switch_off()
else:
pass
def step(self):
if (self.running == False):
os.system("kill -9 %d"%(os.getppid()))
os.killpg(os.getpgid(os.getppid()), signal.SIGTERM)
if (self.clock.day == 5):
self.energy.finalDay(self.NStep)
self.energy.finalWeek()
self.running = False
if self.voting_method:
self.log.collectEnergyValues(self, self.energy.energyByDayTotal, self.energy.energyByDayHVAC, self.energy.energyByDayLPC, configuration.settings.time_by_step, self.energy.energyByStepTotal, self.energy.energyByStepHVACsTotal, self.energy.energyByStepLPCTotal)
self.log.collectComfortValues(self, configuration.settings.time_by_step, self.agentSatisfationByStep, self.fangerSatisfationByStep)
self.log.collectScheduleValues(self, configuration.settings.time_by_step, self.agentsActivityByTime)
self.log.collectSatisfactionValues(self, configuration.settings.time_by_step, self.totalSatisfationByTime, self.averageSatisfationByTime)
else:
self.log.collectEnergyValues(self.modelWay, self.energy.energyByDayTotal, self.energy.energyByDayHVAC, self.energy.energyByDayLPC, configuration.settings.time_by_step, self.energy.energyByStepTotal, self.energy.energyByStepHVACsTotal, self.energy.energyByStepLPCTotal)
self.log.collectComfortValues(self.modelWay, configuration.settings.time_by_step, self.agentSatisfationByStep, self.fangerSatisfationByStep)
self.log.collectScheduleValues(self.modelWay, configuration.settings.time_by_step, self.agentsActivityByTime)
self.log.collectSatisfactionValues(self.modelWay, configuration.settings.time_by_step, self.totalSatisfationByTime, self.averageSatisfationByTime)
if self.modelWay == 0:
self.log.saveScheduleRooms(self.roomsSchedule)
dictAgents = {}
for agent in self.agents:
agent.scheduleLog.append([self.day, agent.arrive, agent.leave])
scheduleByDay = {}
for e in agent.scheduleLog:
d = 'day'+str(e[0])
scheduleByDay[d] = {'arrive':e[1], 'leave': e[2]}
posByState = {}
for k,v in agent.positionByState.items():
posByState[k] = v
dictAgents[str(agent.unique_id)] = {'TComfort': agent.TComfort, 'posByState': posByState, 'schedule': scheduleByDay}
self.log.saveOccupantsValues(dictAgents)
return
if self.modelWay == 0 or self.modelWay == 1:
for hvac in self.HVACs:
if ((self.clock.clock > (configuration.defineMap.ScheduleByTypeRoom.get(hvac.thermalZone.rooms[0].typeRoom)[0])) and (configuration.defineMap.ScheduleByTypeRoom.get(hvac.thermalZone.rooms[0].typeRoom)[1]> self.clock.clock)):
hvac.working = True
else:
hvac.working = False
elif self.modelWay == 2:
for hvac in self.HVACs:
for hours in hvac.thermalZone.schedule[self.clock.day]:
if hours != [False]:
if ((self.clock.getCorrectHour(self.clock.clock+configuration.settings.timeSetOnHVACBeforeGetT))>hours[0]) and ((self.clock.getDownCorrectHour(hours[1]-configuration.settings.timeSetOffHVACBeforeloseT)) > self.clock.clock):
hvac.working = True
elif ((hvac.thermalZone.rooms[0].typeRoom == 'class') and ((self.clock.getCorrectHour(self.clock.clock+configuration.settings.timeSetOnHVACBeforeGetTClass))>hours[0]) and ((self.clock.getDownCorrectHour(hours[1]-configuration.settings.timeSetOffHVACBeforeloseT)) > self.clock.clock)):
hvac.working = True
else:
usr = False
if self.clock.getDownCorrectHour(hours[1]) > self.clock.clock:
for room in hvac.thermalZone.rooms:
if self.ThereIsSomeOccupantInRoom(room) == True:
usr = True
if usr == True:
hvac.working = True
else:
hvac.working = False
else:
hvac.working = False
#Temperature in TZ
if(self.timeToSampling == 'init'):
for tz in self.thermalZones:
tz.getQ(self, configuration.settings.timeToSampling)
self.timeToSampling = configuration.settings.timeToSampling*(1/configuration.settings.time_by_step)
elif(self.timeToSampling > 1):
self.timeToSampling = self.timeToSampling - 1
else:
for tz in self.thermalZones:
tz.step()
tz.getQ(self, configuration.settings.timeToSampling)
self.timeToSampling = configuration.settings.timeToSampling*(1/configuration.settings.time_by_step)
self.schedule.step()
#Rooms occupancy
time = self.clock.clock
day = self.clock.day
for room in self.rooms:
if len(room.agentsInRoom) > 0 and room.typeRoom != 'out' and room.typeRoom != 'restRoom':
self.roomsSchedule.append([room.name, day, time])
#Satisfation collection
time = configuration.settings.time_by_step*self.NStep
sumat = 0
number = 0
for agent in self.agents:
if self.getRoom(agent.pos).typeRoom != 'out' and self.getRoom(agent.pos).typeRoom != 'restroom' and self.getRoom(agent.pos).typeRoom != 'hall' and self.getRoom(agent.pos).typeRoom != 'corridor':
sumat = sumat + agent.comfort
number = number + 1
if number > 0:
self.agentSatisfationByStep.append(sumat/number)
else:
self.agentSatisfationByStep.append(0)
sumat = 0
number = 0
for hvac in self.HVACs:
varaux = False
for room in hvac.thermalZone.rooms:
if self.ThereIsSomeOccupantInRoom(room) and room.typeRoom != 'out' and room.typeRoom != 'restroom' and room.typeRoom != 'corridor' and room.typeRoom != 'hall':
varaux = True
if varaux == True:
sumat = sumat + hvac.fangerValue
number = number + 1
if number > 0:
self.fangerSatisfationByStep.append(sumat/number)
else:
self.fangerSatisfationByStep.append(0)
# Satisfaction SC
if self.voting_method:
time = configuration.settings.time_by_step*self.NStep
sumat = 0
number = 0
for agent in self.agents:
if self.getRoom(agent.pos).typeRoom != 'out' and self.getRoom(agent.pos).typeRoom != 'restroom' and self.getRoom(agent.pos).typeRoom != 'hall' and self.getRoom(agent.pos).typeRoom != 'corridor':
sumat += agent.preference['{:.1f}'.format(self.getRoom(agent.pos).thermalZone.hvac.desiredTemperature)]
number += 1
self.totalSatisfationByTime.append(sumat)
if number > 0:
self.averageSatisfationByTime.append(sumat/number)
else:
self.averageSatisfationByTime.append(0)
#Ocupancy activity collection
time = configuration.settings.time_by_step*self.NStep
sumat = 0
number = 0
for agent in self.agents:
if (agent.state == 'working in my office') or (agent.state == 'in a meeting') or (agent.state == 'working in my laboratory') or (agent.state == 'giving class'):
sumat = sumat + 1
self.agentsActivityByTime.append(sumat)
if len(self.lightsOn) > 0 and (self.clock.clock > configuration.settings.offLights):
for light in self.lightsOn:
light.switch_off()
self.energy.finalStep()
if (self.clock.day > self.day):
self.energy.finalDay(self.NStep)
if self.modelWay == 0:
for agent in self.agents:
timeA = self.clock.getDownCorrectHour(agent.arrive - 0.10)
timeB = self.clock.getDownCorrectHour(agent.leave - 0.10)
agent.scheduleLog.append([self.day, timeA, timeB])
agent.arrive = False
agent.leave = False
if self.occupantsValues != False:
for agent in self.agents:
day = 'day' + str(self.day + 1)
agent.behaviour['arriveTime'] = self.occupantsValues[str(agent.unique_id)]['schedule'][day]['arrive']
agent.behaviour['leaveWorkTime'] = self.occupantsValues[str(agent.unique_id)]['schedule'][day]['leave']
self.day = self.day + 1
self.NStep = self.NStep + 1 | mit |
CvetoslavSimeonov/TelerikAcademy | C#/1-Intro-Programming-Homework/18.Homework10/Program.cs | 100 | using System;
class Homework10
{
static void Main()
{
double c = -2.3;
}
}
| mit |
tockri/scala-quiz | src/test/scala/common/DBFixture.scala | 1577 | package common
import infra.{GroupDao, GroupMemberDao, MemberDao}
import entity.{Group, Member}
import org.joda.time.{DateTime, LocalDate}
import scalikejdbc._
/**
* H2 Databaseへの接続、テーブルの作成
*/
object DBFixture {
Class.forName("org.h2.Driver")
ConnectionPool.singleton("jdbc:h2:mem:scalikejdbc","user","pass")
GlobalSettings.loggingSQLAndTime = LoggingSQLAndTimeSettings(
enabled = true,
singleLineMode = true,
logLevel = 'debug,
warningEnabled = true,
warningThresholdMillis = 1000L,
warningLogLevel = 'WARN
)
DB autoCommit { implicit session =>
SQL("""
create table `member` (
id bigint primary key auto_increment,
name varchar(30) not null,
created_at timestamp not null
);
create table `group` (
id bigint primary key auto_increment,
name varchar(30) not null,
created_at timestamp not null
);
create table group_member (
member_id bigint,
group_id bigint,
created_at timestamp not null,
primary key(member_id, group_id),
foreign key(member_id) references `member`(id) on delete cascade,
foreign key(group_id) references `group`(id) on delete cascade
);
""").execute.apply()
val g1 = GroupDao.insert(Group("Backlog team"))
val g2 = GroupDao.insert(Group("Cacoo team"))
val m1 = MemberDao.insert(Member("Alice"))
val m2 = MemberDao.insert(Member("Bob"))
GroupMemberDao.insert(g1.id, m1.id)
GroupMemberDao.insert(g1.id, m2.id)
GroupMemberDao.insert(g2.id, m2.id)
}
}
| mit |
koto-bank/zeph | assets/js/main.js | 7027 | var LOAD_AT_A_TIME = 25;
var TAGS_SET = false;
var DONE_LOADING = false;
var LOADING_IN_PROGRESS = false;
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { callback(xmlHttp.responseText); }
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
function setAttrs(elem, attrs) {
for (var a in attrs) {
elem.setAttribute(a, attrs[a]);
}
}
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
function loadMore() {
LOADING_IN_PROGRESS = true;
var image_block = document.getElementById("images");;
var query = "/more?offset="+image_block.children.length;
var spinner = document.createElement("div");
spinner.className = "spinner";
image_block.appendChild(spinner);
if (window.location.pathname.startsWith("/search")) {
query = query + "&q=" + getUrlParameter("q");
}
httpGetAsync(query, function(text){
var body = JSON.parse(text);
if (body.length < LOAD_AT_A_TIME) {
DONE_LOADING = true;
}
image_block.removeChild(spinner);
body.forEach(function(image) {
var link = document.createElement("a");
link.href = "/show/"+image.id;
link.target = "_blank";
var im = document.createElement("div");
im.title = image.tags.join(" ");
im.className = "thumbnail";
im.style.backgroundImage = "url(\"/images/preview/"+image.name+"\")";
link.appendChild(im);
image_block.appendChild(link);
});
if (!TAGS_SET) {
var imgs = Array.from(document.getElementsByClassName("thumbnail"));
var tags_block = document.getElementById("tags");
var tags = new Set(imgs.reduce(function(arr, im) {
arr.push(im.title.split(" ")[0]);
return arr;
},[]));
tags.forEach(function(tag) {
var link = document.createElement("a");
link.textContent = tag;
link.href = "/search?q=" + tag;
tags_block.appendChild(link);
tags_block.appendChild(document.createElement("br"));
});
TAGS_SET = true
}
LOADING_IN_PROGRESS = false;
});
}
function drawUploadOrLogin() {
var main_form = document.getElementById("login-or-upload-form");
var upload_button = document.getElementById("upload-button");
httpGetAsync("/user_status", function(text){
var body = JSON.parse(text);
if (body["logined"] == false) {
var form = document.createElement("form");
setAttrs(form, {
action: "/login",
method: "POST"
});
var login = document.createElement("input");
setAttrs(login,{
type: "text",
name: "login",
placeholder: "Login"
});
var pass = document.createElement("input");
setAttrs(pass, {
type: "password",
name: "password",
placeholder: "Password"
});
var confirm_pass = document.createElement("input");
setAttrs(confirm_pass, {
type: "password",
name: "confirm_password",
placeholder: "Confirm password"
});
var confirm_pass_br = document.createElement("br");
var sbm = document.createElement("input");
setAttrs(sbm, {
type: "submit",
value: "Login"
});
var lor = document.createElement("button");
lor.textContent = "Sign up";
lor.onclick = function() {
if (lor.textContent == "Sign up") {
lor.textContent = "Sign in";
sbm.value = "Register";
login.placeholder = "New login";
pass.placeholder = "New password";
form.action = "/adduser";
form.insertBefore(confirm_pass, sbm);
form.insertBefore(confirm_pass_br, sbm);
} else {
lor.textContent = "Sign up";
sbm.value = "Login";
login.placeholder = "Login";
pass.placeholder = "Password";
form.action = "/login";
try {
form.removeChild(confirm_pass);
form.removeChild(confirm_pass_br);
} catch(err) { }
}
}
main_form.appendChild(lor);
form.appendChild(login);
form.appendChild(pass);
form.appendChild(sbm);
main_form.appendChild(form);
} else {
upload_button.textContent = "Upload image (as " + body["name"] + ")";
var form = document.createElement("form");
setAttrs(form, {
action: "/upload_image",
method: "POST",
enctype: "multipart/form-data"
});
var file = document.createElement("input");
setAttrs(file, {
type: "file",
name: "image",
accept: "image/*"});
var tags = document.createElement("input");
setAttrs(tags,{
type: "text",
name: "tags",
placeholder: "Space separated tags"});
var sbm = document.createElement("input");
setAttrs(sbm,{
type: "submit",
value: "Upload"});
form.appendChild(file);
form.appendChild(tags);
form.appendChild(sbm);
main_form.appendChild(form);
}
});
}
function showUploadOrLogin() {
var form = document.getElementById("login-or-upload-form");
if (form.style.bottom != "7%") {
form.style.bottom = "7%";
} else {
form.style.bottom = "-100%";
}
}
window.onload = function() {
loadMore();
drawUploadOrLogin();
document.getElementById("tag-search-field").value = getUrlParameter("q");
}
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
if (!DONE_LOADING && !LOADING_IN_PROGRESS){
loadMore();
}
}
};
| mit |
deep0892/jitendrachatbot | packages/rocketchat-lib/server/methods/chatbot/getResponseFromapiai.js | 22325 | const apiai = require('apiai');
const streamer = new Meteor.Streamer('ResponseParams');
streamer.allowRead('all');
var _ = require('underscore');
Meteor.methods({
getResponseFromapiai(text, rid, custinfo, newroom, action = null, Notagent = true) {
var finallog = rid;
var strattime = new Date();
console.log('start of getResponseFromapiai for roomid: ' + rid + ' Text: ' + text + ' & Action: ' + action);
var dynamicMessageSent = false;
var room = RocketChat.models.Rooms.findOneById(rid);
finallog = finallog + ' ,Rooms Response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
var chatType = 0 //CI;
var hidequotes = false;
var direct = 0;
if (custinfo.manual == 1 && newroom) {
text = 'startchat';
}
if (custinfo.cb == 1 && custinfo.manual != 1) {
hidequotes = true;
direct = 1;
}
var AIAgentId = custinfo.AIAgent;
var leadid = custinfo.leadid;
var chatleadid = custinfo.chatleadid;
if (room && room.cb && room.cb == 1) {
//Mark PB Typing: Start
var parameterOdj = {
msg: 'pbtyping',
parameter: true
}
streamer.emit(rid, parameterOdj);
//Mark PB Typing: End
finallog = finallog + ' ,markRoom Response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
var callevent = false;
var defaultparams = null;
var agentdata = RocketChat.models.LivechatbotAIAgents.getAIAgentDatabyId(AIAgentId);
var userinput = RocketChat.models.LivechatbotUserInput.findOne({
_id: rid
});
finallog = finallog + ' ,Agentuserinput response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
var defaultAction = agentdata.IntentName;
var DeveloperAccessToken = agentdata.DeveloperAccessToken;
if (newroom === false && userinput && userinput.params) {
defaultparams = userinput.params;
} else {
var cjurl = RocketChat.getCjUrl(AIAgentId);
var url = cjurl + "GetDefaultParameters?LeadId=" + chatleadid + "&RoomId=" + rid;
console.log('GetDefaultParameters - ' + url);
try {
defaultparams = HTTP.call("GET", url, {
headers: {
"accept": "application/json"
}
}).data;
defaultparams = RocketChat.ProcessDefaultParameter(defaultparams);
finallog = finallog + ' ,Default param response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
} catch (e) {
RocketChat.models.LivechatErrorlogs.insertLog(rid, 'CJ Api GetDefaultParameters GET', url, null, e);
}
}
if (defaultparams && defaultparams.IsRecommendation) {
hidequotes = false;
}
var previousResponse = null;
var LastResponse = RocketChat.models.LivechatChatbotMessages.getLastMessage(rid);
finallog = finallog + ' ,getlast message response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
if (LastResponse) {
previousResponse = JSON.parse(LastResponse.response);
}
const app = apiai(agentdata.ClentAccessToken);
var customerreplytime = new Date();
var customerreply = text;
var callNextIntent = false;
let options = {
sessionId: rid,
};
let request;
if (action && action != null) {
event = {
name: action,
data: defaultparams
};
request = app.eventRequest(event, options);
} else {
event = null;
request = app.textRequest(text, options);
}
request.on('response', Meteor.bindEnvironment(function(response, errror) {
finallog = finallog + ' ,api.AI response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
var isFieldValidated = true;
var responseparams = response.result.parameters;
var botreply = response.result.fulfillment.speech;
var msgForCust = response.result.fulfillment.messages;
var intentId = response.result.metadata.intentId;
var botreplytime = new Date();
action = response.result.metadata.intentName;
var actionstatus = response.result.actionIncomplete;
var contexts = response.result.contexts;
RocketChat.saveChatbotResponse(rid, customerreply, botreply, new Date(), customerreplytime, botreplytime, action, actionstatus, intentId, JSON.stringify(responseparams), JSON.stringify(response), event);
// Check for the plan selected by customer is from the list shown
if (defaultparams && defaultparams.SelectionType != 'CJ' && actionstatus == false && action == 'Quote-SelectPlan' && responseparams && responseparams.SelectedInsurer) {
isFieldValidated = RocketChat.selectPlanByCustomer(rid, responseparams.SelectedInsurer, response, defaultAction, defaultparams, leadid, chatleadid);
}
// Check validation for the input given by customer.
var result, fieldValue;
if (event == null && isFieldValidated && chatleadid && previousResponse && previousResponse.result && previousResponse.result.metadata.intentName == response.result.metadata.intentName) {
fieldValue = response.result.resolvedQuery;
result = RocketChat.getFieldNameForValidation(previousResponse);
if (result && result.intent) {
isFieldValidated = RocketChat.callValidationApi(chatleadid, rid, result.intent, fieldValue, room.departmentname, AIAgentId);
finallog = finallog + ' ,validation response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
}
}
//Start of logic - check for validation failure for customer input
if (isFieldValidated == false) {
var reply = RocketChat.settings.get('ValidationFailureMessage');
RocketChat.sendMessageByBot(rid, reply, true);
console.log("Validation failed");
RocketChat.deleteContext(rid, DeveloperAccessToken);
Meteor.defer(function() {
Meteor.call('logChatbotStop', rid, leadid, customerreply, action, responseparams, defaultparams, function(error, response) {});
});
RocketChat.models.Rooms.stopChatbot(rid, 0);
RocketChat.models.Subscriptions.markBotOff(rid);
callNextIntent = true;
callevent = false;
} else {
//Emit event for customer actions Start
if (result && result.intent && fieldValue) {
var field = result.intent;
var realName = _.findKey(responseparams, function(value, key) {
return key.toLowerCase() === field.toLowerCase();
});
var parameterOdj = {
msg: 'proposaldetails',
parameter: result.intent,
value: responseparams[realName],
rid: rid
}
streamer.emit(rid, parameterOdj);
}
//Emit event for customer actions End
RocketChat.UpdateActiveIntents(rid, intentId, action, actionstatus);
var contextinfo = RocketChat.getFieldNameForValidation(response);
var dynamicmapping = null;
if (contextinfo && contextinfo.intent && contextinfo.contextName && actionstatus == true) {
var entity = contextinfo.intent.toLowerCase();
dynamicmapping = RocketChat.models.LivechatDynamicListMapping.findByIntentEntity(action, entity);
finallog = finallog + ' ,dynamicmapping response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
}
console.log('Rule Engine Call Start at: ' + new Date());
var RuleEngineRequest = {
data: {
"requestData": {
"current_response": response,
"previous_response": previousResponse,
"default_params": defaultparams,
"response_params": responseparams,
"AIAgentId": AIAgentId,
"direct": direct,
"Notagent": Notagent
}
}
};
var listOutput = RocketChat.CallRulEngine(RuleEngineRequest);
finallog = finallog + ' ,RuleEngine response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
console.log('Rule Engine Call End at: ' + new Date());
console.log("RuleEngine output: ");
console.log(JSON.stringify(listOutput));
RocketChat.updateUserInput_APIAI(rid, defaultAction, defaultparams, responseparams, leadid, false, chatleadid)
if (listOutput) {
listOutput.forEach(function(ruleoutput) {
console.log('ruleoutput');
console.log(JSON.stringify(ruleoutput));
var additionalparams = ruleoutput.userinputparams;
if (ruleoutput && ruleoutput.userinputparams && additionalparams) {
RocketChat.updateUserInput_APIAI(rid, defaultAction, defaultparams, additionalparams, leadid, true, chatleadid)
}
switch (ruleoutput.type) {
case "eventcall":
if (ruleoutput.eventName) {
action = ruleoutput.eventName;
}
callevent = true;
break;
case "CJApiCall":
RocketChat.getEntitieslist_APIAI(response, action, rid, ruleoutput, AIAgentId);
finallog = finallog + ' ,CJApiCall response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
break;
case "SkipIntent":
RocketChat.UpdateActiveIntents(rid, ruleoutput.intentId, ruleoutput.intentname, false);
if (intentId == ruleoutput.intentId && action == ruleoutput.intentname) {
response.result.actionIncomplete = false;
}
break;
case "sendMessageToCustomer":
var message = null;
if (ruleoutput.Ignorebotreply) {
message = ruleoutput.staticmessage;
} else {
if (ruleoutput.staticmessage) {
if (ruleoutput.botreply == "pre")
message = response.result.fulfillment.speech + ruleoutput.staticmessage
else if (ruleoutput.botreply == "post")
message = ruleoutput.staticmessage + response.result.fulfillment.speech
} else if (ruleoutput.InsInfo) {
var InsurerPointer = RocketChat.models.LivechatTooltip.findOne({
_id: "InsurerPointer"
});
var userinput = RocketChat.models.LivechatbotUserInput.findOne({
_id: rid
});
message = InsurerPointer.value[userinput.params.SelectedInsurer.toLowerCase()];
} else {
message = response.result.fulfillment.speech;
console.log("sendMessageToCustomer: " + message);
}
}
finallog = finallog + ' ,sendMessageByBot request - ' + new Date();
var botoff = false;
if (ruleoutput.botoff == true) {
botoff = true;
}
RocketChat.sendMessageByBot(rid, message, botoff);
finallog = finallog + ' ,sendMessageByBot response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
break;
case "sendDynamicControls":
var message = null;
finallog = finallog + ' ,sendDynamicComponentByBot request - ' + new Date();
RocketChat.getEntitieslist_APIAI(response, action, rid, ruleoutput, AIAgentId);
finallog = finallog + ' ,sendDynamicComponentByBot response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
break;
case "ApiAIMethodCall":
finallog = finallog + ' ,ApiAIMethodCall request - ' + new Date();
RocketChat.getEntitieslist_APIAI(response, action, rid, ruleoutput, AIAgentId);
finallog = finallog + ' ,ApiAIMethodCall response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
break;
case "SetFlagTrue":
callNextIntent = true;
callevent = false;
break;
case "LocalMethodCall":
finallog = finallog + ' ,LocalMethodCall request - ' + new Date();
RocketChat.getEntitieslist_APIAI(response, action, rid, ruleoutput, AIAgentId);
finallog = finallog + ' ,LocalMethodCall response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
break;
case "DateFormatCall":
finallog = finallog + ' ,DateFormatCall request - ' + new Date();
RocketChat.getEntitieslist_APIAI(response, action, rid, ruleoutput, AIAgentId);
finallog = finallog + ' ,DateFormatCall response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
break;
case "chatbotoff":
Meteor.defer(function() {
Meteor.call('logChatbotStop', rid, leadid, customerreply, action, responseparams, defaultparams, function(error, response) {});
});
callNextIntent = true;
RocketChat.models.Rooms.stopChatbot(rid, 0);
RocketChat.models.Subscriptions.markBotOff(rid);
callevent = false;
break;
case "hidemsg":
finallog = finallog + ' ,hidemsg request - ' + new Date();
RocketChat.sendHiddenMessageByBot(rid, ruleoutput.msgType);
finallog = finallog + ' ,hidemsg response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
break;
case "showloader":
finallog = finallog + ' ,showloader request - ' + new Date();
var msgid = Random.id();
msgObject = {
_id: msgid,
rid: rid,
msg: ruleoutput.msg,
type: ruleoutput.msg,
hide: false,
username: 'PBee'
};
Meteor.call('sendMessage', msgObject);
finallog = finallog + ' ,showloader response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
break;
case "hideloader":
finallog = finallog + ' ,hideloader request - ' + new Date();
RocketChat.models.Messages.setMessageHide(rid, ruleoutput.msg)
finallog = finallog + ' ,hideloader response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
break;
default:
console.log("no case match for this rule");
}
if (ruleoutput.breakrule == true)
return;
}, this);
} else {
console.log('no rule found, send message from api.ai to customer');
if (msgForCust && msgForCust.length > 0) {
msgForCust.forEach(function(msg) {
console.log(msg.speech);
RocketChat.sendMessageByBot(rid, msg.speech);
});
}
}
}
if (callevent == false && response.result.actionIncomplete == false && callNextIntent == false) {
var nextIntent = RocketChat.findNextIntentToCall(rid, AIAgentId, intentId, action, callevent, defaultAction);
action = nextIntent.action;
callevent = nextIntent.callevent;
}
var parameterOdj = {
msg: 'pbtyping',
parameter: false
}
streamer.emit(rid, parameterOdj);
if (callevent === true) {
Meteor.call('getResponseFromapiai', null, rid, custinfo, false, action, function(error, response) {});
}
finallog = finallog + ' ,end event response - ' + Math.abs(strattime.getTime() - (new Date()).getTime());
strattime = new Date();
RocketChat.models.LivechatbotLogs.insert({
rid: rid,
finallog: finallog,
strattime: strattime,
ts: new Date()
});
},
function(error) {
console.log(error);
}));
request.end();
} else {
return true;
}
}
}); | mit |
Yuvasee/Stork-CRM | resources/views/clients/edit.blade.php | 12909 | @extends('adminlte::layouts.app')
@section('htmlheader_title')
{{ trans('adminlte_lang::message.clients') }} - {{ $client->name }}
@endsection
@section('contentheader_title')
{{ $client->name }}
@endsection
@section('breadcrumbs')
{!! Breadcrumbs::render('clients.edit', $client) !!}
@endsection
@section('main-content')
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#info-tab" aria-controls="info-tab" role="tab" data-toggle="tab">Информация</a></li>
<li role="presentation"><a href="#past-tab" aria-controls="past-tab" role="tab" data-toggle="tab">Прошедшие события</a></li>
<li role="presentation"><a href="#future-tab" aria-controls="future-tab" role="tab" data-toggle="tab">Планируемые события</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Информация -->
<div role="tabpanel" class="tab-pane active" id="info-tab">
<div class="row">
<div class="col-lg-6">
<div class="box box-primary">
<div class="box-body">
@if ($errors->any())
<ul class="alert alert-danger">
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
{!! Form::model($client, [
'method' => 'PATCH',
'url' => ['/clients', $client->id],
'files' => true
]) !!}
@include ('clients.form', ['submitButtonText' => trans('adminlte_lang::message.update')])
{!! Form::close() !!}
<div class="row">
<div class="col-md-6">
<p><b>{{ trans('adminlte_lang::message.creationdate') }}:</b> {{ $client->created_at->format('d.m.Y') }}<br/>
<b>{{ trans('adminlte_lang::message.creator') }}:</b> {{ $client->createdBy->name }}</p>
</div>
<div class="col-md-6" style="text-align: right;">
{!! Form::open([
'method'=>'DELETE',
'url' => ['/clients', $client->id],
'style' => 'display:inline'
]) !!}
{!! Form::button('<i class="fa fa-trash-o" aria-hidden="true"></i>', array(
'type' => 'submit',
'class' => 'btn btn-danger btn-xs',
'title' => 'Delete Action',
'onclick'=>'return confirm("' . trans('adminlte_lang::message.confirmdelete') . '?")'
)) !!}
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
@foreach($contactPersons as $contactPerson)
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title"><i class="fa fa-user"></i> {{ $contactPerson['contact_name' . $contactPerson['id']] }}</h3>
</div>
<div class="box-body">
{!! Form::model($contactPerson, [
'method' => 'PATCH',
'url' => ['/contact-persons', $contactPerson['id']],
]) !!}
<div class="form-group {{ $errors->has('contact_name' . $contactPerson['id']) ? 'has-error' : ''}}">
{!! Form::label('contact_name' . $contactPerson['id'], trans('adminlte_lang::message.contactname')) !!}
{!! Form::text('contact_name' . $contactPerson['id'], null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('contact_name' . $contactPerson['id'], '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('phone_work' . $contactPerson['id']) ? 'has-error' : ''}}">
{!! Form::label('phone_work' . $contactPerson['id'], trans('adminlte_lang::message.phonework')) !!}
{!! Form::text('phone_work' . $contactPerson['id'], null, ['class' => 'form-control']) !!}
{!! $errors->first('phone_work' . $contactPerson['id'], '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('phone_mobile' . $contactPerson['id']) ? 'has-error' : ''}}">
{!! Form::label('phone_mobile' . $contactPerson['id'], trans('adminlte_lang::message.phonemob')) !!}
{!! Form::text('phone_mobile' . $contactPerson['id'], null, ['class' => 'form-control']) !!}
{!! $errors->first('phone_mobile' . $contactPerson['id'], '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('contact_email' . $contactPerson['id']) ? 'has-error' : ''}}">
{!! Form::label('contact_email' . $contactPerson['id'], trans('adminlte_lang::message.email')) !!}
{!! Form::text('contact_email' . $contactPerson['id'], null, ['class' => 'form-control']) !!}
{!! $errors->first('contact_email' . $contactPerson['id'], '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('notes' . $contactPerson['id']) ? 'has-error' : ''}}">
{!! Form::label('notes' . $contactPerson['id'], trans('adminlte_lang::message.notes')) !!}
{!! Form::textarea('notes' . $contactPerson['id'], null, ['class' => 'form-control', 'rows' => '2']) !!}
{!! $errors->first('notes' . $contactPerson['id'], '<p class="help-block">:message</p>') !!}
</div>
{!! Form::hidden('client_id', $client->id) !!}
<div class="form-group">
{!! Form::button('<i class="fa fa-save" aria-hidden="true"></i> ' . trans('adminlte_lang::message.save'), [
'type' => 'submit',
'class' => 'btn btn-success btn-xs',
'title' => trans('adminlte_lang::message.save'),
]) !!}
<a href="{{ url('/contact-persons/' . $contactPerson['id'] . '/delete?client_id=' . $client->id) }}" title="{{ trans('adminlte_lang::message.delete') }}" onclick="return confirm('{{ trans('adminlte_lang::message.confirmdelete') }}?')"><button class="btn btn-danger btn-xs" type="button"><i class="fa fa-trash-o"></i> {{ trans('adminlte_lang::message.delete') }}</button></a>
</div>
{!! Form::close() !!}
</div>
</div>
@endforeach
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title"><i class="fa fa-user"></i> Новое контактное лицо</h3>
</div>
<div class="box-body">
{!! Form::open(['url' => '/clients/' . $client->id . '/new-contact']) !!}
<div class="form-group {{ $errors->has('contact_name_new') ? 'has-error' : ''}}">
{!! Form::label('contact_name_new', trans('adminlte_lang::message.contactname')) !!}
{!! Form::text('contact_name_new', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('contact_name_new', '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('phone_work_new') ? 'has-error' : ''}}">
{!! Form::label('phone_work_new', trans('adminlte_lang::message.phonework')) !!}
{!! Form::text('phone_work_new', null, ['class' => 'form-control']) !!}
{!! $errors->first('phone_work_new', '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('phone_mobile_new') ? 'has-error' : ''}}">
{!! Form::label('phone_mobile_new', trans('adminlte_lang::message.phonemob')) !!}
{!! Form::text('phone_mobile_new', null, ['class' => 'form-control']) !!}
{!! $errors->first('phone_mobile_new', '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('contact_email_new') ? 'has-error' : ''}}">
{!! Form::label('contact_email_new', trans('adminlte_lang::message.email')) !!}
{!! Form::text('contact_email_new', null, ['class' => 'form-control']) !!}
{!! $errors->first('contact_email_new', '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group {{ $errors->has('notes_new') ? 'has-error' : ''}}">
{!! Form::label('notes_new', trans('adminlte_lang::message.notes')) !!}
{!! Form::textarea('notes_new', null, ['class' => 'form-control', 'rows' => '2']) !!}
{!! $errors->first('notes_new', '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group">
{!! Form::button('<i class="fa fa-save" aria-hidden="true"></i> ' . trans('adminlte_lang::message.save'), [
'type' => 'submit',
'class' => 'btn btn-success btn-xs',
'title' => trans('adminlte_lang::message.save'),
]) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
<!-- Прошедшие события -->
<div role="tabpanel" class="tab-pane" id="past-tab">
@include ('clients._actions', ['actions' => $actionsPast, 'tab' => 'past-tab', 'status' => '1'])
</div>
<!-- Планируемые события -->
<div role="tabpanel" class="tab-pane" id="future-tab">
@include ('clients._actions', ['actions' => $actionsFuture, 'tab' => 'future-tab', 'status' => '0'])
</div>
</div>
</div>
@endsection
@section('scripts')
@parent
<script>
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
} //add a suffix
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
window.scrollTo(0, 0);
})
</script>
@endsection | mit |
tennosys/autoworks | config/assets/production.js | 988 | 'use strict';
module.exports = {
client: {
lib: {
css: [
'public/lib/angular-material/angular-material.min.css',
'public/lib/material-design-iconic-font/dist/css/material-design-iconic-font.min.css'
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-animate/angular-animate.min.js',
'public/lib/angular-file-upload/dist/angular-file-upload.min.js',
'public/lib/angular-messages/angular-messages.min.js',
'public/lib/angular-mocks/angular-mocks.js',
'public/lib/angular-resource/angular-resource.min.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
'public/lib/angular-aria/angular-aria.min.js',
'public/lib/angular-material/angular-material.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
}
};
| mit |
poly-mer/community | app/shared/empty/empty.service.ts | 667 | import { Injectable } from "@angular/core";
import * as firebase from "nativescript-plugin-firebase";
import "rxjs/add/operator/map";
import { ErrorObservable } from "rxjs/observable/ErrorObservable";
import { Observable } from "rxjs/Rx";
// import { Config } from '../config';
@Injectable()
export class EmptyService {
constructor() { }
load() {
return Observable.fromPromise(firebase.getCurrentUser())
.map((res) => res.email)
.catch(this.handleErrors);
}
private handleErrors(error: Response): ErrorObservable {
console.log(JSON.stringify(error.json()));
return Observable.throw(error);
}
}
| mit |
fvasquezjatar/fermat-unused | fermat-android-core/src/main/java/com/bitdubai/android_core/app/common/version_1/tabbed_dialog/TabbedDialogFragment.java | 3981 | package com.bitdubai.android_core.app.common.version_1.tabbed_dialog;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import com.bitdubai.fermat.R;
//import com.astuetz.PagerSlidingTabStrip;
//import com.astuetz.PagerSlidingTabStrip.IconTabProvider;
// TODO: RAul; Estas tres clases son la implemtacion de este tipo de tabs que la sacamos de algun lado. No hay mucho que hacer mas que ponerlas mas prolijas y ver si hace falta mejorar el reporte de excepciones.
public class TabbedDialogFragment extends DialogFragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private ContactPagerAdapter adapter;
public static TabbedDialogFragment newInstance() {
TabbedDialogFragment f = new TabbedDialogFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getDialog() != null) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
View root = inflater.inflate(R.layout.wallet_framework_activity_framework_tabbed_dialog, container, false);
tabs = (PagerSlidingTabStrip) root.findViewById(R.id.tabs);
pager = (ViewPager) root.findViewById(R.id.pager);
adapter = new ContactPagerAdapter();
pager.setAdapter(adapter);
tabs.setViewPager(pager);
tabs.setIndicatorHeight(5);
return root;
}
@SuppressWarnings("deprecation")
@Override
public void onStart() {
super.onStart();
// change dialog width
if (getDialog() != null) {
int fullWidth = getDialog().getWindow().getAttributes().width;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
fullWidth = size.x;
} else {
Display display = getActivity().getWindowManager().getDefaultDisplay();
fullWidth = display.getWidth();
}
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
.getDisplayMetrics());
int w = fullWidth - padding;
int h = getDialog().getWindow().getAttributes().height;
getDialog().getWindow().setLayout(w, h);
}
}
public class ContactPagerAdapter extends PagerAdapter implements PagerSlidingTabStrip.IconTabProvider {
private final int[] ICONS = { R.drawable.icono_retailer_1, R.drawable.icono_club_2,
R.drawable.icono_club_1, R.drawable.icono_banco_2, R.drawable.icono_banco_1, R.drawable.ic_action_add_grey};
public ContactPagerAdapter() {
super();
}
@Override
public int getCount() {
return ICONS.length;
}
@Override
public int getPageIconResId(int position) {
return ICONS[position];
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// looks a little bit messy here
TextView v = new TextView(getActivity());
v.setBackgroundResource(R.drawable.background_tiled_diagonal_light);
v.setText("PAGE " + (position + 1));
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
.getDisplayMetrics());
v.setPadding(padding, padding, padding, padding);
v.setGravity(Gravity.CENTER);
container.addView(v, 0);
return v;
}
@Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View) view);
}
@Override
public boolean isViewFromObject(View v, Object o) {
return v == ((View) o);
}
}
}
| mit |
GreenCoinX/greencoin | src/test/allocator_tests.cpp | 3857 | // Copyright (c) 2012-2013 The GreenCoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "allocators.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(allocator_tests)
// Dummy memory page locker for platform independent tests
static const void *last_lock_addr, *last_unlock_addr;
static size_t last_lock_len, last_unlock_len;
class TestLocker
{
public:
bool Lock(const void *addr, size_t len)
{
last_lock_addr = addr;
last_lock_len = len;
return true;
}
bool Unlock(const void *addr, size_t len)
{
last_unlock_addr = addr;
last_unlock_len = len;
return true;
}
};
BOOST_AUTO_TEST_CASE(test_LockedPageManagerBase)
{
const size_t test_page_size = 4096;
LockedPageManagerBase<TestLocker> lpm(test_page_size);
size_t addr;
last_lock_addr = last_unlock_addr = 0;
last_lock_len = last_unlock_len = 0;
/* Try large number of small objects */
addr = 0;
for(int i=0; i<1000; ++i)
{
lpm.LockRange(reinterpret_cast<void*>(addr), 33);
addr += 33;
}
/* Try small number of page-sized objects, straddling two pages */
addr = test_page_size*100 + 53;
for(int i=0; i<100; ++i)
{
lpm.LockRange(reinterpret_cast<void*>(addr), test_page_size);
addr += test_page_size;
}
/* Try small number of page-sized objects aligned to exactly one page */
addr = test_page_size*300;
for(int i=0; i<100; ++i)
{
lpm.LockRange(reinterpret_cast<void*>(addr), test_page_size);
addr += test_page_size;
}
/* one very large object, straddling pages */
lpm.LockRange(reinterpret_cast<void*>(test_page_size*600+1), test_page_size*500);
BOOST_CHECK(last_lock_addr == reinterpret_cast<void*>(test_page_size*(600+500)));
/* one very large object, page aligned */
lpm.LockRange(reinterpret_cast<void*>(test_page_size*1200), test_page_size*500-1);
BOOST_CHECK(last_lock_addr == reinterpret_cast<void*>(test_page_size*(1200+500-1)));
BOOST_CHECK(lpm.GetLockedPageCount() == (
(1000*33+test_page_size-1)/test_page_size + // small objects
101 + 100 + // page-sized objects
501 + 500)); // large objects
BOOST_CHECK((last_lock_len & (test_page_size-1)) == 0); // always lock entire pages
BOOST_CHECK(last_unlock_len == 0); // nothing unlocked yet
/* And unlock again */
addr = 0;
for(int i=0; i<1000; ++i)
{
lpm.UnlockRange(reinterpret_cast<void*>(addr), 33);
addr += 33;
}
addr = test_page_size*100 + 53;
for(int i=0; i<100; ++i)
{
lpm.UnlockRange(reinterpret_cast<void*>(addr), test_page_size);
addr += test_page_size;
}
addr = test_page_size*300;
for(int i=0; i<100; ++i)
{
lpm.UnlockRange(reinterpret_cast<void*>(addr), test_page_size);
addr += test_page_size;
}
lpm.UnlockRange(reinterpret_cast<void*>(test_page_size*600+1), test_page_size*500);
lpm.UnlockRange(reinterpret_cast<void*>(test_page_size*1200), test_page_size*500-1);
/* Check that everything is released */
BOOST_CHECK(lpm.GetLockedPageCount() == 0);
/* A few and unlocks of size zero (should have no effect) */
addr = 0;
for(int i=0; i<1000; ++i)
{
lpm.LockRange(reinterpret_cast<void*>(addr), 0);
addr += 1;
}
BOOST_CHECK(lpm.GetLockedPageCount() == 0);
addr = 0;
for(int i=0; i<1000; ++i)
{
lpm.UnlockRange(reinterpret_cast<void*>(addr), 0);
addr += 1;
}
BOOST_CHECK(lpm.GetLockedPageCount() == 0);
BOOST_CHECK((last_unlock_len & (test_page_size-1)) == 0); // always unlock entire pages
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
melkio/wpc2014it | ARC005/Demo04.Barman/Program.cs | 769 | using MassTransit;
using System;
namespace Demo04.Barman
{
class Program
{
static void Main(String[] args)
{
Console.WriteLine("DEMO 04 - BARMAN");
Bus.Initialize(configuration =>
{
configuration.ReceiveFrom("rabbitmq://localhost/wpc2014/demo04-barman");
configuration.UseRabbitMqRouting();
configuration.SetConcurrentConsumerLimit(1);
configuration.UseJsonSerializer();
configuration.Subscribe(x =>
{
x.Consumer<OrderAcceptedGateway>();
x.Consumer<PrepareOrderCommandHandler>();
});
});
Console.ReadLine();
}
}
}
| mit |
napcs/qedserver | jetty/modules/jetty/src/test/java/org/mortbay/jetty/security/ConstraintTest.java | 11967 | //========================================================================
//$Id: HttpGeneratorTest.java,v 1.1 2005/10/05 14:09:41 janb Exp $
//Copyright 2004-2005 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
package org.mortbay.jetty.security;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.LocalConnector;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.servlet.SessionHandler;
/**
* @author gregw
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class ConstraintTest extends TestCase
{
Server _server = new Server();
LocalConnector _connector = new LocalConnector();
ContextHandler _context = new ContextHandler();
SessionHandler _session = new SessionHandler();
SecurityHandler _security = new SecurityHandler();
RequestHandler _handler = new RequestHandler();
UserRealm _realm = new TestUserRealm();
public ConstraintTest(String arg0)
{
super(arg0);
_server.setConnectors(new Connector[]{_connector});
_context.setContextPath("/ctx");
_server.setHandler(_context);
_context.setHandler(_session);
_session.setHandler(_security);
_security.setHandler(_handler);
Constraint constraint0 = new Constraint();
constraint0.setAuthenticate(true);
constraint0.setName("forbid");
ConstraintMapping mapping0 = new ConstraintMapping();
mapping0.setPathSpec("/forbid/*");
mapping0.setConstraint(constraint0);
Constraint constraint1 = new Constraint();
constraint1.setAuthenticate(true);
constraint1.setName("auth");
constraint1.setRoles(new String[]{Constraint.ANY_ROLE});
ConstraintMapping mapping1 = new ConstraintMapping();
mapping1.setPathSpec("/auth/*");
mapping1.setConstraint(constraint1);
_security.setUserRealm(_realm);
_security.setConstraintMappings(new ConstraintMapping[]
{
mapping0,mapping1
});
}
public static void main(String[] args)
{
junit.textui.TestRunner.run(ConstraintTest.class);
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
_server.start();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception
{
super.tearDown();
_server.stop();
}
public void testBasic()
throws Exception
{
_security.setAuthenticator(new BasicAuthenticator());
String response;
response=_connector.getResponses("GET /ctx/noauth/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
_connector.reopen();
response=_connector.getResponses("GET /ctx/forbid/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 403 Forbidden"));
_connector.reopen();
response=_connector.getResponses("GET /ctx/auth/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 401 Unauthorized"));
assertTrue(response.indexOf("WWW-Authenticate: Basic realm=\"TestRealm\"")>0);
_connector.reopen();
response=_connector.getResponses("GET /ctx/auth/info HTTP/1.0\r\n"+
"Authorization: "+B64Code.encode("user:wrong")+"\r\n"+
"\r\n");
assertTrue(response.startsWith("HTTP/1.1 401 Unauthorized"));
assertTrue(response.indexOf("WWW-Authenticate: Basic realm=\"TestRealm\"")>0);
_connector.reopen();
response=_connector.getResponses("GET /ctx/auth/info HTTP/1.0\r\n"+
"Authorization: "+B64Code.encode("user:pass")+"\r\n"+
"\r\n");
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
}
public void testForm()
throws Exception
{
FormAuthenticator authenticator = new FormAuthenticator();
authenticator.setErrorPage("/testErrorPage");
authenticator.setLoginPage("/testLoginPage");
_security.setAuthenticator(authenticator);
String response;
_connector.reopen();
response=_connector.getResponses("GET /ctx/noauth/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
_connector.reopen();
response=_connector.getResponses("GET /ctx/forbid/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 403 Forbidden"));
_connector.reopen();
response=_connector.getResponses("GET /ctx/auth/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 302 Found"));
assertTrue(response.indexOf("Location")>0);
assertTrue(response.indexOf("testLoginPage")>0);
String session=response.substring(response.indexOf("JSESSIONID=")+11,response.indexOf(";Path=/ctx"));
_connector.reopen();
response=_connector.getResponses("POST /ctx/j_security_check HTTP/1.0\r\n"+
"Cookie: JSESSIONID="+session+"\r\n"+
"Content-Type: application/x-www-form-urlencoded\r\n"+
"Content-Length: 31\r\n"+
"\r\n"+
"j_username=user&j_password=wrong\r\n");
assertTrue(response.startsWith("HTTP/1.1 302 Found"));
assertTrue(response.indexOf("Location")>0);
assertTrue(response.indexOf("testErrorPage")>0);
_connector.reopen();
response=_connector.getResponses("POST /ctx/j_security_check HTTP/1.0\r\n"+
"Cookie: JSESSIONID="+session+"\r\n"+
"Content-Type: application/x-www-form-urlencoded\r\n"+
"Content-Length: 31\r\n"+
"\r\n"+
"j_username=user&j_password=pass\r\n");
assertTrue(response.startsWith("HTTP/1.1 302 Found"));
assertTrue(response.indexOf("Location")>0);
assertTrue(response.indexOf("/ctx/auth/info")>0);
_connector.reopen();
response=_connector.getResponses("GET /ctx/auth/info HTTP/1.0\r\n"+
"Cookie: JSESSIONID="+session+"\r\n"+
"\r\n");
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
}
public void testFormNoCookie()
throws Exception
{
FormAuthenticator authenticator = new FormAuthenticator();
authenticator.setErrorPage("/testErrorPage");
authenticator.setLoginPage("/testLoginPage");
_security.setAuthenticator(authenticator);
String response;
_connector.reopen();
response=_connector.getResponses("GET /ctx/noauth/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
_connector.reopen();
response=_connector.getResponses("GET /ctx/forbid/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 403 Forbidden"));
_connector.reopen();
response=_connector.getResponses("GET /ctx/auth/info HTTP/1.0\r\n\r\n");
assertTrue(response.startsWith("HTTP/1.1 302 Found"));
assertTrue(response.indexOf("Location")>0);
assertTrue(response.indexOf("testLoginPage")>0);
int jsession=response.indexOf(";jsessionid=");
String session = response.substring(jsession + 12, response.indexOf("\r\n",jsession));
_connector.reopen();
response=_connector.getResponses("POST /ctx/j_security_check;jsessionid="+session+" HTTP/1.0\r\n"+
"Content-Type: application/x-www-form-urlencoded\r\n"+
"Content-Length: 31\r\n"+
"\r\n"+
"j_username=user&j_password=wrong\r\n");
assertTrue(response.startsWith("HTTP/1.1 302 Found"));
assertTrue(response.indexOf("Location")>0);
assertTrue(response.indexOf("testErrorPage")>0);
_connector.reopen();
response=_connector.getResponses("POST /ctx/j_security_check;jsessionid="+session+" HTTP/1.0\r\n"+
"Content-Type: application/x-www-form-urlencoded\r\n"+
"Content-Length: 31\r\n"+
"\r\n"+
"j_username=user&j_password=pass\r\n");
assertTrue(response.startsWith("HTTP/1.1 302 Found"));
assertTrue(response.indexOf("Location")>0);
assertTrue(response.indexOf("/ctx/auth/info")>0);
_connector.reopen();
response=_connector.getResponses("GET /ctx/auth/info;jsessionid="+session+" HTTP/1.0\r\n"+
"\r\n");
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
}
class RequestHandler extends AbstractHandler
{
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException
{
((Request)request).setHandled(true);
response.setStatus(200);
response.getOutputStream().println(request.getRequestURI());
}
}
class TestUserRealm implements UserRealm
{
String _username="user";
Object _credentials="pass";
public Principal authenticate(String username, Object credentials, Request request)
{
if (_username!=null && _username.equals(username) &&
_credentials!=null && _credentials.equals(credentials))
return new Principal()
{
public String getName()
{
return _username;
}
};
return null;
}
public void disassociate(Principal user)
{
// TODO Auto-generated method stub
}
public String getName()
{
return "TestRealm";
}
public Principal getPrincipal(final String username)
{
return new Principal()
{
public String getName()
{
return username;
}
};
}
public boolean isUserInRole(Principal user, String role)
{
// TODO Auto-generated method stub
return false;
}
public void logout(Principal user)
{
// TODO Auto-generated method stub
}
public Principal popRole(Principal user)
{
// TODO Auto-generated method stub
return null;
}
public Principal pushRole(Principal user, String role)
{
// TODO Auto-generated method stub
return null;
}
public boolean reauthenticate(Principal user)
{
// TODO Auto-generated method stub
return user!=null;
}
}
}
| mit |
arocketman/CPUemu | src/main/compiler/Compiler.java | 3657 | package main.compiler;
import main.core.Constants;
import main.core.Sim;
import main.core.Utils;
import java.io.*;
import java.util.ArrayList;
/**
* A simple Compiler that takes instructions as text and transforms them accordingly to the CPU syntax.
* @author Andrea Capuano
* @version 0.1
*/
public class Compiler {
Sim system;
public Compiler(Sim system) {
this.system = system;
}
/**
* Given a file containing assembly code, calls the parseInstruction for each line.
* @param file the file containing assembly code.
* @return an ArrayList containing the parsed instructions.
* @throws IOException
*/
public ArrayList<String> loadAssembly(File file) throws IOException {
BufferedReader fileReader = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> instructions = new ArrayList<>();
while ((line = fileReader.readLine()) != null) {
if(!isComment(line)) {
instructions.add(line);
parseInstruction(line);
}
}
return instructions;
}
/**
* Parses an instruction in String form as the instruction itself, the source operand and a destination operand.
* @param line the full textual instruction e.g: "MOVE D0,D1"
*/
private void parseInstruction(String line) {
String instruction,sourceOP,destOP;
if(line.contains(",")) { //Instructions such as MOVE D0,D1
instruction = line.substring(0, line.indexOf(" "));
sourceOP = line.substring(line.indexOf(" ") + 1, line.indexOf(","));
destOP = line.substring(line.indexOf(",") + 1);
}
else{ //Instructions such as JMP 4000
instruction = line.substring(0, line.indexOf(" "));
sourceOP = line.substring(line.indexOf(" ") + 1);
// In these kind of instructions we really don't care about the destination operand.
destOP = Constants.REGISTER_D0;
}
compileInstruction(instruction,sourceOP,destOP);
}
/**
* Given an instruction and the source,destination operands this puts in the system memory such data accordingly to the CPU syntax.
* At the stage of version 0.1, the destination operand must be a data register.
* The source operand can be both a data register or an immediate value.
* Such method transforms the instructions as follows:
* Register operations ADD -> ADDR
* Immediate operations: ADD-> ADDI
* @param instruction the instruction to be compiled.
* @param sourceOP source operand.
* @param destOP destination operand.
*/
public void compileInstruction(String instruction, String sourceOP, String destOP) {
String instruction4 = instruction.substring(0, 3);
if (Utils.isNumeric(sourceOP)) {
instruction4 = instruction4 + "I"; //MOVE -> MOV -> MOVI
byte[] op1 = Utils.encodeIntegerToBytes(sourceOP);
//TODO: As of version 0.1 I'm just using one byte and 'filling up' the other one. This can definitely be improved.
system.getMemory().putInstruction(instruction4);
system.getMemory().putInstruction(op1[0]);
system.getMemory().putInstruction(op1[1]);
system.getMemory().putInstruction(destOP);
} else {
instruction4 = instruction4 + "R"; //MOVE -> MOV -> MOVR
system.getMemory().putInstruction(instruction4 + sourceOP + destOP);
}
}
private boolean isComment(String line) {
return line.startsWith(Constants.COMMENT_CHARACTER);
}
}
| mit |
Payum/PayumBundle | Tests/Controller/CaptureControllerTest.php | 4796 | <?php
namespace Payum\Bundle\PayumBundle\Tests\Controller;
use Payum\Bundle\PayumBundle\Controller\CaptureController;
use Payum\Core\GatewayInterface;
use Payum\Core\Registry\RegistryInterface;
use Payum\Core\Request\Capture;
use Payum\Core\Security\HttpRequestVerifierInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Routing\RouterInterface;
class CaptureControllerTest extends AbstractControllerTest
{
/**
* @test
*/
public function shouldBeSubClassOfController()
{
$rc = new \ReflectionClass(CaptureController::class);
$this->assertTrue($rc->isSubclassOf(AbstractController::class));
}
/**
* @test
*
* @expectedException \Symfony\Component\HttpKernel\Exception\HttpException
* @expectedExceptionMessage This controller requires session to be started.
*/
public function throwBadRequestIfSessionNotStartedOnDoSessionAction()
{
$this->registryMock = $this->createMock(RegistryInterface::class);
$this->httpRequestVerifierMock = $this->createMock(
HttpRequestVerifierInterface::class
);
$controller = new CaptureController();
$controller->setContainer(new ServiceLocator(['payum' => function () { return $this->payum; }]));
$request = Request::create('/');
//guard
$this->assertFalse($request->hasSession());
$controller->doSessionTokenAction($request);
}
/**
* @test
*
* @expectedException \Symfony\Component\HttpKernel\Exception\HttpException
* @expectedExceptionMessage This controller requires token hash to be stored in the session.
*/
public function throwBadRequestIfSessionNotContainPayumTokenOnDoSessionAction()
{
$this->registryMock = $this->createMock(RegistryInterface::class);
$this->httpRequestVerifierMock = $this->createMock(
HttpRequestVerifierInterface::class
);
$controller = new CaptureController();
$controller->setContainer(new ServiceLocator(['payum' => function () { return $this->payum; }]));
$request = Request::create('/');
$request->setSession(new Session(new MockArraySessionStorage()));
$controller->doSessionTokenAction($request);
}
/**
* @test
*/
public function shouldDoRedirectToCaptureWithTokenUrl()
{
$routerMock = $this->createMock(RouterInterface::class);
$routerMock
->expects($this->any())
->method('generate')
->with('payum_capture_do', array(
'payum_token' => 'theToken',
'foo' => 'fooVal',
))
->will($this->returnValue('/payment/capture/theToken?foo=fooVal'))
;
$locator = new ServiceLocator([
'payum' => function () { return $this->payum; },
'router' => function () use ($routerMock) { return $routerMock; }
]);
$this->registryMock = $this->createMock(RegistryInterface::class);
$this->httpRequestVerifierMock = $this->createMock(
HttpRequestVerifierInterface::class
);
$controller = new CaptureController();
$controller->setContainer($locator);
$this->request = Request::create('/');
$this->request->query->set('foo', 'fooVal');
$this->request->setSession(new Session(new MockArraySessionStorage()));
$this->request->getSession()->set('payum_token', 'theToken');
$response = $controller->doSessionTokenAction($this->request);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/payment/capture/theToken?foo=fooVal', $response->getTargetUrl());
}
/**
* @test
*/
public function shouldExecuteCaptureRequest()
{
$controller = new CaptureController();
$controller->setContainer(new ServiceLocator(['payum' => function () { return $this->payum; }]));
$response = $controller->doAction($this->request);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals(self::AFTER_URL, $response->getTargetUrl());
}
protected function initGatewayMock()
{
$this->gatewayMock = $this->createMock(GatewayInterface::class);
$this->gatewayMock
->expects($this->any())
->method('execute')
->with($this->isInstanceOf(Capture::class))
;
}
}
| mit |
bhowick/barter | lib/inventoryHandler.js | 1101 | GET = function (req,res) {
//TESTING THE DATABASE JOINS BECAUSE WHY NOT
if(req.user) {
var queryText = 'SELECT u.itemID, u.quantity, i.name, i.desc, i.img, r.name AS rarity, r.color, c.name AS category, f.name AS fName ' +
'FROM userInventories AS u ' +
'INNER JOIN items AS i ON i.itemID=u.itemID ' +
'JOIN rarities AS r ON r.rarityID=i.rarityID ' +
'JOIN categories AS c ON c.categoryID=i.categoryID ' +
'JOIN itemFunctions AS f ON f.functionID=i.functionID ' +
'WHERE u.userID = ?'; //WHY
req.db.all(queryText, req.user.userID, function (err,rows) { //THIS QUERY I SWEAR
if(err) { //*crosses fingers*
res.send('Looks like your giant query failed.');
}
else{
//'Items' has rows with itemID, quantity, name, desc, img, rarity, category, fName.
var items = rows;
//console.log(items); //Show me that this works, please.
res.render('pages/inventory', {items:items});
}
});
}
else {
res.redirect('/');
}
};//End GET
POST = function (req,res) {
res.render('pages/inventory');
};//End POST
module.exports = {
GET:GET,
POST:POST
};
| mit |
samabhi/pstHealth | venv/lib/python2.7/site-packages/gunicorn/__init__.py | 247 | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
version_info = (0, 14, 2)
__version__ = ".".join(map(str, version_info))
SERVER_SOFTWARE = "gunicorn/%s" % __version__
| mit |
lostfly2/g2 | application/libraries/ftl/context.php | 6833 | <?php
/*
* Created on 2009 Jan 02
* by Martin Wernstahl <[email protected]>
*/
/**
* A context which renders the tags for the parser.
*
* @package FTL_Parser
* @author Martin Wernstahl <[email protected]>
* @copyright Copyright (c) 2008, Martin Wernstahl <[email protected]>
*/
class FTL_Context
{
/**
* Contains tag definitions.
*
* @var array
*/
public $definitions = array();
/**
* Reverse tag finder tree.
*
* @var array
*/
public $tree = array();
/**
* The global data.
*
* @var FTL_VarStack
*/
public $globals;
/**
* A stack of the tag bindings.
*
* @var FTL_Binding
*/
protected $tag_binding_stack = array();
/**
* A stack of tag names.
*
* @var array(string)
*/
protected $tag_name_stack = array();
// --------------------------------------------------------------------
/**
* Init.
*
* Creates a var_stack.
*/
function __construct()
{
$this->globals = new FTL_VarStack();
}
// --------------------------------------------------------------------
/**
* Defines a tag.
*
* @param string The name of the tags (nestings are separated with ":")
* @param callable The function/method to be called
* @return void
*/
public function define_tag($name, $callable)
{
$this->definitions[$name] = $callable;
if(strpos($name, ':') === false)
{
// No nesting, no need for a reverse mapping tree
return;
}
// Create reverse mapping tree, for tags with more than one segment
$l = explode(':', $name);
$c = count($l);
// # key is a tag name
// Fast and nice (currently only up to 5 segment tags):
if($c == 2)
{
$this->tree[$l[1]][$l[0]]['#'] = $name;
}
elseif($c == 3)
{
$this->tree[$l[2]][$l[1]][$l[0]]['#'] = $name;
}
elseif($c == 4)
{
$this->tree[$l[3]][$l[2]][$l[1]][$l[0]]['#'] = $name;
}
elseif($c == 5)
{
$this->tree[$l[4]][$l[3]][$l[2]][$l[1]][$l[0]]['#'] = $name;
}
// TODO: To support more segments, add more rows like this
}
// --------------------------------------------------------------------
/**
* Renders the tags with the name and args supplied.
*
* @param string The tag name
* @param array The args
* @param array The nested block
*/
public function render_tag($name, $args = array(), $block = null)
{
// do we have a compund tag?
if(($pos = strpos($name, ':')) != 0)
{
// split them and parse them separately, as if they are nested
$name1 = substr($name, 0, $pos);
$name2 = substr($name, $pos + 1);
return $this->render_tag($name1, array(), array(
'name' => $name2,
'args' => $args,
'content' => $block
));
}
else
{
$qname = $this->qualified_tag_name($name);
if(is_string($qname) && array_key_exists($qname, $this->definitions))
{
// render
return $this->stack($name, $args, $block, $this->definitions[$qname]);
}
else
{
return $this->tag_missing($name, $args, $block);
}
}
}
// --------------------------------------------------------------------
/**
* Traverses the stack and handles the bindings and var_stack(s).
*
* @param string The tag name
* @param array The tag args
* @param array The nested block
* @param callable The function/method to call
* @return string
*/
protected function stack($name, $args, $block, $call)
{
// get previous locals, to let the data "stack"
$previous = end($this->tag_binding_stack);
$previous_locals = $previous == null ? $this->globals : $previous->locals;
// create the stack and binding
$locals = new FTL_VarStack($previous_locals);
$binding = new FTL_Binding($this, $locals, $name, $args, $block);
$this->tag_binding_stack[] = $binding;
$this->tag_name_stack[] = $name;
// Check if we have a function or a method
if(is_callable($call))
{
$result = call_user_func($call, $binding);
}
else
{
show_error('Error in definition of tag "'.$name.'", the associated <b>static function</b> "'.$call.'" cannot be called.');
}
// jump out
array_pop($this->tag_binding_stack);
array_pop($this->tag_name_stack);
return $result;
}
// --------------------------------------------------------------------
/**
* Makes a qualified guess of the tag definition requested depending on the current nesting.
*
* @param string The name of the tag
* @return string
*/
function qualified_tag_name($name)
{
// Get the path array
$path_chunks = array_merge($this->tag_name_stack, array($name));
// For literal matches
$path = implode(':', $path_chunks);
// Check if we have a tag or a variable
if( ! isset($this->definitions[$path]) && ! isset($this->globals->hash[$name]))
{
// Reverse the chunks, we're starting with the most precise name
$path_chunks = array_reverse($path_chunks);
// Set default tag, which is the last one
$last = current($path_chunks);
// Do we have a tag which ends at the correct name?
if( ! isset($this->tree[$last]))
{
// Nope
return $last;
}
// Start
$c =& $this->tree;
//echo('<pre>');
//var_dump($this->tree);
//echo('</pre>');
// Go through the whole name
while( ! empty($path_chunks))
{
// Get next
$e = array_shift($path_chunks);
// Do we have a matching segment?
if(isset($c[$e]))
{
// Yes
// Do we have a tag here?
if(isset($c[$e]['#']))
{
// Yes
$last = $c[$e]['#'];
}
// Move deeper, to make sure that we don't have any more specific tags
$c =& $c[$e];
}
}
return $last;
}
else
{
return $path;
}
}
// --------------------------------------------------------------------
/**
* Raises a tag missing error.
*
* @param string The tag name
* @param array The tag parameters
* @param array The nested block
* @return string Or abort if needed (default)
*/
public function tag_missing($name, $args = array(), $block = null)
{
throw new Exception('Tag missing: "'.$name.'", scope: "'.$this->current_nesting().'".');
}
// --------------------------------------------------------------------
/**
* Returns the state of the current render stack.
*
* Useful from inside a tag definition. Normally just use XT_Binding::nesting().
*
* @return string
*/
function current_nesting()
{
return implode(':', $this->tag_name_stack);
}
}
/* End of file context.php */
/* Location: ./application/libraries/xt_parser/context.php */ | mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.