Skip to content

Commit

Permalink
Adding options page
Browse files Browse the repository at this point in the history
  • Loading branch information
alandtse committed Jul 28, 2018
1 parent a547a11 commit d0e0fc7
Show file tree
Hide file tree
Showing 6 changed files with 172 additions and 52 deletions.
5 changes: 2 additions & 3 deletions app/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"manifest_version": 2,
"default_locale": "en",
"icons": {
"16": "images/spdx.png",
"128": "images/spdx.png"
},
"background": {
Expand All @@ -17,13 +16,13 @@
},
"browser_action": {
"default_icon": {
"19": "images/spdx.png",
"38": "images/spdx.png"
"32": "images/spdx.png"
}
},
"options_page": "pages/options.html",
"options_ui": {
"page": "pages/options.html",
"open_in_tab": false,
"chrome_style": true
},
"content_scripts": [
Expand Down
56 changes: 49 additions & 7 deletions app/pages/options.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,58 @@
<html>
<head>
<meta charset="utf-8" />
<title>Options</title>
<title>spdx-diff Options</title>
<link rel="stylesheet" type="text/css" href="../styles/options.css">
</head>
<body>

<label>
<input type="checkbox" name="examplOption" checked>
Example Option
</label>

<form id="options">
<fieldset>
<h2>SPDX License List Options</h2>
<div>
<label for="updateFrequency">Check for list update interval</label>
<input id="updateFrequency" type="number" name="updateFrequency" step="1" min="1" max ="365" value="90"
title="Number of days before trying to update the SPDX license list from https://spdx.org. (1 is daily)" required>
<span class="validity"></span>
</div>
<div>
<div id="updatestatus"></div>
<button id="update">Manual Update</button>
</div>
</fieldset>
<fieldset>
<h2>Display Result Options</h2>
<div>
<label for="maxComparisons">Max results</label>
<input id="maxComparisons" type="number" name="maxComparisons" step="1" min="0" value="10"
title="Number of results to show. These must exceed which exceed minimum match percentage (0 is unlimited)" required>
<span class="validity"></span>
</div>
<div>
<label for="minpercentage">Minimum match percentage</label>
<input id="minpercentage" type="number" name="minpercentage" step="0.1" min="0" max="100" value="25"
title="Minimum percentage matches to display" required>
<span class="validity"></span>
</div>
</fieldset>
<fieldset>
<h2>Advanced Options</h2>
<div>
<label for="maxDifference">Maximum length difference</label>
<input id="maxDifference" type="number" name="maxDifference" step="100" min="0" max="100000" value="1000"
title="Maximum difference in length to attempt comparison (0 is unlimited; higher will be slower but more accurate)" required>
<span class="validity"></span>
</div>
<div>
<label for="maxWorkers">Max threads</label>
<input id="maxWorkers" type="number" name="maxWorkers" step="1" min="1" max="20" value="10"
title="Maximum number of worker threads to allow (higher is generally better but dependent on hardware)" required>
<span class="validity"></span>
</div>
</fieldset>
</form>
<div id="status"></div>
<button id="reset">Reset</button>
<button id="save">Save</button>
<script src="../scripts/options.js"></script>
</body>
</html>
92 changes: 55 additions & 37 deletions app/scripts/contentscript.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,28 @@ if(process.env.NODE_ENV === 'development'){

var selectedLicense = "";
var spdx = null;
var showBest = 10;
//var showBest = 10;
var selection = "";
var lastselection = "";
var maxDifference=500;
var processTime = 0;
var list = {};
var lastupdate = null;
var updating = false;
var pendingcompare = false;
var ms_start;
var maxworkers = 10;
//var maxworkers = 10;
var runningworkers = 0;
var workers = [];
var workqueue = [];
var unsorted = {};
var minpercentage = 25.0;
//var minpercentage = 25.0;
var diffsdone = 0;
var diffdisplayed = false;
var options;

restore_options();
createBubble();
loadList();


function workeronmessage(event) {
var progressbar = $('#progress_bubble')[0];
Expand Down Expand Up @@ -123,7 +124,7 @@ function workeronmessage(event) {
workers[event.data.id][1] = false
runningworkers--
var arr = event.data.result;
if (typeof list === "undefined")
if (typeof list["license"] === "undefined")
list["license"] = {};
for (var i=0; i < arr.length; i++){
list["license"][arr[i]["licenseId"]] = arr[i]
Expand Down Expand Up @@ -153,7 +154,7 @@ function workeronmessage(event) {
var ms_end = (new Date()).getTime();
processTime = ms_end - ms_start;
console.log("processTime: " + processTime/1000 + ("s"));
processLicenses(showBest, processTime)
processLicenses(options.showBest, processTime)
break;
case "diffnext":
workers[event.data.id][1] = false
Expand Down Expand Up @@ -190,7 +191,7 @@ chrome.runtime.onMessage.addListener(
var posX = selectCoords[0], posY = selectCoords[1];
renderBubble(posX, posY, selection);
if (spdx && getSelectionText() == lastselection){ //diff previously done on selection
processLicenses(showBest, processTime);
processLicenses(options.showBest, processTime);
return;
} else {
lastselection = selection;
Expand All @@ -213,6 +214,11 @@ chrome.runtime.onMessage.addListener(
}
);

chrome.storage.onChanged.addListener(function(changes, area) {
if (area == "sync" && "options" in changes) {
restore_options();
}
});
// Add bubble to the top of the page.
function createBubble(){
if ($('#license_bubble').length) return;
Expand Down Expand Up @@ -290,7 +296,7 @@ function addSelectFormFromArray(id, arr, number=arr.length, minimum=0) {
}
}
function processLicenses(showBest, processTime=0){
if (spdx && (spdx.length == 0 || spdx[0][3] <= minpercentage)){
if (spdx && (spdx.length == 0 || spdx[0][3] <= options.minpercentage)){
console.log("No results to display");
displayDiff(null, processTime);
return
Expand All @@ -303,15 +309,15 @@ function processLicenses(showBest, processTime=0){
if (i == 0) {
selectedLicense = license;
console.log("Best match of " + showBest + " : " + license + ": " + distance + " (" + percentage+ "%)");
} else if (percentage <= minpercentage) {
} else if (percentage <= options.minpercentage) {
console.log(license+ ": " + distance + " (" + percentage+ "%)");
break;
} else {
console.log(license+ ": " + distance + " (" + percentage+ "%)");
}
dowork({'command':"generateDiff", 'selection': selection, 'spdxid':license,'license':data, 'record':i});
}
addSelectFormFromArray("licenses", spdx, showBest, minpercentage)
addSelectFormFromArray("licenses", spdx, options.showBest, options.minpercentage)
}

function displayDiff(html, time=processTime){
Expand All @@ -335,27 +341,27 @@ function displayDiff(html, time=processTime){
}, false);
}
function spawnworkers(){
if (workers.length == maxworkers)
if (workers.length == options.maxworkers)
return
console.log("Spawning %s workers", maxworkers)
for (var i = 0; i < maxworkers; i++){
console.log("Spawning %s workers", options.maxworkers)
for (var i = 0; i < options.maxworkers; i++){
var worker = new Worker(chrome.runtime.getURL('scripts/worker.js'));
worker.onmessage = workeronmessage;
workers[i]= [worker , false];
}
}
//queue and start work
function processqueue(){
while (workqueue.length && maxworkers > runningworkers){
while (workqueue.length && options.maxworkers > runningworkers){
var work = workqueue.shift();
dowork(work)
}
}
function dowork(message){
spawnworkers()
var offset = maxworkers - runningworkers
if (maxworkers > runningworkers ){
for (var i = runningworkers % maxworkers; i < maxworkers + offset - 1; i = (i + 1) % maxworkers){
var offset = options.maxworkers - runningworkers
if (options.maxworkers > runningworkers ){
for (var i = runningworkers % options.maxworkers; i < options.maxworkers + offset - 1; i = (i + 1) % options.maxworkers){
if (!workers[i][1]) {// worker is available
message["id"] = i;
var worker = workers[i][0]
Expand Down Expand Up @@ -387,24 +393,29 @@ function loadList(){
chrome.storage.local.get(['list'], function(result) {
if (result.list && result.list["licenseListVersion"]){
list = result.list;
console.log('Loading License list version %s from storage with %s licenses last updated %s',
list["licenseListVersion"], list.licenses.length, Date(list["lastupdate"]));
lastupdate = list["lastupdate"]
for (var j = 0; j < list.licenses.length; j++) {
var line = list.licenses[j];
var license = line["licenseId"];
list["license"] = {}
console.log('Attempting to load %s from storage', license);
chrome.storage.local.get([license], function(result) {
if (result){
license = Object.keys(result)[0]
console.log('%s succesfully loaded from storage', license);
list.license[license] = result[license];
}else {
console.log('%s not found in storage; requesting update', license);
updateList()
}
});
console.log('Loading License list version %s from storage with %s licenses last updated %s',
list["licenseListVersion"], list.licenses.length, Date(lastupdate));
if ((Date.now() - lastupdate) >= (options.updateFrequency * 86400000)){
console.log('Last update was over %s days ago; update required', options.updateFrequency);
updateList()
}else{
for (var j = 0; j < list.licenses.length; j++) {
var line = list.licenses[j];
var license = line["licenseId"];
list["license"] = {}
console.log('Attempting to load %s from storage', license);
chrome.storage.local.get([license], function(result) {
if (result){
license = Object.keys(result)[0]
console.log('%s succesfully loaded from storage', license);
list.license[license] = result[license];
}else {
console.log('%s not found in storage; requesting update', license);
updateList()
}
});
}
}
}else {
console.log('No license list found in storage; requesting update');
Expand All @@ -416,7 +427,7 @@ function updateList(){
if (updating){
console.log("Ignoring redundant update request")
return
}else{
}else {
updating = true;
dowork({ 'command':"updatelicenselist"});
}
Expand All @@ -425,9 +436,16 @@ function compareSelection(selection){
var progressbar = $('#progress_bubble')[0];
progressbar.setAttribute('max',Object.keys(list["license"]).length);
for (var license in list["license"]){
dowork({'command':"compare", 'selection': selection, 'spdxid':license,'license':list["license"][license]});
dowork({'command':"compare", 'selection': selection, 'maxLengthDifference':options.maxLengthDifference, 'spdxid':license,'license':list["license"][license]});
}
}
function restore_options() {
chrome.storage.sync.get(['options'], function(result) {
options = result.options;
//if (typeof list === "undefined" || _.isEmpty(list))
loadList();
});
}
//https://stackoverflow.com/questions/2031518/javascript-selection-range-coordinates
function selectRangeCoords(){
var node = window.getSelection();
Expand Down
49 changes: 47 additions & 2 deletions app/scripts/options.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,49 @@
"use strict";
// Enable chromereload by uncommenting this line:
// import 'chromereload/devonly'
if(process.env.NODE_ENV === 'development'){
require('chromereload/devonly')
}

console.log(`'Allo 'Allo! Options`)
// Saves options to chrome.storage
function save_options() {
var updateFrequency = document.getElementById('updateFrequency').value;
var showBest = document.getElementById('maxComparisons').value;
var minpercentage = document.getElementById('minpercentage').value;
var maxLengthDifference = document.getElementById('maxDifference').value;
var maxworkers = document.getElementById('maxWorkers').value;

var options = {
updateFrequency: updateFrequency,
showBest: showBest,
minpercentage: minpercentage,
maxLengthDifference: maxLengthDifference,
maxworkers: maxworkers
};
chrome.storage.sync.set({options:options}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(function() {
status.textContent = '';
}, 750);
});
}

// Restores values using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get(['options'], function(result) {
document.getElementById('updateFrequency').value = result.options.updateFrequency;
document.getElementById('maxComparisons').value = result.options.showBest;
document.getElementById('minpercentage').value = result.options.minpercentage;
document.getElementById('maxDifference').value = result.options.maxLengthDifference;
document.getElementById('maxWorkers').value = result.options.maxworkers;
});
}
function reset() {
var form = document.getElementById('options');
form.reset();
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('reset').addEventListener('click',reset);
document.getElementById('save').addEventListener('click',save_options);
7 changes: 4 additions & 3 deletions app/scripts/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ self.onmessage = function(event) {
case "compare":
var spdxid = event.data.spdxid
var license = event.data.license
comparelicense(event.data["selection"], spdxid, license);
var maxLengthDifference = event.data.maxLengthDifference
comparelicense(event.data["selection"], spdxid, license, maxLengthDifference);
break;
case "sortlicenses":
sortlicenses(event.data.licenses);
Expand Down Expand Up @@ -119,7 +120,7 @@ function processSPDXlist(files, remote=true) {
);
};

function comparelicense(selection, spdxid, license) {
function comparelicense(selection, spdxid, license, maxLengthDifference=1000) {
postMessage({"command": "progressbarmax","value": 0, "stage":"Comparing licenses","id":id});
var result = {}
var count2 = selection.length;
Expand All @@ -134,7 +135,7 @@ function comparelicense(selection, spdxid, license) {
var locdiff = Math.abs(loc2 - loc);
var maxLength = Math.max(count, count2);
var lcs = "";//longestCommonSubstring(cleanText(data), cleanText(selection));
if (difference <= maxLength && difference < 1000) {
if (difference <= maxLength && difference < maxLengthDifference) {
var distance = Levenshtein.get(cleanText(data), cleanText(selection));
var percentage = ((maxLength - distance) / maxLength * 100).toFixed(1);
console.log(id, spdxid + " - Levenshtein Distance (clean): " + distance + " (" + percentage + "%)" + " Length Difference: " + difference + " LOC Diff:" + locdiff);
Expand Down
15 changes: 15 additions & 0 deletions app/styles/options.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
div {
margin-bottom: 10px;
}

input:invalid+span:after {
color: red;
content: '';
padding-left: 5px;
}

input:valid+span:after {
color: green;
content: '';
padding-left: 5px;
}

0 comments on commit d0e0fc7

Please sign in to comment.