Merge branch 'master' into Razer_Chroma_Support

# Conflicts:
#	assets/webconfig/i18n/en.json
#	assets/webconfig/js/content_leds.js
#	libsrc/leddevice/dev_net/ProviderRestApi.cpp
#	libsrc/leddevice/dev_net/ProviderRestApi.h
This commit is contained in:
LordGrey
2021-11-01 15:40:37 +01:00
474 changed files with 24405 additions and 24526 deletions

179
assets/webconfig/js/content_colors.js Normal file → Executable file
View File

@@ -1,84 +1,105 @@
$(document).ready( function() {
performTranslation();
var editor_color = null;
var editor_smoothing = null;
var editor_blackborder = null;
if(window.showOptHelp)
{
//color
$('#conf_cont').append(createRow('conf_cont_color'));
$('#conf_cont_color').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont_color').append(createHelpTable(window.schema.color.properties, $.i18n("edt_conf_color_heading_title")));
//smoothing
$('#conf_cont').append(createRow('conf_cont_smoothing'));
$('#conf_cont_smoothing').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont_smoothing').append(createHelpTable(window.schema.smoothing.properties, $.i18n("edt_conf_smooth_heading_title")));
//blackborder
$('#conf_cont').append(createRow('conf_cont_blackborder'));
$('#conf_cont_blackborder').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
$('#conf_cont_blackborder').append(createHelpTable(window.schema.blackborderdetector.properties, $.i18n("edt_conf_bb_heading_title")));
}
else
{
$('#conf_cont').addClass('row');
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
}
//color
editor_color = createJsonEditor('editor_container_color', {
color : window.schema.color
}, true, true);
$(document).ready(function () {
performTranslation();
editor_color.on('change',function() {
editor_color.validate().length || window.readOnlyMode ? $('#btn_submit_color').attr('disabled', true) : $('#btn_submit_color').attr('disabled', false);
});
$('#btn_submit_color').off().on('click',function() {
requestWriteConfig(editor_color.getValue());
});
//smoothing
editor_smoothing = createJsonEditor('editor_container_smoothing', {
smoothing : window.schema.smoothing
}, true, true);
// update instance listing
updateHyperionInstanceListing();
editor_smoothing.on('change',function() {
editor_smoothing.validate().length || window.readOnlyMode ? $('#btn_submit_smoothing').attr('disabled', true) : $('#btn_submit_smoothing').attr('disabled', false);
});
$('#btn_submit_smoothing').off().on('click',function() {
requestWriteConfig(editor_smoothing.getValue());
});
var editor_color = null;
var editor_smoothing = null;
var editor_blackborder = null;
//blackborder
editor_blackborder = createJsonEditor('editor_container_blackborder', {
blackborderdetector: window.schema.blackborderdetector
}, true, true);
if (window.showOptHelp) {
//color
$('#conf_cont').append(createRow('conf_cont_color'));
$('#conf_cont_color').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont_color').append(createHelpTable(window.schema.color.properties, $.i18n("edt_conf_color_heading_title")));
editor_blackborder.on('change',function() {
editor_blackborder.validate().length || window.readOnlyMode ? $('#btn_submit_blackborder').attr('disabled', true) : $('#btn_submit_blackborder').attr('disabled', false);
});
$('#btn_submit_blackborder').off().on('click',function() {
requestWriteConfig(editor_blackborder.getValue());
});
//wiki links
$('#editor_container_blackborder').append(buildWL("user/moretopics/bbmode","edt_conf_bb_mode_title",true));
//create introduction
if(window.showOptHelp)
{
createHint("intro", $.i18n('conf_colors_color_intro'), "editor_container_color");
createHint("intro", $.i18n('conf_colors_smoothing_intro'), "editor_container_smoothing");
createHint("intro", $.i18n('conf_colors_blackborder_intro'), "editor_container_blackborder");
}
removeOverlay();
//smoothing
$('#conf_cont').append(createRow('conf_cont_smoothing'));
$('#conf_cont_smoothing').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont_smoothing').append(createHelpTable(window.schema.smoothing.properties, $.i18n("edt_conf_smooth_heading_title"), "smoothingHelpPanelId"));
//blackborder
$('#conf_cont').append(createRow('conf_cont_blackborder'));
$('#conf_cont_blackborder').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
$('#conf_cont_blackborder').append(createHelpTable(window.schema.blackborderdetector.properties, $.i18n("edt_conf_bb_heading_title"), "blackborderHelpPanelId"));
}
else {
$('#conf_cont').addClass('row');
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_color_heading_title"), 'editor_container_color', 'btn_submit_color'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_smooth_heading_title"), 'editor_container_smoothing', 'btn_submit_smoothing'));
$('#conf_cont').append(createOptPanel('fa-photo', $.i18n("edt_conf_bb_heading_title"), 'editor_container_blackborder', 'btn_submit_blackborder'));
}
//color
editor_color = createJsonEditor('editor_container_color', {
color: window.schema.color
}, true, true);
editor_color.on('change', function () {
editor_color.validate().length || window.readOnlyMode ? $('#btn_submit_color').attr('disabled', true) : $('#btn_submit_color').attr('disabled', false);
});
$('#btn_submit_color').off().on('click', function () {
requestWriteConfig(editor_color.getValue());
});
//smoothing
editor_smoothing = createJsonEditor('editor_container_smoothing', {
smoothing: window.schema.smoothing
}, true, true);
editor_smoothing.on('change', function () {
var smoothingEnable = editor_smoothing.getEditor("root.smoothing.enable").getValue();
if (smoothingEnable) {
showInputOptionsForKey(editor_smoothing, "smoothing", "enable", true);
$('#smoothingHelpPanelId').show();
} else {
showInputOptionsForKey(editor_smoothing, "smoothing", "enable", false);
$('#smoothingHelpPanelId').hide();
}
editor_smoothing.validate().length || window.readOnlyMode ? $('#btn_submit_smoothing').attr('disabled', true) : $('#btn_submit_smoothing').attr('disabled', false);
});
$('#btn_submit_smoothing').off().on('click', function () {
requestWriteConfig(editor_smoothing.getValue());
});
//blackborder
editor_blackborder = createJsonEditor('editor_container_blackborder', {
blackborderdetector: window.schema.blackborderdetector
}, true, true);
editor_blackborder.on('change', function () {
var blackborderEnable = editor_blackborder.getEditor("root.blackborderdetector.enable").getValue();
if (blackborderEnable) {
showInputOptionsForKey(editor_blackborder, "blackborderdetector", "enable", true);
$('#blackborderHelpPanelId').show();
$('#blackborderWikiLinkId').show();
} else {
showInputOptionsForKey(editor_blackborder, "blackborderdetector", "enable", false);
$('#blackborderHelpPanelId').hide();
$('#blackborderWikiLinkId').hide();
}
editor_blackborder.validate().length || window.readOnlyMode ? $('#btn_submit_blackborder').attr('disabled', true) : $('#btn_submit_blackborder').attr('disabled', false);
});
$('#btn_submit_blackborder').off().on('click', function () {
requestWriteConfig(editor_blackborder.getValue());
});
//wiki links
var wikiElement = $(buildWL("user/advanced/Advanced.html#blackbar-detection", "edt_conf_bb_mode_title", true));
wikiElement.attr('id', 'blackborderWikiLinkId');
$('#editor_container_blackborder').append(wikiElement);
//create introduction
if (window.showOptHelp) {
createHint("intro", $.i18n('conf_colors_color_intro'), "editor_container_color");
createHint("intro", $.i18n('conf_colors_smoothing_intro'), "editor_container_smoothing");
createHint("intro", $.i18n('conf_colors_blackborder_intro'), "editor_container_blackborder");
}
removeOverlay();
});

View File

@@ -1,126 +1,142 @@
$(document).ready( function() {
performTranslation();
$(document).ready(function () {
performTranslation();
// function newsCont(t,e,l)
// {
// var h = '<div style="padding-left:9px;border-left:6px solid #0088cc;">';
// h += '<h4 style="font-weight:bold;font-size:17px">'+t+'</h4>';
// h += e;
// h += '<a href="'+l+'" class="" target="_blank"><i class="fa fa-fw fa-newspaper-o"></i>'+$.i18n('dashboard_newsbox_readmore')+'</a>';
// h += '</div><hr/>';
// $('#dash_news').append(h);
// }
function updateComponents() {
$("div[class*='currentInstance']").remove();
// function createNews(d)
// {
// for(var i = 0; i<d.length; i++)
// {
// if(i > 5)
// break;
//
// var title = d[i].title.rendered;
// var excerpt = d[i].excerpt.rendered;
// var link = d[i].link+'?pk_campaign=WebUI&pk_kwd=news_'+d[i].slug;
//
// newsCont(title,excerpt,link);
// }
// }
var instances_html = '<div class="col-md-6 col-xxl-4 currentInstance-"><div class="panel panel-default">';
instances_html += '<div class="panel-heading panel-instance">';
instances_html += '<div class="dropdown">';
instances_html += '<a id="active_instance_dropdown" class="dropdown-toggle" data-toggle="dropdown" href="#" style="text-decoration:none;display:flex;align-items:center;">';
instances_html += '<div id="active_instance_friendly_name"></div>';
instances_html += '<div id="btn_hypinstanceswitch" style="white-space:nowrap;"><span class="mdi mdi-lightbulb-group mdi-24px" style="margin-right:0;margin-left:5px;"></span><span class="mdi mdi-menu-down mdi-24px"></span></div>';
instances_html += '</a><ul id="hyp_inst_listing" class="dropdown-menu dropdown-alerts" style="cursor:pointer;"></ul>';
instances_html += '</div></div>';
// function getNews()
// {
// var h = '<span style="color:red;font-weight:bold">'+$.i18n('dashboard_newsbox_noconn')+'</span>';
// $.ajax({
// url: 'https://hyperion-project.org/wp-json/wp/v2/posts?_embed',
// dataType: 'json',
// type: 'GET',
// timeout: 2000
// })
// .done( function( data, textStatus, jqXHR ) {
// if(jqXHR.status == 200)
// createNews(data);
// else
// $('#dash_news').html(h);
// })
// .fail( function( jqXHR, textStatus ) {
// $('#dash_news').html(h);
// });
// }
instances_html += '<div class="panel-body">';
instances_html += '<table class="table borderless">';
instances_html += '<thead><tr><th style="vertical-align:middle"><i class="mdi mdi-lightbulb-on fa-fw"></i>';
instances_html += '<span>' + $.i18n('dashboard_componentbox_label_status') + '</span></th>';
// getNews();
var components = window.comps;
var hyperion_enabled = true;
components.forEach(function (obj) {
if (obj.name == "ALL") {
hyperion_enabled = obj.enabled;
}
});
function updateComponents()
{
var components = window.comps;
var components_html = "";
for (var idx=0; idx<components.length;idx++)
{
if(components[idx].name != "ALL")
components_html += '<tr><td>'+$.i18n('general_comp_'+components[idx].name)+'</td><td><i class="fa fa-circle component-'+(components[idx].enabled?"on":"off")+'"></i></td></tr>';
}
$("#tab_components").html(components_html);
var instBtn = '<span style="display:block; margin:3px"><input id="instanceButton"'
+ (hyperion_enabled ? "checked" : "") + ' type="checkbox" data-toggle="toggle" data-size="small" data-onstyle="success" data-on="'
+ $.i18n('general_btn_on') + '" data-off="'
+ $.i18n('general_btn_off') + '"></span>';
//info
var hyperion_enabled = true;
instances_html += '<th style="width:1px;text-align:right">' + instBtn + '</th></tr></thead></table>';
components.forEach( function(obj) {
if (obj.name == "ALL")
{
hyperion_enabled = obj.enabled
}
});
instances_html += '<table class="table borderless">';
instances_html += '<thead><tr><th colspan="3">';
instances_html += '<i class="fa fa-info-circle fa-fw"></i>';
instances_html += '<span>' + $.i18n('dashboard_infobox_label_title') + '</span>';
instances_html += '</th></tr></thead>';
instances_html += '<tbody>';
instances_html += '<tr><td></td><td>' + $.i18n('conf_leds_contr_label_contrtype') + '</td>';
instances_html += '<td style="text-align:right; padding-right:0">';
instances_html += '<span>' + window.serverConfig.device.type + '</span>';
instances_html += '<a class="fa fa-cog fa-fw" onclick="SwitchToMenuItem(\'MenuItemLeds\')" style="text-decoration:none;cursor:pointer"></a>';
instances_html += '</td></tr>';
instances_html += '</tbody></table>';
var instancename = window.currentHyperionInstanceName;
instances_html += '<table class="table first_cell_borderless">';
instances_html += '<thead><tr><th colspan="3">';
instances_html += '<i class="fa fa-eye fa-fw"></i>';
instances_html += '<span>' + $.i18n('dashboard_componentbox_label_title') + '</span>';
instances_html += '</th></tr></thead>';
$('#dash_statush').html(hyperion_enabled ? '<span style="color:green">'+$.i18n('general_btn_on')+'</span>' : '<span style="color:red">'+$.i18n('general_btn_off')+'</span>');
$('#btn_hsc').html(hyperion_enabled ? '<button class="btn btn-sm btn-danger" onClick="requestSetComponentState(\'ALL\',false)">'+$.i18n('dashboard_infobox_label_disableh', instancename)+'</button>' : '<button class="btn btn-sm btn-success" onClick="requestSetComponentState(\'ALL\',true)">'+$.i18n('dashboard_infobox_label_enableh', instancename)+'</button>');
}
var componentBtn = "";
var instance_components = "";
for (var idx = 0; idx < components.length; idx++) {
if (components[idx].name != "ALL") {
if ((components[idx].name === "FORWARDER" && window.currentHyperionInstance != 0) ||
(components[idx].name === "GRABBER" && !window.serverConfig.framegrabber.enable) ||
(components[idx].name === "V4L" && !window.serverConfig.grabberV4L2.enable))
continue;
// add more info
$('#dash_leddevice').html(window.serverConfig.device.type);
$('#dash_currv').html(window.currentVersion);
$('#dash_instance').html(window.currentHyperionInstanceName);
$('#dash_ports').html(window.serverConfig.flatbufServer.port+' | '+window.serverConfig.protoServer.port);
$('#dash_watchedversionbranch').html(window.serverConfig.general.watchedVersionBranch);
var comp_enabled = components[idx].enabled ? "checked" : "";
const general_comp = "general_comp_" + components[idx].name;
componentBtn = '<input ' +
'id="' + general_comp + '" ' + comp_enabled +
' type="checkbox" ' +
'data-toggle="toggle" ' +
'data-size="mini" ' +
'data-onstyle="success" ' +
'data-on="' + $.i18n('general_btn_on') + '" ' +
'data-off="' + $.i18n('general_btn_off') + '">';
getReleases(function(callback){
if(callback)
{
$('#dash_latev').html(window.latestVersion.tag_name);
instance_components += '<tr><td></td><td>' + $.i18n('general_comp_' + components[idx].name) + '</td><td style="text-align:right">' + componentBtn + '</td></tr>';
}
}
if (semverLite.gt(window.latestVersion.tag_name, window.currentVersion))
$('#versioninforesult').html('<div class="bs-callout bs-callout-warning" style="margin:0px"><a target="_blank" href="' + window.latestVersion.html_url + '">'+$.i18n('dashboard_infobox_message_updatewarning', window.latestVersion.tag_name) + '</a></div>');
else
$('#versioninforesult').html('<div class="bs-callout bs-callout-success" style="margin:0px">'+$.i18n('dashboard_infobox_message_updatesuccess')+'</div>');
instances_html += '<tbody>' + instance_components + '</tbody></table>';
instances_html += '</div></div></div>';
}
});
$('.instances').prepend(instances_html);
updateUiOnInstance(window.currentHyperionInstance);
updateHyperionInstanceListing();
$('#instanceButton').bootstrapToggle();
$('#instanceButton').change(e => {
requestSetComponentState('ALL', e.currentTarget.checked);
});
//determine platform
var grabbers = window.serverInfo.grabbers.available;
var html = "";
for (var idx = 0; idx < components.length; idx++) {
if (components[idx].name != "ALL") {
$("#general_comp_" + components[idx].name).bootstrapToggle();
$("#general_comp_" + components[idx].name).bootstrapToggle(hyperion_enabled ? "enable" : "disable");
$("#general_comp_" + components[idx].name).change(e => {
requestSetComponentState(e.currentTarget.id.split('_')[2], e.currentTarget.checked);
});
}
}
}
if(grabbers.indexOf('dispmanx') > -1)
html += 'Raspberry Pi';
else if(grabbers.indexOf('x11') > -1 || grabbers.indexOf('xcb') > -1)
html += 'X86';
else if(grabbers.indexOf('osx') > -1)
html += 'OSX';
else if(grabbers.indexOf('amlogic') > -1)
html += 'Amlogic';
else
html += 'Framebuffer';
// add more info
$('#dash_platform').html(html);
var screenGrabber = window.serverConfig.framegrabber.enable ? $.i18n('general_enabled') : $.i18n('general_disabled');
$('#dash_screen_grabber').html(screenGrabber);
var videoGrabber = window.serverConfig.grabberV4L2.enable ? $.i18n('general_enabled') : $.i18n('general_disabled');
$('#dash_video_grabber').html(videoGrabber);
var fbPort = window.serverConfig.flatbufServer.enable ? window.serverConfig.flatbufServer.port : $.i18n('general_disabled');
$('#dash_fbPort').html(fbPort);
var pbPort = window.serverConfig.protoServer.enable ? window.serverConfig.protoServer.port : $.i18n('general_disabled');
$('#dash_pbPort').html(pbPort);
//interval update
updateComponents();
$(window.hyperion).on("components-updated",updateComponents);
var jsonPort = window.serverConfig.jsonServer.port;
$('#dash_jsonPort').html(jsonPort);
var wsPorts = window.serverConfig.webConfig.port + ' | ' + window.serverConfig.webConfig.sslPort;
$('#dash_wsPorts').html(wsPorts);
if(window.showOptHelp)
createHintH("intro", $.i18n('dashboard_label_intro'), "dash_intro");
$('#dash_currv').html(window.currentVersion);
$('#dash_watchedversionbranch').html(window.serverConfig.general.watchedVersionBranch);
removeOverlay();
getReleases(function (callback) {
if (callback) {
$('#dash_latev').html(window.latestVersion.tag_name);
if (semverLite.gt(window.latestVersion.tag_name, window.currentVersion))
$('#versioninforesult').html('<div class="bs-callout bs-callout-warning" style="margin:0px"><a target="_blank" href="' + window.latestVersion.html_url + '">' + $.i18n('dashboard_infobox_message_updatewarning', window.latestVersion.tag_name) + '</a></div>');
else
$('#versioninforesult').html('<div class="bs-callout bs-callout-info" style="margin:0px">' + $.i18n('dashboard_infobox_message_updatesuccess') + '</div>');
}
});
//interval update
updateComponents();
$(window.hyperion).on("components-updated", updateComponents);
if (window.showOptHelp)
createHintH("intro", $.i18n('dashboard_label_intro'), "dash_intro");
removeOverlay();
});

View File

@@ -1,5 +1,9 @@
$(document).ready( function() {
performTranslation();
// update instance listing
updateHyperionInstanceListing();
var oldEffects = [];
var effects_editor = null;
var confFgEff = window.serverConfig.foregroundEffect.effect;
@@ -12,12 +16,12 @@ $(document).ready( function() {
//foreground effect
$('#conf_cont').append(createRow('conf_cont_fge'));
$('#conf_cont_fge').append(createOptPanel('fa-spinner', $.i18n("edt_conf_fge_heading_title"), 'editor_container_foregroundEffect', 'btn_submit_foregroundEffect'));
$('#conf_cont_fge').append(createHelpTable(window.schema.foregroundEffect.properties, $.i18n("edt_conf_fge_heading_title")));
$('#conf_cont_fge').append(createHelpTable(window.schema.foregroundEffect.properties, $.i18n("edt_conf_fge_heading_title"), "foregroundEffectHelpPanelId"));
//background effect
$('#conf_cont').append(createRow('conf_cont_bge'));
$('#conf_cont_bge').append(createOptPanel('fa-spinner', $.i18n("edt_conf_bge_heading_title"), 'editor_container_backgroundEffect', 'btn_submit_backgroundEffect'));
$('#conf_cont_bge').append(createHelpTable(window.schema.backgroundEffect.properties, $.i18n("edt_conf_bge_heading_title")));
$('#conf_cont_bge').append(createHelpTable(window.schema.backgroundEffect.properties, $.i18n("edt_conf_bge_heading_title"), "backgroundEffectHelpPanelId"));
//effect path
if(storedAccess != 'default')
@@ -64,11 +68,31 @@ $(document).ready( function() {
updateEffectlist();
});
foregroundEffect_editor.on('change',function() {
foregroundEffect_editor.on('change', function () {
var foregroundEffectEnable = foregroundEffect_editor.getEditor("root.foregroundEffect.enable").getValue();
if (foregroundEffectEnable) {
showInputOptionsForKey(foregroundEffect_editor, "foregroundEffect", "enable", true);
$('#foregroundEffectHelpPanelId').show();
} else {
showInputOptionsForKey(foregroundEffect_editor, "foregroundEffect", "enable", false);
$('#foregroundEffectHelpPanelId').hide();
}
foregroundEffect_editor.validate().length || window.readOnlyMode ? $('#btn_submit_foregroundEffect').attr('disabled', true) : $('#btn_submit_foregroundEffect').attr('disabled', false);
});
backgroundEffect_editor.on('change',function() {
backgroundEffect_editor.on('change', function () {
var backgroundEffectEnable = backgroundEffect_editor.getEditor("root.backgroundEffect.enable").getValue();
if (backgroundEffectEnable) {
showInputOptionsForKey(backgroundEffect_editor, "backgroundEffect", "enable", true);
$('#backgroundEffectHelpPanelId').show();
} else {
showInputOptionsForKey(backgroundEffect_editor, "backgroundEffect", "enable", false);
$('#backgroundEffectHelpPanelId').hide();
}
backgroundEffect_editor.validate().length || window.readOnlyMode ? $('#btn_submit_backgroundEffect').attr('disabled', true) : $('#btn_submit_backgroundEffect').attr('disabled', false);
});

View File

@@ -1,204 +1,259 @@
$(document).ready( function() {
performTranslation();
var oldDelList = [];
var effectName = "";
var imageData = "";
var effects_editor = null;
var effectPy = "";
var testrun;
$(document).ready(function () {
performTranslation();
if(window.showOptHelp)
createHintH("intro", $.i18n('effectsconfigurator_label_intro'), "intro_effc");
// update instance listing
updateHyperionInstanceListing();
function updateDelEffectlist(){
var newDelList = window.serverInfo.effects;
if(newDelList.length != oldDelList.length)
{
$('#effectsdellist').html("");
var usrEffArr = [];
var sysEffArr = [];
for(var idx=0; idx<newDelList.length; idx++)
{
if(!/^\:/.test(newDelList[idx].file))
usrEffArr.push('ext_'+newDelList[idx].name+':'+newDelList[idx].name);
else
sysEffArr.push('int_'+newDelList[idx].name+':'+newDelList[idx].name);
}
$('#effectsdellist').append(createSel(usrEffArr, $.i18n('remote_optgroup_usreffets'), true)).append(createSel(sysEffArr, $.i18n('remote_optgroup_syseffets'), true)).trigger('change');
oldDelList = newDelList;
}
}
var oldDelList = [];
var effectName = "";
var imageData = "";
var effects_editor = null;
var effectPyScript = "";
var testrun;
function triggerTestEffect() {
testrun = true;
var args = effects_editor.getEditor('root.args');
requestTestEffect(effectName, ":/effects/" + effectPy.slice(1), JSON.stringify(args.getValue()), imageData);
};
if (window.showOptHelp)
createHintH("intro", $.i18n('effectsconfigurator_label_intro'), "intro_effc");
// Specify upload handler for image files
JSONEditor.defaults.options.upload = function(type, file, cbs) {
var fileReader = new FileReader();
//check file
if (!file.type.startsWith('image')) {
imageData = "";
cbs.failure('File upload error');
// TODO clear file dialog.
showInfoDialog('error', "", $.i18n('infoDialog_writeimage_error_text', file.name));
return;
}
fileReader.onload = function () {
imageData = this.result.split(',')[1];
cbs.success(file.name);
};
fileReader.readAsDataURL(file);
};
$("#effectslist").off().on("change", function(event) {
if(effects_editor != null)
effects_editor.destroy();
for(var idx=0; idx<effects.length; idx++){
if (effects[idx].schemaContent.script == this.value)
{
effects_editor = createJsonEditor('editor_container', {
args : effects[idx].schemaContent,
},false, true, false);
effectPy = ':';
effectPy += effects[idx].schemaContent.script;
imageData = "";
$("#name-input").trigger("change");
$("#eff_desc").html(createEffHint($.i18n(effects[idx].schemaContent.title),$.i18n(effects[idx].schemaContent.title+'_desc')));
break;
}
}
effects_editor.on('change',function() {
if ($("#btn_cont_test").hasClass("btn-success") && effects_editor.validate().length == 0 && effectName != "")
{
triggerTestEffect();
}
if( effects_editor.validate().length == 0 && effectName != "")
{
$('#btn_start_test').attr('disabled', false);
!window.readOnlyMode ? $('#btn_write').attr('disabled', false) : $('#btn_write').attr('disabled', true);
}
else
{
$('#btn_start_test, #btn_write').attr('disabled', true);
}
});
});
// disable or enable control elements
$("#name-input").on('change keyup', function(event) {
effectName = $(this).val();
if ($(this).val() == '') {
effects_editor.disable();
$("#eff_footer").children().attr('disabled',true);
} else {
effects_editor.enable();
$("#eff_footer").children().attr('disabled',false);
!window.readOnlyMode ? $('#btn_write').attr('disabled', false) : $('#btn_write').attr('disabled', true);
function updateDelEffectlist() {
var newDelList = window.serverInfo.effects;
if (newDelList.length != oldDelList.length) {
$('#effectsdellist').html("");
var usrEffArr = [];
var sysEffArr = [];
for (var idx = 0; idx < newDelList.length; idx++) {
if (newDelList[idx].file.startsWith(":")) {
sysEffArr.push(idx);
}
else {
usrEffArr.push(idx);
}
}
if (usrEffArr.length > 0) {
var usrEffGrp = createSelGroup($.i18n('remote_optgroup_usreffets'));
for (var idx = 0; idx < usrEffArr.length; idx++)
{
usrEffGrp.appendChild(createSelOpt('ext_' + newDelList[usrEffArr[idx]].name, newDelList[usrEffArr[idx]].name));
}
$('#effectsdellist').append(usrEffGrp);
}
var sysEffGrp = createSelGroup($.i18n('remote_optgroup_syseffets'));
for (var idx = 0; idx < sysEffArr.length; idx++)
{
sysEffGrp.appendChild(createSelOpt('int_' + newDelList[sysEffArr[idx]].name, newDelList[sysEffArr[idx]].name));
}
$('#effectsdellist').append(sysEffGrp);
$("#effectsdellist").trigger("change");
oldDelList = newDelList;
}
}
function triggerTestEffect() {
testrun = true;
var args = effects_editor.getEditor('root.args');
if ($('input[type=radio][value=url]').is(':checked')) {
requestTestEffect(effectName, effectPyScript, JSON.stringify(args.getValue()), "");
} else {
requestTestEffect(effectName, effectPyScript, JSON.stringify(args.getValue()), imageData);
}
};
// Specify upload handler for image files
JSONEditor.defaults.options.upload = function (type, file, cbs) {
var fileReader = new FileReader();
//check file
if (!file.type.startsWith('image')) {
imageData = "";
cbs.failure('File upload error');
// TODO clear file dialog.
showInfoDialog('error', "", $.i18n('infoDialog_writeimage_error_text', file.name));
return;
}
fileReader.onload = function () {
imageData = this.result.split(',')[1];
cbs.success(file.name);
};
fileReader.readAsDataURL(file);
};
$("#effectslist").off().on("change", function (event) {
if (effects_editor != null)
effects_editor.destroy();
for (var idx = 0; idx < effects.length; idx++) {
if (effects[idx].script == this.value) {
effects_editor = createJsonEditor('editor_container', {
args: effects[idx].schemaContent,
}, false, true, false);
effectPyScript = effects[idx].script;
imageData = "";
$("#name-input").trigger("change");
var desc = $.i18n(effects[idx].schemaContent.title + '_desc');
if (desc === effects[idx].schemaContent.title + '_desc') {
desc = "";
}
$("#eff_desc").html(createEffHint($.i18n(effects[idx].schemaContent.title), desc));
break;
}
}
effects_editor.on('change', function () {
if ($("#btn_cont_test").hasClass("btn-success") && effects_editor.validate().length == 0 && effectName != "") {
triggerTestEffect();
}
if (effects_editor.validate().length == 0 && effectName != "") {
$('#btn_start_test').attr('disabled', false);
!window.readOnlyMode ? $('#btn_write').attr('disabled', false) : $('#btn_write').attr('disabled', true);
}
else {
$('#btn_start_test, #btn_write').attr('disabled', true);
}
});
});
// disable or enable control elements
$("#name-input").on('change keyup', function (event) {
effectName = encodeHTML($(this).val());
if ($(this).val() == '') {
effects_editor.disable();
$("#eff_footer").children().attr('disabled', true);
} else {
effects_editor.enable();
$("#eff_footer").children().attr('disabled', false);
!window.readOnlyMode ? $('#btn_write').attr('disabled', false) : $('#btn_write').attr('disabled', true);
}
});
// Save Effect
$('#btn_write').off().on('click', function () {
if ($('input[type=radio][value=url]').is(':checked')) {
requestWriteEffect(effectName, effectPyScript, JSON.stringify(effects_editor.getValue()), "");
} else {
requestWriteEffect(effectName, effectPyScript, JSON.stringify(effects_editor.getValue()), imageData);
}
$(window.hyperion).one("cmd-create-effect", function (event) {
if (event.response.success)
showInfoDialog('success', "", $.i18n('infoDialog_effconf_created_text', effectName));
});
// Save Effect
$('#btn_write').off().on('click',function() {
requestWriteEffect(effectName,effectPy,JSON.stringify(effects_editor.getValue()),imageData);
$(window.hyperion).one("cmd-create-effect", function(event) {
if (event.response.success)
showInfoDialog('success', "", $.i18n('infoDialog_effconf_created_text', effectName));
});
if (testrun)
setTimeout(requestPriorityClear, 100);
});
if (testrun)
setTimeout(requestPriorityClear,100);
// Start test
$('#btn_start_test').off().on('click', function () {
triggerTestEffect();
});
});
// Stop test
$('#btn_stop_test').off().on('click', function () {
requestPriorityClear();
testrun = false;
});
// Start test
$('#btn_start_test').off().on('click',function() {
triggerTestEffect();
});
// Continuous test
$('#btn_cont_test').off().on('click', function () {
toggleClass('#btn_cont_test', "btn-success", "btn-danger");
});
// Stop test
$('#btn_stop_test').off().on('click',function() {
requestPriorityClear();
testrun = false;
});
// Delete Effect
$('#btn_delete').off().on('click', function () {
var name = $("#effectsdellist").val().split("_")[1];
requestDeleteEffect(name);
$(window.hyperion).one("cmd-delete-effect", function (event) {
if (event.response.success)
showInfoDialog('success', "", $.i18n('infoDialog_effconf_deleted_text', name));
});
});
// Continuous test
$('#btn_cont_test').off().on('click',function() {
toggleClass('#btn_cont_test', "btn-success", "btn-danger");
});
// Disable or enable Delete Effect Button
$('#effectsdellist').off().on('change', function () {
$(this).val() == null ? $('#btn_edit, #btn_delete').prop('disabled', true) : "";
$(this).val().startsWith("int_") ? $('#btn_delete').prop('disabled', true) : $('#btn_delete').prop('disabled', false);
});
// Delete Effect
$('#btn_delete').off().on('click',function() {
var name = $("#effectsdellist").val().split("_")[1];
requestDeleteEffect(name);
$(window.hyperion).one("cmd-delete-effect", function(event) {
if (event.response.success)
showInfoDialog('success', "", $.i18n('infoDialog_effconf_deleted_text', name));
});
});
// Load Effect
$('#btn_edit').off().on('click', function () {
// disable or enable Delete Effect Button
$('#effectsdellist').off().on('change', function(){
$(this).val() == null ? $('#btn_edit, #btn_delete').prop('disabled',true) : "";
$(this).val().startsWith("int_") ? $('#btn_delete').prop('disabled',true) : $('#btn_delete').prop('disabled',false);
});
var name = $("#effectsdellist").val().replace("ext_", "");
if (name.startsWith("int_")) {
name = name.split("_").pop();
$("#name-input").val("My Modded Effect");
}
else {
name = name.split("_").pop();
$("#name-input").val(name);
}
// Load Effect
$('#btn_edit').off().on('click', function(){
var name = $("#effectsdellist").val().replace("ext_","");
var efx = window.serverInfo.effects;
for (var i = 0; i < efx.length; i++) {
if (efx[i].name == name) {
var py = efx[i].script;
$("#effectslist").val(py).trigger("change");
if(name.startsWith("int_"))
{ name = name.split("_").pop();
$("#name-input").val("My Modded Effect");
}
else
{
name = name.split("_").pop();
$("#name-input").val(name);
}
for (var key in efx[i].args) {
var ed = effects_editor.getEditor('root.args.' + [key]);
if (ed)
ed.setValue(efx[i].args[key]);
}
break;
}
}
});
var efx = window.serverInfo.effects;
for(var i = 0; i<efx.length; i++)
{
if(efx[i].name == name)
{
var py = efx[i].script.split("/").pop();
$("#effectslist").val(py).trigger("change");
//Create effect template list
var effects = window.serverSchema.properties.effectSchemas;
for(var key in efx[i].args)
{
var ed = effects_editor.getEditor('root.args.'+[key]);
if(ed)
ed.setValue(efx[i].args[key]);
}
break;
}
}
});
$('#effectslist').html("");
var custTemplatesIDs = [];
var sysTemplatesIDs = [];
//create basic effect list
var effects = window.serverSchema.properties.effectSchemas.internal;
for(var idx=0; idx<effects.length; idx++)
{
$("#effectslist").append(createSelOpt(effects[idx].schemaContent.script, $.i18n(effects[idx].schemaContent.title)));
}
$("#effectslist").trigger("change");
for (var idx = 0; idx < effects.length; idx++) {
if (effects[idx].type === "custom")
custTemplatesIDs.push(idx);
else
sysTemplatesIDs.push(idx);
}
updateDelEffectlist();
//Cannot use createSel(), as Windows filenames include colons ":"
if (custTemplatesIDs.length > 0) {
var custTmplGrp = createSelGroup($.i18n('remote_optgroup_templates_custom'));
for (var idx = 0; idx < custTemplatesIDs.length; idx++)
{
custTmplGrp.appendChild(createSelOpt(effects[custTemplatesIDs[idx]].script, $.i18n(effects[custTemplatesIDs[idx]].schemaContent.title)));
}
$('#effectslist').append(custTmplGrp);
}
//interval update
$(window.hyperion).on("cmd-effects-update", function(event){
window.serverInfo.effects = event.response.data.effects
updateDelEffectlist();
});
var sysTmplGrp = createSelGroup($.i18n('remote_optgroup_templates_system'));
for (var idx = 0; idx < sysTemplatesIDs.length; idx++)
{
sysTmplGrp.appendChild(createSelOpt(effects[sysTemplatesIDs[idx]].script, $.i18n(effects[sysTemplatesIDs[idx]].schemaContent.title)));
}
$('#effectslist').append(sysTmplGrp);
removeOverlay();
$("#effectslist").trigger("change");
updateDelEffectlist();
//interval update
$(window.hyperion).on("cmd-effects-update", function (event) {
window.serverInfo.effects = event.response.data.effects
updateDelEffectlist();
});
removeOverlay();
});

View File

@@ -1,200 +1,182 @@
$(document).ready( function() {
performTranslation();
$(document).ready(function () {
performTranslation();
var importedConf;
var confName;
var conf_editor = null;
var importedConf;
var confName;
var conf_editor = null;
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_gen_heading_title"), 'editor_container', 'btn_submit'));
if(window.showOptHelp)
{
$('#conf_cont').append(createHelpTable(window.schema.general.properties, $.i18n("edt_conf_gen_heading_title")));
}
else
$('#conf_imp').appendTo('#conf_cont');
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_gen_heading_title"), 'editor_container', 'btn_submit', 'panel-system'));
if (window.showOptHelp) {
$('#conf_cont').append(createHelpTable(window.schema.general.properties, $.i18n("edt_conf_gen_heading_title")));
}
else
$('#conf_imp').appendTo('#conf_cont');
conf_editor = createJsonEditor('editor_container', {
general: window.schema.general
}, true, true);
conf_editor = createJsonEditor('editor_container', {
general: window.schema.general
}, true, true);
conf_editor.on('change',function() {
conf_editor.validate().length || window.readOnlyMode ? $('#btn_submit').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
conf_editor.on('change', function () {
conf_editor.validate().length || window.readOnlyMode ? $('#btn_submit').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
$('#btn_submit').off().on('click',function() {
requestWriteConfig(conf_editor.getValue());
});
$('#btn_submit').off().on('click', function () {
window.showOptHelp = conf_editor.getEditor("root.general.showOptHelp").getValue();
requestWriteConfig(conf_editor.getValue());
});
// Instance handling
function handleInstanceRename(e)
{
conf_editor.on('change',function() {
window.readOnlyMode ? $('#btn_cl_save').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#btn_ma_save').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
var inst = e.currentTarget.id.split("_")[1];
showInfoDialog('renInst', $.i18n('conf_general_inst_renreq_t'), getInstanceNameByIndex(inst));
// Instance handling
function handleInstanceRename(e) {
$("#id_btn_ok").off().on('click', function(){
requestInstanceRename(inst, $('#renInst_name').val())
});
conf_editor.on('change', function () {
window.readOnlyMode ? $('#btn_cl_save').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#btn_ma_save').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
$('#renInst_name').off().on('input',function(e) {
(e.currentTarget.value.length >= 5 && e.currentTarget.value != getInstanceNameByIndex(inst)) ? $('#id_btn_ok').attr('disabled', false) : $('#id_btn_ok').attr('disabled', true);
});
}
var inst = e.currentTarget.id.split("_")[1];
showInfoDialog('renInst', $.i18n('conf_general_inst_renreq_t'), getInstanceNameByIndex(inst));
function handleInstanceStartStop(e)
{
var inst = e.currentTarget.id.split("_")[1];
var start = (e.currentTarget.className == "btn btn-danger")
requestInstanceStartStop(inst, start)
}
$("#id_btn_ok").off().on('click', function () {
requestInstanceRename(inst, encodeHTML($('#renInst_name').val()))
});
function handleInstanceDelete(e)
{
var inst = e.currentTarget.id.split("_")[1];
showInfoDialog('delInst',$.i18n('conf_general_inst_delreq_h'),$.i18n('conf_general_inst_delreq_t',getInstanceNameByIndex(inst)));
$("#id_btn_yes").off().on('click', function(){
requestInstanceDelete(inst)
});
}
$('#renInst_name').off().on('input', function (e) {
(e.currentTarget.value.length >= 5 && e.currentTarget.value != getInstanceNameByIndex(inst)) ? $('#id_btn_ok').attr('disabled', false) : $('#id_btn_ok').attr('disabled', true);
});
}
function buildInstanceList()
{
var inst = serverInfo.instance
$('.itbody').html("");
for(var key in inst)
{
var startBtnColor = inst[key].running ? "success" : "danger";
var startBtnIcon = inst[key].running ? "stop" : "play";
var startBtnText = inst[key].running ? $.i18n('general_btn_stop') : $.i18n('general_btn_start');
var renameBtn = '<button id="instren_'+inst[key].instance+'" type="button" class="btn btn-primary"><i class="fa fa-fw fa-pencil"></i>'+$.i18n('general_btn_rename')+'</button>';
var startBtn = ""
var delBtn = "";
if(inst[key].instance > 0)
{
delBtn = '<button id="instdel_'+inst[key].instance+'" type="button" class="btn btn-warning"><i class="fa fa-fw fa-remove"></i>'+$.i18n('general_btn_delete')+'</button>';
startBtn = '<button id="inst_'+inst[key].instance+'" type="button" class="btn btn-'+startBtnColor+'"><i class="fa fa-fw fa-'+startBtnIcon+'"></i>'+startBtnText+'</button>';
}
$('.itbody').append(createTableRow([inst[key].friendly_name, renameBtn, startBtn, delBtn], false, true));
$('#instren_'+inst[key].instance).off().on('click', handleInstanceRename);
$('#inst_'+inst[key].instance).off().on('click', handleInstanceStartStop);
$('#instdel_'+inst[key].instance).off().on('click', handleInstanceDelete);
window.readOnlyMode ? $('#instren_'+inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#inst_'+inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#instdel_'+inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
}
}
function handleInstanceDelete(e) {
var inst = e.currentTarget.id.split("_")[1];
showInfoDialog('delInst', $.i18n('conf_general_inst_delreq_h'), $.i18n('conf_general_inst_delreq_t', getInstanceNameByIndex(inst)));
$("#id_btn_yes").off().on('click', function () {
requestInstanceDelete(inst)
});
}
createTable('ithead', 'itbody', 'itable');
$('.ithead').html(createTableRow([$.i18n('conf_general_inst_namehead'), "", $.i18n('conf_general_inst_actionhead'), ""], true, true));
buildInstanceList();
function buildInstanceList() {
var inst = serverInfo.instance
$('.itbody').html("");
for (var key in inst) {
var enable_style = inst[key].running ? "checked" : "";
var renameBtn = '<button id="instren_' + inst[key].instance + '" type="button" class="btn btn-primary"><i class="mdi mdi-lead-pencil""></i></button>';
var startBtn = ""
var delBtn = "";
if (inst[key].instance > 0) {
delBtn = '<button id="instdel_' + inst[key].instance + '" type="button" class="btn btn-danger"><i class="mdi mdi-delete-forever""></i></button>';
startBtn = '<input id="inst_' + inst[key].instance + '"' + enable_style + ' type="checkbox" data-toggle="toggle" data-onstyle="success font-weight-bold" data-on="' + $.i18n('general_btn_on') + '" data-offstyle="default font-weight-bold" data-off="' + $.i18n('general_btn_off') + '">';
$('#inst_name').off().on('input',function(e) {
(e.currentTarget.value.length >= 5) && !window.readOnlyMode ? $('#btn_create_inst').attr('disabled', false) : $('#btn_create_inst').attr('disabled', true);
if(5-e.currentTarget.value.length >= 1 && 5-e.currentTarget.value.length <= 4)
$('#inst_chars_needed').html(5-e.currentTarget.value.length + " " + $.i18n('general_chars_needed'))
else
$('#inst_chars_needed').html("<br />")
});
}
$('.itbody').append(createTableRow([inst[key].friendly_name, startBtn, renameBtn, delBtn], false, true));
$('#instren_' + inst[key].instance).off().on('click', handleInstanceRename);
$('#btn_create_inst').off().on('click',function(e) {
requestInstanceCreate($('#inst_name').val());
$('#inst_name').val("");
$('#btn_create_inst').attr('disabled', true)
});
$('#inst_' + inst[key].instance).bootstrapToggle();
$('#inst_' + inst[key].instance).change(e => {
requestInstanceStartStop(e.currentTarget.id.split('_').pop(), e.currentTarget.checked);
});
$('#instdel_' + inst[key].instance).off().on('click', handleInstanceDelete);
$(hyperion).off("instance-updated").on("instance-updated", function(event) {
buildInstanceList()
});
window.readOnlyMode ? $('#instren_' + inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#inst_' + inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
window.readOnlyMode ? $('#instdel_' + inst[key].instance).attr('disabled', true) : $('#btn_submit').attr('disabled', false);
}
}
//import
function dis_imp_btn(state)
{
state || window.readOnlyMode ? $('#btn_import_conf').attr('disabled', true) : $('#btn_import_conf').attr('disabled', false);
}
createTable('ithead', 'itbody', 'itable');
$('.ithead').html(createTableRow([$.i18n('conf_general_inst_namehead'), "", $.i18n('conf_general_inst_actionhead'), ""], true, true));
buildInstanceList();
function readFile(evt)
{
var f = evt.target.files[0];
$('#inst_name').off().on('input', function (e) {
(e.currentTarget.value.length >= 5) && !window.readOnlyMode ? $('#btn_create_inst').attr('disabled', false) : $('#btn_create_inst').attr('disabled', true);
if (5 - e.currentTarget.value.length >= 1 && 5 - e.currentTarget.value.length <= 4)
$('#inst_chars_needed').html(5 - e.currentTarget.value.length + " " + $.i18n('general_chars_needed'))
else
$('#inst_chars_needed').html("<br />")
});
if (f)
{
var r = new FileReader();
r.onload = function(e)
{
var content = e.target.result.replace(/[^:]?\/\/.*/g, ''); //remove Comments
$('#btn_create_inst').off().on('click', function (e) {
requestInstanceCreate(encodeHTML($('#inst_name').val()));
$('#inst_name').val("");
$('#btn_create_inst').attr('disabled', true)
});
//check file is json
var check = isJsonString(content);
if(check.length != 0)
{
showInfoDialog('error', "", $.i18n('infoDialog_import_jsonerror_text', f.name, JSON.stringify(check)));
dis_imp_btn(true);
}
else
{
content = JSON.parse(content);
//check for hyperion json
if(typeof content.leds === 'undefined' || typeof content.general === 'undefined')
{
showInfoDialog('error', "", $.i18n('infoDialog_import_hyperror_text', f.name));
dis_imp_btn(true);
}
else
{
dis_imp_btn(false);
importedConf = content;
confName = f.name;
}
}
}
r.readAsText(f);
}
}
$(hyperion).off("instance-updated").on("instance-updated", function (event) {
buildInstanceList()
});
$('#btn_import_conf').off().on('click', function(){
showInfoDialog('import', $.i18n('infoDialog_import_confirm_title'), $.i18n('infoDialog_import_confirm_text', confName));
//import
function dis_imp_btn(state) {
state || window.readOnlyMode ? $('#btn_import_conf').attr('disabled', true) : $('#btn_import_conf').attr('disabled', false);
}
$('#id_btn_import').off().on('click', function(){
requestWriteConfig(importedConf, true);
setTimeout(initRestart, 100);
});
});
function readFile(evt) {
var f = evt.target.files[0];
$('#select_import_conf').off().on('change', function(e){
if (window.File && window.FileReader && window.FileList && window.Blob)
readFile(e);
else
showInfoDialog('error', "", $.i18n('infoDialog_import_comperror_text'));
});
if (f) {
var r = new FileReader();
r.onload = function (e) {
var content = e.target.result.replace(/[^:]?\/\/.*/g, ''); //remove Comments
//export
$('#btn_export_conf').off().on('click', function(){
var name = window.serverConfig.general.name;
//check file is json
var check = isJsonString(content);
if (check.length != 0) {
showInfoDialog('error', "", $.i18n('infoDialog_import_jsonerror_text', f.name, JSON.stringify(check)));
dis_imp_btn(true);
}
else {
content = JSON.parse(content);
//check for hyperion json
if (typeof content.leds === 'undefined' || typeof content.general === 'undefined') {
showInfoDialog('error', "", $.i18n('infoDialog_import_hyperror_text', f.name));
dis_imp_btn(true);
}
else {
dis_imp_btn(false);
importedConf = content;
confName = f.name;
}
}
}
r.readAsText(f);
}
}
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
$('#btn_import_conf').off().on('click', function () {
showInfoDialog('import', $.i18n('infoDialog_import_confirm_title'), $.i18n('infoDialog_import_confirm_text', confName));
var timestamp = d.getFullYear() + '.' +
(month<10 ? '0' : '') + month + '.' +
(day<10 ? '0' : '') + day;
$('#id_btn_import').off().on('click', function () {
requestWriteConfig(importedConf, true);
setTimeout(initRestart, 100);
});
});
download(JSON.stringify(window.serverConfig, null, "\t"), 'Hyperion-'+window.currentVersion+'-Backup ('+name+') '+timestamp+'.json', "application/json");
});
$('#select_import_conf').off().on('change', function (e) {
if (window.File && window.FileReader && window.FileList && window.Blob)
readFile(e);
else
showInfoDialog('error', "", $.i18n('infoDialog_import_comperror_text'));
});
//create introduction
if(window.showOptHelp)
{
createHint("intro", $.i18n('conf_general_intro'), "editor_container");
createHint("intro", $.i18n('conf_general_tok_desc'), "tok_desc_cont");
createHint("intro", $.i18n('conf_general_inst_desc'), "inst_desc_cont");
}
//export
$('#btn_export_conf').off().on('click', function () {
var name = window.serverConfig.general.name;
removeOverlay();
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var timestamp = d.getFullYear() + '.' +
(month < 10 ? '0' : '') + month + '.' +
(day < 10 ? '0' : '') + day;
download(JSON.stringify(window.serverConfig, null, "\t"), 'Hyperion-' + window.currentVersion + '-Backup (' + name + ') ' + timestamp + '.json', "application/json");
});
//create introduction
if (window.showOptHelp) {
createHint("intro", $.i18n('conf_general_intro'), "editor_container");
createHint("intro", $.i18n('conf_general_tok_desc'), "tok_desc_cont");
createHint("intro", $.i18n('conf_general_inst_desc'), "inst_desc_cont");
}
removeOverlay();
});

1049
assets/webconfig/js/content_grabber.js Normal file → Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -1,354 +1,381 @@
var instNameInit = false
$(document).ready(function () {
var darkModeOverwrite = getStorage("darkModeOverwrite", true);
var darkModeOverwrite = getStorage("darkModeOverwrite", true);
if (darkModeOverwrite == "false" || darkModeOverwrite == null) {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
handleDarkMode();
}
if(darkModeOverwrite == "false" || darkModeOverwrite == null)
{
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
handleDarkMode();
}
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
setStorage("darkMode", "off", false);
}
}
if(getStorage("darkMode", false) == "on")
{
handleDarkMode();
}
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
setStorage("darkMode", "off", false);
}
}
loadContentTo("#container_connection_lost", "connection_lost");
loadContentTo("#container_restart", "restart");
initWebSocket();
if (getStorage("darkMode", false) == "on") {
handleDarkMode();
}
$(window.hyperion).on("cmd-serverinfo", function (event) {
window.serverInfo = event.response.info;
window.readOnlyMode = window.sysInfo.hyperion.readOnlyMode;
// comps
window.comps = event.response.info.components
loadContentTo("#container_connection_lost", "connection_lost");
loadContentTo("#container_restart", "restart");
initWebSocket();
$(window.hyperion).trigger("ready");
$(window.hyperion).on("cmd-serverinfo", function (event) {
window.serverInfo = event.response.info;
window.comps.forEach(function (obj) {
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
});
// comps
window.comps = event.response.info.components
// determine button visibility
var running = window.serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
// update listing at button
updateHyperionInstanceListing()
if (!instNameInit) {
window.currentHyperionInstanceName = getInstanceNameByIndex(0);
instNameInit = true;
}
$(window.hyperion).trigger("ready");
updateSessions();
}); // end cmd-serverinfo
window.comps.forEach(function (obj) {
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
});
// Update language selection
$("#language-select").on('changed.bs.select',function (e, clickedIndex, isSelected, previousValue){
var newLang = availLang[clickedIndex-1];
if (newLang !== storedLang)
{
setStorage("langcode", newLang);
reload();
}
});
// determine button visibility
var running = window.serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
updateSessions();
}); // end cmd-serverinfo
$("#language-select").selectpicker(
{
container: 'body'
});
// Update language selection
$("#language-select").on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
var newLang = availLang[clickedIndex];
if (newLang !== storedLang) {
setStorage("langcode", newLang);
reload();
}
});
$(".bootstrap-select").click(function () {
$(this).addClass("open");
});
$("#language-select").selectpicker(
{
container: 'body'
});
$(document).click(function(){
$(".bootstrap-select").removeClass("open");
});
$(".bootstrap-select").click(function () {
$(this).addClass("open");
});
$(".bootstrap-select").click(function(e){
e.stopPropagation();
});
//End language selection
$(window.hyperion).on("cmd-sessions-update", function (event) {
window.serverInfo.sessions = event.response.data;
updateSessions();
});
$(document).click(function () {
$(".bootstrap-select").removeClass("open");
});
$(window.hyperion).on("cmd-authorize-tokenRequest cmd-authorize-getPendingTokenRequests", function (event) {
var val = event.response.info;
if (Array.isArray(event.response.info)) {
if (event.response.info.length == 0) {
return
}
val = event.response.info[0]
if (val.comment == '')
$('#modal_dialog').modal('hide');
}
$(".bootstrap-select").click(function (e) {
e.stopPropagation();
});
showInfoDialog("grantToken", $.i18n('conf_network_tok_grantT'), $.i18n('conf_network_tok_grantMsg') + '<br><span style="font-weight:bold">App: ' + val.comment + '</span><br><span style="font-weight:bold">Code: ' + val.id + '</span>')
$("#tok_grant_acc").off().on('click', function () {
tokenList.push(val)
// forward event, in case we need to rebuild the list now
$(window.hyperion).trigger({ type: "build-token-list" });
requestHandleTokenRequest(val.id, true)
});
$("#tok_deny_acc").off().on('click', function () {
requestHandleTokenRequest(val.id, false)
});
});
//End language selection
$(window.hyperion).one("cmd-authorize-getTokenList", function (event) {
tokenList = event.response.info;
requestServerInfo();
});
$(window.hyperion).on("cmd-sessions-update", function (event) {
window.serverInfo.sessions = event.response.data;
updateSessions();
});
$(window.hyperion).on("cmd-sysinfo", function (event) {
requestServerInfo();
window.sysInfo = event.response.info;
$(window.hyperion).on("cmd-authorize-tokenRequest cmd-authorize-getPendingTokenRequests", function (event) {
var val = event.response.info;
if (Array.isArray(event.response.info)) {
if (event.response.info.length == 0) {
return
}
val = event.response.info[0]
if (val.comment == '')
$('#modal_dialog').modal('hide');
}
window.currentVersion = window.sysInfo.hyperion.version;
window.currentChannel = window.sysInfo.hyperion.channel;
});
showInfoDialog("grantToken", $.i18n('conf_network_tok_grantT'), $.i18n('conf_network_tok_grantMsg') + '<br><span style="font-weight:bold">App: ' + val.comment + '</span><br><span style="font-weight:bold">Code: ' + val.id + '</span>')
$("#tok_grant_acc").off().on('click', function () {
tokenList.push(val)
// forward event, in case we need to rebuild the list now
$(window.hyperion).trigger({ type: "build-token-list" });
requestHandleTokenRequest(val.id, true)
});
$("#tok_deny_acc").off().on('click', function () {
requestHandleTokenRequest(val.id, false)
});
});
$(window.hyperion).one("cmd-authorize-getTokenList", function (event) {
tokenList = event.response.info;
});
$(window.hyperion).on("cmd-sysinfo", function (event) {
window.sysInfo = event.response.info;
window.currentVersion = window.sysInfo.hyperion.version;
window.currentChannel = window.sysInfo.hyperion.channel;
window.readOnlyMode = window.sysInfo.hyperion.readOnlyMode;
});
$(window.hyperion).one("cmd-config-getschema", function (event) {
window.serverSchema = event.response.info;
window.schema = window.serverSchema.properties;
$(window.hyperion).one("cmd-config-getschema", function (event) {
window.serverSchema = event.response.info;
requestServerConfig();
requestTokenInfo();
requestGetPendingTokenRequests();
window.schema = window.serverSchema.properties;
});
//Switch to last selected instance and load related config
var lastSelectedInstance = getStorage('lastSelectedInstance', false);
if (lastSelectedInstance == null || window.serverInfo.instance && !window.serverInfo.instance[lastSelectedInstance]) {
lastSelectedInstance = 0;
}
instanceSwitch(lastSelectedInstance);
$(window.hyperion).on("cmd-config-getconfig", function (event) {
window.serverConfig = event.response.info;
requestSysInfo();
requestSysInfo();
});
window.showOptHelp = window.serverConfig.general.showOptHelp;
});
$(window.hyperion).on("cmd-config-getconfig", function (event) {
window.serverConfig = event.response.info;
$(window.hyperion).on("cmd-config-setconfig", function (event) {
if (event.response.success === true) {
showNotification('success', $.i18n('dashboard_alert_message_confsave_success'), $.i18n('dashboard_alert_message_confsave_success_t'))
}
});
window.showOptHelp = window.serverConfig.general.showOptHelp;
});
$(window.hyperion).on("cmd-authorize-login", function (event) {
$("#main-nav").removeAttr('style')
$("#top-navbar").removeAttr('style')
$(window.hyperion).on("cmd-config-setconfig", function (event) {
if (event.response.success === true) {
showNotification('success', $.i18n('dashboard_alert_message_confsave_success'), $.i18n('dashboard_alert_message_confsave_success_t'))
}
});
if (window.defaultPasswordIsSet === true && getStorage("suppressDefaultPwWarning") !== "true" )
{
var supprPwWarnCheckbox = '<div class="text-right">'+$.i18n('dashboard_message_do_not_show_again')
+ ' <input id="chk_suppressDefaultPw" type="checkbox" onChange="suppressDefaultPwWarning()"> </div>'
showNotification('warning', $.i18n('dashboard_message_default_password'), $.i18n('dashboard_message_default_password_t'), '<a style="cursor:pointer" onClick="changePassword()">'
+ $.i18n('InfoDialog_changePassword_title') + '</a>' + supprPwWarnCheckbox)
}
else
//if logged on and pw != default show option to lock ui
$("#btn_lock_ui").removeAttr('style')
$(window.hyperion).on("cmd-authorize-login", function (event) {
$("#main-nav").removeAttr('style')
$("#top-navbar").removeAttr('style')
if (window.defaultPasswordIsSet === true && getStorage("suppressDefaultPwWarning") !== "true") {
var supprPwWarnCheckbox = '<div class="text-right">' + $.i18n('dashboard_message_do_not_show_again')
+ ' <input id="chk_suppressDefaultPw" type="checkbox" onChange="suppressDefaultPwWarning()"> </div>'
showNotification('warning', $.i18n('dashboard_message_default_password'), $.i18n('dashboard_message_default_password_t'), '<a style="cursor:pointer" onClick="changePassword()">'
+ $.i18n('InfoDialog_changePassword_title') + '</a>' + supprPwWarnCheckbox)
}
else
//if logged on and pw != default show option to lock ui
$("#btn_lock_ui").removeAttr('style')
if (event.response.hasOwnProperty('info'))
setStorage("loginToken", event.response.info.token, true);
if (event.response.hasOwnProperty('info'))
setStorage("loginToken", event.response.info.token, true);
requestServerConfigSchema();
});
requestServerConfigSchema();
});
$(window.hyperion).on("cmd-authorize-newPassword", function (event) {
if (event.response.success === true) {
showInfoDialog("success", $.i18n('InfoDialog_changePassword_success'));
// not necessarily true, but better than nothing
window.defaultPasswordIsSet = false;
}
});
$(window.hyperion).on("cmd-authorize-newPassword", function (event) {
if (event.response.success === true) {
showInfoDialog("success", $.i18n('InfoDialog_changePassword_success'));
// not necessarily true, but better than nothing
window.defaultPasswordIsSet = false;
}
});
$(window.hyperion).on("cmd-authorize-newPasswordRequired", function (event) {
var loginToken = getStorage("loginToken", true)
$(window.hyperion).on("cmd-authorize-newPasswordRequired", function (event) {
var loginToken = getStorage("loginToken", true)
if (event.response.info.newPasswordRequired == true) {
window.defaultPasswordIsSet = true;
if (event.response.info.newPasswordRequired == true) {
window.defaultPasswordIsSet = true;
if (loginToken)
requestTokenAuthorization(loginToken)
else
requestAuthorization('hyperion');
}
else {
$("#main-nav").attr('style', 'display:none')
$("#top-navbar").attr('style', 'display:none')
if (loginToken)
requestTokenAuthorization(loginToken)
else
requestAuthorization('hyperion');
}
else {
$("#main-nav").attr('style', 'display:none')
$("#top-navbar").attr('style', 'display:none')
if (loginToken)
requestTokenAuthorization(loginToken)
else
loadContentTo("#page-content", "login")
}
});
if (loginToken)
requestTokenAuthorization(loginToken)
else
loadContentTo("#page-content", "login")
}
});
$(window.hyperion).on("cmd-authorize-adminRequired", function (event) {
//Check if a admin login is required.
//If yes: check if default pw is set. If no: go ahead to get server config and render page
if (event.response.info.adminRequired === true)
requestRequiresDefaultPasswortChange();
else
requestServerConfigSchema();
});
$(window.hyperion).on("cmd-authorize-adminRequired", function (event) {
//Check if a admin login is required.
//If yes: check if default pw is set. If no: go ahead to get server config and render page
if (event.response.info.adminRequired === true)
requestRequiresDefaultPasswortChange();
else
requestServerConfigSchema();
});
$(window.hyperion).on("error", function (event) {
//If we are getting an error "No Authorization" back with a set loginToken we will forward to new Login (Token is expired.
//e.g.: hyperiond was started new in the meantime)
if (event.reason == "No Authorization" && getStorage("loginToken", true)) {
removeStorage("loginToken", true);
requestRequiresAdminAuth();
}
else {
showInfoDialog("error", "Error", event.reason);
}
});
$(window.hyperion).on("error", function (event) {
//If we are getting an error "No Authorization" back with a set loginToken we will forward to new Login (Token is expired.
//e.g.: hyperiond was started new in the meantime)
if (event.reason == "No Authorization" && getStorage("loginToken", true)) {
removeStorage("loginToken", true);
requestRequiresAdminAuth();
}
else if (event.reason == "Selected Hyperion instance isn't running") {
//Switch to default instance
instanceSwitch(0);
} else {
showInfoDialog("error", "Error", event.reason);
}
});
$(window.hyperion).on("open", function (event) {
requestRequiresAdminAuth();
});
$(window.hyperion).on("open", function (event) {
requestRequiresAdminAuth();
});
$(window.hyperion).one("ready", function (event) {
loadContent();
});
$(window.hyperion).one("ready", function (event) {
// Content will be loaded by the instance load/switch
});
$(window.hyperion).on("cmd-adjustment-update", function (event) {
window.serverInfo.adjustment = event.response.data
});
$(window.hyperion).on("cmd-adjustment-update", function (event) {
window.serverInfo.adjustment = event.response.data
});
$(window.hyperion).on("cmd-videomode-update", function (event) {
window.serverInfo.videomode = event.response.data.videomode
});
$(window.hyperion).on("cmd-videomode-update", function (event) {
window.serverInfo.videomode = event.response.data.videomode
});
$(window.hyperion).on("cmd-components-update", function (event) {
let obj = event.response.data
$(window.hyperion).on("cmd-components-update", function (event) {
let obj = event.response.data
// notfication in index
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
// notfication in index
if (obj.name == "ALL") {
if (obj.enabled)
$("#hyperion_disabled_notify").fadeOut("fast");
else
$("#hyperion_disabled_notify").fadeIn("fast");
}
window.comps.forEach((entry, index) => {
if (entry.name === obj.name) {
window.comps[index] = obj;
}
});
// notify the update
$(window.hyperion).trigger("components-updated", event.response.data);
});
window.comps.forEach((entry, index) => {
if (entry.name === obj.name) {
window.comps[index] = obj;
}
});
// notify the update
$(window.hyperion).trigger("components-updated", event.response.data);
});
$(window.hyperion).on("cmd-instance-update", function (event) {
window.serverInfo.instance = event.response.data
var avail = event.response.data;
// notify the update
$(window.hyperion).trigger("instance-updated");
$(window.hyperion).on("cmd-instance-update", function (event) {
window.serverInfo.instance = event.response.data
var avail = event.response.data;
// notify the update
$(window.hyperion).trigger("instance-updated");
// if our current instance is no longer available we are at instance 0 again.
var isInData = false;
for (var key in avail) {
if (avail[key].instance == currentHyperionInstance && avail[key].running) {
isInData = true;
}
}
// if our current instance is no longer available we are at instance 0 again.
var isInData = false;
for (var key in avail) {
if (avail[key].instance == currentHyperionInstance && avail[key].running) {
isInData = true;
}
}
if (!isInData) {
//Delete Storage information about the last used but now stopped instance
if (getStorage('lastSelectedInstance', false))
removeStorage('lastSelectedInstance', false)
if (!isInData) {
//Delete Storage information about the last used but now stopped instance
if (getStorage('lastSelectedInstance', false))
removeStorage('lastSelectedInstance', false)
currentHyperionInstance = 0;
currentHyperionInstanceName = getInstanceNameByIndex(0);
requestServerConfig();
setTimeout(requestServerInfo, 100)
setTimeout(requestTokenInfo, 200)
setTimeout(loadContent, 300, undefined, true)
}
currentHyperionInstance = 0;
currentHyperionInstanceName = getInstanceNameByIndex(0);
requestServerConfig();
setTimeout(requestServerInfo, 100)
setTimeout(requestTokenInfo, 200)
setTimeout(loadContent, 300, undefined, true)
}
// determine button visibility
var running = serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
// determine button visibility
var running = serverInfo.instance.filter(entry => entry.running);
if (running.length > 1)
$('#btn_hypinstanceswitch').toggle(true)
else
$('#btn_hypinstanceswitch').toggle(false)
// update listing for button
updateHyperionInstanceListing()
});
// update listing for button
updateHyperionInstanceListing()
});
$(window.hyperion).on("cmd-instance-switchTo", function (event) {
requestServerConfig();
setTimeout(requestServerInfo, 200)
setTimeout(requestTokenInfo, 400)
setTimeout(loadContent, 400, undefined, true)
});
$(window.hyperion).on("cmd-instance-switchTo", function (event) {
requestServerConfig();
setTimeout(requestServerInfo, 200)
setTimeout(requestTokenInfo, 400)
setTimeout(loadContent, 400, undefined, true)
});
$(window.hyperion).on("cmd-effects-update", function (event) {
window.serverInfo.effects = event.response.data.effects
});
$(window.hyperion).on("cmd-effects-update", function (event) {
window.serverInfo.effects = event.response.data.effects
});
$(".mnava").bind('click.menu', function (e) {
loadContent(e);
window.scrollTo(0, 0);
});
$(".mnava").bind('click.menu', function (e) {
loadContent(e);
window.scrollTo(0, 0);
});
$(window).scroll(function() {
if ($(window).scrollTop() > 65)
$("#navbar_brand_logo").css("display", "none");
else
$("#navbar_brand_logo").css("display", "");
});
$('#side-menu li a, #side-menu li ul li a').click(function() {
$('#side-menu').find('.active').toggleClass('inactive'); // find all active classes and set inactive;
$(this).addClass('active');
});
});
function suppressDefaultPwWarning(){
if (document.getElementById('chk_suppressDefaultPw').checked)
setStorage("suppressDefaultPwWarning", "true");
else
setStorage("suppressDefaultPwWarning", "false");
function suppressDefaultPwWarning() {
if (document.getElementById('chk_suppressDefaultPw').checked)
setStorage("suppressDefaultPwWarning", "true");
else
setStorage("suppressDefaultPwWarning", "false");
}
$(function () {
var sidebar = $('#side-menu'); // cache sidebar to a variable for performance
sidebar.delegate('a.inactive', 'click', function () {
sidebar.find('.active').toggleClass('active inactive');
$(this).toggleClass('active inactive');
});
var sidebar = $('#side-menu'); // cache sidebar to a variable for performance
sidebar.delegate('a.inactive', 'click', function () {
sidebar.find('.active').toggleClass('active inactive');
$(this).toggleClass('active inactive');
});
});
// hotfix body padding when bs modals overlap
$(document.body).on('hide.bs.modal,hidden.bs.modal', function () {
$('body').css('padding-right', '0');
$('body').css('padding-right', '0');
});
//Dark Mode
$("#btn_darkmode").off().on("click",function(e){
if(getStorage("darkMode", false) != "on")
{
handleDarkMode();
setStorage("darkModeOverwrite", true, true);
}
else {
setStorage("darkMode", "off", false);
setStorage("darkModeOverwrite", true, true);
location.reload();
}
$("#btn_darkmode").off().on("click", function (e) {
if (getStorage("darkMode", false) != "on") {
handleDarkMode();
setStorage("darkModeOverwrite", true, true);
}
else {
setStorage("darkMode", "off", false);
setStorage("darkModeOverwrite", true, true);
location.reload();
}
});
// Menuitem toggle;
function SwitchToMenuItem(target, item) {
document.getElementById(target).click(); // Get <a href menu item;
let sidebar = $('#side-menu'); // Get sidebar menu;
sidebar.find('.active').toggleClass('inactive'); // find all active classes and set inactive;
sidebar.find('.in').removeClass("in"); // Find all collapsed menu items and close it by remove "in" class;
$('#' + target).removeClass('inactive'); // Remove inactive state by classname;
$('#' + target).addClass('active'); // Add active state by classname;
let cl_object = $('#' + target).closest('ul'); // Find closest ul sidemenu header;
cl_object.addClass('in'); // Add class "in" to expand header in sidebar menu;
if (item) { // Jump to div "item" if available. Time limit 3 seconds
function scrollTo(counter) {
if(counter < 30) {
setTimeout(function() {
counter++;
if ($('#' + item).length)
$('#' + item)[0].scrollIntoView();
else
scrollTo(counter);
}, 100);
}
}
scrollTo(0);
}
};

View File

@@ -0,0 +1,99 @@
$(document).ready(function () {
performTranslation();
// update instance listing
updateHyperionInstanceListing();
var conf_editor_instCapt = null;
// Instance Capture
$('#conf_cont').append(createRow('conf_cont_instCapt'));
$('#conf_cont_instCapt').append(createOptPanel('fa-camera', $.i18n("edt_conf_instCapture_heading_title"), 'editor_container_instCapt', 'btn_submit_instCapt', ''));
if (window.showOptHelp) {
$('#conf_cont_instCapt').append(createHelpTable(window.schema.instCapture.properties, $.i18n("edt_conf_instCapture_heading_title")));
}
// Instance Capture
conf_editor_instCapt = createJsonEditor('editor_container_instCapt', {
instCapture: window.schema.instCapture
}, true, true);
var grabber_config_info_html = '<div class="bs-callout bs-callout-info" style="margin-top:0px"><h4>' + $.i18n('dashboard_infobox_label_title') + '</h4 >';
grabber_config_info_html += '<span>' + $.i18n('conf_grabber_inst_grabber_config_info') + '</span>';
grabber_config_info_html += '<a class="fa fa-cog fa-fw" onclick="SwitchToMenuItem(\'MenuItemGrabber\')" style="text-decoration:none;cursor:pointer"></a>';
grabber_config_info_html += '</div>';
$('#editor_container_instCapt').append(grabber_config_info_html);
conf_editor_instCapt.on('ready', function () {
if (!window.serverConfig.framegrabber.enable) {
conf_editor_instCapt.getEditor("root.instCapture.systemEnable").setValue(false);
conf_editor_instCapt.getEditor("root.instCapture.systemEnable").disable();
}
else {
conf_editor_instCapt.getEditor("root.instCapture.systemEnable").setValue(window.serverConfig.instCapture.systemEnable);
}
if (!window.serverConfig.grabberV4L2.enable) {
conf_editor_instCapt.getEditor("root.instCapture.v4lEnable").setValue(false);
conf_editor_instCapt.getEditor("root.instCapture.v4lEnable").disable();
}
else {
conf_editor_instCapt.getEditor("root.instCapture.v4lEnable").setValue(window.serverConfig.instCapture.v4lEnable);
}
});
conf_editor_instCapt.on('change', function () {
if (!conf_editor_instCapt.validate().length) {
if (!window.serverConfig.framegrabber.enable && !window.serverConfig.grabberV4L2.enable) {
$('#btn_submit_instCapt').attr('disabled', true);
} else {
window.readOnlyMode ? $('#btn_submit_instCapt').attr('disabled', true) : $('#btn_submit_instCapt').attr('disabled', false);
}
}
else {
$('#btn_submit_instCapt').attr('disabled', true);
}
});
conf_editor_instCapt.watch('root.instCapture.systemEnable', () => {
var screenEnable = conf_editor_instCapt.getEditor("root.instCapture.systemEnable").getValue();
if (screenEnable) {
conf_editor_instCapt.getEditor("root.instCapture.systemGrabberDevice").setValue(window.serverConfig.framegrabber.available_devices);
conf_editor_instCapt.getEditor("root.instCapture.systemGrabberDevice").disable();
showInputOptions("instCapture", ["systemGrabberDevice"], true);
showInputOptions("instCapture", ["systemPriority"], true);
} else {
showInputOptions("instCapture", ["systemGrabberDevice"], false);
showInputOptions("instCapture", ["systemPriority"], false);
}
});
conf_editor_instCapt.watch('root.instCapture.v4lEnable', () => {
var videoEnable = conf_editor_instCapt.getEditor("root.instCapture.v4lEnable").getValue();
if (videoEnable) {
conf_editor_instCapt.getEditor("root.instCapture.v4lGrabberDevice").setValue(window.serverConfig.grabberV4L2.available_devices);
conf_editor_instCapt.getEditor("root.instCapture.v4lGrabberDevice").disable();
showInputOptions("instCapture", ["v4lGrabberDevice"], true);
showInputOptions("instCapture", ["v4lPriority"], true);
}
else {
if (!window.serverConfig.grabberV4L2.enable) {
conf_editor_instCapt.getEditor("root.instCapture.v4lEnable").disable();
}
showInputOptions("instCapture", ["v4lGrabberDevice"], false);
showInputOptions("instCapture", ["v4lPriority"], false);
}
});
$('#btn_submit_instCapt').off().on('click', function () {
requestWriteConfig(conf_editor_instCapt.getValue());
});
removeOverlay();
});

View File

@@ -1,212 +1,185 @@
var conf_editor = null;
var createdCont = false;
var isScroll = true;
performTranslation();
requestLoggingStart();
requestLoggingStop();
$(document).ready(function() {
var messages;
var loguplmess = "";
var reportUrl = 'https://report.hyperion-project.org/#';
$(document).ready(function () {
$('#conf_cont').append(createOptPanel('fa-reorder', $.i18n("edt_conf_log_heading_title"), 'editor_container', 'btn_submit'));
if(window.showOptHelp)
{
$('#conf_cont').append(createHelpTable(window.schema.logger.properties, $.i18n("edt_conf_log_heading_title")));
createHintH("intro", $.i18n('conf_logging_label_intro'), "log_head");
}
$("#log_upl_pol").append('<span style="color:grey;font-size:80%">'+$.i18n("conf_logging_uplpolicy")+' '+buildWL("user/support#report_privacy_policy",$.i18n("conf_logging_contpolicy")));
requestLoggingStart();
conf_editor = createJsonEditor('editor_container', {
logger : window.schema.logger
}, true, true);
$('#conf_cont').append(createOptPanel('fa-reorder', $.i18n("edt_conf_log_heading_title"), 'editor_container', 'btn_submit'));
if (window.showOptHelp) {
$('#conf_cont').append(createHelpTable(window.schema.logger.properties, $.i18n("edt_conf_log_heading_title")));
createHintH("intro", $.i18n('conf_logging_label_intro'), "log_head");
}
conf_editor.on('change',function() {
conf_editor.validate().length || window.readOnlyMode ? $('#btn_submit').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
conf_editor = createJsonEditor('editor_container', {
logger: window.schema.logger
}, true, true);
$('#btn_submit').off().on('click',function() {
requestWriteConfig(conf_editor.getValue());
});
conf_editor.on('change', function () {
conf_editor.validate().length || window.readOnlyMode ? $('#btn_submit').attr('disabled', true) : $('#btn_submit').attr('disabled', false);
});
$('#btn_logupload').off().on('click',function() {
uploadLog();
$(this).attr("disabled", true);
$('#upl_link').html($.i18n('conf_logging_uploading'))
});
$('#btn_submit').off().on('click', function () {
//show prev uploads
var ent;
var displayedLogLevel = conf_editor.getEditor("root.logger.level").getValue();
var newLogLevel = { logger: {} };
newLogLevel.logger.level = displayedLogLevel;
if(getStorage("prev_reports"))
{
ent = JSON.parse(getStorage("prev_reports"));
$('#prev_reports').append('<h4 style="margin-top:30px">'+$.i18n('conf_logging_lastreports')+'</h4>');
for(var i = 0; i<ent.length; i++)
{
$('#prev_reports').append('<p><a href="'+reportUrl+ent[i].id+'" target="_blank">'+ent[i].title+'('+ent[i].time+')</a></p>');
}
}
else
ent = [];
requestWriteConfig(newLogLevel);
});
function updateLastReports(id,time,title)
{
if(ent.length > 4)
ent.pop();
ent.unshift({"id": id ,"time": time,"title": title})
setStorage("prev_reports",JSON.stringify(ent));
}
function infoSummary() {
var info = "";
function uploadLog()
{
var log = "";
var config = JSON.stringify(window.serverConfig, null).replace(/"/g, '\\"');
var prios = window.serverInfo.priorities;
var comps = window.serverInfo.components;
var sys = window.sysInfo.system;
var shy = window.sysInfo.hyperion;
var info;
info += 'Hyperion System Summary Report (' + window.serverConfig.general.name + '), Reported instance: ' + window.currentHyperionInstanceName + '\n';
//create log
log = (messages ? loguplmess : "Log was empty!");
info += "\n< ----- System information -------------------- >\n";
info += getSystemInfo() + '\n';
//create general info
info = "### GENERAL ### \n";
info += 'Build: '+shy.build+'\n';
info += 'Build time: '+shy.time+'\n';
info += 'Version: '+shy.version+'\n';
info += 'UI Lang: '+storedLang+' (BrowserL: '+navigator.language+')\n';
info += 'UI Access: '+storedAccess+'\n';
info += 'Log lvl: '+window.serverConfig.logger.level+'\n';
info += 'Avail Capt: '+window.serverInfo.grabbers.available+'\n';
info += 'Database: '+(shy.readOnlyMode ? "ready-only" : "read/write")+'\n';
info += '\n';
info += "\n< ----- Configured Instances ------------------ >\n";
var instances = window.serverInfo.instance;
for (var i = 0; i < instances.length; i++) {
info += instances[i].instance + ': ' + instances[i].friendly_name + ' Running: ' + instances[i].running + '\n';
}
info += 'Distribution: '+sys.prettyName+'\n';
info += 'Architecture: '+sys.architecture+'\n';
info += "\n< ----- This instance's priorities ------------ >\n";
var prios = window.serverInfo.priorities;
for (var i = 0; i < prios.length; i++) {
info += prios[i].priority + ': ';
if (prios[i].visible) {
info += ' VISIBLE!';
}
else {
info += ' ';
}
info += ' (' + prios[i].componentId + ') Owner: ' + prios[i].owner + '\n';
}
info += 'priorities_autoselect: ' + window.serverInfo.priorities_autoselect + '\n';
if (sys.cpuModelName)
info += 'CPU Model: ' + sys.cpuModelName + '\n';
if (sys.cpuModelType)
info += 'CPU Type: ' + sys.cpuModelType + '\n';
if (sys.cpuRevision)
info += 'CPU Revision: ' + sys.cpuRevision + '\n';
if (sys.cpuHardware)
info += 'CPU Hardware: ' + sys.cpuHardware + '\n';
info += "\n< ----- This instance components' status ------->\n";
var comps = window.serverInfo.components;
for (var i = 0; i < comps.length; i++) {
info += comps[i].name + ' - ' + comps[i].enabled + '\n';
}
info += 'Kernel: ' + sys.kernelType+' ('+sys.kernelVersion+' (WS: '+sys.wordSize+'))' + '\n';
info += 'Qt Version: ' + sys.qtVersion + '\n';
info += 'Python Version: ' + sys.pyVersion + '\n';
info += 'Browser/OS: ' + navigator.userAgent + '\n\n';
info += "\n< ----- This instance's configuration --------- >\n";
info += JSON.stringify(window.serverConfig) + '\n';
//create prios
info += "### PRIORITIES ### \n";
for(var i = 0; i<prios.length; i++)
{
info += prios[i].priority;
if(prios[i].visible)
info += ' VISIBLE!';
else
info += ' ';
info += ' ('+prios[i].component+') Owner: '+prios[i].owner+'\n';
}
info += '\npriorities_autoselect: '+window.serverInfo.priorities_autoselect+'\n\n';
info += "\n< ----- Current Log --------------------------- >\n";
var logMsgs = document.getElementById("logmessages").textContent;
if (logMsgs.length !== 0) {
info += logMsgs;
} else {
info += "Log is empty!";
}
//create comps
info += '### COMPONENTS ### \n';
for(var i = 0; i<comps.length; i++)
{
info += comps[i].enabled+' - '+comps[i].name+'\n';
}
return info;
}
//escape data
info = JSON.stringify(info);
log = JSON.stringify(log);
config = JSON.stringify(config);
var title = 'Hyperion '+window.currentVersion+' Report ('+window.serverConfig.general.name+' ('+window.serverInfo.ledDevices.active+'))';
function createLogContainer() {
$.ajax({
url: 'https://api.hyperion-project.org/report.php',
crossDomain: true,
contentType: 'application/json',
type: 'POST',
timeout: 7000,
data: '{"title":"'+title+'","info":'+info+',"log":'+log+',"config":'+config+'}'
})
.done( function( data, textStatus, jqXHR ) {
reportUrl += data.id;
if(textStatus == "success")
{
$('#upl_link').html($.i18n('conf_logging_yourlink')+': <a href="'+reportUrl+'" target="_blank">'+reportUrl+'</a>');
$("html, body").animate({ scrollTop: 9999 }, "fast");
updateLastReports(data.id,data.time,title);
}
else
{
$('#btn_logupload').attr("disabled", false);
$('#upl_link').html('<span style="color:red">'+$.i18n('conf_logging_uplfailed')+'<span>');
}
})
.fail( function( jqXHR, textStatus ) {
console.log(jqXHR,textStatus);
$('#btn_logupload').attr("disabled", false);
$('#upl_link').html('<span style="color:red">'+$.i18n('conf_logging_uplfailed')+'<span>');
});
}
const isScrollEnableStyle = (isScroll ? "checked" : "");
if (!window.loggingHandlerInstalled)
{
window.loggingHandlerInstalled = true;
$(window.hyperion).on("cmd-logging-update",function(event){
$('#log_content').html('<pre><div id="logmessages" style="overflow:scroll;max-height:400px"></div></pre>');
$('#log_footer').append('<label class="checkbox-inline">'
+ '<input id = "btn_scroll"' + isScrollEnableStyle + ' type = "checkbox"'
+ 'data-toggle="toggle" data-onstyle="success" data-on="' + $.i18n('general_btn_on') + '" data-off="' + $.i18n('general_btn_off') + '">'
+ $.i18n('conf_logging_btn_autoscroll') + '</label>'
);
if ($("#logmessages").length == 0 && window.loggingStreamActive)
{
requestLoggingStop();
window.loggingStreamActive = false;
}
$(`#btn_scroll`).bootstrapToggle();
$(`#btn_scroll`).change(e => {
if (e.currentTarget.checked) {
//Scroll to end of log
isScroll = true;
if ($("#logmessages").length > 0) {
$('#logmessages')[0].scrollTop = $('#logmessages')[0].scrollHeight;
}
} else {
isScroll = false;
}
});
messages = (event.response.result.messages);
if(messages.length != 0 && !createdCont)
{
$('#log_content').html('<pre><div id="logmessages" style="overflow:scroll;max-height:400px"></div></pre><button class="btn btn-primary" id="btn_autoscroll"><i class="fa fa-long-arrow-down fa-fw"></i>'+$.i18n('conf_logging_btn_autoscroll')+'</button>');
createdCont = true;
$('#log_footer').append('<button class="btn btn-primary pull-right" id="btn_clipboard"><i class="fa fa-fw fa-clipboard"></i>' + $.i18n("conf_logging_btn_clipboard") + '</button>');
$('#btn_autoscroll').off().on('click',function() {
toggleClass('#btn_autoscroll', "btn-success", "btn-danger");
});
}
$('#btn_clipboard').off().on('click', function () {
const temp = document.createElement('textarea');
temp.textContent = infoSummary();
document.body.append(temp);
temp.select();
document.execCommand("copy");
temp.remove();
});
}
for(var idx = 0; idx < messages.length; idx++)
{
var app_name = messages[idx].appName;
var logger_name = messages[idx].loggerName;
var function_ = messages[idx].function;
var line = messages[idx].line;
var file_name = messages[idx].fileName;
var msg = messages[idx].message;
var level_string = messages[idx].levelString;
var utime = messages[idx].utime;
function updateLogOutput(messages) {
var debug = "";
if(level_string == "DEBUG") {
debug = "("+file_name+":"+line+":"+function_+"()) ";
}
if (messages.length != 0) {
var date = new Date(parseInt(utime));
for (var idx = 0; idx < messages.length; idx++) {
var app_name = messages[idx].appName;
var logger_name = messages[idx].loggerName;
var function_ = messages[idx].function;
var line = messages[idx].line;
var file_name = messages[idx].fileName;
var msg = encodeHTML(messages[idx].message);
var level_string = messages[idx].levelString;
var utime = messages[idx].utime;
$("#logmessages").append("\n <code>"+date.toISOString()+" ["+app_name+" "+logger_name+"] ("+level_string+") "+debug+msg+"</code>");
loguplmess += "["+app_name+" "+logger_name+"] ("+level_string+") "+debug+msg+"\n";
}
var debug = "";
if (level_string == "DEBUG") {
debug = "(" + file_name + ":" + line + ":" + function_ + "()) ";
}
if($("#btn_autoscroll").hasClass('btn-success'))
{
$('#logmessages').stop().animate({
scrollTop: $('#logmessages')[0].scrollHeight
}, 800);
}
});
}
var date = new Date(parseInt(utime));
var newLogLine = date.toISOString() + " [" + app_name + " " + logger_name + "] (" + level_string + ") " + debug + msg;
removeOverlay();
$("#logmessages").append("<code>" + newLogLine + "</code>\n");
}
if (isScroll && $("#logmessages").length > 0) {
$('#logmessages').stop().animate({
scrollTop: $('#logmessages')[0].scrollHeight
}, 800);
}
}
}
if (!window.loggingHandlerInstalled) {
window.loggingHandlerInstalled = true;
$(window.hyperion).on("cmd-logging-update", function (event) {
var messages = (event.response.result.messages);
if (messages.length != 0) {
if (!createdCont) {
createLogContainer();
createdCont = true;
}
updateLogOutput(messages)
}
});
}
$(window.hyperion).on("cmd-settings-update", function (event) {
var obj = event.response.data
if (obj.logger) {
Object.getOwnPropertyNames(obj).forEach(function (val, idx, array) {
window.serverConfig[val] = obj[val];
});
var currentlogLevel = window.serverConfig.logger.level;
conf_editor.getEditor("root.logger.level").setValue(currentlogLevel);
location.reload();
}
});
removeOverlay();
});

View File

@@ -1,218 +1,250 @@
$(document).ready( function() {
performTranslation();
$(document).ready(function () {
performTranslation();
var conf_editor_net = null;
var conf_editor_json = null;
var conf_editor_proto = null;
var conf_editor_fbs = null;
var conf_editor_bobl = null;
var conf_editor_forw = null;
var BOBLIGHT_ENABLED = window.comps.find(element => element.name == "BOBLIGHTSERVER");
if(window.showOptHelp)
{
//network
$('#conf_cont').append(createRow('conf_cont_net'))
$('#conf_cont_net').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_net_heading_title"), 'editor_container_net', 'btn_submit_net'));
$('#conf_cont_net').append(createHelpTable(window.schema.network.properties, $.i18n("edt_conf_net_heading_title")));
var conf_editor_net = null;
var conf_editor_json = null;
var conf_editor_proto = null;
var conf_editor_fbs = null;
var conf_editor_bobl = null;
var conf_editor_forw = null;
//jsonserver
$('#conf_cont').append(createRow('conf_cont_json'))
$('#conf_cont_json').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_js_heading_title"), 'editor_container_jsonserver', 'btn_submit_jsonserver'));
$('#conf_cont_json').append(createHelpTable(window.schema.jsonServer.properties, $.i18n("edt_conf_js_heading_title")));
if (window.showOptHelp) {
//network
$('#conf_cont').append(createRow('conf_cont_net'))
$('#conf_cont_net').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_net_heading_title"), 'editor_container_net', 'btn_submit_net', 'panel-system'));
$('#conf_cont_net').append(createHelpTable(window.schema.network.properties, $.i18n("edt_conf_net_heading_title")));
//flatbufserver
$('#conf_cont').append(createRow('conf_cont_flatbuf'))
$('#conf_cont_flatbuf').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fbs_heading_title"), 'editor_container_fbserver', 'btn_submit_fbserver'));
$('#conf_cont_flatbuf').append(createHelpTable(window.schema.flatbufServer.properties, $.i18n("edt_conf_fbs_heading_title")));
//jsonserver
$('#conf_cont').append(createRow('conf_cont_json'))
$('#conf_cont_json').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_js_heading_title"), 'editor_container_jsonserver', 'btn_submit_jsonserver', 'panel-system'));
$('#conf_cont_json').append(createHelpTable(window.schema.jsonServer.properties, $.i18n("edt_conf_js_heading_title")));
//protoserver
$('#conf_cont').append(createRow('conf_cont_proto'))
$('#conf_cont_proto').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_pbs_heading_title"), 'editor_container_protoserver', 'btn_submit_protoserver'));
$('#conf_cont_proto').append(createHelpTable(window.schema.protoServer.properties, $.i18n("edt_conf_pbs_heading_title")));
//flatbufserver
$('#conf_cont').append(createRow('conf_cont_flatbuf'))
$('#conf_cont_flatbuf').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fbs_heading_title"), 'editor_container_fbserver', 'btn_submit_fbserver', 'panel-system'));
$('#conf_cont_flatbuf').append(createHelpTable(window.schema.flatbufServer.properties, $.i18n("edt_conf_fbs_heading_title"), "flatbufServerHelpPanelId"));
//boblight
$('#conf_cont').append(createRow('conf_cont_bobl'))
$('#conf_cont_bobl').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_bobls_heading_title"), 'editor_container_boblightserver', 'btn_submit_boblightserver'));
$('#conf_cont_bobl').append(createHelpTable(window.schema.boblightServer.properties, $.i18n("edt_conf_bobls_heading_title")));
//protoserver
$('#conf_cont').append(createRow('conf_cont_proto'))
$('#conf_cont_proto').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_pbs_heading_title"), 'editor_container_protoserver', 'btn_submit_protoserver', 'panel-system'));
$('#conf_cont_proto').append(createHelpTable(window.schema.protoServer.properties, $.i18n("edt_conf_pbs_heading_title"), "protoServerHelpPanelId"));
//forwarder
if(storedAccess != 'default')
{
$('#conf_cont').append(createRow('conf_cont_fw'))
$('#conf_cont_fw').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fw_heading_title"), 'editor_container_forwarder', 'btn_submit_forwarder'));
$('#conf_cont_fw').append(createHelpTable(window.schema.forwarder.properties, $.i18n("edt_conf_fw_heading_title")));
}
}
else
{
$('#conf_cont').addClass('row');
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_net_heading_title"), 'editor_container_net', 'btn_submit_net'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_js_heading_title"), 'editor_container_jsonserver', 'btn_submit_jsonserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fbs_heading_title"), 'editor_container_fbserver', 'btn_submit_fbserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_pbs_heading_title"), 'editor_container_protoserver', 'btn_submit_protoserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_bobls_heading_title"), 'editor_container_boblightserver', 'btn_submit_boblightserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fw_heading_title"), 'editor_container_forwarder', 'btn_submit_forwarder'));
//boblight
if (BOBLIGHT_ENABLED) {
$('#conf_cont').append(createRow('conf_cont_bobl'))
$('#conf_cont_bobl').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_bobls_heading_title"), 'editor_container_boblightserver', 'btn_submit_boblightserver', 'panel-system'));
$('#conf_cont_bobl').append(createHelpTable(window.schema.boblightServer.properties, $.i18n("edt_conf_bobls_heading_title"), "boblightServerHelpPanelId"));
}
$("#conf_cont_tok").removeClass('row');
}
//forwarder
if (storedAccess != 'default') {
$('#conf_cont').append(createRow('conf_cont_fw'))
$('#conf_cont_fw').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fw_heading_title"), 'editor_container_forwarder', 'btn_submit_forwarder', 'panel-system'));
$('#conf_cont_fw').append(createHelpTable(window.schema.forwarder.properties, $.i18n("edt_conf_fw_heading_title"), "forwarderHelpPanelId"));
}
}
else {
$('#conf_cont').addClass('row');
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_net_heading_title"), 'editor_container_net', 'btn_submit_net'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_js_heading_title"), 'editor_container_jsonserver', 'btn_submit_jsonserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fbs_heading_title"), 'editor_container_fbserver', 'btn_submit_fbserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_pbs_heading_title"), 'editor_container_protoserver', 'btn_submit_protoserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_bobls_heading_title"), 'editor_container_boblightserver', 'btn_submit_boblightserver'));
$('#conf_cont').append(createOptPanel('fa-sitemap', $.i18n("edt_conf_fw_heading_title"), 'editor_container_forwarder', 'btn_submit_forwarder'));
// net
conf_editor_net = createJsonEditor('editor_container_net', {
network : window.schema.network
}, true, true);
$("#conf_cont_tok").removeClass('row');
}
conf_editor_net.on('change',function() {
conf_editor_net.validate().length || window.readOnlyMode ? $('#btn_submit_net').attr('disabled', true) : $('#btn_submit_net').attr('disabled', false);
});
// net
conf_editor_net = createJsonEditor('editor_container_net', {
network: window.schema.network
}, true, true);
$('#btn_submit_net').off().on('click',function() {
requestWriteConfig(conf_editor_net.getValue());
});
conf_editor_net.on('change', function () {
conf_editor_net.validate().length || window.readOnlyMode ? $('#btn_submit_net').attr('disabled', true) : $('#btn_submit_net').attr('disabled', false);
});
//json
conf_editor_json = createJsonEditor('editor_container_jsonserver', {
jsonServer : window.schema.jsonServer
}, true, true);
$('#btn_submit_net').off().on('click', function () {
requestWriteConfig(conf_editor_net.getValue());
});
conf_editor_json.on('change',function() {
conf_editor_json.validate().length || window.readOnlyMode ? $('#btn_submit_jsonserver').attr('disabled', true) : $('#btn_submit_jsonserver').attr('disabled', false);
});
//json
conf_editor_json = createJsonEditor('editor_container_jsonserver', {
jsonServer: window.schema.jsonServer
}, true, true);
$('#btn_submit_jsonserver').off().on('click',function() {
requestWriteConfig(conf_editor_json.getValue());
});
conf_editor_json.on('change', function () {
conf_editor_json.validate().length || window.readOnlyMode ? $('#btn_submit_jsonserver').attr('disabled', true) : $('#btn_submit_jsonserver').attr('disabled', false);
});
//flatbuffer
conf_editor_fbs = createJsonEditor('editor_container_fbserver', {
flatbufServer : window.schema.flatbufServer
}, true, true);
$('#btn_submit_jsonserver').off().on('click', function () {
requestWriteConfig(conf_editor_json.getValue());
});
conf_editor_fbs.on('change',function() {
conf_editor_fbs.validate().length || window.readOnlyMode ? $('#btn_submit_fbserver').attr('disabled', true) : $('#btn_submit_fbserver').attr('disabled', false);
});
//flatbuffer
conf_editor_fbs = createJsonEditor('editor_container_fbserver', {
flatbufServer: window.schema.flatbufServer
}, true, true);
$('#btn_submit_fbserver').off().on('click',function() {
requestWriteConfig(conf_editor_fbs.getValue());
});
conf_editor_fbs.on('change', function () {
var flatbufServerEnable = conf_editor_fbs.getEditor("root.flatbufServer.enable").getValue();
if (flatbufServerEnable) {
showInputOptionsForKey(conf_editor_fbs, "flatbufServer", "enable", true);
$('#flatbufServerHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_fbs, "flatbufServer", "enable", false);
$('#flatbufServerHelpPanelId').hide();
}
conf_editor_fbs.validate().length || window.readOnlyMode ? $('#btn_submit_fbserver').attr('disabled', true) : $('#btn_submit_fbserver').attr('disabled', false);
});
//protobuffer
conf_editor_proto = createJsonEditor('editor_container_protoserver', {
protoServer : window.schema.protoServer
}, true, true);
$('#btn_submit_fbserver').off().on('click', function () {
requestWriteConfig(conf_editor_fbs.getValue());
});
conf_editor_proto.on('change',function() {
conf_editor_proto.validate().length || window.readOnlyMode ? $('#btn_submit_protoserver').attr('disabled', true) : $('#btn_submit_protoserver').attr('disabled', false);
});
//protobuffer
conf_editor_proto = createJsonEditor('editor_container_protoserver', {
protoServer: window.schema.protoServer
}, true, true);
$('#btn_submit_protoserver').off().on('click',function() {
requestWriteConfig(conf_editor_proto.getValue());
});
conf_editor_proto.on('change', function () {
var protoServerEnable = conf_editor_proto.getEditor("root.protoServer.enable").getValue();
if (protoServerEnable) {
showInputOptionsForKey(conf_editor_proto, "protoServer", "enable", true);
$('#protoServerHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_proto, "protoServer", "enable", false);
$('#protoServerHelpPanelId').hide();
}
conf_editor_proto.validate().length || window.readOnlyMode ? $('#btn_submit_protoserver').attr('disabled', true) : $('#btn_submit_protoserver').attr('disabled', false);
});
//boblight
conf_editor_bobl = createJsonEditor('editor_container_boblightserver', {
boblightServer : window.schema.boblightServer
}, true, true);
$('#btn_submit_protoserver').off().on('click', function () {
requestWriteConfig(conf_editor_proto.getValue());
});
conf_editor_bobl.on('change',function() {
conf_editor_bobl.validate().length || window.readOnlyMode ? $('#btn_submit_boblightserver').attr('disabled', true) : $('#btn_submit_boblightserver').attr('disabled', false);
});
//boblight
if (BOBLIGHT_ENABLED) {
conf_editor_bobl = createJsonEditor('editor_container_boblightserver', {
boblightServer: window.schema.boblightServer
}, true, true);
$('#btn_submit_boblightserver').off().on('click',function() {
requestWriteConfig(conf_editor_bobl.getValue());
});
conf_editor_bobl.on('change', function () {
var boblightServerEnable = conf_editor_bobl.getEditor("root.boblightServer.enable").getValue();
if (boblightServerEnable) {
showInputOptionsForKey(conf_editor_bobl, "boblightServer", "enable", true);
$('#boblightServerHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_bobl, "boblightServer", "enable", false);
$('#boblightServerHelpPanelId').hide();
}
conf_editor_bobl.validate().length || window.readOnlyMode ? $('#btn_submit_boblightserver').attr('disabled', true) : $('#btn_submit_boblightserver').attr('disabled', false);
});
if(storedAccess != 'default')
{
//forwarder
conf_editor_forw = createJsonEditor('editor_container_forwarder', {
forwarder : window.schema.forwarder
}, true, true);
$('#btn_submit_boblightserver').off().on('click', function () {
requestWriteConfig(conf_editor_bobl.getValue());
});
}
conf_editor_forw.on('change',function() {
conf_editor_forw.validate().length || window.readOnlyMode ? $('#btn_submit_forwarder').attr('disabled', true) : $('#btn_submit_forwarder').attr('disabled', false);
});
if (storedAccess != 'default') {
//forwarder
conf_editor_forw = createJsonEditor('editor_container_forwarder', {
forwarder: window.schema.forwarder
}, true, true);
$('#btn_submit_forwarder').off().on('click',function() {
requestWriteConfig(conf_editor_forw.getValue());
});
}
conf_editor_forw.on('change', function () {
var forwarderEnable = conf_editor_forw.getEditor("root.forwarder.enable").getValue();
if (forwarderEnable) {
showInputOptionsForKey(conf_editor_forw, "forwarder", "enable", true);
$('#forwarderHelpPanelId').show();
} else {
showInputOptionsForKey(conf_editor_forw, "forwarder", "enable", false);
$('#forwarderHelpPanelId').hide();
}
conf_editor_forw.validate().length || window.readOnlyMode ? $('#btn_submit_forwarder').attr('disabled', true) : $('#btn_submit_forwarder').attr('disabled', false);
});
//create introduction
if(window.showOptHelp)
{
createHint("intro", $.i18n('conf_network_net_intro'), "editor_container_net");
createHint("intro", $.i18n('conf_network_json_intro'), "editor_container_jsonserver");
createHint("intro", $.i18n('conf_network_fbs_intro'), "editor_container_fbserver");
createHint("intro", $.i18n('conf_network_proto_intro'), "editor_container_protoserver");
createHint("intro", $.i18n('conf_network_bobl_intro'), "editor_container_boblightserver");
createHint("intro", $.i18n('conf_network_forw_intro'), "editor_container_forwarder");
createHint("intro", $.i18n('conf_network_tok_intro'), "tok_desc_cont");
}
$('#btn_submit_forwarder').off().on('click', function () {
requestWriteConfig(conf_editor_forw.getValue());
});
}
// Token handling
function buildTokenList()
{
$('.tktbody').html("");
for(var key in tokenList)
{
var lastUse = (tokenList[key].last_use) ? tokenList[key].last_use : "-";
var btn = '<button id="tok'+tokenList[key].id+'" type="button" class="btn btn-danger">'+$.i18n('general_btn_delete')+'</button>';
$('.tktbody').append(createTableRow([tokenList[key].comment, lastUse, btn], false, true));
$('#tok'+tokenList[key].id).off().on('click', handleDeleteToken);
}
}
//create introduction
if (window.showOptHelp) {
createHint("intro", $.i18n('conf_network_net_intro'), "editor_container_net");
createHint("intro", $.i18n('conf_network_json_intro'), "editor_container_jsonserver");
createHint("intro", $.i18n('conf_network_fbs_intro'), "editor_container_fbserver");
createHint("intro", $.i18n('conf_network_proto_intro'), "editor_container_protoserver");
if (BOBLIGHT_ENABLED) {
createHint("intro", $.i18n('conf_network_bobl_intro'), "editor_container_boblightserver");
}
createHint("intro", $.i18n('conf_network_forw_intro'), "editor_container_forwarder");
createHint("intro", $.i18n('conf_network_tok_intro'), "tok_desc_cont");
}
createTable('tkthead', 'tktbody', 'tktable');
$('.tkthead').html(createTableRow([$.i18n('conf_network_tok_cidhead'), $.i18n('conf_network_tok_lastuse'), $.i18n('general_btn_delete')], true, true));
buildTokenList();
// Token handling
function buildTokenList() {
$('.tktbody').html("");
for (var key in tokenList) {
var lastUse = (tokenList[key].last_use) ? tokenList[key].last_use : "-";
var btn = '<button id="tok' + tokenList[key].id + '" type="button" class="btn btn-danger">' + $.i18n('general_btn_delete') + '</button>';
$('.tktbody').append(createTableRow([tokenList[key].comment, lastUse, btn], false, true));
$('#tok' + tokenList[key].id).off().on('click', handleDeleteToken);
}
}
function handleDeleteToken(e)
{
var key = e.currentTarget.id.replace("tok","");
requestTokenDelete(key);
$('#tok'+key).parent().parent().remove();
// rm deleted token id
tokenList = tokenList.filter(function( obj ) {
return obj.id !== key;
});
}
createTable('tkthead', 'tktbody', 'tktable');
$('.tkthead').html(createTableRow([$.i18n('conf_network_tok_cidhead'), $.i18n('conf_network_tok_lastuse'), $.i18n('general_btn_delete')], true, true));
buildTokenList();
$('#btn_create_tok').off().on('click',function() {
requestToken($('#tok_comment').val())
$('#tok_comment').val("")
$('#btn_create_tok').attr('disabled', true)
});
$('#tok_comment').off().on('input',function(e) {
(e.currentTarget.value.length >= 10) ? $('#btn_create_tok').attr('disabled', false) : $('#btn_create_tok').attr('disabled', true);
if(10-e.currentTarget.value.length >= 1 && 10-e.currentTarget.value.length <= 9)
$('#tok_chars_needed').html(10-e.currentTarget.value.length + " " + $.i18n('general_chars_needed'))
else
$('#tok_chars_needed').html("<br />")
});
$(window.hyperion).off("cmd-authorize-createToken").on("cmd-authorize-createToken", function(event) {
var val = event.response.info;
showInfoDialog("newToken",$.i18n('conf_network_tok_diaTitle'),$.i18n('conf_network_tok_diaMsg')+'<br><div style="font-weight:bold">'+val.token+'</div>')
tokenList.push(val)
buildTokenList()
});
function handleDeleteToken(e) {
var key = e.currentTarget.id.replace("tok", "");
requestTokenDelete(key);
$('#tok' + key).parent().parent().remove();
// rm deleted token id
tokenList = tokenList.filter(function (obj) {
return obj.id !== key;
});
}
//Reorder hardcoded token div after the general token setting div
$("#conf_cont_tok").insertAfter("#conf_cont_net");
$('#btn_create_tok').off().on('click', function () {
requestToken(encodeHTML($('#tok_comment').val()))
$('#tok_comment').val("")
$('#btn_create_tok').attr('disabled', true)
});
$('#tok_comment').off().on('input', function (e) {
(e.currentTarget.value.length >= 10) ? $('#btn_create_tok').attr('disabled', false) : $('#btn_create_tok').attr('disabled', true);
if (10 - e.currentTarget.value.length >= 1 && 10 - e.currentTarget.value.length <= 9)
$('#tok_chars_needed').html(10 - e.currentTarget.value.length + " " + $.i18n('general_chars_needed'))
else
$('#tok_chars_needed').html("<br />")
});
$(window.hyperion).off("cmd-authorize-createToken").on("cmd-authorize-createToken", function (event) {
var val = event.response.info;
showInfoDialog("newToken", $.i18n('conf_network_tok_diaTitle'), $.i18n('conf_network_tok_diaMsg') + '<br><div style="font-weight:bold">' + val.token + '</div>')
tokenList.push(val)
buildTokenList()
});
function checkApiTokenState(state)
{
if(state == false)
$("#conf_cont_tok").attr('style', 'display:none')
else
$("#conf_cont_tok").removeAttr('style')
}
//Reorder hardcoded token div after the general token setting div
$("#conf_cont_tok").insertAfter("#conf_cont_net");
$('#root_network_apiAuth').change(function () {
var state = $(this).is(":checked");
checkApiTokenState(state);
})
function checkApiTokenState(state) {
if (state == false)
$("#conf_cont_tok").attr('style', 'display:none')
else
$("#conf_cont_tok").removeAttr('style')
}
checkApiTokenState(window.serverConfig.network.apiAuth);
removeOverlay();
$('#root_network_apiAuth').change(function () {
var state = $(this).is(":checked");
checkApiTokenState(state);
})
checkApiTokenState(window.serverConfig.network.apiAuth);
removeOverlay();
});

View File

@@ -1,13 +1,16 @@
$(document).ready(function() {
$(document).ready(function () {
performTranslation();
// update instance listing
updateHyperionInstanceListing();
var oldEffects = [];
var cpcolor = '#B500FF';
var mappingList = window.serverSchema.properties.color.properties.imageToLedMappingType.enum;
var duration = 0;
var rgb = {r:255,g:0,b:0};
var duration = ENDLESS;
var rgb = { r: 255, g: 0, b: 0 };
var lastImgData = "";
var lastFileName= "";
var lastFileName = "";
//create html
createTable('ssthead', 'sstbody', 'sstcont');
@@ -16,8 +19,7 @@ $(document).ready(function() {
//create introduction
if(window.showOptHelp)
{
if (window.showOptHelp) {
createHint("intro", $.i18n('remote_color_intro', $.i18n('remote_losthint')), "color_intro");
createHint("intro", $.i18n('remote_input_intro', $.i18n('remote_losthint')), "sstcont");
createHint("intro", $.i18n('remote_adjustment_intro', $.i18n('remote_losthint')), "adjust_content");
@@ -30,83 +32,73 @@ $(document).ready(function() {
var sColor = sortProperties(window.serverSchema.properties.color.properties.channelAdjustment.items.properties);
var values = window.serverInfo.adjustment[0];
for(var key in sColor)
{
if(sColor[key].key != "id" && sColor[key].key != "leds")
{
var title = '<label for="cr_'+sColor[key].key+'">'+$.i18n(sColor[key].title)+'</label>';
for (var key in sColor) {
if (sColor[key].key != "id" && sColor[key].key != "leds") {
var title = '<label for="cr_' + sColor[key].key + '">' + $.i18n(sColor[key].title) + '</label>';
var property;
var value = values[sColor[key].key];
if(sColor[key].type == "array")
{
property = '<div id="cr_'+sColor[key].key+'" class="input-group colorpicker-component" ><input type="text" class="form-control" /><span class="input-group-addon"><i></i></span></div>';
if (sColor[key].type == "array") {
property = '<div id="cr_' + sColor[key].key + '" class="input-group colorpicker-component" ><input type="text" class="form-control" /><span class="input-group-addon"><i></i></span></div>';
$('.crtbody').append(createTableRow([title, property], false, true));
createCP('cr_'+sColor[key].key, value, function(rgb,hex,e){
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), '['+rgb.r+','+rgb.g+','+rgb.b+']');
createCP('cr_' + sColor[key].key, value, function (rgb, hex, e) {
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), '[' + rgb.r + ',' + rgb.g + ',' + rgb.b + ']');
});
}
else if(sColor[key].type == "boolean")
{
property = '<div class="checkbox"><input id="cr_'+sColor[key].key+'" type="checkbox" value="'+value+'"/><label></label></div>';
else if (sColor[key].type == "boolean") {
property = '<div class="checkbox"><input id="cr_' + sColor[key].key + '" type="checkbox" value="' + value + '"/><label></label></div>';
$('.crtbody').append(createTableRow([title, property], false, true));
$('#cr_'+sColor[key].key).off().on('change', function(e){
$('#cr_' + sColor[key].key).off().on('change', function (e) {
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), e.currentTarget.checked);
});
}
else
{
if(sColor[key].key == "brightness" || sColor[key].key == "brightnessCompensation" || sColor[key].key == "backlightThreshold")
property = '<div class="input-group"><input id="cr_'+sColor[key].key+'" type="number" class="form-control" min="0" max="100" step="10" value="'+value+'"/><span class="input-group-addon">'+$.i18n("edt_append_percent")+'</span></div>';
else {
if (sColor[key].key == "brightness" || sColor[key].key == "brightnessCompensation" || sColor[key].key == "backlightThreshold")
property = '<div class="input-group"><input id="cr_' + sColor[key].key + '" type="number" class="form-control" min="0" max="100" step="10" value="' + value + '"/><span class="input-group-addon">' + $.i18n("edt_append_percent") + '</span></div>';
else
property = '<input id="cr_'+sColor[key].key+'" type="number" class="form-control" min="0.1" max="4.0" step="0.1" value="'+value+'"/>';
property = '<input id="cr_' + sColor[key].key + '" type="number" class="form-control" min="0.1" max="4.0" step="0.1" value="' + value + '"/>';
$('.crtbody').append(createTableRow([title, property], false, true));
$('#cr_'+sColor[key].key).off().on('change', function(e){
valValue(this.id,this.value,this.min,this.max);
$('#cr_' + sColor[key].key).off().on('change', function (e) {
valValue(this.id, this.value, this.min, this.max);
requestAdjustment(e.target.id.substr(e.target.id.indexOf("_") + 1), e.currentTarget.value);
});
}
}
}
function sendEffect()
{
function sendEffect() {
var efx = $("#effect_select").val();
if(efx != "__none__")
{
if (efx != "__none__") {
requestPriorityClear();
$(window.hyperion).one("cmd-clear", function(event) {
setTimeout(function() {requestPlayEffect(efx,duration)}, 100);
$(window.hyperion).one("cmd-clear", function (event) {
setTimeout(function () { requestPlayEffect(efx, duration) }, 100);
});
}
}
function sendColor()
{
requestSetColor(rgb.r, rgb.g, rgb.b,duration);
function sendColor() {
requestSetColor(rgb.r, rgb.g, rgb.b, duration);
}
function updateInputSelect()
{
function updateInputSelect() {
$('.sstbody').html("");
var prios = window.serverInfo.priorities;
var clearAll = false;
for(var i = 0; i < prios.length; i++)
{
var origin = prios[i].origin ? prios[i].origin : "System";
for (var i = 0; i < prios.length; i++) {
var origin = prios[i].origin ? prios[i].origin : "System";
origin = origin.split("@");
var ip = origin[1];
origin = origin[0];
var owner = prios[i].owner;
var active = prios[i].active;
var visible = prios[i].visible;
var owner = prios[i].owner;
var active = prios[i].active;
var visible = prios[i].visible;
var priority = prios[i].priority;
var compId = prios[i].componentId;
var duration = prios[i].duration_ms/1000;
var compId = prios[i].componentId;
var duration = prios[i].duration_ms / 1000;
var value = "0,0,0";
var btn_type = "default";
var btn_text = $.i18n('remote_input_setsource_btn');
@@ -115,40 +107,38 @@ $(document).ready(function() {
if (active)
btn_type = "primary";
if(priority > 254)
if (priority > 254)
continue;
if(priority < 254 && (compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE") )
if (priority < 254 && (compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE"))
clearAll = true;
if (visible)
{
if (visible) {
btn_state = "disabled";
btn_type = "success";
btn_text = $.i18n('remote_input_sourceactiv_btn');
}
if(ip)
origin += '<br/><span style="font-size:80%; color:grey;">'+$.i18n('remote_input_ip')+' '+ip+'</span>';
if (ip)
origin += '<br/><span style="font-size:80%; color:grey;">' + $.i18n('remote_input_ip') + ' ' + ip + '</span>';
if("value" in prios[i])
if ("value" in prios[i])
value = prios[i].value.RGB;
switch (compId)
{
switch (compId) {
case "EFFECT":
owner = $.i18n('remote_effects_label_effects')+' '+owner;
owner = $.i18n('remote_effects_label_effects') + ' ' + owner;
break;
case "COLOR":
owner = $.i18n('remote_color_label_color')+' '+'<div style="width:18px; height:18px; border-radius:20px; margin-bottom:-4px; border:1px grey solid; background-color: rgb('+value+'); display:inline-block" title="RGB: ('+value+')"></div>';
owner = $.i18n('remote_color_label_color') + ' ' + '<div style="width:18px; height:18px; border-radius:20px; margin-bottom:-4px; border:1px grey solid; background-color: rgb(' + value + '); display:inline-block" title="RGB: (' + value + ')"></div>';
break;
case "IMAGE":
owner = $.i18n('remote_effects_label_picture')+' '+owner;
owner = $.i18n('remote_effects_label_picture') + ' ' + owner;
break;
case "GRABBER":
owner = $.i18n('general_comp_GRABBER')+': ('+owner+')';
case "GRABBER":
owner = $.i18n('general_comp_GRABBER') + ': (' + owner + ')';
break;
case "V4L":
owner = $.i18n('general_comp_V4L')+': ('+owner+')';
owner = $.i18n('general_comp_V4L') + ': (' + owner + ')';
break;
case "BOBLIGHTSERVER":
owner = $.i18n('general_comp_BOBLIGHTSERVER');
@@ -161,126 +151,114 @@ $(document).ready(function() {
break;
}
if(duration && compId != "GRABBER" && compId != "FLATBUFSERVER" && compId != "PROTOSERVER")
owner += '<br/><span style="font-size:80%; color:grey;">'+$.i18n('remote_input_duration')+' '+duration.toFixed(0)+$.i18n('edt_append_s')+'</span>';
if (duration && compId != "GRABBER" && compId != "FLATBUFSERVER" && compId != "PROTOSERVER")
owner += '<br/><span style="font-size:80%; color:grey;">' + $.i18n('remote_input_duration') + ' ' + duration.toFixed(0) + $.i18n('edt_append_s') + '</span>';
var btn = '<button id="srcBtn'+i+'" type="button" '+btn_state+' class="btn btn-'+btn_type+' btn_input_selection" onclick="requestSetSource('+priority+');">'+btn_text+'</button>';
var btn = '<button id="srcBtn' + i + '" type="button" ' + btn_state + ' class="btn btn-' + btn_type + ' btn_input_selection" onclick="requestSetSource(' + priority + ');">' + btn_text + '</button>';
if((compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE") && priority < 254)
btn += '<button type="button" class="btn btn-sm btn-danger" style="margin-left:10px;" onclick="requestPriorityClear('+priority+');"><i class="fa fa-close"></button>';
if ((compId == "EFFECT" || compId == "COLOR" || compId == "IMAGE") && priority < 254)
btn += '<button type="button" class="btn btn-sm btn-danger" style="margin-left:10px;" onclick="requestPriorityClear(' + priority + ');"><i class="fa fa-close"></button>';
if(btn_type != 'default')
if (btn_type != 'default')
$('.sstbody').append(createTableRow([origin, owner, priority, btn], false, true));
}
var btn_auto_color = (window.serverInfo.priorities_autoselect? "btn-success" : "btn-danger");
var btn_auto_state = (window.serverInfo.priorities_autoselect? "disabled" : "enabled");
var btn_auto_text = (window.serverInfo.priorities_autoselect? $.i18n('general_btn_on') : $.i18n('general_btn_off'));
var btn_call_state = (clearAll? "enabled" : "disabled");
$('#auto_btn').html('<button id="srcBtn'+i+'" type="button" '+btn_auto_state+' class="btn '+btn_auto_color+'" style="margin-right:5px;display:inline-block;" onclick="requestSetSource(\'auto\');">'+$.i18n('remote_input_label_autoselect')+' ('+btn_auto_text+')</button>');
$('#auto_btn').append('<button type="button" '+btn_call_state+' class="btn btn-danger" style="display:inline-block;" onclick="requestClearAll();">'+$.i18n('remote_input_clearall')+'</button>');
var btn_auto_color = (window.serverInfo.priorities_autoselect ? "btn-success" : "btn-danger");
var btn_auto_state = (window.serverInfo.priorities_autoselect ? "disabled" : "enabled");
var btn_auto_text = (window.serverInfo.priorities_autoselect ? $.i18n('general_btn_on') : $.i18n('general_btn_off'));
var btn_call_state = (clearAll ? "enabled" : "disabled");
$('#auto_btn').html('<button id="srcBtn' + i + '" type="button" ' + btn_auto_state + ' class="btn ' + btn_auto_color + '" style="margin-right:5px;display:inline-block;" onclick="requestSetSource(\'auto\');">' + $.i18n('remote_input_label_autoselect') + ' (' + btn_auto_text + ')</button>');
$('#auto_btn').append('<button type="button" ' + btn_call_state + ' class="btn btn-danger" style="display:inline-block;" onclick="requestClearAll();">' + $.i18n('remote_input_clearall') + '</button>');
var max_width=100;
$('.btn_input_selection').each(function() {
var max_width = 100;
$('.btn_input_selection').each(function () {
if ($(this).innerWidth() > max_width)
max_width = $(this).innerWidth();
});
$('.btn_input_selection').css("min-width",max_width+"px");
$('.btn_input_selection').css("min-width", max_width + "px");
}
function updateLedMapping()
{
function updateLedMapping() {
var mapping = window.serverInfo.imageToLedMappingType;
$('#mappingsbutton').html("");
for(var ix = 0; ix < mappingList.length; ix++)
{
if(mapping == mappingList[ix])
for (var ix = 0; ix < mappingList.length; ix++) {
if (mapping == mappingList[ix])
var btn_style = 'btn-success';
else
var btn_style = 'btn-primary';
$('#mappingsbutton').append('<button type="button" id="lmBtn_'+mappingList[ix]+'" class="btn '+btn_style+'" style="margin:3px;min-width:200px" onclick="requestMappingType(\''+mappingList[ix]+'\');">'+$.i18n('remote_maptype_label_'+mappingList[ix])+'</button><br/>');
$('#mappingsbutton').append('<button type="button" id="lmBtn_' + mappingList[ix] + '" class="btn ' + btn_style + '" style="margin:3px;min-width:200px" onclick="requestMappingType(\'' + mappingList[ix] + '\');">' + $.i18n('remote_maptype_label_' + mappingList[ix]) + '</button><br/>');
}
}
function initComponents()
{
function initComponents() {
var components = window.comps;
var hyperionEnabled = true;
components.forEach( function(obj) {
if (obj.name == "ALL")
{
components.forEach(function (obj) {
if (obj.name == "ALL") {
hyperionEnabled = obj.enabled;
}
});
for (const comp of components)
{
if(comp.name === "ALL")
for (const comp of components) {
if (comp.name === "ALL" || (comp.name === "FORWARDER" && window.currentHyperionInstance != 0) ||
(comp.name === "GRABBER" && !window.serverConfig.framegrabber.enable) ||
(comp.name === "V4L" && !window.serverConfig.grabberV4L2.enable))
continue;
const enable_style = (comp.enabled? "checked" : "");
const comp_btn_id = "comp_btn_"+comp.name;
const enable_style = (comp.enabled ? "checked" : "");
const comp_btn_id = "comp_btn_" + comp.name;
if ($("#"+comp_btn_id).length === 0)
{
var d='<span style="display:block;margin:3px">'
+'<input id="'+comp_btn_id+'"'+enable_style+' type="checkbox"'
+'data-toggle="toggle" data-onstyle="success" data-on="'+$.i18n('general_btn_on')+'" data-off="'+$.i18n('general_btn_off')+'">'
+'&nbsp;&nbsp;&nbsp;<label>'+$.i18n('general_comp_'+comp.name)+'</label>'
+'</span>';
if ($("#" + comp_btn_id).length === 0) {
var d = '<span style="display:block;margin:3px">'
+ '<label class="checkbox-inline">'
+ '<input id = "' + comp_btn_id + '"' + enable_style + ' type = "checkbox"'
+ 'data-toggle="toggle" data-onstyle="success" data-on="' + $.i18n('general_btn_on') + '" data-off="' + $.i18n('general_btn_off') + '">'
+ $.i18n('general_comp_' + comp.name) + '</label > '
+ '</span>';
$('#componentsbutton').append(d);
$(`#${comp_btn_id}`).bootstrapToggle();
$(`#${comp_btn_id}`).bootstrapToggle((hyperionEnabled ? "enable" : "disable"));
$(`#${comp_btn_id}`).change(e => {
requestSetComponentState(e.currentTarget.id.split('_').pop(), e.currentTarget.checked);
//console.log(e.currentTarget.checked)
requestSetComponentState(e.currentTarget.id.split('_').pop(), e.currentTarget.checked);
});
}
}
}
function updateComponent( component )
{
if (component.name == "ALL")
{
function updateComponent(component) {
if (component.name == "ALL") {
var components = window.comps;
var hyperionEnabled = component.enabled;
for (const comp of components)
{
for (const comp of components) {
if(comp.name === "ALL")
continue;
if (comp.name === "ALL")
continue;
const comp_btn_id = "comp_btn_"+comp.name;
const comp_btn_id = "comp_btn_" + comp.name;
if ( !hyperionEnabled )
{
if (!hyperionEnabled) {
$(`#${comp_btn_id}`).bootstrapToggle('off');
$(`#${comp_btn_id}`).bootstrapToggle("disable");
}
else
{
else {
$(`#${comp_btn_id}`).bootstrapToggle("enable");
if ( comp.enabled !== $(`#${comp_btn_id}`).prop("checked") )
{
if (comp.enabled !== $(`#${comp_btn_id}`).prop("checked")) {
$(`#${comp_btn_id}`).bootstrapToggle().prop('checked', comp.enabled).change();
}
}
}
}
else
{
const comp_btn_id = "comp_btn_"+component.name;
else {
const comp_btn_id = "comp_btn_" + component.name;
//console.log ("updateComponent: ", component.name, "Current Checked: ", $(`#${comp_btn_id}`).prop("checked"), "New Checked: ", component.enabled, );
// In case Buttons were disabled before, status may be different to component status
if ( component.enabled != $(`#${comp_btn_id}`).prop("checked") )
{
if (component.enabled != $(`#${comp_btn_id}`).prop("checked")) {
// console.log ("Update status to Checked = ", component.enabled);
if ( component.enabled )
if (component.enabled)
$(`#${comp_btn_id}`).bootstrapToggle("on");
else
$(`#${comp_btn_id}`).bootstrapToggle("off");
@@ -288,21 +266,19 @@ $(document).ready(function() {
}
}
function updateEffectlist()
{
function updateEffectlist() {
var newEffects = window.serverInfo.effects;
if (newEffects.length != oldEffects.length)
{
if (newEffects.length != oldEffects.length) {
$('#effect_select').html('<option value="__none__"></option>');
var usrEffArr = [];
var sysEffArr = [];
for(var i = 0; i < newEffects.length; i++) {
for (var i = 0; i < newEffects.length; i++) {
var effectName = newEffects[i].name;
if(!/^\:/.test(newEffects[i].file)){
if (!/^\:/.test(newEffects[i].file)) {
usrEffArr.push(effectName);
}
else{
else {
sysEffArr.push(effectName);
}
}
@@ -312,74 +288,70 @@ $(document).ready(function() {
}
}
function updateVideoMode()
{
var videoModes = ["2D","3DSBS","3DTAB"];
function updateVideoMode() {
var videoModes = ["2D", "3DSBS", "3DTAB"];
var currVideoMode = window.serverInfo.videomode;
$('#videomodebtns').html("");
for(var ix = 0; ix < videoModes.length; ix++)
{
if(currVideoMode == videoModes[ix])
for (var ix = 0; ix < videoModes.length; ix++) {
if (currVideoMode == videoModes[ix])
var btn_style = 'btn-success';
else
var btn_style = 'btn-primary';
$('#videomodebtns').append('<button type="button" id="vModeBtn_'+videoModes[ix]+'" class="btn '+btn_style+'" style="margin:3px;min-width:200px" onclick="requestVideoMode(\''+videoModes[ix]+'\');">'+$.i18n('remote_videoMode_'+videoModes[ix])+'</button><br/>');
$('#videomodebtns').append('<button type="button" id="vModeBtn_' + videoModes[ix] + '" class="btn ' + btn_style + '" style="margin:3px;min-width:200px" onclick="requestVideoMode(\'' + videoModes[ix] + '\');">' + $.i18n('remote_videoMode_' + videoModes[ix]) + '</button><br/>');
}
}
// colorpicker and effect
if (getStorage('rmcpcolor') != null)
{
if (getStorage('rmcpcolor') != null) {
cpcolor = getStorage('rmcpcolor');
rgb = hexToRgb(cpcolor);
}
if (getStorage('rmduration') != null)
{
if (getStorage('rmduration') != null) {
$("#remote_duration").val(getStorage('rmduration'));
duration = getStorage('rmduration');
}
createCP('cp2', cpcolor, function(rgbT,hex){
createCP('cp2', cpcolor, function (rgbT, hex) {
rgb = rgbT;
sendColor();
setStorage('rmcpcolor', hex);
updateInputSelect();
});
$("#reset_color").off().on("click", function(){
$("#reset_color").off().on("click", function () {
requestPriorityClear();
lastImgData = "";
$("#effect_select").val("__none__");
$("#remote_input_img").val("");
});
$("#remote_duration").off().on("change", function(){
duration = valValue(this.id,this.value,this.min,this.max);
$("#remote_duration").off().on("change", function () {
duration = valValue(this.id, this.value, this.min, this.max);
setStorage('rmduration', duration);
});
$("#effect_select").off().on("change", function(event) {
$("#effect_select").off().on("change", function (event) {
sendEffect();
});
$("#remote_input_reseff, #remote_input_rescol").off().on("click", function(){
if(this.id == "remote_input_rescol")
$("#remote_input_reseff, #remote_input_rescol").off().on("click", function () {
if (this.id == "remote_input_rescol")
sendColor();
else
sendEffect();
});
$("#remote_input_repimg").off().on("click", function(){
if(lastImgData != "")
$("#remote_input_repimg").off().on("click", function () {
if (lastImgData != "")
requestSetImage(lastImgData, duration, lastFileName);
});
$("#remote_input_img").change(function(){
readImg(this, function(src,fileName){
$("#remote_input_img").change(function () {
readImg(this, function (src, fileName) {
lastFileName = fileName;
if(src.includes(","))
if (src.includes(","))
lastImgData = src.split(",")[1];
else
lastImgData = src;
@@ -397,27 +369,27 @@ $(document).ready(function() {
// interval updates
$(window.hyperion).on('components-updated', function(e, comp){
$(window.hyperion).on('components-updated', function (e, comp) {
//console.log ("components-updated", e, comp);
updateComponent (comp);
updateComponent(comp);
});
$(window.hyperion).on("cmd-priorities-update", function(event){
$(window.hyperion).on("cmd-priorities-update", function (event) {
window.serverInfo.priorities = event.response.data.priorities;
window.serverInfo.priorities_autoselect = event.response.data.priorities_autoselect;
updateInputSelect();
});
$(window.hyperion).on("cmd-imageToLedMapping-update", function(event){
$(window.hyperion).on("cmd-imageToLedMapping-update", function (event) {
window.serverInfo.imageToLedMappingType = event.response.data.imageToLedMappingType;
updateLedMapping();
});
$(window.hyperion).on("cmd-videomode-update", function(event){
$(window.hyperion).on("cmd-videomode-update", function (event) {
window.serverInfo.videomode = event.response.data.videomode;
updateVideoMode();
});
$(window.hyperion).on("cmd-effects-update", function(event){
$(window.hyperion).on("cmd-effects-update", function (event) {
window.serverInfo.effects = event.response.data.effects;
updateEffectlist();
});

View File

@@ -3,7 +3,7 @@
var conf_editor = null;
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_webc_heading_title"), 'editor_container', 'btn_submit'));
$('#conf_cont').append(createOptPanel('fa-wrench', $.i18n("edt_conf_webc_heading_title"), 'editor_container', 'btn_submit', 'panel-system'));
if(window.showOptHelp)
{
$('#conf_cont').append(createHelpTable(window.schema.webConfig.properties, $.i18n("edt_conf_webc_heading_title")));

View File

@@ -33,37 +33,39 @@ window.comps = [];
window.defaultPasswordIsSet = null;
tokenList = {};
const ENDLESS = -1;
function initRestart()
{
$(window.hyperion).off();
requestServerConfigReload();
window.watchdog = 10;
connectionLostDetection('restart');
$(window.hyperion).off();
requestServerConfigReload();
window.watchdog = 10;
connectionLostDetection('restart');
}
function connectionLostDetection(type)
{
if ( window.watchdog > 2 )
{
var interval_id = window.setInterval(function(){clearInterval(interval_id);}, 9999); // Get a reference to the last
for (var i = 1; i < interval_id; i++)
window.clearInterval(i);
if(type == 'restart')
{
$("body").html($("#container_restart").html());
// setTimeout delay for probably slower systems, some browser don't execute THIS action
setTimeout(restartAction,250);
}
else
{
$("body").html($("#container_connection_lost").html());
connectionLostAction();
}
}
else
{
$.get( "/cgi/cfg_jsonserver", function() {window.watchdog=0}).fail(function() {window.watchdog++;});
}
if ( window.watchdog > 2 )
{
var interval_id = window.setInterval(function(){clearInterval(interval_id);}, 9999); // Get a reference to the last
for (var i = 1; i < interval_id; i++)
window.clearInterval(i);
if(type == 'restart')
{
$("body").html($("#container_restart").html());
// setTimeout delay for probably slower systems, some browser don't execute THIS action
setTimeout(restartAction,250);
}
else
{
$("body").html($("#container_connection_lost").html());
connectionLostAction();
}
}
else
{
$.get( "/cgi/cfg_jsonserver", function() {window.watchdog=0}).fail(function() {window.watchdog++;});
}
}
setInterval(connectionLostDetection, 3000);
@@ -72,107 +74,107 @@ setInterval(connectionLostDetection, 3000);
function initWebSocket()
{
if ("WebSocket" in window)
{
if (window.websocket == null)
{
window.jsonPort = '';
if(document.location.port == '' && document.location.protocol == "http:")
window.jsonPort = '80';
else if (document.location.port == '' && document.location.protocol == "https:")
window.jsonPort = '443';
else
window.jsonPort = document.location.port;
window.websocket = (document.location.protocol == "https:") ? new WebSocket('wss://'+document.location.hostname+":"+window.jsonPort) : new WebSocket('ws://'+document.location.hostname+":"+window.jsonPort);
if ("WebSocket" in window)
{
if (window.websocket == null)
{
window.jsonPort = '';
if(document.location.port == '' && document.location.protocol == "http:")
window.jsonPort = '80';
else if (document.location.port == '' && document.location.protocol == "https:")
window.jsonPort = '443';
else
window.jsonPort = document.location.port;
window.websocket = (document.location.protocol == "https:") ? new WebSocket('wss://'+document.location.hostname+":"+window.jsonPort) : new WebSocket('ws://'+document.location.hostname+":"+window.jsonPort);
window.websocket.onopen = function (event) {
$(window.hyperion).trigger({type:"open"});
window.websocket.onopen = function (event) {
$(window.hyperion).trigger({type:"open"});
$(window.hyperion).on("cmd-serverinfo", function(event) {
window.watchdog = 0;
});
};
$(window.hyperion).on("cmd-serverinfo", function(event) {
window.watchdog = 0;
});
};
window.websocket.onclose = function (event) {
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
var reason;
switch(event.code)
{
case 1000: reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled."; break;
case 1001: reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page."; break;
case 1002: reason = "An endpoint is terminating the connection due to a protocol error"; break;
case 1003: reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message)."; break;
case 1004: reason = "Reserved. The specific meaning might be defined in the future."; break;
case 1005: reason = "No status code was actually present."; break;
case 1006: reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame"; break;
case 1007: reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message)."; break;
case 1008: reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy."; break;
case 1009: reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process."; break;
case 1010: reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason; break;
case 1011: reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request."; break;
case 1015: reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified)."; break;
default: reason = "Unknown reason";
}
$(window.hyperion).trigger({type:"close", reason:reason});
window.watchdog = 10;
connectionLostDetection();
};
window.websocket.onclose = function (event) {
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
var reason;
switch(event.code)
{
case 1000: reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled."; break;
case 1001: reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page."; break;
case 1002: reason = "An endpoint is terminating the connection due to a protocol error"; break;
case 1003: reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message)."; break;
case 1004: reason = "Reserved. The specific meaning might be defined in the future."; break;
case 1005: reason = "No status code was actually present."; break;
case 1006: reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame"; break;
case 1007: reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message)."; break;
case 1008: reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy."; break;
case 1009: reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process."; break;
case 1010: reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason; break;
case 1011: reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request."; break;
case 1015: reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified)."; break;
default: reason = "Unknown reason";
}
$(window.hyperion).trigger({type:"close", reason:reason});
window.watchdog = 10;
connectionLostDetection();
};
window.websocket.onmessage = function (event) {
try
{
var response = JSON.parse(event.data);
var success = response.success;
var cmd = response.command;
var tan = response.tan
if (success || typeof(success) == "undefined")
{
$(window.hyperion).trigger({type:"cmd-"+cmd, response:response});
}
else
{
// skip tan -1 error handling
if(tan != -1){
var error = response.hasOwnProperty("error")? response.error : "unknown";
$(window.hyperion).trigger({type:"error",reason:error});
console.log("[window.websocket::onmessage] ",error)
}
}
}
catch(exception_error)
{
$(window.hyperion).trigger({type:"error",reason:exception_error});
console.log("[window.websocket::onmessage] ",exception_error)
}
};
window.websocket.onmessage = function (event) {
try
{
var response = JSON.parse(event.data);
var success = response.success;
var cmd = response.command;
var tan = response.tan
if (success || typeof(success) == "undefined")
{
$(window.hyperion).trigger({type:"cmd-"+cmd, response:response});
}
else
{
// skip tan -1 error handling
if(tan != -1){
var error = response.hasOwnProperty("error")? response.error : "unknown";
$(window.hyperion).trigger({type:"error",reason:error});
console.log("[window.websocket::onmessage] ",error)
}
}
}
catch(exception_error)
{
$(window.hyperion).trigger({type:"error",reason:exception_error});
console.log("[window.websocket::onmessage] ",exception_error)
}
};
window.websocket.onerror = function (error) {
$(window.hyperion).trigger({type:"error",reason:error});
console.log("[window.websocket::onerror] ",error)
};
}
}
else
{
$(window.hyperion).trigger("error");
alert("Websocket is not supported by your browser");
return;
}
window.websocket.onerror = function (error) {
$(window.hyperion).trigger({type:"error",reason:error});
console.log("[window.websocket::onerror] ",error)
};
}
}
else
{
$(window.hyperion).trigger("error");
alert("Websocket is not supported by your browser");
return;
}
}
function sendToHyperion(command, subcommand, msg)
{
if (typeof subcommand != 'undefined' && subcommand.length > 0)
subcommand = ',"subcommand":"'+subcommand+'"';
else
subcommand = "";
if (typeof subcommand != 'undefined' && subcommand.length > 0)
subcommand = ',"subcommand":"'+subcommand+'"';
else
subcommand = "";
if (typeof msg != 'undefined' && msg.length > 0)
msg = ","+msg;
else
msg = "";
if (typeof msg != 'undefined' && msg.length > 0)
msg = ","+msg;
else
msg = "";
window.websocket.send('{"command":"'+command+'", "tan":'+window.wsTan+subcommand+msg+'}');
window.websocket.send('{"command":"'+command+'", "tan":'+window.wsTan+subcommand+msg+'}');
}
// Send a json message to Hyperion and wait for a matching response
@@ -228,248 +230,256 @@ async function __sendAsync (data) {
// Test if admin requires authentication
function requestRequiresAdminAuth()
{
sendToHyperion("authorize","adminRequired");
sendToHyperion("authorize","adminRequired");
}
// Test if the default password needs to be changed
function requestRequiresDefaultPasswortChange()
{
sendToHyperion("authorize","newPasswordRequired");
sendToHyperion("authorize","newPasswordRequired");
}
// Change password
function requestChangePassword(oldPw, newPw)
{
sendToHyperion("authorize","newPassword",'"password": "'+oldPw+'", "newPassword":"'+newPw+'"');
sendToHyperion("authorize","newPassword",'"password": "'+oldPw+'", "newPassword":"'+newPw+'"');
}
function requestAuthorization(password)
{
sendToHyperion("authorize","login",'"password": "' + password + '"');
sendToHyperion("authorize","login",'"password": "' + password + '"');
}
function requestTokenAuthorization(token)
{
sendToHyperion("authorize","login",'"token": "' + token + '"');
sendToHyperion("authorize","login",'"token": "' + token + '"');
}
function requestToken(comment)
{
sendToHyperion("authorize","createToken",'"comment": "'+comment+'"');
sendToHyperion("authorize","createToken",'"comment": "'+comment+'"');
}
function requestTokenInfo()
{
sendToHyperion("authorize","getTokenList","");
sendToHyperion("authorize","getTokenList","");
}
function requestGetPendingTokenRequests (id, state) {
sendToHyperion("authorize", "getPendingTokenRequests", "");
sendToHyperion("authorize", "getPendingTokenRequests", "");
}
function requestHandleTokenRequest(id, state)
{
sendToHyperion("authorize","answerRequest",'"id":"'+id+'", "accept":'+state);
sendToHyperion("authorize","answerRequest",'"id":"'+id+'", "accept":'+state);
}
function requestTokenDelete(id)
{
sendToHyperion("authorize","deleteToken",'"id":"'+id+'"');
sendToHyperion("authorize","deleteToken",'"id":"'+id+'"');
}
function requestInstanceRename(inst, name)
{
sendToHyperion("instance", "saveName",'"instance": '+inst+', "name": "'+name+'"');
sendToHyperion("instance", "saveName",'"instance": '+inst+', "name": "'+name+'"');
}
function requestInstanceStartStop(inst, start)
{
if(start)
sendToHyperion("instance","startInstance",'"instance": '+inst);
else
sendToHyperion("instance","stopInstance",'"instance": '+inst);
if(start)
sendToHyperion("instance","startInstance",'"instance": '+inst);
else
sendToHyperion("instance","stopInstance",'"instance": '+inst);
}
function requestInstanceDelete(inst)
{
sendToHyperion("instance","deleteInstance",'"instance": '+inst);
sendToHyperion("instance","deleteInstance",'"instance": '+inst);
}
function requestInstanceCreate(name)
{
sendToHyperion("instance","createInstance",'"name": "'+name+'"');
sendToHyperion("instance","createInstance",'"name": "'+name+'"');
}
function requestInstanceSwitch(inst)
{
sendToHyperion("instance","switchTo",'"instance": '+inst);
sendToHyperion("instance","switchTo",'"instance": '+inst);
}
function requestServerInfo()
{
sendToHyperion("serverinfo","",'"subscribe":["components-update","sessions-update","priorities-update", "imageToLedMapping-update", "adjustment-update", "videomode-update", "effects-update", "settings-update", "instance-update"]');
sendToHyperion("serverinfo","",'"subscribe":["components-update","sessions-update","priorities-update", "imageToLedMapping-update", "adjustment-update", "videomode-update", "effects-update", "settings-update", "instance-update"]');
}
function requestSysInfo()
{
sendToHyperion("sysinfo");
sendToHyperion("sysinfo");
}
function requestServerConfigSchema()
{
sendToHyperion("config","getschema");
sendToHyperion("config","getschema");
}
function requestServerConfig()
{
sendToHyperion("config", "getconfig");
sendToHyperion("config", "getconfig");
}
function requestServerConfigReload()
{
sendToHyperion("config", "reload");
sendToHyperion("config", "reload");
}
function requestLedColorsStart()
{
window.ledStreamActive=true;
sendToHyperion("ledcolors", "ledstream-start");
window.ledStreamActive=true;
sendToHyperion("ledcolors", "ledstream-start");
}
function requestLedColorsStop()
{
window.ledStreamActive=false;
sendToHyperion("ledcolors", "ledstream-stop");
window.ledStreamActive=false;
sendToHyperion("ledcolors", "ledstream-stop");
}
function requestLedImageStart()
{
window.imageStreamActive=true;
sendToHyperion("ledcolors", "imagestream-start");
window.imageStreamActive=true;
sendToHyperion("ledcolors", "imagestream-start");
}
function requestLedImageStop()
{
window.imageStreamActive=false;
sendToHyperion("ledcolors", "imagestream-stop");
window.imageStreamActive=false;
sendToHyperion("ledcolors", "imagestream-stop");
}
function requestPriorityClear(prio)
{
if(typeof prio !== 'number')
prio = window.webPrio;
if(typeof prio !== 'number')
prio = window.webPrio;
sendToHyperion("clear", "", '"priority":'+prio+'');
sendToHyperion("clear", "", '"priority":'+prio+'');
}
function requestClearAll()
{
requestPriorityClear(-1)
requestPriorityClear(-1)
}
function requestPlayEffect(effectName, duration)
{
sendToHyperion("effect", "", '"effect":{"name":"'+effectName+'"},"priority":'+window.webPrio+',"duration":'+validateDuration(duration)+',"origin":"'+window.webOrigin+'"');
sendToHyperion("effect", "", '"effect":{"name":"'+effectName+'"},"priority":'+window.webPrio+',"duration":'+validateDuration(duration)+',"origin":"'+window.webOrigin+'"');
}
function requestSetColor(r,g,b,duration)
{
sendToHyperion("color", "", '"color":['+r+','+g+','+b+'], "priority":'+window.webPrio+',"duration":'+validateDuration(duration)+',"origin":"'+window.webOrigin+'"');
sendToHyperion("color", "", '"color":['+r+','+g+','+b+'], "priority":'+window.webPrio+',"duration":'+validateDuration(duration)+',"origin":"'+window.webOrigin+'"');
}
function requestSetImage(data,duration,name)
{
sendToHyperion("image", "", '"imagedata":"'+data+'", "priority":'+window.webPrio+',"duration":'+validateDuration(duration)+', "format":"auto", "origin":"'+window.webOrigin+'", "name":"'+name+'"');
sendToHyperion("image", "", '"imagedata":"'+data+'", "priority":'+window.webPrio+',"duration":'+validateDuration(duration)+', "format":"auto", "origin":"'+window.webOrigin+'", "name":"'+name+'"');
}
function requestSetComponentState(comp, state)
{
var state_str = state ? "true" : "false";
sendToHyperion("componentstate", "", '"componentstate":{"component":"'+comp+'","state":'+state_str+'}');
var state_str = state ? "true" : "false";
sendToHyperion("componentstate", "", '"componentstate":{"component":"'+comp+'","state":'+state_str+'}');
}
function requestSetSource(prio)
{
if ( prio == "auto" )
sendToHyperion("sourceselect", "", '"auto":true');
else
sendToHyperion("sourceselect", "", '"priority":'+prio);
if ( prio == "auto" )
sendToHyperion("sourceselect", "", '"auto":true');
else
sendToHyperion("sourceselect", "", '"priority":'+prio);
}
function requestWriteConfig(config, full)
{
if(full === true)
window.serverConfig = config;
else
{
jQuery.each(config, function(i, val) {
window.serverConfig[i] = val;
});
}
if(full === true)
window.serverConfig = config;
else
{
jQuery.each(config, function(i, val) {
window.serverConfig[i] = val;
});
}
sendToHyperion("config","setconfig", '"config":'+JSON.stringify(window.serverConfig));
sendToHyperion("config","setconfig", '"config":'+JSON.stringify(window.serverConfig));
}
function requestWriteEffect(effectName,effectPy,effectArgs,data)
{
var cutArgs = effectArgs.slice(1, -1);
sendToHyperion("create-effect", "", '"name":"'+effectName+'", "script":"'+effectPy+'", '+cutArgs+',"imageData":"'+data+'"');
var cutArgs = effectArgs.slice(1, -1);
sendToHyperion("create-effect", "", '"name":"'+effectName+'", "script":"'+effectPy+'", '+cutArgs+',"imageData":"'+data+'"');
}
function requestTestEffect(effectName,effectPy,effectArgs,data)
{
sendToHyperion("effect", "", '"effect":{"name":"'+effectName+'", "args":'+effectArgs+'}, "priority":'+window.webPrio+', "origin":"'+window.webOrigin+'", "pythonScript":"'+effectPy+'", "imageData":"'+data+'"');
sendToHyperion("effect", "", '"effect":{"name":"'+effectName+'", "args":'+effectArgs+'}, "priority":'+window.webPrio+', "origin":"'+window.webOrigin+'", "pythonScript":"'+effectPy+'", "imageData":"'+data+'"');
}
function requestDeleteEffect(effectName)
{
sendToHyperion("delete-effect", "", '"name":"'+effectName+'"');
sendToHyperion("delete-effect", "", '"name":"'+effectName+'"');
}
function requestLoggingStart()
{
window.loggingStreamActive=true;
sendToHyperion("logging", "start");
window.loggingStreamActive=true;
sendToHyperion("logging", "start");
}
function requestLoggingStop()
{
window.loggingStreamActive=false;
sendToHyperion("logging", "stop");
window.loggingStreamActive=false;
sendToHyperion("logging", "stop");
}
function requestMappingType(type)
{
sendToHyperion("processing", "", '"mappingType": "'+type+'"');
sendToHyperion("processing", "", '"mappingType": "'+type+'"');
}
function requestVideoMode(newMode)
{
sendToHyperion("videomode", "", '"videoMode": "'+newMode+'"');
sendToHyperion("videomode", "", '"videoMode": "'+newMode+'"');
}
function requestAdjustment(type, value, complete)
{
if(complete === true)
sendToHyperion("adjustment", "", '"adjustment": '+type+'');
else
sendToHyperion("adjustment", "", '"adjustment": {"'+type+'": '+value+'}');
if(complete === true)
sendToHyperion("adjustment", "", '"adjustment": '+type+'');
else
sendToHyperion("adjustment", "", '"adjustment": {"'+type+'": '+value+'}');
}
async function requestLedDeviceDiscovery(type, params)
{
let data = { ledDeviceType: type, params: params };
let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "discover", data, Math.floor(Math.random() * 1000) );
return sendAsyncToHyperion("leddevice", "discover", data, Math.floor(Math.random() * 1000) );
}
async function requestLedDeviceProperties(type, params)
{
let data = { ledDeviceType: type, params: params };
let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "getProperties", data, Math.floor(Math.random() * 1000));
return sendAsyncToHyperion("leddevice", "getProperties", data, Math.floor(Math.random() * 1000));
}
function requestLedDeviceIdentification(type, params)
{
sendToHyperion("leddevice", "identify", '"ledDeviceType": "'+type+'","params": '+JSON.stringify(params)+'');
let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "identify", data, Math.floor(Math.random() * 1000));
}
async function requestInputSourcesDiscovery(type, params) {
let data = { sourceType: type, params: params };
return sendAsyncToHyperion("inputsource", "discover", data, Math.floor(Math.random() * 1000));
}

View File

@@ -0,0 +1,33 @@
var storedLang;
var availLang = ['cs', 'de', 'en', 'es', 'fr', 'it', 'nl', 'nb', 'pl', 'pt', 'ro', 'sv', 'vi', 'ru', 'tr', 'zh-CN'];
var availLangText = ['Čeština', 'Deutsch', 'English', 'Español', 'Français', 'Italiano', 'Nederlands', 'Norsk Bokmål', 'Polski', 'Português', 'Română', 'Svenska', 'Tiếng Việt', 'русский', 'Türkçe', '汉语'];
//$.i18n.debug = true;
//i18n
function initTrans(lc) {
$.i18n().load("i18n", lc).done(
function () {
$.i18n().locale = lc;
performTranslation();
});
}
storedLang = getStorage("langcode");
if (storedLang == null || storedLang === "undefined") {
var langLocale = $.i18n().locale.substring(0, 2);
//Test, if language is supported by hyperion
var langIdx = availLang.indexOf(langLocale);
if (langIdx === -1) {
// If language is not supported by hyperion, try fallback language
langLocale = $.i18n().options.fallbackLocale.substring(0, 2);
langIdx = availLang.indexOf(langLocale);
if (langIdx === -1) {
langLocale = 'en';
}
}
storedLang = langLocale;
setStorage("langcode", storedLang);
}
initTrans(storedLang);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,607 @@
/**
* cldrpluralparser.js
* A parser engine for CLDR plural rules.
*
* Copyright 2012-2014 Santhosh Thottingal and other contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
* @source https://github.com/santhoshtr/CLDRPluralRuleParser
* @author Santhosh Thottingal <santhosh.thottingal@gmail.com>
* @author Timo Tijhof
* @author Amir Aharoni
*/
/**
* Evaluates a plural rule in CLDR syntax for a number
* @param {string} rule
* @param {integer} number
* @return {boolean} true if evaluation passed, false if evaluation failed.
*/
// UMD returnExports https://github.com/umdjs/umd/blob/master/returnExports.js
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.pluralRuleParser = factory();
}
}(this, function() {
function pluralRuleParser(rule, number) {
'use strict';
/*
Syntax: see http://unicode.org/reports/tr35/#Language_Plural_Rules
-----------------------------------------------------------------
condition = and_condition ('or' and_condition)*
('@integer' samples)?
('@decimal' samples)?
and_condition = relation ('and' relation)*
relation = is_relation | in_relation | within_relation
is_relation = expr 'is' ('not')? value
in_relation = expr (('not')? 'in' | '=' | '!=') range_list
within_relation = expr ('not')? 'within' range_list
expr = operand (('mod' | '%') value)?
operand = 'n' | 'i' | 'f' | 't' | 'v' | 'w'
range_list = (range | value) (',' range_list)*
value = digit+
digit = 0|1|2|3|4|5|6|7|8|9
range = value'..'value
samples = sampleRange (',' sampleRange)* (',' ('…'|'...'))?
sampleRange = decimalValue '~' decimalValue
decimalValue = value ('.' value)?
*/
// We don't evaluate the samples section of the rule. Ignore it.
rule = rule.split('@')[0].replace(/^\s*/, '').replace(/\s*$/, '');
if (!rule.length) {
// Empty rule or 'other' rule.
return true;
}
// Indicates the current position in the rule as we parse through it.
// Shared among all parsing functions below.
var pos = 0,
operand,
expression,
relation,
result,
whitespace = makeRegexParser(/^\s+/),
value = makeRegexParser(/^\d+/),
_n_ = makeStringParser('n'),
_i_ = makeStringParser('i'),
_f_ = makeStringParser('f'),
_t_ = makeStringParser('t'),
_v_ = makeStringParser('v'),
_w_ = makeStringParser('w'),
_is_ = makeStringParser('is'),
_isnot_ = makeStringParser('is not'),
_isnot_sign_ = makeStringParser('!='),
_equal_ = makeStringParser('='),
_mod_ = makeStringParser('mod'),
_percent_ = makeStringParser('%'),
_not_ = makeStringParser('not'),
_in_ = makeStringParser('in'),
_within_ = makeStringParser('within'),
_range_ = makeStringParser('..'),
_comma_ = makeStringParser(','),
_or_ = makeStringParser('or'),
_and_ = makeStringParser('and');
function debug() {
// console.log.apply(console, arguments);
}
debug('pluralRuleParser', rule, number);
// Try parsers until one works, if none work return null
function choice(parserSyntax) {
return function() {
var i, result;
for (i = 0; i < parserSyntax.length; i++) {
result = parserSyntax[i]();
if (result !== null) {
return result;
}
}
return null;
};
}
// Try several parserSyntax-es in a row.
// All must succeed; otherwise, return null.
// This is the only eager one.
function sequence(parserSyntax) {
var i, parserRes,
originalPos = pos,
result = [];
for (i = 0; i < parserSyntax.length; i++) {
parserRes = parserSyntax[i]();
if (parserRes === null) {
pos = originalPos;
return null;
}
result.push(parserRes);
}
return result;
}
// Run the same parser over and over until it fails.
// Must succeed a minimum of n times; otherwise, return null.
function nOrMore(n, p) {
return function() {
var originalPos = pos,
result = [],
parsed = p();
while (parsed !== null) {
result.push(parsed);
parsed = p();
}
if (result.length < n) {
pos = originalPos;
return null;
}
return result;
};
}
// Helpers - just make parserSyntax out of simpler JS builtin types
function makeStringParser(s) {
var len = s.length;
return function() {
var result = null;
if (rule.substr(pos, len) === s) {
result = s;
pos += len;
}
return result;
};
}
function makeRegexParser(regex) {
return function() {
var matches = rule.substr(pos).match(regex);
if (matches === null) {
return null;
}
pos += matches[0].length;
return matches[0];
};
}
/**
* Integer digits of n.
*/
function i() {
var result = _i_();
if (result === null) {
debug(' -- failed i', parseInt(number, 10));
return result;
}
result = parseInt(number, 10);
debug(' -- passed i ', result);
return result;
}
/**
* Absolute value of the source number (integer and decimals).
*/
function n() {
var result = _n_();
if (result === null) {
debug(' -- failed n ', number);
return result;
}
result = parseFloat(number, 10);
debug(' -- passed n ', result);
return result;
}
/**
* Visible fractional digits in n, with trailing zeros.
*/
function f() {
var result = _f_();
if (result === null) {
debug(' -- failed f ', number);
return result;
}
result = (number + '.').split('.')[1] || 0;
debug(' -- passed f ', result);
return result;
}
/**
* Visible fractional digits in n, without trailing zeros.
*/
function t() {
var result = _t_();
if (result === null) {
debug(' -- failed t ', number);
return result;
}
result = (number + '.').split('.')[1].replace(/0$/, '') || 0;
debug(' -- passed t ', result);
return result;
}
/**
* Number of visible fraction digits in n, with trailing zeros.
*/
function v() {
var result = _v_();
if (result === null) {
debug(' -- failed v ', number);
return result;
}
result = (number + '.').split('.')[1].length || 0;
debug(' -- passed v ', result);
return result;
}
/**
* Number of visible fraction digits in n, without trailing zeros.
*/
function w() {
var result = _w_();
if (result === null) {
debug(' -- failed w ', number);
return result;
}
result = (number + '.').split('.')[1].replace(/0$/, '').length || 0;
debug(' -- passed w ', result);
return result;
}
// operand = 'n' | 'i' | 'f' | 't' | 'v' | 'w'
operand = choice([n, i, f, t, v, w]);
// expr = operand (('mod' | '%') value)?
expression = choice([mod, operand]);
function mod() {
var result = sequence(
[operand, whitespace, choice([_mod_, _percent_]), whitespace, value]
);
if (result === null) {
debug(' -- failed mod');
return null;
}
debug(' -- passed ' + parseInt(result[0], 10) + ' ' + result[2] + ' ' + parseInt(result[4], 10));
return parseFloat(result[0]) % parseInt(result[4], 10);
}
function not() {
var result = sequence([whitespace, _not_]);
if (result === null) {
debug(' -- failed not');
return null;
}
return result[1];
}
// is_relation = expr 'is' ('not')? value
function is() {
var result = sequence([expression, whitespace, choice([_is_]), whitespace, value]);
if (result !== null) {
debug(' -- passed is : ' + result[0] + ' == ' + parseInt(result[4], 10));
return result[0] === parseInt(result[4], 10);
}
debug(' -- failed is');
return null;
}
// is_relation = expr 'is' ('not')? value
function isnot() {
var result = sequence(
[expression, whitespace, choice([_isnot_, _isnot_sign_]), whitespace, value]
);
if (result !== null) {
debug(' -- passed isnot: ' + result[0] + ' != ' + parseInt(result[4], 10));
return result[0] !== parseInt(result[4], 10);
}
debug(' -- failed isnot');
return null;
}
function not_in() {
var i, range_list,
result = sequence([expression, whitespace, _isnot_sign_, whitespace, rangeList]);
if (result !== null) {
debug(' -- passed not_in: ' + result[0] + ' != ' + result[4]);
range_list = result[4];
for (i = 0; i < range_list.length; i++) {
if (parseInt(range_list[i], 10) === parseInt(result[0], 10)) {
return false;
}
}
return true;
}
debug(' -- failed not_in');
return null;
}
// range_list = (range | value) (',' range_list)*
function rangeList() {
var result = sequence([choice([range, value]), nOrMore(0, rangeTail)]),
resultList = [];
if (result !== null) {
resultList = resultList.concat(result[0]);
if (result[1][0]) {
resultList = resultList.concat(result[1][0]);
}
return resultList;
}
debug(' -- failed rangeList');
return null;
}
function rangeTail() {
// ',' range_list
var result = sequence([_comma_, rangeList]);
if (result !== null) {
return result[1];
}
debug(' -- failed rangeTail');
return null;
}
// range = value'..'value
function range() {
var i, array, left, right,
result = sequence([value, _range_, value]);
if (result !== null) {
debug(' -- passed range');
array = [];
left = parseInt(result[0], 10);
right = parseInt(result[2], 10);
for (i = left; i <= right; i++) {
array.push(i);
}
return array;
}
debug(' -- failed range');
return null;
}
function _in() {
var result, range_list, i;
// in_relation = expr ('not')? 'in' range_list
result = sequence(
[expression, nOrMore(0, not), whitespace, choice([_in_, _equal_]), whitespace, rangeList]
);
if (result !== null) {
debug(' -- passed _in:' + result);
range_list = result[5];
for (i = 0; i < range_list.length; i++) {
if (parseInt(range_list[i], 10) === parseFloat(result[0])) {
return (result[1][0] !== 'not');
}
}
return (result[1][0] === 'not');
}
debug(' -- failed _in ');
return null;
}
/**
* The difference between "in" and "within" is that
* "in" only includes integers in the specified range,
* while "within" includes all values.
*/
function within() {
var range_list, result;
// within_relation = expr ('not')? 'within' range_list
result = sequence(
[expression, nOrMore(0, not), whitespace, _within_, whitespace, rangeList]
);
if (result !== null) {
debug(' -- passed within');
range_list = result[5];
if ((result[0] >= parseInt(range_list[0], 10)) &&
(result[0] < parseInt(range_list[range_list.length - 1], 10))) {
return (result[1][0] !== 'not');
}
return (result[1][0] === 'not');
}
debug(' -- failed within ');
return null;
}
// relation = is_relation | in_relation | within_relation
relation = choice([is, not_in, isnot, _in, within]);
// and_condition = relation ('and' relation)*
function and() {
var i,
result = sequence([relation, nOrMore(0, andTail)]);
if (result) {
if (!result[0]) {
return false;
}
for (i = 0; i < result[1].length; i++) {
if (!result[1][i]) {
return false;
}
}
return true;
}
debug(' -- failed and');
return null;
}
// ('and' relation)*
function andTail() {
var result = sequence([whitespace, _and_, whitespace, relation]);
if (result !== null) {
debug(' -- passed andTail' + result);
return result[3];
}
debug(' -- failed andTail');
return null;
}
// ('or' and_condition)*
function orTail() {
var result = sequence([whitespace, _or_, whitespace, and]);
if (result !== null) {
debug(' -- passed orTail: ' + result[3]);
return result[3];
}
debug(' -- failed orTail');
return null;
}
// condition = and_condition ('or' and_condition)*
function condition() {
var i,
result = sequence([and, nOrMore(0, orTail)]);
if (result) {
for (i = 0; i < result[1].length; i++) {
if (result[1][i]) {
return true;
}
}
return result[0];
}
return false;
}
result = condition();
/**
* For success, the pos must have gotten to the end of the rule
* and returned a non-null.
* n.b. This is part of language infrastructure,
* so we do not throw an internationalizable message.
*/
if (result === null) {
throw new Error('Parse error at position ' + pos.toString() + ' for rule: ' + rule);
}
if (pos !== rule.length) {
debug('Warning: Rule not parsed completely. Parser stopped at ' + rule.substr(0, pos) + ' for rule: ' + rule);
}
return result;
}
return pluralRuleParser;
}));

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2011-2013 Santhosh Thottingal, Neil Kandalgaonkar
@@ -17,7 +17,7 @@
'use strict';
var MessageParserEmitter = function () {
this.language = $.i18n.languages[String.locale] || $.i18n.languages['default'];
this.language = $.i18n.languages[ String.locale ] || $.i18n.languages[ 'default' ];
};
MessageParserEmitter.prototype = {
@@ -38,36 +38,36 @@
messageParserEmitter = this;
switch ( typeof node ) {
case 'string':
case 'number':
ret = node;
break;
case 'object':
case 'string':
case 'number':
ret = node;
break;
case 'object':
// node is an array of nodes
subnodes = $.map( node.slice( 1 ), function ( n ) {
return messageParserEmitter.emit( n, replacements );
} );
subnodes = $.map( node.slice( 1 ), function ( n ) {
return messageParserEmitter.emit( n, replacements );
} );
operation = node[0].toLowerCase();
operation = node[ 0 ].toLowerCase();
if ( typeof messageParserEmitter[operation] === 'function' ) {
ret = messageParserEmitter[operation]( subnodes, replacements );
} else {
throw new Error( 'unknown operation "' + operation + '"' );
}
if ( typeof messageParserEmitter[ operation ] === 'function' ) {
ret = messageParserEmitter[ operation ]( subnodes, replacements );
} else {
throw new Error( 'unknown operation "' + operation + '"' );
}
break;
case 'undefined':
break;
case 'undefined':
// Parsing the empty string (as an entire expression, or as a
// paramExpression in a template) results in undefined
// Perhaps a more clever parser can detect this, and return the
// empty string? Or is that useful information?
// The logical thing is probably to return the empty string here
// when we encounter undefined.
ret = '';
break;
default:
throw new Error( 'unexpected type in AST: ' + typeof node );
ret = '';
break;
default:
throw new Error( 'unexpected type in AST: ' + typeof node );
}
return ret;
@@ -80,7 +80,7 @@
* in our children and pass them upwards
*
* @param {Array} nodes Mixed, some single nodes, some arrays of nodes.
* @return String
* @return {string}
*/
concat: function ( nodes ) {
var result = '';
@@ -106,11 +106,11 @@
* @return {string} replacement
*/
replace: function ( nodes, replacements ) {
var index = parseInt( nodes[0], 10 );
var index = parseInt( nodes[ 0 ], 10 );
if ( index < replacements.length ) {
// replacement is not a string, don't touch!
return replacements[index];
return replacements[ index ];
} else {
// index not found, fallback to displaying variable
return '$' + ( index + 1 );
@@ -124,11 +124,11 @@
* convertNumber.
*
* @param {Array} nodes List [ {String|Number}, {String}, {String} ... ]
* @return {String} selected pluralized form according to current
* @return {string} selected pluralized form according to current
* language.
*/
plural: function ( nodes ) {
var count = parseFloat( this.language.convertNumber( nodes[0], 10 ) ),
var count = parseFloat( this.language.convertNumber( nodes[ 0 ], 10 ) ),
forms = nodes.slice( 1 );
return forms.length ? this.language.convertPlural( count, forms ) : '';
@@ -139,10 +139,10 @@
* {{gender:gender|masculine|feminine|neutral}}.
*
* @param {Array} nodes List [ {String}, {String}, {String} , {String} ]
* @return {String} selected gender form according to current language
* @return {string} selected gender form according to current language
*/
gender: function ( nodes ) {
var gender = nodes[0],
var gender = nodes[ 0 ],
forms = nodes.slice( 1 );
return this.language.gender( gender, forms );
@@ -153,12 +153,12 @@
* putting {{grammar:form|word}} in a message
*
* @param {Array} nodes List [{Grammar case eg: genitive}, {String word}]
* @return {String} selected grammatical form according to current
* @return {string} selected grammatical form according to current
* language.
*/
grammar: function ( nodes ) {
var form = nodes[0],
word = nodes[1];
var form = nodes[ 0 ],
word = nodes[ 1 ];
return word && form && this.language.convertGrammar( word, form );
}

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2012 Santhosh Thottingal
@@ -11,7 +11,7 @@
* @licence GNU General Public Licence 2.0 or later
* @licence MIT License
*/
( function ( $, undefined ) {
( function ( $ ) {
'use strict';
$.i18n = $.i18n || {};
@@ -45,7 +45,6 @@
'crh-cyrl': [ 'ru' ],
csb: [ 'pl' ],
cv: [ 'ru' ],
'de-DE': [ 'de' ],
'de-at': [ 'de' ],
'de-ch': [ 'de' ],
'de-formal': [ 'de' ],

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2012 Santhosh Thottingal
@@ -16,7 +16,7 @@
( function ( $ ) {
'use strict';
var nav, I18N,
var I18N,
slice = Array.prototype.slice;
/**
* @constructor
@@ -30,61 +30,52 @@
this.locale = this.options.locale;
this.messageStore = this.options.messageStore;
this.languages = {};
this.init();
};
I18N.prototype = {
/**
* Initialize by loading locales and setting up
* String.prototype.toLocaleString and String.locale.
* Localize a given messageKey to a locale.
* @param {string} messageKey
* @return {string} Localized message
*/
init: function () {
var i18n = this;
localize: function ( messageKey ) {
var localeParts, localePartIndex, locale, fallbackIndex,
tryingLocale, message;
// Set locale of String environment
String.locale = i18n.locale;
locale = this.locale;
fallbackIndex = 0;
// Override String.localeString method
String.prototype.toLocaleString = function () {
var localeParts, localePartIndex, value, locale, fallbackIndex,
tryingLocale, message;
while ( locale ) {
// Iterate through locales starting at most-specific until
// localization is found. As in fi-Latn-FI, fi-Latn and fi.
localeParts = locale.split( '-' );
localePartIndex = localeParts.length;
value = this.valueOf();
locale = i18n.locale;
fallbackIndex = 0;
do {
tryingLocale = localeParts.slice( 0, localePartIndex ).join( '-' );
message = this.messageStore.get( tryingLocale, messageKey );
while ( locale ) {
// Iterate through locales starting at most-specific until
// localization is found. As in fi-Latn-FI, fi-Latn and fi.
localeParts = locale.split( '-' );
localePartIndex = localeParts.length;
do {
tryingLocale = localeParts.slice( 0, localePartIndex ).join( '-' );
message = i18n.messageStore.get( tryingLocale, value );
if ( message ) {
return message;
}
localePartIndex--;
} while ( localePartIndex );
if ( locale === 'en' ) {
break;
if ( message ) {
return message;
}
locale = ( $.i18n.fallbacks[i18n.locale] && $.i18n.fallbacks[i18n.locale][fallbackIndex] ) ||
i18n.options.fallbackLocale;
$.i18n.log( 'Trying fallback locale for ' + i18n.locale + ': ' + locale );
localePartIndex--;
} while ( localePartIndex );
fallbackIndex++;
if ( locale === this.options.fallbackLocale ) {
break;
}
// key not found
return '';
};
locale = ( $.i18n.fallbacks[ this.locale ] &&
$.i18n.fallbacks[ this.locale ][ fallbackIndex ] ) ||
this.options.fallbackLocale;
$.i18n.log( 'Trying fallback locale for ' + this.locale + ': ' + locale + ' (' + messageKey + ')' );
fallbackIndex++;
}
// key not found
return '';
},
/*
@@ -132,26 +123,28 @@
* If the data argument is null/undefined/false,
* all cached messages for the i18n instance will get reset.
*
* @param {String|Object} source
* @param {String} locale Language tag
* @returns {jQuery.Promise}
* @param {string|Object} source
* @param {string} locale Language tag
* @return {jQuery.Promise}
*/
load: function ( source, locale ) {
var fallbackLocales, locIndex, fallbackLocale, sourceMap = {};
if ( !source && !locale ) {
source = 'i18n';
source = 'i18n/' + $.i18n().locale + '.json';
locale = $.i18n().locale;
}
if ( typeof source === 'string' &&
source.split( '.' ).pop() !== 'json'
if ( typeof source === 'string' &&
// source extension should be json, but can have query params after that.
source.split( '?' )[ 0 ].split( '.' ).pop() !== 'json'
) {
// Load specified locale then check for fallbacks when directory is specified in load()
sourceMap[locale] = source + '/' + locale + '.json';
fallbackLocales = ( $.i18n.fallbacks[locale] || [] )
// Load specified locale then check for fallbacks when directory is
// specified in load()
sourceMap[ locale ] = source + '/' + locale + '.json';
fallbackLocales = ( $.i18n.fallbacks[ locale ] || [] )
.concat( this.options.fallbackLocale );
for ( locIndex in fallbackLocales ) {
fallbackLocale = fallbackLocales[locIndex];
sourceMap[fallbackLocale] = source + '/' + fallbackLocale + '.json';
for ( locIndex = 0; locIndex < fallbackLocales.length; locIndex++ ) {
fallbackLocale = fallbackLocales[ locIndex ];
sourceMap[ fallbackLocale ] = source + '/' + fallbackLocale + '.json';
}
return this.load( sourceMap );
} else {
@@ -168,11 +161,11 @@
* @return {string}
*/
parse: function ( key, parameters ) {
var message = key.toLocaleString();
var message = this.localize( key );
// FIXME: This changes the state of the I18N object,
// should probably not change the 'this.parser' but just
// pass it to the parser.
this.parser.language = $.i18n.languages[$.i18n().locale] || $.i18n.languages['default'];
this.parser.language = $.i18n.languages[ $.i18n().locale ] || $.i18n.languages[ 'default' ];
if ( message === '' ) {
message = key;
}
@@ -202,7 +195,7 @@
// NOTE: It should only change language for this one call.
// Then cache instances of I18N somewhere.
if ( options && options.locale && i18n && i18n.locale !== options.locale ) {
String.locale = i18n.locale = options.locale;
i18n.locale = options.locale;
}
if ( !i18n ) {
@@ -231,28 +224,38 @@
i18n = new I18N();
$.data( document, 'i18n', i18n );
}
String.locale = i18n.locale;
return this.each( function () {
var $this = $( this ),
messageKey = $this.data( 'i18n' );
messageKey = $this.data( 'i18n' ),
lBracket, rBracket, type, key;
if ( messageKey ) {
$this.text( i18n.parse( messageKey ) );
lBracket = messageKey.indexOf( '[' );
rBracket = messageKey.indexOf( ']' );
if ( lBracket !== -1 && rBracket !== -1 && lBracket < rBracket ) {
type = messageKey.slice( lBracket + 1, rBracket );
key = messageKey.slice( rBracket + 1 );
if ( type === 'html' ) {
$this.html( i18n.parse( key ) );
} else {
$this.attr( type, i18n.parse( key ) );
}
} else {
$this.text( i18n.parse( messageKey ) );
}
} else {
$this.find( '[data-i18n]' ).i18n();
}
} );
};
String.locale = String.locale || $( 'html' ).attr( 'lang' );
if ( !String.locale ) {
if ( typeof window.navigator !== 'undefined' ) {
nav = window.navigator;
String.locale = nav.language || nav.userLanguage || '';
} else {
String.locale = '';
function getDefaultLocale() {
var locale = $( 'html' ).attr( 'lang' );
if ( !locale ) {
locale = navigator.language || navigator.userLanguage || '';
}
return locale;
}
$.i18n.languages = {};
@@ -262,7 +265,7 @@
parse: function ( message, parameters ) {
return message.replace( /\$(\d+)/g, function ( str, match ) {
var index = parseInt( match, 10 ) - 1;
return parameters[index] !== undefined ? parameters[index] : '$' + match;
return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
} );
},
emitter: {}
@@ -276,7 +279,7 @@
};
/* Static members */
I18N.defaults = {
locale: String.locale,
locale: getDefaultLocale(),
fallbackLocale: 'en',
parser: $.i18n.parser,
messageStore: $.i18n.messageStore

View File

@@ -1,7 +1,8 @@
/*global pluralRuleParser */
/* global pluralRuleParser */
( function ( $ ) {
'use strict';
// jscs:disable
var language = {
// CLDR plural rules generated using
// libs/CLDRPluralRuleParser/tools/PluralXML2JSON.html
@@ -19,6 +20,16 @@
few: 'n % 100 = 3..10',
many: 'n % 100 = 11..99'
},
ars: {
zero: 'n = 0',
one: 'n = 1',
two: 'n = 2',
few: 'n % 100 = 3..10',
many: 'n % 100 = 11..99'
},
as: {
one: 'i = 0 or n = 1'
},
be: {
one: 'n % 10 = 1 and n % 100 != 11',
few: 'n % 10 = 2..4 and n % 100 != 12..14',
@@ -55,6 +66,11 @@
da: {
one: 'n = 1 or t != 0 and i = 0,1'
},
dsb: {
one: 'v = 0 and i % 100 = 1 or f % 100 = 1',
two: 'v = 0 and i % 100 = 2 or f % 100 = 2',
few: 'v = 0 and i % 100 = 3..4 or f % 100 = 3..4'
},
fa: {
one: 'i = 0 or n = 1'
},
@@ -62,7 +78,7 @@
one: 'i = 0,1'
},
fil: {
one: 'i = 0..1 and v = 0'
one: 'v = 0 and i = 1,2,3 or v = 0 and i % 10 != 4,6,9 or v != 0 and f % 10 != 4,6,9'
},
fr: {
one: 'i = 0,1'
@@ -85,9 +101,10 @@
one: 'n = 0..1'
},
gv: {
one: 'n % 10 = 1',
two: 'n % 10 = 2',
few: 'n % 100 = 0,20,40,60'
one: 'v = 0 and i % 10 = 1',
two: 'v = 0 and i % 10 = 2',
few: 'v = 0 and i % 100 = 0,20,40,60,80',
many: 'v != 0'
},
he: {
one: 'i = 1 and v = 0',
@@ -101,6 +118,11 @@
one: 'v = 0 and i % 10 = 1 and i % 100 != 11 or f % 10 = 1 and f % 100 != 11',
few: 'v = 0 and i % 10 = 2..4 and i % 100 != 12..14 or f % 10 = 2..4 and f % 100 != 12..14'
},
hsb: {
one: 'v = 0 and i % 100 = 1 or f % 100 = 1',
two: 'v = 0 and i % 100 = 2 or f % 100 = 2',
few: 'v = 0 and i % 100 = 3..4 or f % 100 = 3..4'
},
hy: {
one: 'i = 0,1'
},
@@ -175,20 +197,20 @@
few: 'v = 0 and i % 10 = 2..4 and i % 100 != 12..14',
many: 'v = 0 and i != 1 and i % 10 = 0..1 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 12..14'
},
prg: {
zero: 'n % 10 = 0 or n % 100 = 11..19 or v = 2 and f % 100 = 11..19',
one: 'n % 10 = 1 and n % 100 != 11 or v = 2 and f % 10 = 1 and f % 100 != 11 or v != 2 and f % 10 = 1'
},
pt: {
one: 'i = 1 and v = 0 or i = 0 and t = 1'
one: 'i = 0..1'
},
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
pt_PT: {
one: 'n = 1 and v = 0'
},
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
ro: {
one: 'i = 1 and v = 0',
few: 'v != 0 or n = 0 or n != 1 and n % 100 = 1..19'
},
ru: {
one: 'v = 0 and i % 10 = 1 and i % 100 != 11',
few: 'v = 0 and i % 10 = 2..4 and i % 100 != 12..14',
many: 'v = 0 and i % 10 = 0 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 11..14'
},
se: {
@@ -244,7 +266,7 @@
one: 'n = 0..1'
},
tl: {
one: 'i = 0..1 and v = 0'
one: 'v = 0 and i = 1,2,3 or v = 0 and i % 10 != 4,6,9 or v != 0 and f % 10 != 4,6,9'
},
tzm: {
one: 'n = 0..1 or n = 11..99'
@@ -261,21 +283,22 @@
one: 'i = 0 or n = 1'
}
},
// jscs:enable
/**
* Plural form transformations, needed for some languages.
*
* @param count
* integer Non-localized quantifier
* @param forms
* array List of plural forms
* @return string Correct form for quantifier in this language
* @param {integer} count
* Non-localized quantifier
* @param {Array} forms
* List of plural forms
* @return {string} Correct form for quantifier in this language
*/
convertPlural: function ( count, forms ) {
var pluralRules,
pluralFormIndex,
index,
explicitPluralPattern = new RegExp( '\\d+=', 'i' ),
explicitPluralPattern = /\d+=/i,
formCount,
form;
@@ -285,13 +308,13 @@
// Handle for Explicit 0= & 1= values
for ( index = 0; index < forms.length; index++ ) {
form = forms[index];
form = forms[ index ];
if ( explicitPluralPattern.test( form ) ) {
formCount = parseInt( form.substring( 0, form.indexOf( '=' ) ), 10 );
formCount = parseInt( form.slice( 0, form.indexOf( '=' ) ), 10 );
if ( formCount === count ) {
return ( form.substr( form.indexOf( '=' ) + 1 ) );
return ( form.slice( form.indexOf( '=' ) + 1 ) );
}
forms[index] = undefined;
forms[ index ] = undefined;
}
}
@@ -301,25 +324,25 @@
}
} );
pluralRules = this.pluralRules[$.i18n().locale];
pluralRules = this.pluralRules[ $.i18n().locale ];
if ( !pluralRules ) {
// default fallback.
return ( count === 1 ) ? forms[0] : forms[1];
return ( count === 1 ) ? forms[ 0 ] : forms[ 1 ];
}
pluralFormIndex = this.getPluralForm( count, pluralRules );
pluralFormIndex = Math.min( pluralFormIndex, forms.length - 1 );
return forms[pluralFormIndex];
return forms[ pluralFormIndex ];
},
/**
* For the number, get the plural for index
*
* @param number
* @param pluralRules
* @return plural form index
* @param {integer} number
* @param {Object} pluralRules
* @return {integer} plural form index
*/
getPluralForm: function ( number, pluralRules ) {
var i,
@@ -327,8 +350,8 @@
pluralFormIndex = 0;
for ( i = 0; i < pluralForms.length; i++ ) {
if ( pluralRules[pluralForms[i]] ) {
if ( pluralRuleParser( pluralRules[pluralForms[i]], number ) ) {
if ( pluralRules[ pluralForms[ i ] ] ) {
if ( pluralRuleParser( pluralRules[ pluralForms[ i ] ], number ) ) {
return pluralFormIndex;
}
@@ -344,6 +367,7 @@
*
* @param {number} num Value to be converted
* @param {boolean} integer Convert the return value to an integer
* @return {string} The number converted into a String.
*/
convertNumber: function ( num, integer ) {
var tmp, item, i,
@@ -360,28 +384,28 @@
// Check if the restore to Latin number flag is set:
if ( integer ) {
if ( parseFloat( num ) === num ) {
if ( parseFloat( num, 10 ) === num ) {
return num;
}
tmp = [];
for ( item in transformTable ) {
tmp[transformTable[item]] = item;
tmp[ transformTable[ item ] ] = item;
}
transformTable = tmp;
}
for ( i = 0; i < numberString.length; i++ ) {
if ( transformTable[numberString[i]] ) {
convertedNumber += transformTable[numberString[i]];
if ( transformTable[ numberString[ i ] ] ) {
convertedNumber += transformTable[ numberString[ i ] ];
} else {
convertedNumber += numberString[i];
convertedNumber += numberString[ i ];
}
}
return integer ? parseFloat( convertedNumber ) : convertedNumber;
return integer ? parseFloat( convertedNumber, 10 ) : convertedNumber;
},
/**
@@ -390,11 +414,12 @@
* Override this method for languages that need special grammar rules
* applied dynamically.
*
* @param word {String}
* @param form {String}
* @return {String}
* @param {string} word
* @param {string} form
* @return {string}
*/
convertGrammar: function ( word, form ) { /*jshint unused: false */
// eslint-disable-next-line no-unused-vars
convertGrammar: function ( word, form ) {
return word;
},
@@ -405,12 +430,12 @@
*
* These details may be overriden per language.
*
* @param gender
* string male, female, or anything else for neutral.
* @param forms
* array List of gender forms
* @param {string} gender
* male, female, or anything else for neutral.
* @param {Array} forms
* List of gender forms
*
* @return string
* @return {string}
*/
gender: function ( gender, forms ) {
if ( !forms || forms.length === 0 ) {
@@ -418,25 +443,26 @@
}
while ( forms.length < 2 ) {
forms.push( forms[forms.length - 1] );
forms.push( forms[ forms.length - 1 ] );
}
if ( gender === 'male' ) {
return forms[0];
return forms[ 0 ];
}
if ( gender === 'female' ) {
return forms[1];
return forms[ 1 ];
}
return ( forms.length === 3 ) ? forms[2] : forms[0];
return ( forms.length === 3 ) ? forms[ 2 ] : forms[ 0 ];
},
/**
* Get the digit transform table for the given language
* See http://cldr.unicode.org/translation/numbering-systems
* @param language
* @returns {Array|boolean} List of digits in the passed language or false
*
* @param {string} language
* @return {Array|boolean} List of digits in the passed language or false
* representation, or boolean false if there is no information.
*/
digitTransformTable: function ( language ) {
@@ -448,6 +474,7 @@
lo: '໐໑໒໓໔໕໖໗໘໙',
or: '୦୧୨୩୪୫୬୭୮୯',
kh: '០១២៣៤៥៦៧៨៩',
nqo: '߀߁߂߃߄߅߆߇߈߉', // Note that the digits go right to left
pa: '੦੧੨੩੪੫੬੭੮੯',
gu: '૦૧૨૩૪૫૬૭૮૯',
hi: '०१२३४५६७८९',
@@ -458,15 +485,15 @@
bo: '༠༡༢༣༤༥༦༧༨༩' // FIXME use iso 639 codes
};
if ( !tables[language] ) {
if ( !tables[ language ] ) {
return false;
}
return tables[language].split( '' );
return tables[ language ].split( '' );
}
};
$.extend( $.i18n.languages, {
'default': language
default: language
} );
}( jQuery ) );

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library - Message Store
*
* Copyright (C) 2012 Santhosh Thottingal
@@ -12,7 +12,7 @@
* @licence MIT License
*/
( function ( $, window, undefined ) {
( function ( $ ) {
'use strict';
var MessageStore = function () {
@@ -20,6 +20,20 @@
this.sources = {};
};
function jsonMessageLoader( url ) {
var deferred = $.Deferred();
$.getJSON( url )
.done( deferred.resolve )
.fail( function ( jqxhr, settings, exception ) {
$.i18n.log( 'Error in loading messages from ' + url + ' Exception: ' + exception );
// Ignore 404 exception, because we are handling fallabacks explicitly
deferred.resolve();
} );
return deferred.promise();
}
/**
* See https://github.com/wikimedia/jquery.i18n/wiki/Specification#wiki-Message_File_Loading
*/
@@ -41,25 +55,22 @@
* null/undefined/false,
* all cached messages for the i18n instance will get reset.
*
* @param {String|Object} source
* @param {String} locale Language tag
* @param {string|Object} source
* @param {string} locale Language tag
* @return {jQuery.Promise}
*/
load: function ( source, locale ) {
var key = null,
deferred = null,
deferreds = [],
messageStore = this;
if ( typeof source === 'string' ) {
// This is a URL to the messages file.
$.i18n.log( 'Loading messages from: ' + source );
deferred = jsonMessageLoader( source )
.done( function ( localization ) {
messageStore.set( locale, localization );
return jsonMessageLoader( source )
.then( function ( localization ) {
return messageStore.load( localization, locale );
} );
return deferred.promise();
}
if ( locale ) {
@@ -74,7 +85,7 @@
locale = key;
// No {locale} given, assume data is a group of languages,
// call this function again for each language.
deferreds.push( messageStore.load( source[key], locale ) );
deferreds.push( messageStore.load( source[ key ], locale ) );
}
}
return $.when.apply( $, deferreds );
@@ -85,41 +96,28 @@
/**
* Set messages to the given locale.
* If locale exists, add messages to the locale.
* @param locale
* @param messages
*
* @param {string} locale
* @param {Object} messages
*/
set: function ( locale, messages ) {
if ( !this.messages[locale] ) {
this.messages[locale] = messages;
if ( !this.messages[ locale ] ) {
this.messages[ locale ] = messages;
} else {
this.messages[locale] = $.extend( this.messages[locale], messages );
this.messages[ locale ] = $.extend( this.messages[ locale ], messages );
}
},
/**
*
* @param locale
* @param messageKey
* @returns {Boolean}
* @param {string} locale
* @param {string} messageKey
* @return {boolean}
*/
get: function ( locale, messageKey ) {
return this.messages[locale] && this.messages[locale][messageKey];
return this.messages[ locale ] && this.messages[ locale ][ messageKey ];
}
};
function jsonMessageLoader( url ) {
var deferred = $.Deferred();
$.getJSON( url )
.done( deferred.resolve )
.fail( function ( jqxhr, settings, exception ) {
$.i18n.log( 'Error in loading messages from ' + url + ' Exception: ' + exception );
// Ignore 404 exception, because we are handling fallabacks explicitly
deferred.resolve();
} );
return deferred.promise();
}
$.extend( $.i18n.messageStore, new MessageStore() );
}( jQuery, window ) );
}( jQuery ) );

View File

@@ -1,4 +1,4 @@
/**
/*!
* jQuery Internationalization library
*
* Copyright (C) 2011-2013 Santhosh Thottingal, Neil Kandalgaonkar
@@ -18,7 +18,7 @@
var MessageParser = function ( options ) {
this.options = $.extend( {}, $.i18n.parser.defaults, options );
this.language = $.i18n.languages[String.locale] || $.i18n.languages['default'];
this.language = $.i18n.languages[ String.locale ] || $.i18n.languages[ 'default' ];
this.emitter = $.i18n.parser.emitter;
};
@@ -30,7 +30,7 @@
return message.replace( /\$(\d+)/g, function ( str, match ) {
var index = parseInt( match, 10 ) - 1;
return parameters[index] !== undefined ? parameters[index] : '$' + match;
return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
} );
},
@@ -39,8 +39,8 @@
return this.simpleParse( message, replacements );
}
this.emitter.language = $.i18n.languages[$.i18n().locale] ||
$.i18n.languages['default'];
this.emitter.language = $.i18n.languages[ $.i18n().locale ] ||
$.i18n.languages[ 'default' ];
return this.emitter.emit( this.ast( message ), replacements );
},
@@ -58,7 +58,7 @@
var i, result;
for ( i = 0; i < parserSyntax.length; i++ ) {
result = parserSyntax[i]();
result = parserSyntax[ i ]();
if ( result !== null ) {
return result;
@@ -78,7 +78,7 @@
result = [];
for ( i = 0; i < parserSyntax.length; i++ ) {
res = parserSyntax[i]();
res = parserSyntax[ i ]();
if ( res === null ) {
pos = originalPos;
@@ -123,7 +123,7 @@
return function () {
var result = null;
if ( message.substr( pos, len ) === s ) {
if ( message.slice( pos, pos + len ) === s ) {
result = s;
pos += len;
}
@@ -134,15 +134,15 @@
function makeRegexParser( regex ) {
return function () {
var matches = message.substr( pos ).match( regex );
var matches = message.slice( pos ).match( regex );
if ( matches === null ) {
return null;
}
pos += matches[0].length;
pos += matches[ 0 ].length;
return matches[0];
return matches[ 0 ];
};
}
@@ -152,9 +152,9 @@
anyCharacter = makeRegexParser( /^./ );
dollar = makeStringParser( '$' );
digits = makeRegexParser( /^\d+/ );
regularLiteral = makeRegexParser( /^[^{}\[\]$\\]/ );
regularLiteralWithoutBar = makeRegexParser( /^[^{}\[\]$\\|]/ );
regularLiteralWithoutSpace = makeRegexParser( /^[^{}\[\]$\s]/ );
regularLiteral = makeRegexParser( /^[^{}[\]$\\]/ );
regularLiteralWithoutBar = makeRegexParser( /^[^{}[\]$\\|]/ );
regularLiteralWithoutSpace = makeRegexParser( /^[^{}[\]$\s]/ );
// There is a general pattern:
// parse a thing;
@@ -189,7 +189,7 @@
function escapedLiteral() {
var result = sequence( [ backslash, anyCharacter ] );
return result === null ? null : result[1];
return result === null ? null : result[ 1 ];
}
choice( [ escapedLiteral, regularLiteralWithoutSpace ] );
@@ -203,13 +203,13 @@
return null;
}
return [ 'REPLACE', parseInt( result[1], 10 ) - 1 ];
return [ 'REPLACE', parseInt( result[ 1 ], 10 ) - 1 ];
}
templateName = transform(
// see $wgLegalTitleChars
// not allowing : due to the need to catch "PLURAL:$1"
makeRegexParser( /^[ !"$&'()*,.\/0-9;=?@A-Z\^_`a-z~\x80-\xFF+\-]+/ ),
makeRegexParser( /^[ !"$&'()*,./0-9;=?@A-Z^_`a-z~\x80-\xFF+-]+/ ),
function ( result ) {
return result.toString();
@@ -224,23 +224,23 @@
return null;
}
expr = result[1];
expr = result[ 1 ];
// use a "CONCAT" operator if there are multiple nodes,
// otherwise return the first node, raw.
return expr.length > 1 ? [ 'CONCAT' ].concat( expr ) : expr[0];
return expr.length > 1 ? [ 'CONCAT' ].concat( expr ) : expr[ 0 ];
}
function templateWithReplacement() {
var result = sequence( [ templateName, colon, replacement ] );
return result === null ? null : [ result[0], result[2] ];
return result === null ? null : [ result[ 0 ], result[ 2 ] ];
}
function templateWithOutReplacement() {
var result = sequence( [ templateName, colon, paramExpression ] );
return result === null ? null : [ result[0], result[2] ];
return result === null ? null : [ result[ 0 ], result[ 2 ] ];
}
templateContents = choice( [
@@ -254,7 +254,7 @@
nOrMore( 0, templateParam )
] );
return res === null ? null : res[0].concat( res[1] );
return res === null ? null : res[ 0 ].concat( res[ 1 ] );
},
function () {
var res = sequence( [ templateName, nOrMore( 0, templateParam ) ] );
@@ -263,7 +263,7 @@
return null;
}
return [ res[0] ].concat( res[1] );
return [ res[ 0 ] ].concat( res[ 1 ] );
}
] );
@@ -273,7 +273,7 @@
function template() {
var result = sequence( [ openTemplate, templateContents, closeTemplate ] );
return result === null ? null : result[1];
return result === null ? null : result[ 1 ];
}
expression = choice( [ template, replacement, literal ] );
@@ -294,7 +294,8 @@
/*
* For success, the pos must have gotten to the end of the input
* and returned a non-null.
* n.b. This is part of language infrastructure, so we do not throw an internationalizable message.
* n.b. This is part of language infrastructure, so we do not throw an
* internationalizable message.
*/
if ( result === null || pos !== message.length ) {
throw new Error( 'Parse error at position ' + pos.toString() + ' in input: ' + message );

View File

@@ -0,0 +1,22 @@
/**
* Bosnian (bosanski) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.bs = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'instrumental': // instrumental
word = 's ' + word;
break;
case 'lokativ': // locative
word = 'o ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,22 @@
/**
* Lower Sorbian (Dolnoserbski) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.dsb = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'instrumental': // instrumental
word = 'z ' + word;
break;
case 'lokatiw': // lokatiw
word = 'wo ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,49 @@
/**
* Finnish (Suomi) language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.fi = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
// vowel harmony flag
var aou = word.match( /[aou][^äöy]*$/i ),
origWord = word;
if ( word.match( /wiki$/i ) ) {
aou = false;
}
// append i after final consonant
if ( word.match( /[bcdfghjklmnpqrstvwxz]$/i ) ) {
word += 'i';
}
switch ( form ) {
case 'genitive':
word += 'n';
break;
case 'elative':
word += ( aou ? 'sta' : 'stä' );
break;
case 'partitive':
word += ( aou ? 'a' : 'ä' );
break;
case 'illative':
// Double the last letter and add 'n'
word += word.slice( -1 ) + 'n';
break;
case 'inessive':
word += ( aou ? 'ssa' : 'ssä' );
break;
default:
word = origWord;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,38 @@
/**
* Irish (Gaeilge) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.ga = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
if ( form === 'ainmlae' ) {
switch ( word ) {
case 'an Domhnach':
word = 'Dé Domhnaigh';
break;
case 'an Luan':
word = 'Dé Luain';
break;
case 'an Mháirt':
word = 'Dé Mháirt';
break;
case 'an Chéadaoin':
word = 'Dé Chéadaoin';
break;
case 'an Déardaoin':
word = 'Déardaoin';
break;
case 'an Aoine':
word = 'Dé hAoine';
break;
case 'an Satharn':
word = 'Dé Sathairn';
break;
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,31 @@
/**
* Hebrew (עברית) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.he = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'prefixed':
case 'תחילית': // the same word in Hebrew
// Duplicate prefixed "Waw", but only if it's not already double
if ( word.slice( 0, 1 ) === 'ו' && word.slice( 0, 2 ) !== 'וו' ) {
word = 'ו' + word;
}
// Remove the "He" if prefixed
if ( word.slice( 0, 1 ) === 'ה' ) {
word = word.slice( 1 );
}
// Add a hyphen (maqaf) before numbers and non-Hebrew letters
if ( word.slice( 0, 1 ) < 'א' || word.slice( 0, 1 ) > 'ת' ) {
word = '־' + word;
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,21 @@
/**
* Upper Sorbian (Hornjoserbsce) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.hsb = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'instrumental': // instrumental
word = 'z ' + word;
break;
case 'lokatiw': // lokatiw
word = 'wo ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,26 @@
/**
* Hungarian language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.hu = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'rol':
word += 'ról';
break;
case 'ba':
word += 'ba';
break;
case 'k':
word += 'k';
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,25 @@
/**
* Armenian (Հայերեն) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.hy = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
if ( form === 'genitive' ) { // սեռական հոլով
if ( word.slice( -1 ) === 'ա' ) {
word = word.slice( 0, -1 ) + 'այի';
} else if ( word.slice( -1 ) === 'ո' ) {
word = word.slice( 0, -1 ) + 'ոյի';
} else if ( word.slice( -4 ) === 'գիրք' ) {
word = word.slice( 0, -4 ) + 'գրքի';
} else {
word = word + 'ի';
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,54 @@
/**
* Latin (lingua Latina) language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.la = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'genitive':
// only a few declensions, and even for those mostly the singular only
word = word.replace( /u[ms]$/i, 'i' ); // 2nd declension singular
word = word.replace( /ommunia$/i, 'ommunium' ); // 3rd declension neuter plural (partly)
word = word.replace( /a$/i, 'ae' ); // 1st declension singular
word = word.replace( /libri$/i, 'librorum' ); // 2nd declension plural (partly)
word = word.replace( /nuntii$/i, 'nuntiorum' ); // 2nd declension plural (partly)
word = word.replace( /tio$/i, 'tionis' ); // 3rd declension singular (partly)
word = word.replace( /ns$/i, 'ntis' );
word = word.replace( /as$/i, 'atis' );
word = word.replace( /es$/i, 'ei' ); // 5th declension singular
break;
case 'accusative':
// only a few declensions, and even for those mostly the singular only
word = word.replace( /u[ms]$/i, 'um' ); // 2nd declension singular
word = word.replace( /ommunia$/i, 'am' ); // 3rd declension neuter plural (partly)
word = word.replace( /a$/i, 'ommunia' ); // 1st declension singular
word = word.replace( /libri$/i, 'libros' ); // 2nd declension plural (partly)
word = word.replace( /nuntii$/i, 'nuntios' );// 2nd declension plural (partly)
word = word.replace( /tio$/i, 'tionem' ); // 3rd declension singular (partly)
word = word.replace( /ns$/i, 'ntem' );
word = word.replace( /as$/i, 'atem' );
word = word.replace( /es$/i, 'em' ); // 5th declension singular
break;
case 'ablative':
// only a few declensions, and even for those mostly the singular only
word = word.replace( /u[ms]$/i, 'o' ); // 2nd declension singular
word = word.replace( /ommunia$/i, 'ommunibus' ); // 3rd declension neuter plural (partly)
word = word.replace( /a$/i, 'a' ); // 1st declension singular
word = word.replace( /libri$/i, 'libris' ); // 2nd declension plural (partly)
word = word.replace( /nuntii$/i, 'nuntiis' ); // 2nd declension plural (partly)
word = word.replace( /tio$/i, 'tione' ); // 3rd declension singular (partly)
word = word.replace( /ns$/i, 'nte' );
word = word.replace( /as$/i, 'ate' );
word = word.replace( /es$/i, 'e' ); // 5th declension singular
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,98 @@
/**
* Malayalam language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.ml = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
form = form.toLowerCase();
switch ( form ) {
case 'ഉദ്ദേശിക':
case 'dative':
if ( word.slice( -1 ) === 'ു' ||
word.slice( -1 ) === 'ൂ' ||
word.slice( -1 ) === 'ൗ' ||
word.slice( -1 ) === 'ൌ'
) {
word += 'വിന്';
} else if ( word.slice( -1 ) === '' ) {
word = word.slice( 0, -1 ) + 'ത്തിന്';
} else if ( word.slice( -1 ) === 'ൻ' ) {
// Atomic chillu n. അവൻ -> അവന്
word = word.slice( 0, -1 ) + 'ന്';
} else if ( word.slice( -3 ) === 'ന്\u200d' ) {
// chillu n. അവൻ -> അവന്
word = word.slice( 0, -1 );
} else if ( word.slice( -1 ) === 'ൾ' || word.slice( -3 ) === 'ള്\u200d' ) {
word += 'ക്ക്';
} else if ( word.slice( -1 ) === 'ർ' || word.slice( -3 ) === 'ര്\u200d' ) {
word += 'ക്ക്';
} else if ( word.slice( -1 ) === 'ൽ' ) {
// Atomic chillu ൽ , ഫയൽ -> ഫയലിന്
word = word.slice( 0, -1 ) + 'ലിന്';
} else if ( word.slice( -3 ) === 'ല്\u200d' ) {
// chillu ല്\u200d , ഫയല്\u200d -> ഫയലിന്
word = word.slice( 0, -2 ) + 'ിന്';
} else if ( word.slice( -2 ) === 'ു്' ) {
word = word.slice( 0, -2 ) + 'ിന്';
} else if ( word.slice( -1 ) === '്' ) {
word = word.slice( 0, -1 ) + 'ിന്';
} else {
// കാവ്യ -> കാവ്യയ്ക്ക്, ഹരി -> ഹരിയ്ക്ക്, മല -> മലയ്ക്ക്
word += 'യ്ക്ക്';
}
break;
case 'സംബന്ധിക':
case 'genitive':
if ( word.slice( -1 ) === '' ) {
word = word.slice( 0, -1 ) + 'ത്തിന്റെ';
} else if ( word.slice( -2 ) === 'ു്' ) {
word = word.slice( 0, -2 ) + 'ിന്റെ';
} else if ( word.slice( -1 ) === '്' ) {
word = word.slice( 0, -1 ) + 'ിന്റെ';
} else if ( word.slice( -1 ) === 'ു' ||
word.slice( -1 ) === 'ൂ' ||
word.slice( -1 ) === 'ൗ' ||
word.slice( -1 ) === 'ൌ'
) {
word += 'വിന്റെ';
} else if ( word.slice( -1 ) === 'ൻ' ) {
// Atomic chillu n. അവൻ -> അവന്റെ
word = word.slice( 0, -1 ) + 'ന്റെ';
} else if ( word.slice( -3 ) === 'ന്\u200d' ) {
// chillu n. അവൻ -> അവന്റെ
word = word.slice( 0, -1 ) + 'റെ';
} else if ( word.slice( -3 ) === 'ള്\u200d' ) {
// chillu n. അവൾ -> അവളുടെ
word = word.slice( 0, -2 ) + 'ുടെ';
} else if ( word.slice( -1 ) === 'ൾ' ) {
// Atomic chillu n. അവള്\u200d -> അവളുടെ
word = word.slice( 0, -1 ) + 'ളുടെ';
} else if ( word.slice( -1 ) === 'ൽ' ) {
// Atomic l. മുയല്\u200d -> മുയലിന്റെ
word = word.slice( 0, -1 ) + 'ലിന്റെ';
} else if ( word.slice( -3 ) === 'ല്\u200d' ) {
// chillu l. മുയല്\u200d -> അവളുടെ
word = word.slice( 0, -2 ) + 'ിന്റെ';
} else if ( word.slice( -3 ) === 'ര്\u200d' ) {
// chillu r. അവര്\u200d -> അവരുടെ
word = word.slice( 0, -2 ) + 'ുടെ';
} else if ( word.slice( -1 ) === 'ർ' ) {
// Atomic chillu r. അവർ -> അവരുടെ
word = word.slice( 0, -1 ) + 'രുടെ';
} else {
word += 'യുടെ';
}
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,75 @@
/**
* Ossetian (Ирон) language functions
*
* @author Santhosh Thottingal
*/
( function ( $ ) {
'use strict';
$.i18n.languages.os = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
var endAllative, jot, hyphen, ending;
// Ending for allative case
endAllative = 'мæ';
// Variable for 'j' beetwen vowels
jot = '';
// Variable for "-" for not Ossetic words
hyphen = '';
// Variable for ending
ending = '';
if ( word.match( /тæ$/i ) ) {
// Checking if the $word is in plural form
word = word.slice( 0, -1 );
endAllative = 'æм';
} else if ( word.match( /[аæеёиоыэюя]$/i ) ) {
// Works if word is in singular form.
// Checking if word ends on one of the vowels: е, ё, и, о, ы, э, ю,
// я.
jot = 'й';
} else if ( word.match( /у$/i ) ) {
// Checking if word ends on 'у'. 'У' can be either consonant 'W' or
// vowel 'U' in cyrillic Ossetic.
// Examples: {{grammar:genitive|аунеу}} = аунеуы,
// {{grammar:genitive|лæппу}} = лæппуйы.
if ( !word.slice( -2, -1 ).match( /[аæеёиоыэюя]$/i ) ) {
jot = 'й';
}
} else if ( !word.match( /[бвгджзйклмнопрстфхцчшщьъ]$/i ) ) {
hyphen = '-';
}
switch ( form ) {
case 'genitive':
ending = hyphen + jot + 'ы';
break;
case 'dative':
ending = hyphen + jot + 'æн';
break;
case 'allative':
ending = hyphen + endAllative;
break;
case 'ablative':
if ( jot === 'й' ) {
ending = hyphen + jot + 'æ';
} else {
ending = hyphen + jot + 'æй';
}
break;
case 'superessive':
ending = hyphen + jot + 'ыл';
break;
case 'equative':
ending = hyphen + jot + 'ау';
break;
case 'comitative':
ending = hyphen + 'имæ';
break;
}
return word + ending;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,29 @@
/**
* Russian (Русский) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.ru = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
if ( form === 'genitive' ) { // родительный падеж
if ( word.slice( -1 ) === 'ь' ) {
word = word.slice( 0, -1 ) + 'я';
} else if ( word.slice( -2 ) === 'ия' ) {
word = word.slice( 0, -2 ) + 'ии';
} else if ( word.slice( -2 ) === 'ка' ) {
word = word.slice( 0, -2 ) + 'ки';
} else if ( word.slice( -2 ) === 'ти' ) {
word = word.slice( 0, -2 ) + 'тей';
} else if ( word.slice( -2 ) === 'ды' ) {
word = word.slice( 0, -2 ) + 'дов';
} else if ( word.slice( -3 ) === 'ник' ) {
word = word.slice( 0, -3 ) + 'ника';
}
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,26 @@
/**
* Slovenian (Slovenščina) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.sl = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
// locative
case 'mestnik':
word = 'o ' + word;
break;
// instrumental
case 'orodnik':
word = 'z ' + word;
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -0,0 +1,39 @@
/**
* Ukrainian (Українська) language functions
*/
( function ( $ ) {
'use strict';
$.i18n.languages.uk = $.extend( {}, $.i18n.languages[ 'default' ], {
convertGrammar: function ( word, form ) {
switch ( form ) {
case 'genitive': // родовий відмінок
if ( word.slice( -1 ) === 'ь' ) {
word = word.slice( 0, -1 ) + 'я';
} else if ( word.slice( -2 ) === 'ія' ) {
word = word.slice( 0, -2 ) + 'ії';
} else if ( word.slice( -2 ) === 'ка' ) {
word = word.slice( 0, -2 ) + 'ки';
} else if ( word.slice( -2 ) === 'ти' ) {
word = word.slice( 0, -2 ) + 'тей';
} else if ( word.slice( -2 ) === 'ды' ) {
word = word.slice( 0, -2 ) + 'дов';
} else if ( word.slice( -3 ) === 'ник' ) {
word = word.slice( 0, -3 ) + 'ника';
}
break;
case 'accusative': // знахідний відмінок
if ( word.slice( -2 ) === 'ія' ) {
word = word.slice( 0, -2 ) + 'ію';
}
break;
}
return word;
}
} );
}( jQuery ) );

View File

@@ -1421,7 +1421,7 @@ JSONEditor.AbstractEditor = Class.extend({
this.template_engine = this.jsoneditor.template;
this.iconlib = this.jsoneditor.iconlib;
this.access = this.jsoneditor.access;
this.translate = this.jsoneditor.translate || JSONEditor.defaults.translate;
this.original_schema = options.schema;
@@ -1447,7 +1447,7 @@ JSONEditor.AbstractEditor = Class.extend({
if (!deps) {
return;
}
var self = this;
Object.keys(deps).forEach(function(dependency) {
var path = self.path.split('.');
@@ -1464,13 +1464,13 @@ JSONEditor.AbstractEditor = Class.extend({
if (this.path === path || !wrapper) {
return;
}
var self = this;
var editor = this.jsoneditor.getEditor(path);
var value = editor ? editor.getValue() : undefined;
var previousStatus = this.dependenciesFulfilled;
this.dependenciesFulfilled = false;
if (!editor || !editor.dependenciesFulfilled) {
this.dependenciesFulfilled = false;
} else if (Array.isArray(choices)) {
@@ -1504,7 +1504,7 @@ JSONEditor.AbstractEditor = Class.extend({
this.dependenciesFulfilled = !value;
}
}
if (this.dependenciesFulfilled !== previousStatus) {
this.notify();
}
@@ -1535,7 +1535,7 @@ JSONEditor.AbstractEditor = Class.extend({
this.updateHeaderText();
this.register();
this.onWatchedFieldChange();
//hide input fields, if they didn't match the current access level
var storedAccess = this.access
if(this.schema.access){
@@ -1544,12 +1544,12 @@ JSONEditor.AbstractEditor = Class.extend({
else if(this.schema.access == 'advanced' && storedAccess == 'default')
{
this.container.style.display = "none";
}
}
else if(this.schema.access == 'expert' && storedAccess != 'expert')
{
this.container.style.display = "none";
//this.disable();
}
}
}
},
@@ -1839,7 +1839,14 @@ JSONEditor.AbstractEditor = Class.extend({
this.parent = null;
},
getDefault: function() {
if(this.schema["default"]) return this.schema["default"];
var def = this.schema["default"];
if(def) {
if (typeof def === "string") {
return $.i18n(def);
} else {
return def;
}
}
if(this.schema["enum"]) return this.schema["enum"][0];
var type = this.schema.type || this.schema.oneOf;
@@ -2039,7 +2046,7 @@ JSONEditor.defaults.editors.string = JSONEditor.AbstractEditor.extend({
if(this.schema.append) this.append = this.theme.getFormInputAppend(this.getAppend());
this.placeholder = this.schema.default;
this.format = this.schema.format;
if(!this.format && this.schema.media && this.schema.media.type) {
this.format = this.schema.media.type.replace(/(^(application|text)\/(x-)?(script\.)?)|(-source$)/g,'');
@@ -2050,7 +2057,7 @@ JSONEditor.defaults.editors.string = JSONEditor.AbstractEditor.extend({
if(this.options.format) {
this.format = this.options.format;
}
// Specific format
if(this.format) {
// Text Area
@@ -2139,7 +2146,7 @@ JSONEditor.defaults.editors.string = JSONEditor.AbstractEditor.extend({
}
// Number or integer adds html5 tag 'number'
else if (this.schema.type == "number" || this.schema.type == "integer"){
var min = this.schema.minimum
var max = this.schema.maximum
var step = this.schema.step
@@ -2233,7 +2240,7 @@ JSONEditor.defaults.editors.string = JSONEditor.AbstractEditor.extend({
if(this.format) this.input.setAttribute('data-schemaformat',this.format);
if(this.defaultValue) this.input.setAttribute('data-schemaformat',this.format);
if(this.formname && this.label)this.label.setAttribute('for',this.formname);
this.control = this.theme.getFormControl(this.label, this.input, this.description, this.append, this.placeholder);
this.container.appendChild(this.control);
@@ -5097,7 +5104,7 @@ JSONEditor.defaults.editors.select = JSONEditor.AbstractEditor.extend({
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.schema.append) this.append = this.theme.getFormInputAppend(this.getAppend());
if(this.options.compact) this.container.className += ' compact';
this.input = this.theme.getSelectInput(this.enum_options);
@@ -5115,7 +5122,7 @@ JSONEditor.defaults.editors.select = JSONEditor.AbstractEditor.extend({
});
if(this.formname)this.label.setAttribute('for',this.formname);
this.control = this.theme.getFormControl(this.label, this.input, this.description);
this.container.appendChild(this.control);
@@ -6220,6 +6227,121 @@ JSONEditor.defaults.editors.arraySelectize = JSONEditor.AbstractEditor.extend({
}
});
// Imported from Version 1.4.0.beta.0 | https://cdn.jsdelivr.net/npm/@json-editor/json-editor@1.4.0-beta.0/dist/jsoneditor.js
JSONEditor.defaults.editors.radio = JSONEditor.defaults.editors.string.extend({
build: function () {
var self = this;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.options.infoText) this.infoButton = this.theme.getInfoButton(this.options.infoText);
if(this.options.compact) this.container.classList.add('compact');
this.radioContainer = document.createElement('div');
this.enum_values = this.schema.enum;
this.enum_titles = this.options.enum_titles || [];
this.radioGroup = [];
var radioInputEventhandler = function(e) {
e.preventDefault();
e.stopPropagation();
self.setValue(this.value);
self.onChange(true);
};
for(var i = 0; i < this.enum_values.length; i++) {
var id = this.key + '-' + i;
// form radio elements
var radioInput = this.theme.getFormInputField('radio');
radioInput.name = this.formname;
radioInput.value = this.enum_values[i];
radioInput.id = id;
radioInput.classList.add('radio__field');
radioInput.addEventListener('change', radioInputEventhandler, false);
this.radioGroup.push(radioInput);
// form-label for radio elements
var radioLabel = document.createElement('label');
radioLabel.htmlFor = id;
radioLabel.classList.add('radio');
// contains the displayed text to the label
var radioLabelText = document.createElement('span');
radioLabelText.innerText = $.i18n(this.options.enum_titles[i]) || this.enum_values[i];
radioLabelText.classList.add('radio__label');
// permits the addition of styles for the radio itself (if you want it to look differently than browser default)
var radioLabelIcon = document.createElement('span');
radioLabelIcon.classList.add('radio__icon');
radioLabel.appendChild(radioInput);
radioLabel.appendChild(radioLabelIcon);
radioLabel.appendChild(radioLabelText);
this.radioContainer.appendChild(radioLabel);
}
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
for (var j = 0; j < this.radioGroup.length; j++) {
this.radioGroup[j].disabled = true;
}
this.radioContainer.classList.add('readonly');
}
var radioContainerWrapper = this.theme.getContainer();
radioContainerWrapper.appendChild(this.radioContainer);
this.input = radioContainerWrapper;
this.control = this.theme.getFormControl(this.label, radioContainerWrapper, this.description, this.infoButton);
this.container.appendChild(this.control);
},
enable: function() {
if(!this.always_disabled) {
for (var i = 0; i<this.radioGroup.length; i++) {
this.radioGroup[i].disabled = false;
}
this.radioContainer.classList.remove('readonly');
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
for (var i = 0; i<this.radioGroup.length; i++) {
this.radioGroup[i].disabled = true;
}
this.radioContainer.classList.add('readonly');
this._super();
},
destroy: function() {
if(this.radioContainer.parentNode && this.radioContainer.parentNode.parentNode) this.radioContainer.parentNode.parentNode.removeChild(this.radioContainer.parentNode);
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
this._super();
},
getNumColumns: function() {
return 2;
},
setValue: function (val) {
for(var i = 0; i < this.radioGroup.length; i++) {
if(this.radioGroup[i].value == val) {
this.radioGroup[i].checked = true;
this.value = val;
if(this.options.displayValue) {
this.displayRating.innerHTML = this.value;
}
this.onChange();
break;
}
}
}
});
// colorpicker creation and handling, build on top of strings editor
JSONEditor.defaults.editors.colorPicker = JSONEditor.defaults.editors.string.extend({
getValue: function() {
@@ -6246,9 +6368,9 @@ JSONEditor.defaults.editors.colorPicker = JSONEditor.defaults.editors.string.ext
$(this.input).colorpicker('updatePicker', rgb2hex(val));
$(this.input).colorpicker('updateComponent', 'rgb('+val+')');
},
build: function() {
this._super();
var myinput = this;
@@ -6270,12 +6392,12 @@ JSONEditor.defaults.editors.colorPicker = JSONEditor.defaults.editors.string.ext
$("#event_catcher").detach().insertAfter(myinput.input);
$("#event_catcher").attr("id", "selector");
$(this.input).colorpicker().on('changeColor', function(e) {
$(myinput).val(e.color.toRGB()).change();
});
});
},
destroy: function() {
$(this.input).colorpicker('destroy');
}
@@ -6299,9 +6421,9 @@ JSONEditor.defaults.editors.colorPickerRGBA = JSONEditor.defaults.editors.string
// $(this.input).colorpicker('updatePicker', rgb2hex(val));
$(this.input).colorpicker('updateComponent', 'rgba('+val+')');
},
build: function() {
this._super();
var myinput = this;
@@ -6326,12 +6448,12 @@ JSONEditor.defaults.editors.colorPickerRGBA = JSONEditor.defaults.editors.string
$("#event_catcher").detach().insertAfter(myinput.input);
$("#event_catcher").attr("id", "selector");
$(this.input).colorpicker().on('changeColor', function(e) {
$(myinput).val(e.color.toRGB()).change();
});
});
},
destroy: function() {
$(this.input).colorpicker('destroy');
}
@@ -6501,7 +6623,7 @@ JSONEditor.AbstractTheme = Class.extend({
},
getRangeInput: function(min,max,step) {
if (typeof step == "undefined") step = 1;
var el = this.getFormInputField('number');
if (typeof min != "undefined") el.setAttribute('min',min);
if (typeof max != "undefined") el.setAttribute('max',max);
@@ -6741,13 +6863,13 @@ JSONEditor.defaults.themes.bootstrap3 = JSONEditor.AbstractTheme.extend({
getFormControl: function(label, input, description, append, placeholder) {
var group = document.createElement('div');
var subgroup = document.createElement('div');
if(placeholder)
input.setAttribute('placeholder',placeholder);
if (input.type === 'checkbox'){
var helplabel = document.createElement("label")
group.className += ' form-group';
group.style.minHeight = "30px";
label.className += ' col-form-label col-sm-5 col-md-3 col-lg-5 col-xxl-4';
@@ -6783,7 +6905,7 @@ JSONEditor.defaults.themes.bootstrap3 = JSONEditor.AbstractTheme.extend({
subgroup.className += ' input-group col-sm-7 col-md-9 col-lg-7 col-xxl-8';
subgroup.appendChild(input);
}
if(description) group.appendChild(description);
@@ -7089,10 +7211,10 @@ JSONEditor.defaults.template = 'default';
JSONEditor.defaults.options = {};
// String translate function
JSONEditor.defaults.translate = function(key, variables) {
JSONEditor.defaults.translate = function(key, variables) {
return $.i18n(key, variables);
};
// Miscellaneous Plugin Settings
@@ -7167,7 +7289,12 @@ JSONEditor.defaults.resolvers.unshift(function(schema) {
});
// Use the `select` editor for dynamic enumSource enums
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.enumSource) return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
if(schema.enumSource) {
if(schema.format === "radio") {
return "radio";
}
return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
}
});
// Use the `enum` or `select` editors for schemas with enumerated properties
JSONEditor.defaults.resolvers.unshift(function(schema) {
@@ -7176,6 +7303,11 @@ JSONEditor.defaults.resolvers.unshift(function(schema) {
return "enum";
}
else if(schema.type === "number" || schema.type === "integer" || schema.type === "string") {
if(schema.format === "radio") {
return "radio";
}
return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
}
}

View File

@@ -1,148 +1,112 @@
var availAccess = ['default', 'advanced', 'expert'];
var storedAccess;
var storedLang;
var availLang = ['cs','de','en','es','fr','it','nl','pl','ro','sv','vi','ru','tr','zh-CN'];
var availLangText = ['Čeština', 'Deutsch', 'English', 'Español', 'Français', 'Italiano', 'Nederlands', 'Polski', 'Română', 'Svenska', 'Tiếng Việt', 'русский', 'Türkçe', '汉语'];
var availAccess = ['default','advanced','expert'];
//$.i18n.debug = true;
//Change Password
function changePassword(){
showInfoDialog('changePassword', $.i18n('InfoDialog_changePassword_title'));
showInfoDialog('changePassword', $.i18n('InfoDialog_changePassword_title'));
// fill default pw if default is set
if(window.defaultPasswordIsSet)
$('#oldPw').val('hyperion')
// fill default pw if default is set
if(window.defaultPasswordIsSet)
$('#current-password').val('hyperion')
$('#id_btn_ok').off().on('click',function() {
var oldPw = $('#oldPw').val();
var newPw = $('#newPw').val();
$('#id_btn_ok').off().on('click',function() {
var oldPw = $('#current-password').val();
var newPw = $('#new-password').val();
requestChangePassword(oldPw, newPw)
});
requestChangePassword(oldPw, newPw);
history.pushState({}, "New password");
});
$('#newPw, #oldPw').off().on('input',function(e) {
($('#oldPw').val().length >= 8 && $('#newPw').val().length >= 8) && !window.readOnlyMode ? $('#id_btn_ok').attr('disabled', false) : $('#id_btn_ok').attr('disabled', true);
});
$('#new-password, #current-password').off().on('input',function(e) {
($('#current-password').val().length >= 8 && $('#new-password').val().length >= 8) && !window.readOnlyMode ? $('#id_btn_ok').attr('disabled', false) : $('#id_btn_ok').attr('disabled', true);
});
}
$(document).ready( function() {
$(document).ready(function () {
//i18n
function initTrans(lc){
if (lc == 'auto')
{
$.i18n().load().done(
function() {
performTranslation();
});
}
else
{
$.i18n().locale = lc;
$.i18n().load( "i18n", lc ).done(
function() {
performTranslation();
});
}
}
if (!storageComp()) {
showInfoDialog('warning', "Can't store settings", "Your browser doesn't support localStorage. You can't save a specific language setting (fallback to 'auto detection') and access level (fallback to 'default'). Some wizards may be hidden. You could still use the webinterface without further issues");
$('#language-select').attr("disabled", true);
$('#btn_setaccess').attr("disabled", true);
}
if (storageComp())
{
storedLang = getStorage("langcode");
if (storedLang == null)
{
setStorage("langcode", 'auto');
storedLang = 'auto';
initTrans(storedLang);
}
else
{
initTrans(storedLang);
}
}
else
{
showInfoDialog('warning', "Can't store settings", "Your browser doesn't support localStorage. You can't save a specific language setting (fallback to 'auto detection') and access level (fallback to 'default'). Some wizards may be hidden. You could still use the webinterface without further issues");
initTrans('auto');
storedLang = 'auto';
storedAccess = "default";
$('#btn_setlang').attr("disabled", true);
$('#btn_setaccess').attr("disabled", true);
}
initLanguageSelection();
initLanguageSelection();
//access
storedAccess = getStorage("accesslevel");
if (storedAccess == null) {
storedAccess = "default";
setStorage("accesslevel", storedAccess);
}
//access
storedAccess = getStorage("accesslevel");
if (storedAccess == null)
{
setStorage("accesslevel", "default");
storedAccess = "default";
}
if (!storageComp()) {
showInfoDialog('warning', $.i18n('InfoDialog_nostorage_title'), $.i18n('InfoDialog_nostorage_text'));
$('#btn_setlang').attr("disabled", true);
}
$('#btn_setaccess').off().on('click',function() {
var newAccess;
showInfoDialog('select', $.i18n('InfoDialog_access_title'), $.i18n('InfoDialog_access_text'));
$('#btn_setaccess').off().on('click',function() {
var newAccess;
showInfoDialog('select', $.i18n('InfoDialog_access_title'), $.i18n('InfoDialog_access_text'));
for (var lcx = 0; lcx<availAccess.length; lcx++)
{
$('#id_select').append(createSelOpt(availAccess[lcx], $.i18n('general_access_'+availAccess[lcx])));
}
for (var lcx = 0; lcx<availAccess.length; lcx++)
{
$('#id_select').append(createSelOpt(availAccess[lcx], $.i18n('general_access_'+availAccess[lcx])));
}
$('#id_select').val(storedAccess);
$('#id_select').val(storedAccess);
$('#id_select').off().on('change',function() {
newAccess = $('#id_select').val();
if (newAccess == storedAccess)
$('#id_btn_saveset').attr('disabled', true);
else
$('#id_btn_saveset').attr('disabled', false);
});
$('#id_select').off().on('change',function() {
newAccess = $('#id_select').val();
if (newAccess == storedAccess)
$('#id_btn_saveset').attr('disabled', true);
else
$('#id_btn_saveset').attr('disabled', false);
});
$('#id_btn_saveset').off().on('click',function() {
setStorage("accesslevel", newAccess);
reload();
});
$('#id_btn_saveset').off().on('click',function() {
setStorage("accesslevel", newAccess);
reload();
});
$('#id_select').trigger('change');
});
$('#id_select').trigger('change');
});
// change pw btn
$('#btn_changePassword').off().on('click',function() {
changePassword();
});
// change pw btn
$('#btn_changePassword').off().on('click',function() {
changePassword();
});
//Lock Ui
$('#btn_lock_ui').off().on('click',function() {
removeStorage('loginToken', true);
location.replace('/');
});
//Lock Ui
$('#btn_lock_ui').off().on('click',function() {
removeStorage('loginToken', true);
location.replace('/');
});
//hide menu elements
if (storedAccess != 'expert')
$('#load_webconfig').toggle(false);
//hide menu elements
if (storedAccess != 'expert')
$('#load_webconfig').toggle(false);
// instance switcher
$('#btn_instanceswitch').off().on('click',function() {
var lsys = window.sysInfo.system.hostName+':'+window.serverConfig.webConfig.port;
showInfoDialog('iswitch', $.i18n('InfoDialog_iswitch_title'), $.i18n('InfoDialog_iswitch_text'));
// instance switcher
$('#btn_instanceswitch').off().on('click',function() {
var lsys = window.sysInfo.system.hostName+':'+window.serverConfig.webConfig.port;
showInfoDialog('iswitch', $.i18n('InfoDialog_iswitch_title'), $.i18n('InfoDialog_iswitch_text'));
for (var i = 0; i<window.wSess.length; i++)
{
if(lsys != window.wSess[i].host+':'+window.wSess[i].port)
{
var hyperionAddress = window.wSess[i].address;
if(hyperionAddress.indexOf(':') > -1 && hyperionAddress.length == 36) hyperionAddress = '['+hyperionAddress+']';
hyperionAddress = 'http://'+hyperionAddress+':'+window.wSess[i].port;
$('#id_select').append(createSelOpt(hyperionAddress, window.wSess[i].name));
}
}
for (var i = 0; i<window.wSess.length; i++)
{
if(lsys != window.wSess[i].host+':'+window.wSess[i].port)
{
var hyperionAddress = window.wSess[i].address;
if(hyperionAddress.indexOf(':') > -1 && hyperionAddress.length == 36) hyperionAddress = '['+hyperionAddress+']';
hyperionAddress = 'http://'+hyperionAddress+':'+window.wSess[i].port;
$('#id_select').append(createSelOpt(hyperionAddress, window.wSess[i].name));
}
}
$('#id_btn_saveset').off().on('click',function() {
$("#loading_overlay").addClass("overlay");
window.location.href = $('#id_select').val();
});
$('#id_btn_saveset').off().on('click',function() {
$("#loading_overlay").addClass("overlay");
window.location.href = $('#id_select').val();
});
});
});
});

File diff suppressed because it is too large Load Diff

525
assets/webconfig/js/wizard.js Normal file → Executable file
View File

@@ -53,6 +53,9 @@ function startWizardRGB() {
$('#wizp2_body').append('<table class="table borderless" style="width:200px"><tbody><tr><td class="ltd"><label>' + $.i18n('wiz_rgb_qrend') + '</label></td><td class="itd"><select id="wiz_r_select" class="form-control wselect"></select></td></tr><tr><td class="ltd"><label>' + $.i18n('wiz_rgb_qgend') + '</label></td><td class="itd"><select id="wiz_g_select" class="form-control wselect"></select></td></tr></tbody></table>');
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save"><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_save') + '</button><button type="button" class="btn btn-primary" id="btn_wiz_checkok" style="display:none" data-dismiss="modal"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_ok') + '</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
@@ -424,11 +427,14 @@ function startWizardCC() {
}
//create html
$('#wiz_header').html('<i class="fa fa-magic fa-fw"></i>' + $.i18n('wiz_cc_title'));
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n('wiz_cc_title') + '</h4><p>' + $.i18n('wiz_cc_intro1') + '</p><label>' + $.i18n('wiz_cc_kwebs') + '</label><input class="form-control" style="width:170px;margin:auto" id="wiz_cc_kodiip" type="text" placeholder="' + kodiAddress + '" value="' + kodiAddress + '" /><span id="kodi_status"></span><span id="multi_cali"></span>');
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n('wiz_cc_title') + '</h4><p>' + $.i18n('wiz_cc_intro1') + '</p><label>' + $.i18n('wiz_cc_kwebs') + '</label><input class="form-control" style="width:170px;margin:auto" id="wiz_cc_kodiip" type="text" placeholder="' + kodiAddress + '" value="' + kodiAddress + '" /><span id="kodi_status"></span><span id="multi_cali"></span>');
$('#wizp1_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_cont" disabled="disabled"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_continue') + '</button><button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
$('#wizp2_body').html('<div id="wiz_cc_desc" style="font-weight:bold"></div><div id="editor_container_wiz"></div>');
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_back"><i class="fa fa-fw fa-chevron-left"></i>' + $.i18n('general_btn_back') + '</button><button type="button" class="btn btn-primary" id="btn_wiz_next">' + $.i18n('general_btn_next') + '<i style="margin-left:4px;"class="fa fa-fw fa-chevron-right"></i></button><button type="button" class="btn btn-warning" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_save') + '</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
@@ -437,10 +443,9 @@ function startWizardCC() {
});
$('#wiz_cc_kodiip').off().on('change', function () {
kodiAddress = $(this).val().trim();
$('#wizp1_body').find("kodiAddress").val(kodiAddress);
$('#kodi_status').html('');
// Remove Kodi's default Web-Socket port (9090) from display and ensure Kodi's default REST-API port (8080) is mapped to web-socket port to ease migration
@@ -670,6 +675,9 @@ function startWizardPhilipsHue(e) {
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>' + $.i18n('general_btn_save') + '</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
$('#wizp3_body').html('<span>' + $.i18n('wiz_hue_press_link') + '</span> <br /><br /><center><span id="connectionTime"></span><br /><i class="fa fa-cog fa-spin" style="font-size:100px"></i></center>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
@@ -688,24 +696,27 @@ function startWizardPhilipsHue(e) {
function checkHueBridge(cb, hueUser) {
var usr = (typeof hueUser != "undefined") ? hueUser : 'config';
if (usr == 'config') $('#wiz_hue_discovered').html("");
$.ajax({
url: 'http://' + hueIPs[hueIPsinc].internalipaddress + '/api/' + usr,
type: "GET",
dataType: "json",
success: function (json) {
if (json.config) {
cb(true, usr);
} else if (json.name && json.bridgeid && json.modelid) {
$('#wiz_hue_discovered').html("Bridge: " + json.name + ", Modelid: " + json.modelid + ", API-Version: " + json.apiversion);
cb(true);
} else {
cb(false);
}
},
timeout: 2500
}).fail(function () {
cb(false);
});
if (hueIPs[hueIPsinc]) {
$.ajax({
url: 'http://' + hueIPs[hueIPsinc].internalipaddress + '/api/' + usr,
type: "GET",
dataType: "json",
success: function (json) {
if (json.config) {
cb(true, usr);
} else if (json.name && json.bridgeid && json.modelid) {
$('#wiz_hue_discovered').html("Bridge: " + json.name + ", Modelid: " + json.modelid + ", API-Version: " + json.apiversion);
cb(true);
} else {
cb(false);
}
},
timeout: 2500
}).fail(function () {
cb(false);
});
}
}
function checkBridgeResult(reply, usr) {
@@ -780,27 +791,41 @@ function useGroupId(id) {
}
async function discover_hue_bridges() {
$('#wiz_hue_ipstate').html($.i18n('edt_dev_spec_devices_discovery_inprogress'));
$('#wiz_hue_discovered').html("")
const res = await requestLedDeviceDiscovery('philipshue');
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info;
// Process devices returned by discovery
console.log(r);
if (r.devices.length == 0)
if (r.devices.length == 0) {
$('#wiz_hue_ipstate').html($.i18n('wiz_hue_failure_ip'));
$('#wiz_hue_discovered').html("")
}
else {
for (const device of r.devices) {
console.log("Device:", device);
//console.log("Device:", device);
if (device && device.ip && device.port) {
var ip = device.hostname + ":" + device.port;
console.log("Host:", ip);
var ip;
if (device.hostname && device.domain) {
ip = device.hostname + "." + device.domain + ":" + device.port;
} else {
ip = device.ip + ":" + device.port;
}
hueIPs.push({ internalipaddress: ip });
if (ip) {
if (!hueIPs.some(item => item.internalipaddress === ip)) {
hueIPs.push({ internalipaddress: ip });
}
}
}
}
var usr = $('#user').val();
if (usr != "") {
checkHueBridge(checkUserResult, usr);
@@ -826,9 +851,17 @@ async function getProperties_hue_bridge(hostAddress, username, resourceFilter) {
}
}
function identify_hue_device(hostAddress, username, id) {
async function identify_hue_device(hostAddress, username, id) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { host: hostAddress, user: username, lightId: id };
requestLedDeviceIdentification("philipshue", params);
await requestLedDeviceIdentification('philipshue', params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
}
function getHueIPs() {
@@ -870,12 +903,12 @@ function beginWizardHue() {
}
}
//check if ip is empty/reachable/search for bridge
if (eV("output") == "") {
if (eV("host") == "") {
//getHueIPs();
discover_hue_bridges();
}
else {
var ip = eV("output");
var ip = eV("host");
$('#ip').val(ip);
hueIPs.unshift({ internalipaddress: ip });
if (usr != "") {
@@ -940,7 +973,7 @@ function beginWizardHue() {
//Start with a clean configuration
var d = {};
d.output = $('#ip').val();
d.host = $('#ip').val();
d.username = $('#user').val();
d.type = 'philipshue';
d.colorOrder = 'rgb';
@@ -1179,7 +1212,6 @@ function get_hue_lights() {
}
(cC == 0 || window.readOnlyMode) ? $('#btn_wiz_save').attr("disabled", true) : $('#btn_wiz_save').attr("disabled", false);
});
}
$('.hue_sel_watch').trigger('change');
@@ -1200,100 +1232,6 @@ function abortConnection(UserInterval) {
$("#wiz_hue_usrstate").html($.i18n('wiz_hue_failure_connection'));
}
//****************************
// Wizard WLED
//****************************
var lights = null;
function startWizardWLED(e) {
//create html
var wled_title = 'wiz_wled_title';
var wled_intro1 = 'wiz_wled_intro1';
$('#wiz_header').html('<i class="fa fa-magic fa-fw"></i>' + $.i18n(wled_title));
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n(wled_title) + '</h4><p>' + $.i18n(wled_intro1) + '</p>');
$('#wizp1_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_cont"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_continue') + '</button><button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
/*$('#wizp2_body').html('<div id="wh_topcontainer"></div>');
$('#wh_topcontainer').append('<div class="form-group" id="usrcont" style="display:none"></div>');
$('#wizp2_body').append('<div id="hue_ids_t" style="display:none"><p style="font-weight:bold" id="hue_id_headline">'+$.i18n('wiz_wled_desc2')+'</p></div>');
createTable("lidsh", "lidsb", "hue_ids_t");
$('.lidsh').append(createTableRow([$.i18n('edt_dev_spec_lights_title'),$.i18n('wiz_pos'),$.i18n('wiz_identify')], true));
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>'+$.i18n('general_btn_save')+'</button><button type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'+$.i18n('general_btn_cancel')+'</button>');
*/
//open modal
$("#wizard_modal").modal({
backdrop: "static",
keyboard: false,
show: true
});
//listen for continue
$('#btn_wiz_cont').off().on('click', function () {
/* For testing only
discover_wled();
var hostAddress = conf_editor.getEditor("root.specificOptions.host").getValue();
if(hostAddress != "")
{
getProperties_wled(hostAddress,"info");
identify_wled(hostAddress)
}
For testing only */
});
}
async function discover_wled() {
const res = await requestLedDeviceDiscovery('wled');
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process devices returned by discovery
console.log(r);
if (r.devices.length == 0)
$('#wiz_hue_ipstate').html($.i18n('wiz_hue_failure_ip'));
else {
for (const device of r.devices) {
console.log("Device:", device);
var ip = device.hostname + ":" + device.port;
console.log("Host:", ip);
//wledIPs.push({internalipaddress : ip});
}
}
}
}
async function getProperties_wled(hostAddress, resourceFilter) {
let params = { host: hostAddress, filter: resourceFilter };
const res = await requestLedDeviceProperties('wled', params);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process properties returned
console.log(r);
}
}
function identify_wled(hostAddress) {
let params = { host: hostAddress };
requestLedDeviceIdentification("wled", params);
}
//****************************
// Wizard Yeelight
//****************************
@@ -1323,6 +1261,9 @@ function startWizardYeelight(e) {
+ $.i18n('general_btn_save') + '</button><buttowindow.serverConfig.device = d;n type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'
+ $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({ backdrop: "static", keyboard: false, show: true });
@@ -1422,8 +1363,17 @@ async function discover_yeelight_lights() {
var light = {};
light.host = device.hostname;
light.port = device.port;
light.name = device.other.name;
light.model = device.other.model;
if (device.txt) {
light.name = device.name;
light.model = device.txt.md;
//Yeelight does not provide correct API port with mDNS response, use default one
light.port = 55443;
}
else {
light.name = device.other.name;
light.model = device.other.model;
}
lights.push(light);
}
}
@@ -1453,7 +1403,8 @@ async function discover_yeelight_lights() {
}
function assign_yeelight_lights() {
var models = ['color', 'color1', 'color2', 'color4', 'stripe', 'strip1'];
// Model mappings, see https://www.home-assistant.io/integrations/yeelight/
var models = ['color', 'color1', 'YLDP02YL', 'YLDP02YL', 'color2', 'YLDP06YL', 'color4', 'YLDP13YL', 'stripe', 'YLDD04YL', 'strip1', 'YLDD01YL', 'YLDD02YL'];
// If records are left for configuration
if (Object.keys(lights).length > 0) {
@@ -1518,7 +1469,7 @@ function assign_yeelight_lights() {
$('.yee_sel_watch').trigger('change');
}
else {
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights','Yeelights') + '</p>';
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights', 'Yeelights') + '</p>';
$('#wizp2_body').append(noLightsTxt);
}
}
@@ -1538,9 +1489,16 @@ async function getProperties_yeelight(hostname, port) {
}
}
function identify_yeelight_device(hostname, port) {
async function identify_yeelight_device(hostname, port) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { hostname: hostname, port: port };
requestLedDeviceIdentification("yeelight", params);
await requestLedDeviceIdentification("yeelight", params);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
}
//****************************
@@ -1572,6 +1530,9 @@ function startWizardAtmoOrb(e) {
+ $.i18n('general_btn_save') + '</button><buttowindow.serverConfig.device = d;n type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'
+ $.i18n('general_btn_cancel') + '</button>');
if (getStorage("darkMode", false) == "on")
$('#wizard_logo').attr("src", 'img/hyperion/logo_negativ.png');
//open modal
$("#wizard_modal").modal({ backdrop: "static", keyboard: false, show: true });
@@ -1592,7 +1553,7 @@ function beginWizardAtmoOrb() {
configuredLights = configruedOrbIds.split(",").map(Number);
}
var multiCastGroup = conf_editor.getEditor("root.specificOptions.output").getValue();
var multiCastGroup = conf_editor.getEditor("root.specificOptions.host").getValue();
var multiCastPort = parseInt(conf_editor.getEditor("root.specificOptions.port").getValue());
discover_atmoorb_lights(multiCastGroup, multiCastPort);
@@ -1634,7 +1595,7 @@ function beginWizardAtmoOrb() {
d.orbIds = finalLights.toString();
d.useOrbSmoothing = (eV("useOrbSmoothing") == true);
d.output = conf_editor.getEditor("root.specificOptions.output").getValue();
d.host = conf_editor.getEditor("root.specificOptions.host").getValue();
d.port = parseInt(conf_editor.getEditor("root.specificOptions.port").getValue());
d.latchTime = parseInt(conf_editor.getEditor("root.specificOptions.latchTime").getValue());;
@@ -1651,14 +1612,12 @@ async function discover_atmoorb_lights(multiCastGroup, multiCastPort) {
var light = {};
var params = {};
if (multiCastGroup !== "")
{
if (multiCastGroup !== "") {
params.multiCastGroup = multiCastGroup;
}
if (multiCastPort !== 0)
{
params.multiCastPort = multiCastPort;
if (multiCastPort !== 0) {
params.multiCastPort = multiCastPort;
}
// Get discovered lights
@@ -1668,7 +1627,7 @@ async function discover_atmoorb_lights(multiCastGroup, multiCastPort) {
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info;
// Process devices returned by discovery
for (const device of r.devices) {
if (device.id !== "") {
@@ -1750,7 +1709,7 @@ function assign_atmoorb_lights() {
$('.lidsb').append(createTableRow([orbId + lightAnnotation, '<select id="orb_' + lightid + '" ' + enabled + ' class="orb_sel_watch form-control">'
+ options
+ '</select>', '<button class="btn btn-sm btn-primary" ' + enabled + ' onClick=identify_atmoorb_device(' + orbId + ')>'
+ '</select>', '<button class="btn btn-sm btn-primary" ' + enabled + ' onClick=identify_atmoorb_device("' + orbId + '")>'
+ $.i18n('wiz_identify_light', orbId) + '</button>']));
}
@@ -1769,281 +1728,19 @@ function assign_atmoorb_lights() {
$('.orb_sel_watch').trigger('change');
}
else {
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights','AtmoOrbs') + '</p>';
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights', 'AtmoOrbs') + '</p>';
$('#wizp2_body').append(noLightsTxt);
}
}
function identify_atmoorb_device(orbId) {
async function identify_atmoorb_device(orbId) {
// Take care that new record cannot be save during background process
$('#btn_wiz_save').attr('disabled', true);
let params = { id: orbId };
requestLedDeviceIdentification("atmoorb", params);
}
await requestLedDeviceIdentification("atmoorb", params);
//****************************
// Wizard/Routines Nanoleaf
//****************************
async function discover_nanoleaf() {
const res = await requestLedDeviceDiscovery('nanoleaf');
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process devices returned by discovery
console.log(r);
if (r.devices.length == 0)
$('#wiz_hue_ipstate').html($.i18n('wiz_hue_failure_ip'));
else {
for (const device of r.devices) {
console.log("Device:", device);
var ip = device.hostname + ":" + device.port;
console.log("Host:", ip);
//nanoleafIPs.push({internalipaddress : ip});
}
}
}
}
async function getProperties_nanoleaf(hostAddress, authToken, resourceFilter) {
let params = { host: hostAddress, token: authToken, filter: resourceFilter };
const res = await requestLedDeviceProperties('nanoleaf', params);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process properties returned
console.log(r);
}
}
function identify_nanoleaf(hostAddress, authToken) {
let params = { host: hostAddress, token: authToken };
requestLedDeviceIdentification("nanoleaf", params);
}
//****************************
// Wizard Cololight
//****************************
var lights = null;
var selectedLightId = null;
function startWizardCololight(e) {
//create html
var cololight_title = 'wiz_cololight_title';
var cololight_intro1 = 'wiz_cololight_intro1';
$('#wiz_header').html('<i class="fa fa-magic fa-fw"></i>' + $.i18n(cololight_title));
$('#wizp1_body').html('<h4 style="font-weight:bold;text-transform:uppercase;">' + $.i18n(cololight_title) + '</h4><p>' + $.i18n(cololight_intro1) + '</p>');
$('#wizp1_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_cont"><i class="fa fa-fw fa-check"></i>' + $.i18n('general_btn_continue') + '</button><button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-fw fa-close"></i>' + $.i18n('general_btn_cancel') + '</button>');
$('#wizp2_body').html('<div id="wh_topcontainer"></div>');
$('#wh_topcontainer').append('<div class="form-group" id="usrcont" style="display:none"></div>');
$('#wizp2_body').append('<div id="colo_ids_t" style="display:none"><p style="font-weight:bold" id="colo_id_headline">' + $.i18n('wiz_cololight_desc2') + '</p></div>');
createTable("lidsh", "lidsb", "colo_ids_t");
$('.lidsh').append(createTableRow([$.i18n('edt_dev_spec_lights_title'), $.i18n('wiz_identify')], true));
$('#wizp2_footer').html('<button type="button" class="btn btn-primary" id="btn_wiz_save" style="display:none"><i class="fa fa-fw fa-save"></i>'
+ $.i18n('general_btn_save') + '</button><buttowindow.serverConfig.device = d;n type="button" class="btn btn-danger" id="btn_wiz_abort"><i class="fa fa-fw fa-close"></i>'
+ $.i18n('general_btn_cancel') + '</button>');
//open modal
$("#wizard_modal").modal({
backdrop: "static",
keyboard: false,
show: true
});
//listen for continue
$('#btn_wiz_cont').off().on('click', function () {
beginWizardCololight();
$('#wizp1').toggle(false);
$('#wizp2').toggle(true);
});
}
function beginWizardCololight() {
lights = [];
discover_cololights();
$('#btn_wiz_save').off().on("click", function () {
//LED device config
//Start with a clean configuration
var d = {};
d.type = 'cololight';
//Cololight does not resolve into stable hostnames (as devices named the same), therefore use IP
if (!lights[selectedLightId].ip) {
d.host = lights[selectedLightId].host;
} else {
d.host = lights[selectedLightId].ip;
}
var coloLightProperties = lights[selectedLightId].props;
if (Object.keys(coloLightProperties).length === 0) {
alert($.i18n('wiz_cololight_noprops'));
d.hardwareLedCount = 1;
} else {
if (coloLightProperties.ledCount > 0) {
d.hardwareLedCount = coloLightProperties.ledCount;
} else if (coloLightProperties.modelType === "Strip")
d.hardwareLedCount = 120;
}
d.colorOrder = conf_editor.getEditor("root.generalOptions.colorOrder").getValue();
d.latchTime = parseInt(conf_editor.getEditor("root.specificOptions.latchTime").getValue());;
window.serverConfig.device = d;
//LED layout - have initial layout prepared matching the LED-count
var coloLightLedConfig = [];
if (coloLightProperties.modelType === "Strip") {
coloLightLedConfig = createClassicLedLayoutSimple(d.hardwareLedCount / 2, d.hardwareLedCount / 4, d.hardwareLedCount / 4, 0, d.hardwareLedCount / 4 * 3, false);
} else {
coloLightLedConfig = createClassicLedLayoutSimple(0, 0, 0, d.hardwareLedCount, 0, true);
}
window.serverConfig.leds = coloLightLedConfig;
//smoothing off
window.serverConfig.smoothing.enable = false;
requestWriteConfig(window.serverConfig, true);
resetWizard();
});
$('#btn_wiz_abort').off().on('click', resetWizard);
}
async function discover_cololights() {
const res = await requestLedDeviceDiscovery('cololight');
if (res && !res.error) {
const r = res.info;
// Process devices returned by discovery
for (const device of r.devices) {
if (device.ip !== "") {
if (getIpInLights(device.ip).length === 0) {
var light = {};
light.ip = device.ip;
light.host = device.hostname;
light.name = device.name;
light.type = device.type;
lights.push(light);
}
}
}
assign_cololight_lights();
}
}
function assign_cololight_lights() {
// If records are left for configuration
if (Object.keys(lights).length > 0) {
$('#wh_topcontainer').toggle(false);
$('#colo_ids_t, #btn_wiz_save').toggle(true);
$('.lidsb').html("");
var options = "";
for (var lightid in lights) {
lights[lightid].id = lightid;
var lightHostname = lights[lightid].host;
var lightIP = lights[lightid].ip;
var val = lightHostname + " (" + lightIP + ")";
options += '<option value="' + lightid + '">' + val + '</option>';
}
var enabled = 'enabled';
$('.lidsb').append(createTableRow(['<select id="colo_select_id" ' + enabled + ' class="colo_sel_watch form-control">'
+ options
+ '</select>', '<button id="wiz_identify_btn" class="btn btn-sm btn-primary">'
+ $.i18n('wiz_identify') + '</button>']));
$('.colo_sel_watch').bind("change", function () {
selectedLightId = $('#colo_select_id').val();
var lightIP = lights[selectedLightId].ip;
$('#wiz_identify_btn').unbind().bind('click', function (event) { identify_cololight_device(lightIP); });
if (!lights[selectedLightId].props) {
getProperties_cololight(lightIP);
}
});
$('.colo_sel_watch').trigger('change');
}
else {
var noLightsTxt = '<p style="font-weight:bold;color:red;">' + $.i18n('wiz_noLights','Cololights') + '</p>';
$('#wizp2_body').append(noLightsTxt);
}
}
async function getProperties_cololight(ip) {
let params = { host: ip };
const res = await requestLedDeviceProperties('cololight', params);
if (res && !res.error) {
var coloLightProperties = res.info;
//Store properties along light with given IP-address
var id = getIpInLights(ip)[0].id;
lights[id].props = coloLightProperties;
}
}
function identify_cololight_device(hostAddress) {
let params = { host: hostAddress };
requestLedDeviceIdentification("cololight", params);
}
//****************************
// Wizard/Routines RS232-Devices
//****************************
async function discover_providerRs232(rs232Type) {
const res = await requestLedDeviceDiscovery(rs232Type);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process serialPorts returned by discover
console.log(r);
}
}
//****************************
// Wizard/Routines HID (USB)-Devices
//****************************
async function discover_providerHid(hidType) {
const res = await requestLedDeviceDiscovery(hidType);
// TODO: error case unhandled
// res can be: false (timeout) or res.error (not found)
if (res && !res.error) {
const r = res.info
// Process HID returned by discover
console.log(r);
if (!window.readOnlyMode) {
$('#btn_wiz_save').attr('disabled', false);
}
}