How to use elem method in wpt

Best JavaScript code snippet using wpt

design_abstract.js

Source:design_abstract.js Github

copy

Full Screen

1String.prototype.replaceAll = function(find, replace) {2 var str = this;3 return str.replace(new RegExp(find, 'g'), replace);4};5if ( typeof (String.prototype.trim) === "undefined") {6 String.prototype.trim = function() {7 return String(this).replace(/^\s+|\s+$/g, '');8 };9}10function isiPhonePad() {11 return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) || (navigator.userAgent.match(/iPad/i) != null)12 );13}14function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}15function hexToV(h) {16 var r= parseInt((cutHex(h)).substring(0,2),16)17 var g= parseInt((cutHex(h)).substring(2,4),16)18 var b= parseInt((cutHex(h)).substring(4,6),16)19 return (r+g+b)/3.020}21function setupCanvas() {22 var design = $('#canvas').data("design");23 var images = $('#canvas').data("images");24 $('#canvas').data("sendLayoutToServerTimes", [])25 design.region_proposals = false;26 if ($('#canvas').data("stage") != undefined)27 $('#canvas').data("stage").destroy();28 if ($('#canvas').data("latencyTimes") == undefined)29 $('#canvas').data("latencyTimes",[]);30 $('#canvas').hide(); 31 $('#canvas').data("mousePos", 0)32 $('#canvas').data("dragging", false)33 $('#canvas').data("lastDist", 1);34 $('#canvas').data("show_lock_icons", true);35 $('#canvas').data("show_fixed_opacity", false);36 $('#canvas').data("align_lines", [])37 $('#canvas').data("energy", 9999)38 $('#canvas').data("energy_lists", {})39 $('#canvas').data("plot_energy_list", [])40 $('#canvas').data("layout_stack", [])41 $('#canvas').data("layout_stack_idx", -1)42 43 $('#canvas').data("user_layout_stack", [])44 $('#canvas').data("user_layout_stack_idx", -1)45 if ($('#canvas').data("user_input_log")==undefined)46 $('#canvas').data("user_input_log", [])47 48 if ($('#canvas').data("status_log")==undefined)49 $('#canvas').data("status_log", ['Setup'])50 51 52 if ($('#canvas').data("layout_log")==undefined)53 $('#canvas').data("layout_log", [])54 //$('#canvas').data("paused", false)55 $('#canvas').data('killed', false)56 $('#canvas').data("overlap_mode", false)57 $('#canvas').data("region_mode", false)58 $('#canvas').data("text_mode", false)59 60 $('#canvas').data("suggestion", [])61 $('#canvas').data("previous_suggestions", [])62 if (!("saved_layouts" in design))63 design.saved_layouts = []64 if (!("overlap_regions" in design))65 design.overlap_regions = []66 if (!("regions" in design))67 design.regions = []68 69 if (!("element_alts" in design))70 design.element_alts = {}71 72 if (!("rules" in design)) 73 design.rules=[]74 75 if (!("directory" in design)) 76 design.directory=''77 78 79 $('#design_width').val(design.width)80 $('#design_height').val(design.height)81 var stage = new Kinetic.Stage({82 container : 'canvas',83 width : design.width,84 height : design.height85 });86 var layer = new Kinetic.Layer({87 id : 'layer',88 });89 stage.add(layer);90 91 $('#canvas').data("mousedown",false)92 $(document).mousedown(function(evt){$('#canvas').data("mousedown",true)})93 $(document).mouseup( function(evt){94 //console.log("stage mouseup")95 $('#canvas').data("mousedown",false)96 $('#canvas').data("select_rect").hide()97 $('#canvas').data("select_rect").getLayer().draw()98 $('#canvas').data("select_start", false) 99 })100 var previewRect = new Kinetic.Rect({101 x : 0,102 y : 0,103 width : design.width,104 height : design.height,105 name : 'preview',106 fillPatternImage : images.background107 });108 layer.add(previewRect);109 previewRect.hide();110 $('#canvas').data("preview_image", previewRect);111 $('#canvas').data("preview", -1);112 var col = design.background_color113 if ((col != undefined) && (col.indexOf('#') == -1))114 col = '#' + col;115 if (!("background_elem" in design))116 {117 back_elem = {}118 back_elem.id = '0';119 back_elem.type = "background";120 back_elem.text = '';121 back_elem.font = 'Garamond';122 back_elem.color = design.background_color;123 back_elem.group_id = 0;124 back_elem.importance = 0;125 back_elem.anchors = [];126 back_elem.loaded = false;127 back_elem.resizing = false;128 back_elem.selected = false;129 back_elem.bold = false;130 back_elem.italic = false;131 back_elem.shadow = false;132 back_elem.strokeEnabled = true;133 back_elem.strokeWidth = 2;134 back_elem.align = "center"135 back_elem.x = 0136 back_elem.y = 0137 back_elem.fname=design.background_fname 138 139 140 back_elem.offset_x=0141 back_elem.offset_y=0142 design.background_elem=back_elem143 }144 else145 {146 $('#background_offset_x').val(design.background_elem.offset_x)147 $('#background_offset_y').val(design.background_elem.offset_y)148 }149 var backgroundRect = new Kinetic.Rect({150 x : 0,151 y : 0,152 width : design.width,153 height : design.height,154 fill : col,155 name : 'background',156 stroke : 'Black',157 strokeWidth : 4,158 strokeEnabled: true,159 fillPatternImage : images.background160 //fillPatternOffset: {x:design.background_elem.offset_x, y:design.background_elem.offset_y}161 });162 layer.add(backgroundRect);163 backgroundRect.moveToBottom()164 design.background = backgroundRect;165 console.log('design.background_color:'+design.background_color)166 console.log('design.background_fname:'+design.background_fname)167 168 169 design.background_elem.img = backgroundRect170 171 setupSelectRectangle(design,layer)172 173 $('#canvas').data("selected", design.background_elem)174 setupElementCallbacks(backgroundRect, design.background_elem);175 var sugg_stage = new Kinetic.Stage({176 container : 'suggestion_canvas',177 width : design.width,178 height : design.height179 });180 var sugg_layer = new Kinetic.Layer({181 id : 'sugg_layer',182 });183 var backgroundRect2 = new Kinetic.Rect({184 x : 0,185 y : 0,186 width : design.width,187 height : design.height,188 fill : col,189 fillPatternImage : images.background190 });191 sugg_layer.add(backgroundRect2);192 design.sugg_background = backgroundRect2;193 //console.log("background color: "+design.background_color)194 sugg_stage.add(sugg_layer);195 var overlap_layer = new Kinetic.Layer();196 stage.add(overlap_layer);197 $('#canvas').data("overlap_layer", overlap_layer);198 var region_layer = new Kinetic.Layer();199 stage.add(region_layer);200 $('#canvas').data("region_layer", region_layer);201 $('#canvas').data("stage", stage);202 $('#canvas').data("sugg_stage", sugg_stage);203 console.log("stage:" + stage)204 var max_group_id = 0;205 var max_id = 0;206 $.each(design.elements, function(i, elem) {207 if ("group_id" in elem)208 max_group_id = Math.max(max_group_id, elem.group_id);209 if (("id" in elem))210 max_id = Math.max(max_id, elem.id)211 });212 $('#canvas').data("images_rendering",0)213 $.each(design.elements, function(i, elem) {214 elem.loaded = false;215 elem.resizing = false;216 elem.fixed = false;217 elem.align_type = -1;218 elem.num_lines = 0;219 //elem.num_align=-1;220 elem.selected = false;221 elem.old_text = '';222 if ('orig_text' in elem)223 {224 elem.orig_text=elem.orig_text.trim()225 elem.text=elem.text.trim()226 }227 228 if (elem.color=='black')229 elem.color='000'230 elem.fixed_amount = 0.0;231 if ($('#canvas').data("init_fixed_amount")!=undefined)232 elem.fixed_amount =$('#canvas').data("init_fixed_amount");233 234 elem.hidden_img = 0;235 elem.hidden = false;236 delete elem["img"];237 delete elem["sugg_img"];238 if (!("group_id" in elem)) {239 max_group_id = max_group_id + 1;240 elem.group_id = max_group_id;241 }242 if (!("id" in elem)) {243 max_id = max_id + 1;244 elem.id = max_id;245 }246 247 //if (!("constraints" in elem)) {248 elem.constraints = {'size':[],'alignment':[]}249 //}250 251 if (!("shadow" in elem)) { 252 elem.shadow =false253 }254 if (!("allow_overlap" in elem))255 elem.allow_overlap = false;256 if (!("fix_alignment" in elem))257 elem.fix_alignment = false;258 if (!("fix_alternate" in elem))259 elem.fix_alternate = false;260 if (!("optional" in elem))261 elem.optional = false;262 if (elem.type == 'graphic')263 elem.type_id = 2;264 if (elem.type == 'text')265 elem.type_id = 1;266 if (elem.id in design.element_alts) {267 var alt_id = 0;268 $.each(design.element_alts[elem.id], function(i, e) {269 e.alternate_id = alt_id;270 alt_id += 1;271 });272 }273 274 if ($('#canvas').data("randomizeInit")) {275 276 $.each(design.elements, function(i, e) {277 var new_height = 0278 279 console.log("num lines:"+e.num_lines)280 if (e.type == 'graphic') {281 new_height = Math.round(Math.random()*100+50) 282 } else if (e.type == 'text') {283 284 if (e.num_lines==0)285 e.num_lines=e.text.split("\n").length286 new_height = Math.round((Math.random()*20+15) * Math.min(e.num_lines,3))287 }288 289 console.log("design height " + design.height + ", e height " + e.height)290 291 e.height = new_height292 e.width = e.height * e.aspect_ratio293 294 var new_x = Math.random() * (design.width - e.width)295 var new_y = Math.random() * (design.height - e.height)296 297 e.x = new_x298 e.y = new_y299 });300 301 }302 303 304 305 //if ($('#canvas').data("suggestionsEnabled"))306 setupLockingCallbacks(elem, layer)307 if ("fname" in elem) {308 elem.alternate_id = 0;309 setupImageElement(elem, images[elem.fname], layer, sugg_layer, false)310 var missing_or = true;311 $.each(design.overlap_regions, function(j, or) {312 if (or.elem_id == elem.id)313 missing_or = false;314 });315 if ((missing_or) && (!elem.allow_overlap)) {316 overlap = {}317 overlap.elem_id = elem.id318 overlap.x_min = 0319 overlap.y_min = 0320 overlap.x_max = 1321 overlap.y_max = 1322 design.overlap_regions.push(overlap)323 }324 } else if (elem.type == 'text') {325 if (elem.color == undefined)326 elem.color = '#000'327 if (elem.color.indexOf('#') == -1)328 elem.color = '#' + elem.color;329 elem.text = elem.text.trim()330 elem.sugg_align = elem.align;331 renderTextAlts(elem, false)332 }333 elem.last_x = elem.x;334 elem.last_y = elem.y;335 });336 window.addEventListener('keydown', keyPressed);337 layer.draw();338 sugg_layer.draw();339 //$('#suggestion_canvas').data("stage",sugg_stage);340 //setTimeout(sendDesign,500);341 //sendCurrentDesign();342 $.each(design.elements, function(i, elem) {343 var found_other = false;344 $.each(design.elements, function(j, elem2) {345 if ((i != j) && (elem.group_id == elem2.group_id))346 found_other = true;347 });348 if (!found_other)349 elem.group_id = -1;350 });351 setupStageCallbacks(stage);352 var curr_layout=getCurrentLayout()353 addLayoutToStack(curr_layout)354 $('#canvas').data("runs", {})355 if ($('#canvas').data("suggestionsEnabled")) {356 startSuggestions()357 }358 //design.elements.sort(function(e1,e2){return e1.importance-e2.importance})359 console.log("text to render: "+$('#canvas').data("images_rendering"))360 if ((design.saved_layouts.length>0) && ($('#canvas').data("sequence_index")==undefined))361 {362 var func = function(){363 renderSavedLayouts(design.saved_layouts,curr_layout)364 }365 executeAfterTextRendering(func)366 }367 else368 $('#canvas').show()369 370 allowUpdates()371 372 $('#canvas').data("started", !($('#canvas').data("automaticUpdate")))373}374function executeAfterTextRendering(func)375{376 var images_remaining = $('#canvas').data("images_rendering")377 if ((images_remaining != undefined) && (images_remaining==0))378 {379 console.log("executing function")380 func()381 }382 else383 {384 setTimeout(function (){385 executeAfterTextRendering(func) 386 },100)387 }388 389 390}391function renderSavedLayouts(layouts,curr_layout)392{393 394 //console.log("rendering saved layouts: "+layouts)395 396 if (layouts.length==0)397 {398 setCurrentLayout(curr_layout)399 $('#canvas').show()400 return401 402 }403 404 if (layouts[0]==null)405 {406 renderSavedLayouts(layouts.slice(1),curr_layout)407 return 408 }409 410 411 console.log("rendering saved layout: "+layouts[0])412 413 setCurrentLayout(layouts[0],true,true)414 415 $('#canvas').data("stage").toDataURL({416 callback : function(data_url) {417 var img = new Image();418 419 img.onload = function() {420 421 var sugg_id = Math.round(Math.random() * 100000) 422 addSavedLayout(img,data_url,layouts[0],sugg_id,false) 423 renderSavedLayouts(layouts.slice(1),curr_layout)424 425 }426 img.src=data_url427 }428 });429 430}431function setupSelectRectangle(design,layer)432{433 434 console.log("setupSelectRectangle\n, background col:"+design.background_color)435 436 $('#canvas').data("invert", false)437 var select_color = 'black'438 var select_opacity = 0.1439 440 var background_val;441 if (design.background_color!=undefined)442 background_val=hexToV(design.background_color)443 444 if ((design.background_fname.indexOf("black") > -1) || ((design.background_fname=='') && (background_val<50)))445 {446 console.log('inverting selector')447 $('#canvas').data("invert", true)448 $("#invert_select").prop("checked", true)449 select_color = 'white'450 select_opacity = 0.2451 }452 var select_rect = new Kinetic.Rect({453 x : 0,454 y : 0,455 width : 100,456 height : 100,457 fill : 'blue',458 stroke : select_color,459 opacity : select_opacity,460 strokeWidth : 1,461 visible : false462 });463 layer.add(select_rect);464 $('#canvas').data("select_rect", select_rect)465 $('#canvas').data("select_start", false)466 467 468 469}470function allowUpdates() {471 472 if (!$('#canvas').data("suggestionsEnabled"))473 return474 $('#canvas').data("started", true)475 $('#canvas').data("energy_lists", {})476 if ($('#canvas').data("layoutStartTime") == undefined)477 $('#canvas').data("layoutStartTime", new Date())478 479 $.each($('#canvas').data("runs"), function(i, run) {480 run.converged=false481 });482 483 $('#checkingImage').css("visibility",'visible');484 485 486 var sug_check=$('#canvas').data("suggestion_check");487 if ((sug_check==undefined) || (sug_check==-1))488 {489 console.log("adding checkForSuggestions"+$('#canvas').data("suggestion_check"))490 491 if ($('#canvas').data("automaticUpdate"))492 suggestion_check=setInterval(checkForSuggestions, 100);493 else494 suggestion_check=setInterval(checkForSuggestions, 200); 495 496 $('#canvas').data("suggestion_check",suggestion_check)497 }498}499function setupLockingCallbacks(elem, layer) {500 //console.log("background color:"+$('#canvas').data("design").background_color)501 //var filt=Kinetic.Filters.Invert;502 var filt = 0;503 //if ($('#canvas').data("invert"))504 // filt=Kinetic.Filters.Invert505 var images = $('#canvas').data("images");506 var size = 15507 if (!$('#canvas').data("suggestionsEnabled"))508 size =0.1509 510 if ($('#canvas').data("playback"))511 size = 15512 elem.unlock_img = new Kinetic.Image({513 x : elem.x + elem.width,514 y : elem.y,515 image : images['unlocked'],516 height : size,517 width : size,518 draggable : false,519 visible : false,520 filter : filt,521 opacity : 0.75522 });523 elem.tweakable_img = new Kinetic.Image({524 x : elem.x + elem.width,525 y : elem.y,526 image : images['tweakable'],527 height : size,528 width : size,529 draggable : false,530 visible : false,531 filter : filt,532 opacity : 0.75533 });534 elem.lock_img = new Kinetic.Image({535 x : elem.x + elem.width,536 y : elem.y,537 image : images['locked'],538 height : size,539 width : size,540 draggable : false,541 visible : false,542 filter : filt,543 opacity : 0.75544 });545 layer.add(elem.unlock_img)546 layer.add(elem.tweakable_img)547 layer.add(elem.lock_img)548 if (elem.fixed_amount<0.5)549 elem.state_img = elem.unlock_img;550 else if (elem.fixed_amount<1)551 elem.state_img = elem.tweakable_img;552 else553 elem.state_img = elem.lock_img;554 elem.unlock_img.on("click tap", function(evt) {555 556 var new_state='locked'557 //if ($('#canvas').data("automaticUpdate"))558 // new_state='tweakable'559 560 setElementState(elem.id, new_state)561 $('#canvas').data("user_input_log").push("St-"+String(elem.id)+"-"+new_state )562 $('#canvas').data("status_log").push("St-"+String(elem.id)+"-"+new_state )563 sendCurrentLayout('State Change')564 565 allowUpdates()566 567 });568 569 elem.tweakable_img.on("click tap", function(evt) {570 571 setElementState(elem.id, 'locked')572 $('#canvas').data("user_input_log").push("St-"+String(elem.id)+"-locked" )573 $('#canvas').data("status_log").push("St-"+String(elem.id)+"-locked" )574 sendCurrentLayout('State Change')575 576 allowUpdates()577 });578 elem.lock_img.on("click tap", function(evt) {579 580 setElementState(elem.id, 'unlocked')581 $('#canvas').data("user_input_log").push("St-"+String(elem.id)+"-unlocked" )582 $('#canvas').data("status_log").push("St-"+String(elem.id)+"-unlocked" )583 sendCurrentLayout('State Change')584 allowUpdates()585 });586}587function setElementState(elem_id, new_state,fix_amount) {588 $.each($('#canvas').data("design").elements, function(i, elem) {589 if (elem.id == elem_id) {590 var old_state_img = elem.state_img;591 elem.unlock_img.hide()592 elem.tweakable_img.hide()593 elem.lock_img.hide()594 if (new_state == 'unlocked') {595 elem.fix_alignment=false596 elem.state_img = elem.unlock_img597 elem.fixed_amount = 0598 }599 if (new_state == 'tweakable') {600 elem.state_img = elem.tweakable_img601 elem.fixed_amount = 0.5602 }603 if (new_state == 'locked') {604 elem.state_img = elem.lock_img605 elem.fixed_amount = 1606 }607 608 if (fix_amount !=undefined)609 elem.fixed_amount=fix_amount610 console.log("elem " + elem.id + " is " + new_state + " with fixed amount " + elem.fixed_amount)611 elem.state_img.setPosition(old_state_img.getPosition())612 elem.state_img.show()613 elem.state_img.getLayer().draw()614 }615 });616}617function changeElementStates(new_state) {618 $('#canvas').data("user_input_log").push("State-" + new_state)619 $('#canvas').data("status_log").push("State-" + new_state)620 $.each($('#canvas').data("design").elements, function(i, e) {621 if (e.selected) {622 setElementState(e.id, new_state)623 }624 });625 626 sendCurrentLayout('State Change')627 allowUpdates()628}629function designSizeChanged() {630 var design = $('#canvas').data("design")631 var new_width = parseInt($('#design_width').val())632 var new_height = parseInt($('#design_height').val())633 if ((new_width > 0) && (new_height > 0)) {634 console.log("designSizeChanged")635 deselectAll()636 retargetElements(new_height,new_width)637 638 design.width = new_width639 design.height = new_height640 641 $('#canvas').data("stage").setWidth(new_width)642 $('#canvas').data("stage").setHeight(new_height)643 644 645 design.background_elem.img.attrs.width=new_width646 design.background_elem.img.attrs.height=new_height647 648 $('#canvas').data("sugg_stage").attrs.width=new_width649 $('#canvas').data("sugg_stage").attrs.height=new_height650 651 design.sugg_background.attrs.width=new_width652 design.sugg_background.attrs.height=new_height653 654 $('#canvas').data("preview_image").attrs.width=new_width655 $('#canvas').data("preview_image").attrs.height=new_height656 657 design.background_elem.img.getLayer().draw()658 659 660 $.each(design.elements, function(i, elem) {661 setElementState(elem.id, 'unlocked',0.05)662 elem.state_img.hide()663 })664 665 $("#suggestion_layout0").hide()666 $("#suggestion_layout1").hide()667 $("#suggestion_layout2").hide()668 669 $('#suggestion_table').parent().css("height",new_height+30) 670 $('#gallery_table').parent().css("height",new_height+30)671 deleteGallery()672 673 674 if ($('#canvas').data("suggestionsEnabled")) 675 startSuggestions()676 677 allowUpdates()678 }679}680function retargetElements(new_height, new_width)681{682 var design = $('#canvas').data("design")683 var new_diag =Math.sqrt(new_height*new_height + new_width*new_width)684 var curr_diag=Math.sqrt(design.height*design.height + design.width*design.width )685 686 var scale = (new_diag/ curr_diag);687 688 $.each(design.elements, function(i, elem) {689 elem.aspect_ratio=elem.img.getWidth()/elem.img.getHeight()690 var width = elem.height * elem.aspect_ratio691 var mid_x = (elem.x + width / 2) / design.width;692 var mid_y = (elem.y + elem.height / 2) / design.height;693 elem.height = elem.height * scale694 elem.width = elem.height * elem.aspect_ratio695 elem.x = Math.max(0, mid_x * new_width - elem.width / 2);696 elem.y = Math.max(0, mid_y * new_height - elem.height / 2);697 698 //console.log("elem.text: "+elem.text)699 //console.log("element "+elem.id +" exceed by "+(elem.x+elem.width-design.width))700 //console.log("elem.x: "+elem.x)701 702 703 elem.x = elem.x - Math.max(0,(elem.x+elem.width)-new_width) 704 elem.y = elem.y - Math.max(0,(elem.y+elem.height)-new_height)705 706 elem.img.setPosition(elem.x, elem.y)707 708 });709 710}711function setupImageElement(elem, image, layer, sugg_layer, selected) {712 var design = $('#canvas').data("design");713 var scale = 1;714 while (Math.max(image.height * scale, image.height * scale) > Math.max(design.width, design.height) * 0.5) {715 scale = scale * 0.9;716 }717 if (!$('#canvas').data("hideContent")) {718 img = new Kinetic.Image({719 x : elem.x,720 y : elem.y,721 image : image,722 height : Math.round(image.height * scale),723 width : Math.round(image.width * scale),724 name : elem.id,725 strokeEnabled : false, //$('#canvas').data("hideContent"),726 stroke : 'Black',727 strokeWidth : 2,728 //lineJoin : 'round',729 //dashArray : [7, 5],730 name : elem.id,731 draggable : true732 });733 layer.add(img);734 img.moveToBottom()735 img.moveUp()736 elem.img = img;737 elem.aspect_ratio = image.width / image.height;738 elem.img.setHeight(elem.height);739 elem.img.setWidth(elem.height * elem.aspect_ratio);740 //console.log("setting up image with height "+elem.height)741 var img2 = img.clone();742 img2.attrs.strokeEnabled = false;743 sugg_layer.add(img2);744 elem.sugg_img = img2;745 setupElementCallbacks(img, elem);746 elem.anchors = createAnchors(elem, layer, selected)747 moveAnchors(elem)748 elem.loaded = true;749 } else {750 var text = new Kinetic.Text({751 x : 0,752 y : 0,753 text : '',754 fill : 'black',755 height : Math.round(image.height * scale),756 width : Math.round(image.width * scale),757 fontSize : 30,758 fontFamily : 'Calibri',759 align : 'center'760 });761 text.toImage({762 x : 0,763 y : 0,764 width : (text.getWidth()),765 height : (text.getHeight()),766 callback : function(text_img) {767 768 console.log("scale")769 console.log(scale)770 var add_background = function(pixels) {771 var d = pixels.data;772 for (var i = 0; i < d.length; i += 4) {773 //|| (i%(4*text_img.width)> 4*text_img.width-8 )774 //if ((i<2*text_img.width-50) || (i>d.length-2*text_img.width+50) || (i%(2*text_img.width-54)<4) || (i%(2*text_img.width-54)> 2*text_img.width -64 )775 //{776 // d[i] =0777 // d[i+1] =0778 // d[i+2] =0779 //}780 //else781 //{782 783 var alpha = (d[i + 3] / 255)784 785 d[i] += alpha * d[i] + (1 - alpha) * 135;786 d[i + 1] += alpha * d[i + 1] + (1 - alpha) * 206;787 d[i + 2] += alpha * d[i + 2] + (1 - alpha) * 235;788 //}789 d[i + 3] = 255;790 }791 return pixels;792 };793 img = new Kinetic.Image({794 x : elem.x,795 y : elem.y,796 image : text_img,797 height : Math.round(image.height * scale),798 width : Math.round(image.width * scale),799 name : elem.id,800 strokeEnabled : false,//$('#canvas').data("hideContent"),801 stroke : 'Black',802 strokeWidth : 2,803 //lineJoin : 'round',804 //dashArray : [7, 5],805 name : elem.id,806 draggable : true,807 filter : add_background808 });809 layer.add(img);810 elem.img = img;811 elem.aspect_ratio = image.width / image.height;812 elem.img.setHeight(elem.height);813 elem.img.setWidth(elem.height * elem.aspect_ratio);814 //console.log("setting up image with height "+elem.height)815 var img2 = img.clone();816 img2.attrs.strokeEnabled = false;817 sugg_layer.add(img2);818 elem.sugg_img = img2;819 setupElementCallbacks(img, elem);820 elem.anchors = createAnchors(elem, layer, selected)821 moveAnchors(elem)822 elem.loaded = true;823 }824 });825 }826}827function createAnchors(elem, layer, visible) {828 var anchors = {}829 anchors["topLeft"] = createScaleAnchor(0, 0, "topLeft", layer, elem, visible)830 anchors["topRight"] = createScaleAnchor(0, 0, "topRight", layer, elem, visible)831 anchors["bottomLeft"] = createScaleAnchor(0, 0, "bottomLeft", layer, elem, visible)832 anchors["bottomRight"] = createScaleAnchor(0, 0, "bottomRight", layer, elem, visible)833 834 //if ((elem.type == 'text') && ((elem.text.indexOf(" ") > -1) || (elem.text.indexOf("\n") > -1))) {835 // anchors["midRight"] = createAspectRatioAnchor(0, 0, "midRight", layer, elem, visible)836 // anchors["midLeft"] = createAspectRatioAnchor(0, 0, "midLeft", layer, elem, visible)837 //}838 //839 return anchors;840}841function createAspectRatioAnchor(x, y, name, layer, elem, selected) {842 var anchor = new Kinetic.Rect({843 x : x,844 y : y,845 width : 8,846 height : 8,847 fill : 'red',848 opacity : 1,849 name : name,850 draggable : true,851 visible : selected852 });853 anchor.rotate(150)854 layer.add(anchor);855 anchor.on('dragstart', function() {856 elem.anchor_pos = layer.getStage().getPointerPosition()857 $('#canvas').data("user_input_log").push("AR")858 $('#canvas').data("status_log").push("AR")859 console.log("ar dragstart")860 });861 anchor.on('dragmove', function() {862 $('#canvas').data("select_start", false)863 864 //console.log("ar dragmove")865 if ((elem.anchor_pos == 0) || (elem.fix_alternate))866 return;867 868 elem.resizing = true;869 //anchorImageUpdate(this,element);870 //console.log("layer "+anchor.getLayer())871 var alts = $('#canvas').data("design").element_alts[elem.id];872 var next_pos = layer.getStage().getPointerPosition()873 874 var pos_diff=elem.anchor_pos.x - next_pos.x875 //console.log("pos_diff:"+pos_diff)876 var flip = 1;877 if (name == 'midLeft')878 flip = -1;879 if (flip * (pos_diff) > 5) {880 console.log("checking")881 if ((elem.num_lines + 1) in alts) {882 console.log("setting "+(elem.num_lines + 1))883 selectAlternateElement(elem, elem.num_lines + 1)884 elem.anchor_pos = 0;885 }886 moveAnchors(elem)887 layer.draw();888 } else if (flip * (-1*pos_diff) > 5) {889 console.log("checking")890 891 if ((elem.num_lines - 1) in alts) {892 selectAlternateElement(elem, elem.num_lines - 1)893 elem.anchor_pos = 0;894 }895 moveAnchors(elem)896 layer.draw();897 }898 });899 anchor.on('dragend', function() {900 901 elem.resizing = false902 moveAnchors(elem)903 904 drawAlignmentLines(elem, 'dragging')905 layer.draw();906 });907 return anchor;908}909function createScaleAnchor(x, y, name, layer, element, selected) {910 var anchor = new Kinetic.Circle({911 x : x,912 y : y,913 fill : 'red',914 opacity : 1,915 radius : 6,916 name : name,917 draggable : true,918 visible : selected919 });920 layer.add(anchor);921 anchor.on('dragstart', function() {922 $('#canvas').data("user_input_log").push("S")923 $('#canvas').data("status_log").push("S")924 });925 anchor.on('dragmove', function() {926 console.log("dragmove scale")927 $('#canvas').data("select_start", false)928 929 930 element.resizing = true;931 //allowUpdates()932 var shift = anchorImageUpdate(this, element);933 934 935 if ((!$('#canvas').data("suggestionsEnabled")) ||(!$('#canvas').data("automaticUpdate")))936 {937 $.each($('#canvas').data("design").elements, function(i, e) {938 939 940 if (element.constraints['size'].indexOf(e.id)!=-1)941 {942 var new_height=shift.new_height;943 if (element.type=='text')944 new_height=(shift.new_height/Math.max(1,element.num_lines))*e.num_lines945 946 console.log("new height: "+new_height)947 e.x=e.img.getX()+shift.x_offset948 e.y=e.img.getY()+shift.y_offset949 950 console.log(e.x)951 952 e.img.setX(e.x)953 e.img.setY(e.y)954 955 956 e.img.setWidth(e.aspect_ratio*new_height)957 e.img.setHeight(new_height)958 959 e.width=e.img.getWidth()960 e.height=e.img.getHeight() 961 962 963 e.state_img.setPosition(e.x + e.width, e.y)964 }965 })966 }967 else968 $('#canvas').data("started",false)969 970 971 972 console.log("shift:")973 console.log(shift)974 drawAlignmentLines(element, name)975 //if ($("#infer_locking_select").prop("checked") && (element.fixed_amount == 0))976 // setElementState(element.id, 'tweakable')977 //978 layer.draw();979 });980 anchor.on('dragend', function() {981 982 $.each($('#canvas').data("design").elements, function(i, e) {983 if ((e != element)) {984 if ($("#infer_locking_select").prop("checked")) {985 var overlap = getOverlap(e.img, element.img)986 if ((overlap > 0.1) && (e.fixed_amount != 1)&& (!e.allow_overlap)&& (!element.allow_overlap)) {987 988 setElementState(e.id, 'unlocked')989 990 /*991 if (e.fix_alignment)992 {993 e.fix_alignment=false994 sendCurrentDesign()995 }996 */997 }998 }999 }1000 });1001 element.resizing = false1002 1003 sendCurrentLayout('Scale')1004 });1005 return anchor;1006}1007function anchorImageAspectRatioUpdate(anchor, elem) {1008 var anchor_pos = anchor.getAbsolutePosition()1009 //console.log("element "+ elem.id+" anchor "+ anchor.attrs.name+" has position: "+anchor_pos.x + " "+ anchor_pos.y )1010 var new_height = 1;1011 var new_width = 1;1012 if (anchor.attrs.name == "topLeft") {1013 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y1014 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x1015 }1016 if (anchor.attrs.name == "bottomLeft") {1017 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y1018 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x1019 }1020 if (anchor.attrs.name == "bottomRight") {1021 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y1022 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x1023 }1024 if (anchor.attrs.name == "topRight") {1025 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y1026 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x1027 }1028 var aspect_ratio = new_width / new_height;1029 var nearest_elem = elem;1030 var min_dist = 999;1031 $.each($('#canvas').data("design").element_alts[elem.id], function(i, e) {1032 var dist = Math.abs(aspect_ratio - e.aspect_ratio)1033 if (dist < min_dist) {1034 nearest_elem = e1035 min_dist = dist1036 }1037 });1038 if (elem != nearest_elem) {1039 setAlternate(elem, nearest_elem);1040 if (anchor.attrs.name.indexOf("Left") > -1) {1041 nearest_elem.img.setX(anchor_pos.x)1042 }1043 return true1044 }1045 /*1046 new_height=Math.max(new_height,10);1047 elem.img.setHeight(new_height)1048 elem.height=new_height1049 if ("aspect_ratio" in elem)1050 elem.img.setWidth(new_height*elem.aspect_ratio)1051 else1052 {1053 new_width=Math.max(new_width,10)1054 elem.img.setWidth(new_width)1055 elem.width=new_width1056 }1057 if ((anchor.attrs.name=="topLeft") || (anchor.attrs.name=="bottomLeft") )1058 {1059 var right_pos=elem.anchors["bottomRight"].getAbsolutePosition().x;1060 elem.img.setX(right_pos-elem.img.getWidth())1061 }1062 */1063 //moveAnchors(elem)1064}1065function setAlternate(elem, alt_elem) {1066 console.log("setAlternate for element " + elem.id)1067 var layer = $('#canvas').data("stage").get('#layer')[0];1068 var design = $('#canvas').data("design")1069 var scale = alt_elem.num_lines / elem.num_lines1070 console.log("setting alternate text :" + alt_elem.text)1071 console.log("orig element selected? " + elem.selected)1072 console.log("alternate id :" + alt_elem.alternate_id)1073 alt_elem.x = elem.x1074 alt_elem.y = elem.y1075 alt_elem.height = elem.height * scale1076 alt_elem.align_type = elem.align_type1077 alt_elem.align = elem.align1078 alt_elem.group_id = elem.group_id1079 alt_elem.importance = elem.importance1080 alt_elem.selected = elem.selected1081 alt_elem.fix_alignment = elem.fix_alignment1082 alt_elem.fixed_amount = elem.fixed_amount1083 //alt_elem.unlock_img=elem.unlock_img1084 //alt_elem.tweakable_img=elem.tweakable_img1085 //alt_elem.lock_img=elem.lock_img1086 alt_elem.optional = elem.optional1087 elem.img.remove()1088 elem.sugg_img.remove();1089 $.each(design.element_alts[elem.id], function(i, e) {1090 e.img.remove()1091 $.each(e.alignment_imgs, function(j, ai) {1092 ai.remove()1093 });1094 $.each(e.anchors, function(i, a) {1095 a.hide()1096 });1097 });1098 if (alt_elem.num_lines > 1) {1099 if (alt_elem.img != alt_elem.alignment_imgs[alt_elem.align]) {1100 alt_elem.img = alt_elem.alignment_imgs[alt_elem.align];1101 }1102 }1103 alt_elem.img.setPosition(elem.img.attrs.x, elem.img.attrs.y)1104 //alt_elem.img.attrs.strokeEnabled = elem.selected1105 alt_elem.img.setHeight(elem.img.getHeight() * scale)1106 alt_elem.img.setWidth(alt_elem.img.getHeight() * alt_elem.aspect_ratio)1107 alt_elem.img.setOpacity(1)1108 alt_elem.width=alt_elem.img.getWidth()1109 alt_elem.height=alt_elem.img.getHeight()1110 alt_elem.state_img = elem.state_img1111 alt_elem.state_img.setPosition(alt_elem.x + alt_elem.width, alt_elem.y)1112 layer.add(alt_elem.img)1113 alt_elem.img.show()1114 setHidden(alt_elem, elem.hidden)1115 1116 1117 $.each(alt_elem.anchors, function(i, a) {1118 //layer.add(a)1119 1120 a.moveToTop()1121 if (elem.selected)1122 a.show();1123 });1124 1125 moveAnchors(alt_elem)1126 layer.draw()1127 var idx = design.elements.indexOf(elem);1128 design.elements[idx] = alt_elem;1129 if ($('#canvas').data("selected") == elem) {1130 console.log("element was selected already")1131 $("#num_lines_select").val(alt_elem.num_lines).attr('selected', true);1132 $("#user_text").val(alt_elem.text);1133 $('#canvas').data("selected", alt_elem)1134 }1135 if (alt_elem.fixed_amount < 0.5)1136 setElementState(alt_elem.id, 'unlocked')1137 else if ((alt_elem.fixed_amount >0.1) && (alt_elem.fixed_amount <0.9))1138 setElementState(alt_elem.id, 'tweakable')1139 else1140 setElementState(alt_elem.id, 'locked')1141 1142 sendCurrentLayout('Aspect Ratio')1143}1144function anchorImageUpdate(anchor, elem) {1145 var anchor_pos = anchor.getAbsolutePosition()1146 //console.log("element "+ elem.id+" anchor "+ anchor.attrs.name+" has position: "+anchor_pos.x + " "+ anchor_pos.y )1147 var old_x=elem.x1148 var old_y=elem.y1149 var old_width=elem.width1150 console.log(anchor.attrs.name )1151 1152 1153 var new_height = 1;1154 var new_width = 1;1155 if (anchor.attrs.name == "topLeft") {1156 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y1157 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x1158 1159 }1160 if (anchor.attrs.name == "bottomLeft") {1161 1162 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y1163 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x1164 elem.img.setY(anchor_pos.y)1165 }1166 if (anchor.attrs.name == "bottomRight") {1167 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y1168 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x1169 elem.img.setY(anchor_pos.y)1170 }1171 if (anchor.attrs.name == "topRight") {1172 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y1173 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x1174 }1175 var right_pos = elem.anchors["bottomRight"].getAbsolutePosition().x;1176 new_height = Math.max(new_height, 10);1177 elem.img.setHeight(new_height)1178 elem.height = new_height1179 if ("aspect_ratio" in elem)1180 elem.img.setWidth(new_height * elem.aspect_ratio)1181 else {1182 new_width = Math.max(new_width, 10)1183 elem.img.setWidth(new_width)1184 elem.width = new_width1185 }1186 if ((anchor.attrs.name == "topLeft") || (anchor.attrs.name == "bottomLeft")) {1187 1188 elem.img.setX(right_pos - elem.img.getWidth())1189 }1190 elem.x = elem.img.attrs.x1191 elem.y = elem.img.attrs.y1192 elem.width = elem.img.getWidth()1193 elem.height = elem.img.getHeight()1194 elem.state_img.setPosition(elem.x + elem.width, elem.y)1195 moveAnchors(elem)1196 1197 var shift={}1198 shift.x_offset=elem.x-old_x1199 shift.y_offset=elem.y-old_y1200 shift.new_height=elem.height1201 1202 if (elem.type=='text')1203 $("#fontSizeInput").val((elem.height/elem.init_height)*elem.init_font_size)1204 1205 return shift1206}1207function keyPressed(evt) {1208 console.log("Key pressed: " + evt.keyCode)1209 var input_focused = $("*:focus").length > 0;1210 if (input_focused)1211 {1212 console.log("input focused")1213 return;1214 }1215 if (evt.keyCode == 49)1216 saveCurrentLayout()1217 if (evt.keyCode == 67) {1218 if ($('#canvas').data("overlap_mode")) {1219 $('#canvas').data("design").overlap_regions = [];1220 toggleOverlapMode();1221 toggleOverlapMode();1222 sendCurrentDesign();1223 }1224 }1225 if (evt.keyCode == 65 && evt.shiftKey)1226 selectAllElements()1227 if (evt.keyCode == 189 && evt.shiftKey)1228 scaleCurrentElement(0.9)1229 if (evt.keyCode == 187 && evt.shiftKey)1230 scaleCurrentElement(1.1)1231 //if ((evt.keyCode == 68) || (evt.keyCode == 46))1232 // deleteCurrentElement()1233 //if (evt.keyCode == 80)1234 // toggleOverlapMode()1235 //if (evt.keyCode == 82)1236 // toggleRegionMode()1237 /*1238 if (evt.keyCode == 32) {1239 switchPauseState();1240 evt.preventDefault();1241 }1242 if (evt.keyCode==70)1243 {1244 $.each($('#canvas').data("design").elements, function(i, elem){1245 if (elem.selected)1246 {1247 if (elem.fixed_amount<1)1248 elem.fixed_amount=11249 else1250 elem.fixed_amount=0.251251 //setStroke(elem.img,true, 1.5,elem.fixed_amount );1252 //elem.img.attrs.opacity=elem.fixed_amount1253 }1254 });1255 $('#canvas').data("design").elements[0].img.getLayer().draw();1256 sendCurrentLayout();1257 }1258 */1259}1260function toggleRegionMode() {1261 var stage = $('#canvas').data("stage");1262 var design = $('#canvas').data("design");1263 var region_layer = $('#canvas').data("region_layer");1264 var layer = stage.get('#layer')[0];1265 if ($('#canvas').data("region_mode")) {1266 //layer.show();1267 console.log("disabling region mode")1268 region_layer.removeChildren();1269 region_layer.draw()1270 $('#canvas').data("region_mode", false)1271 $('#region_controls').hide()1272 } else {1273 console.log("enabling region mode")1274 deselectAll(design.background_elem)1275 design.background_elem.img.getLayer().draw();1276 var backgroundRect = new Kinetic.Rect({1277 x : 0,1278 y : 0,1279 fill : 'black',1280 opacity : 0.25,1281 width : design.width,1282 height : design.height1283 });1284 region_layer.add(backgroundRect)1285 backgroundRect.moveToTop()1286 $.each(design.regions, function(i, reg) {1287 var fill_color = getRegionColor(reg)1288 var rect = new Kinetic.Rect({1289 x : reg.x,1290 y : reg.y,1291 fill : fill_color,1292 opacity : 0.25,1293 width : reg.width,1294 height : reg.height,1295 draggable : true,1296 stroke : 'Red',1297 strokeWidth : 2,1298 lineJoin : 'round',1299 dashArray : [7, 5],1300 strokeEnabled : false1301 });1302 reg.img = rect1303 region_layer.add(rect)1304 reg.anchors = createAnchors(reg, region_layer, false)1305 moveAnchors(reg)1306 setupElementCallbacks(rect, reg)1307 });1308 region_layer.draw()1309 $('#canvas').data("region_mode", true)1310 $('#region_controls').show()1311 hideBackgroundControls()1312 $('#element_controls').hide()1313 }1314}1315function getRegionColor(reg) {1316 if (reg.allow_text && (!reg.allow_graphic))1317 return '#5F5'1318 else if (reg.allow_graphic && (!reg.allow_text))1319 return '#55F'1320 else if (reg.allow_graphic && (reg.allow_text))1321 return '#5FF'1322 else1323 return 'white'1324}1325function toggleOverlapMode() {1326 var stage = $('#canvas').data("stage");1327 var design = $('#canvas').data("design");1328 var overlap_layer = $('#canvas').data("overlap_layer");1329 var layer = stage.get('#layer')[0];1330 if ($('#canvas').data("overlap_mode")) {1331 //layer.show();1332 console.log("disabling overlap mode")1333 overlap_layer.removeChildren();1334 overlap_layer.draw()1335 $('#canvas').data("overlap_mode", false)1336 } else {1337 //layer.hide();1338 console.log("enabling overlap mode")1339 var backgroundRect = new Kinetic.Rect({1340 x : 0,1341 y : 0,1342 fill : 'black',1343 opacity : 0.25,1344 width : design.width,1345 height : design.height1346 });1347 overlap_layer.add(backgroundRect)1348 backgroundRect.moveToTop()1349 //var elem_list=design.elements1350 //elem_list.push(design.back_elem)1351 $.each(design.elements, function(i, elem) {1352 var x = elem.x1353 var y = elem.y1354 var w = elem.img.getWidth()1355 var h = elem.img.getHeight()1356 var draw_overlap = false;1357 if (elem.type == 'text')1358 draw_overlap = true1359 else1360 $.each(design.overlap_regions, function(i, or) {1361 if (or.elem_id == elem.id) {1362 draw_overlap = true;1363 x = x + w * or.x_min;1364 y = y + h * or.y_min;1365 w = w * (or.x_max - or.x_min);1366 h = h * (or.y_max - or.y_min);1367 }1368 });1369 if (draw_overlap) {1370 var rect = new Kinetic.Rect({1371 x : x,1372 y : y,1373 fill : 'white',1374 opacity : 0.25,1375 width : w,1376 height : h1377 });1378 overlap_layer.add(rect)1379 }1380 });1381 for (var i = 0; i < design.overlap_regions.length; i++) {1382 var or = design.overlap_regions[i]1383 console.log("or.elem_id " + or.elem_id)1384 if (or.elem_id == 0) {1385 var rect = new Kinetic.Rect({1386 x : or.x_min * design.width,1387 y : or.y_min * design.height,1388 fill : 'white',1389 opacity : 0.25,1390 width : design.width * (or.x_max - or.x_min),1391 height : design.height * (or.y_max - or.y_min)1392 });1393 overlap_layer.add(rect)1394 console.log("adding rectangle " + rect.attrs.x + " " + rect.attrs.y + " ")1395 }1396 }1397 overlap_layer.draw()1398 overlap_layer.on("mousedown", function(evt) {1399 console.log("mouse down")1400 var mousePos = stage.getPointerPosition();1401 var overlapRect = new Kinetic.Rect({1402 x : mousePos.x,1403 y : mousePos.y,1404 fill : 'white',1405 opacity : 0.25,1406 width : 0,1407 height : 0,1408 id : "current_overlap"1409 });1410 overlap_layer.add(overlapRect)1411 overlap_layer.draw()1412 $('#canvas').data("mousePos", mousePos)1413 console.log("down")1414 console.log($('#canvas').data("mousePos"))1415 });1416 overlap_layer.on("mousemove", function() {1417 var mousePos0 = $('#canvas').data("mousePos")1418 if (mousePos0 == 0)1419 return;1420 var mousePos = stage.getPointerPosition();1421 var overlapRect = stage.get('#current_overlap')[0];1422 //if (overlapRect!=undefined)1423 //{1424 if (mousePos.y < mousePos0.y)1425 overlapRect.setY(mousePos.y)1426 if (mousePos.x < mousePos0.x)1427 overlapRect.setX(mousePos.x)1428 overlapRect.setHeight(Math.abs(mousePos.y - mousePos0.y))1429 overlapRect.setWidth(Math.abs(mousePos.x - mousePos0.x))1430 //console.log(overlapRect.getWidth()+" "+overlapRect.getHeight())1431 //overlap_layer.draw()1432 //}1433 });1434 overlap_layer.on("mouseup", function() {1435 console.log("mouse up (overlap)")1436 if (($('#canvas').data("mousePos") == 0))1437 return;1438 $('#canvas').data("mousePos", 0)1439 console.log($('#canvas').data("mousePos"))1440 var overlapRect = stage.get('#current_overlap')[0];1441 //var elem=findElement(overlapRect.attrs.x,overlapRect.attrs.y,overlapRect.getWidth(),overlapRect.getHeight())1442 var elem = design.background_elem;1443 overlap = {}1444 overlap.elem_id = elem.id1445 console.log("Creating new OR with elem id " + elem.id)1446 overlap.x_min = (overlapRect.attrs.x - elem.x) / elem.img.getWidth()1447 overlap.y_min = (overlapRect.attrs.y - elem.y) / elem.img.getHeight()1448 overlap.x_max = overlap.x_min + overlapRect.getWidth() / elem.img.getWidth()1449 overlap.y_max = overlap.y_min + overlapRect.getHeight() / elem.img.getHeight()1450 if ((overlap.x_max - overlap.x_min > 0.01) && (overlap.y_max - overlap.y_min > 0.01)) {1451 console.log("")1452 design.overlap_regions.push(overlap)1453 overlap_layer.draw()1454 sendCurrentDesign()1455 }1456 });1457 $('#canvas').data("overlap_mode", true)1458 }1459}1460function selectAllElements() {1461 console.log("select all")1462 var elements = $('#canvas').data("design").elements;1463 $.each(elements, function(i, e) {1464 e.img.attrs.strokeEnabled = false;//true;1465 $.each(e.anchors, function(i, a) {1466 a.hide();1467 });1468 e.selected = true;1469 });1470 elements[0].img.getLayer().draw();1471}1472/*1473function switchPauseState() {1474 if ($('#canvas').data("paused") == false)1475 pauseSuggestions()1476 else1477 resumeSuggestions()1478}1479function pauseSuggestions() {1480 //$('#pauseButton').text("Resume")1481 //$('#pauseButton').removeClass("btn-warning")1482 //$('#pauseButton').addClass("btn-success")1483 $('#pauseButton').hide()1484 $('#startButton').show()1485 $('#canvas').data("paused", true)1486}1487*/1488function resumeSuggestions() {1489 if (!$('#canvas').data("suggestionsEnabled"))1490 return1491 if ($('#canvas').data("design").elements.length <= 1) {1492 console.log("not enough elements to start suggestions")1493 //return1494 }1495 if (($('#suggestion_status').text() == "Inactive"))1496 startSuggestions()1497 $('#canvas').data("status_log").push("Resume")1498 sendCurrentLayout('Resume')1499 /*1500 $('#pauseButton').show()1501 $('#startButton').hide()1502 $('#canvas').data("paused", false)1503 */1504}1505function deleteCurrentElement() {1506 1507 $('#element_controls').hide()1508 document.body.style.cursor = "default";1509 $('#canvas').data("text_mode", false)1510 $('#canvas').data("user_input_log").push("Remove")1511 $('#canvas').data("status_log").push("Remove")1512 var layer = $('#canvas').data("stage").get('#layer')[0];1513 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];1514 var elements;1515 if ($('#canvas').data("region_mode"))1516 elements = $('#canvas').data("design").regions1517 else1518 elements = $('#canvas').data("design").elements1519 if ($('#canvas').data("selected").type == 'background')1520 return;1521 var rem = elements.indexOf($('#canvas').data("selected"));1522 console.log("removing element " + rem)1523 elements[rem].img.destroy();1524 if ("sugg_img" in elements[rem]) {1525 elements[rem].sugg_img.destroy();1526 }1527 console.log(elements)1528 $.each(elements[rem].anchors, function(i, a) {1529 a.destroy();1530 });1531 elements[rem].lock_img.destroy()1532 elements[rem].unlock_img.destroy()1533 elements[rem].tweakable_img.destroy()1534 $.each($('#canvas').data("align_lines"), function(i, al) {1535 al[0].destroy()1536 });1537 $('#canvas').data("align_lines", [])1538 elements.splice(rem, 1);1539 sendCurrentDesign();1540 sendCurrentLayout('Delete');1541 layer.draw()1542 sugg_layer.draw()1543 $('#canvas').data("selected", $('#canvas').data("design").background_elem)1544 1545 deleteGallery()1546}1547function scaleCurrentElement(scale_factor) {1548 var elem = $('#canvas').data("selected");1549 if ((elem != undefined) && (elem.type != "background")) {1550 var curr_height = elem.img.getHeight()1551 var new_height = Math.max(curr_height * scale_factor, 5);1552 elem.height = new_height;1553 elem.img.setHeight(new_height)1554 if (elem.type == 'region') {1555 elem.img.setWidth(elem.img.getWidth() * scale_factor)1556 elem.width = elem.img.getWidth();1557 } else1558 elem.img.setWidth(new_height * elem.aspect_ratio)1559 elem.width = elem.img.getWidth();1560 moveAnchors(elem)1561 elem.img.getLayer().draw()1562 }1563}1564/*1565 function setCurrentSuggestion(evt)1566 {1567 setCurrentLayout($('#suggestion_canvas').data("layout"))1568 elements[0].img.getLayer().draw();1569 }1570 */1571function copyCurrentDesign() {1572 var design = $('#canvas').data("design");1573 var design_copy = jQuery.extend(true, {}, design);1574 //$.each(design_copy, function (i, elem){1575 //});1576 return design_copy;1577}1578function addSavedLayout(img,data_url,curr_layout,sugg_id,save_to_server){1579 console.log("addSavedLayout")1580 1581 var new_layout_elem = $('#saved_layout0').clone()1582 new_layout_elem.data("preview_image", img);1583 new_layout_elem.data("layout", curr_layout);1584 new_layout_elem.data("time", new Date());1585 new_layout_elem.data("sugg_id", sugg_id);1586 new_layout_elem.attr("id", "saved_layout" + sugg_id)1587 new_layout_elem.mouseover(function() {1588 viewLayout('saved', sugg_id)1589 })1590 new_layout_elem.click(function() {1591 setFixedLayout('saved', sugg_id)1592 })1593 //new_layout_elem.dblclick(function() {setFixedLayout('saved',count)})1594 var stage = $('#canvas').data("stage");1595 var canvas = new_layout_elem[0];1596 var ctx = canvas.getContext("2d")1597 ctx.drawImage(img, 0, 0, stage.attrs.width / 3, stage.attrs.height / 3);1598 var remove_layout_elem = $('#remove_saved_layout0').clone()1599 remove_layout_elem.click(function() {1600 removeSavedLayout(sugg_id)1601 })1602 1603 1604 $('#saved_table').append($('<tr>').append($('<td>').append(new_layout_elem), $('<td>').append(remove_layout_elem)))1605 1606 1607 if (save_to_server)1608 {1609 var hit_id = gup('hitId')1610 var fname = 'layouts/' + $('#canvas').data("design").name + '-' + gup('workerId') + "-" + hit_id + "-" + String(sugg_id) + '.png'1611 saveImageOnServer(fname, data_url)1612 }1613 1614 1615 1616 var retarget=gup('retarget')1617 if (retarget!='')1618 {1619 var splt=retarget.split("_")1620 var new_width=parseInt(splt[0])1621 var new_height=parseInt(splt[1]) 1622 retargetElements(new_height,new_width) 1623 var retarget_layout =getCurrentLayout()1624 1625 setCurrentLayout(curr_layout)1626 1627 new_layout_elem.data("retarget_layout", retarget_layout);1628 1629 console.log("retarget_layout:"+retarget_layout)1630 }1631 1632 1633 1634 1635}1636function saveCurrentLayout() {1637 var stage = $('#canvas').data("stage");1638 var curr_layout = getCurrentLayout()1639 1640 1641 $('#saved_text').show()1642 $('#gallery_text').hide()1643 1644 $('#saved_lk').click()1645 $('#showGalleryButton').show()1646 1647 var num_saved = $('#saved_table').find("tr").length - 1;1648 var max_saved = 100;1649 if (gup("maxSaved") != undefined)1650 max_saved = parseInt(gup("maxSaved"))1651 if (num_saved >= max_saved) {1652 alert("You have reached the maximum number of saved layouts: " + max_saved + ". Remove other layouts before saving.")1653 return;1654 }1655 $('#canvas').data("user_input_log").push("Save")1656 $('#canvas').data("status_log").push("Save")1657 $.each($('#canvas').data("design").elements, function(i, e) {1658 e.state_img.show()1659 });1660 1661 1662 stage.toDataURL({1663 1664 callback: function(data_url2) {1665 1666 var sugg_id = Math.round(Math.random() * 100000)1667 1668 1669 console.log("rendering first time")1670 var fname='layouts/states/'+$('#canvas').data("design").name+'-'+gup('workerId')+"-"+gup('hitId')+"-"+String(sugg_id)1671 saveDesignOnServer(data_url2,'',fname)1672 1673 $.each($('#canvas').data("design").elements, function(i, e) {1674 e.img.attrs.strokeEnabled = false;1675 e.state_img.hide()1676 $.each(e.anchors, function(i, a) {1677 a.hide();1678 });1679 });1680 1681 $.each($('#canvas').data("align_lines"), function(i, al) {1682 al[0].hide()1683 }); 1684 1685 stage.toDataURL({1686 callback : function(data_url) {1687 var img = new Image();1688 1689 img.onload = function() {1690 1691 console.log("rendering second time")1692 //$('#canvas').data("saved_images").push(img);1693 //$('#canvas').data("saved_layouts").push(curr_layout);1694 //$('#canvas').data("saved_designs").push(copyCurrentDesign());1695 1696 //var count = $("#saved_table").children().children().length;1697 1698 //$("#saved_row").parent().css("padding",1)1699 1700 addSavedLayout(img,data_url,curr_layout,sugg_id,true)1701 1702 /*1703 for (var i=0;i < Math.min(saved_layouts.length,9);i++)1704 {1705 1706 $('#saved_layout'+i).data("preview_image",saved_images[i]);1707 $('#saved_layout'+i).data("layout",saved_layouts[i]);1708 var canvas=$('#saved_layout'+i)[0];1709 var ctx=canvas.getContext("2d")1710 ctx.drawImage(saved_images[i],0,0,stage.attrs.width/3,stage.attrs.height/3);1711 1712 }1713 */1714 1715 $.each($('#canvas').data("design").elements, function(i, e) {1716 if (e.selected) {1717 e.img.attrs.strokeEnabled = false;//true;1718 e.state_img.show()1719 $.each(e.anchors, function(i, a) {1720 a.show();1721 });1722 }1723 });1724 $.each($('#canvas').data("align_lines"), function(i, al) {1725 al[0].show()1726 });1727 1728 //resetLayout() 1729 1730 }1731 img.src = data_url;1732 1733 }1734 });1735 1736 1737 }1738 });1739 1740 1741 1742}1743function removeSavedLayout(id) {1744 console.log("id to remove:" + id)1745 $("#saved_layout" + id).parent().parent().remove()1746 $('#canvas').data("user_input_log").push("Rm Layout")1747 $('#canvas').data("status_log").push("Rm Layout")1748}1749function saveDesign() {1750 1751 console.log("saveDesign")1752 var stage = $('#canvas').data("stage");1753 var design = $('#canvas').data("design");1754 $.each(design.elements, function(i, e) {1755 //e.img.attrs.strokeEnabled = false;1756 e.state_img.hide()1757 $.each(e.anchors, function(i, a) {1758 a.hide();1759 });1760 });1761 $.each($('#canvas').data("align_lines"), function(i, al) {1762 al[0].hide()1763 });1764 console.log("height " + design.elements[0].height)1765 1766 1767 1768 var saved_canvases = $("#saved_table").find("canvas")1769 console.log("saved_canvases.length:" + saved_canvases.length)1770 design.saved_layouts=[]1771 $.each(saved_canvases, function(i, saved_img) {1772 design.saved_layouts.push($(saved_img).data("layout"))1773 });1774 1775 1776 stage.toDataURL({1777 callback : function(data_url) {1778 saveDesignOnServer(data_url, design)1779 $.each(design.elements, function(i, e) {1780 if (e.selected) {1781 e.img.attrs.strokeEnabled = false;//true;1782 e.state_img.show()1783 $.each(e.anchors, function(i, a) {1784 a.show();1785 });1786 }1787 });1788 $.each($('#canvas').data("align_lines"), function(i, al) {1789 al[0].show()1790 });1791 }1792 });1793}1794function setFixedLayout(layout_type, layout_num) {1795 viewLayout('interactive', -1);1796 deselectAll()1797 console.log("setting " + layout_type + " layout: " + layout_num)1798 //setCurrentLayout($('#canvas').data("saved_layouts")[i],true)1799 1800 setCurrentLayout($('#' + layout_type + '_layout' + layout_num).data("layout"), true);1801 //pauseSuggestions();1802 sendCurrentLayout('set-'+layout_type);1803 $.each($('#canvas').data("design").elements, function(i,e){1804 1805 if (e.selected)1806 console.log("ERROR: element "+i+" is selected")1807 })1808 $('#canvas').data("user_input_log").push("Load-" + layout_type+"-"+layout_num)1809 $('#canvas').data("status_log").push("Load-" + layout_type+"-"+layout_num)1810 if (layout_type=='gallery')1811 removeAllConstraints()1812 //if (!$('#canvas').data("noSuggestions"))1813 // $('#suggestion_lk').click()1814 if ($('#canvas').data("overlap_mode")) {1815 toggleOverlapMode();1816 toggleOverlapMode();1817 }1818 if ($('#canvas').data("region_mode")) {1819 toggleRegionMode();1820 toggleRegionMode();1821 }1822}1823function resetLayout(reset_canvas) {1824 if (reset_canvas==undefined)1825 reset_canvas=true1826 1827 deselectAll()1828 var design = $('#canvas').data("design");1829 var run_offset = $('#canvas').data("run_offset");1830 if (run_offset == undefined)1831 run_offset = 0;1832 run_offset = 0;1833 $('#canvas').data("run_offset", run_offset)1834 $('#canvas').data("user_input_log").push("Reset")1835 $('#canvas').data("status_log").push("Reset")1836 var curr_layout = getCurrentLayout()1837 removeAllConstraints();1838 //$.each($('#canvas').data("design").elements,function (i,e){e.fixed_amount=0.01})1839 //return1840 $.each(design.elements, function(i, e) {1841 1842 var new_height = 01843 1844 if (e.type == 'graphic') {1845 new_height = Math.round(Math.random()*50+50)1846 } else if (e.type == 'text') {1847 1848 /*1849 if (e.num_lines<=3)1850 {1851 //var num_lines=Math.round(Math.random()*2+1)1852 console.log(num_lines)1853 selectAlternateElement(e,num_lines)1854 1855 }1856 */1857 new_height = Math.round((Math.random()*10+10) * e.num_lines)1858 }1859 console.log("design height " + design.height + ", e height " + e.height)1860 e.height = new_height1861 e.width = e.height * e.aspect_ratio1862 var new_x = Math.random() * (design.width - e.width)1863 var new_y = Math.random() * (design.height - e.height)1864 e.x = new_x1865 e.y = new_y1866 e.last_x = new_x1867 e.last_y = new_y1868 e.img.setPosition(new_x, new_y)1869 e.img.setWidth(e.width)1870 e.img.setHeight(e.height)1871 1872 e.state_img.setPosition(e.x + e.width, e.y)1873 e.state_img.hide()1874 });1875 1876 sendCurrentLayout('Reset',true)1877 if (reset_canvas)1878 {1879 addLayoutToStack(getCurrentLayout())1880 }1881 else1882 {1883 setCurrentLayout(curr_layout)1884 }1885 design.elements[0].img.getLayer().draw()1886 1887 $('#canvas').data("energy_lists", {})1888 $('#checkingImage').css("visibility","hidden");1889 $('#canvas').data("started", true)1890 //stopSuggestions()1891 allowUpdates()1892 //startSuggestions(run_offset)1893}1894function resetRuns() {1895 1896 //console.log("reset run "+run_id);1897 deselectAll()1898 1899 1900 1901 1902 var design = $('#canvas').data("design");1903 1904 1905 $.each(design.elements, function(i, e) {1906 setElementState(e.id, 'unlocked')1907 })1908 1909 var curr_layout = getCurrentLayout()1910 1911 1912 $('#canvas').data("layout_log").push(['user-More Designs',new Date().getTime(),curr_layout,";"])1913 $('#canvas').data("user_input_log").push("More Designs")1914 $('#canvas').data("status_log").push("More Designs")1915 1916 $.each($('#canvas').data("runs"), function(i, run) {1917 if (run.id > -1) {1918 run.converged=false1919 1920 console.log("reset run: "+run.id)1921 1922 $.each(design.elements, function(i, e) {1923 1924 var new_height = 01925 1926 if (e.type == 'graphic') {1927 1928 new_height = Math.round(Math.random()*100+50)1929 1930 } else if (e.type == 'text') {1931 1932 //if (e.num_lines<=3)1933 //{1934 // var num_lines=Math.round(Math.random()*2+1)1935 // console.log(num_lines)1936 // selectAlternateElement(e,num_lines) 1937 //}1938 new_height = Math.round((Math.random()*20+10) * e.num_lines)1939 }1940 1941 console.log("design height " + design.height + ", e height " + e.height)1942 1943 e.height = new_height1944 e.width = e.height * e.aspect_ratio1945 1946 var new_x = Math.random() * (design.width - e.width)1947 var new_y = Math.random() * (design.height - e.height)1948 1949 e.x = new_x1950 e.y = new_y1951 1952 e.fixed_amount = 0.01953 e.state_img.hide()1954 1955 });1956 console.log("calling with run id"+run.id)1957 sendCurrentLayout(undefined,true,run.id)1958 $('#canvas').data("energy_lists")[run.id]=[]1959 }1960 });1961 1962 setCurrentLayout(curr_layout)1963 1964 $('#canvas').data("started", true)1965 allowUpdates()1966}1967function viewLayout(layout_type, layout_num) {1968 console.log("view " + layout_type + " layout " + layout_num)1969 if (layout_type!='interactive')1970 {1971 $('#canvas').data("user_input_log").push("View-" + layout_type+"-"+layout_num)1972 $('#canvas').data("status_log").push("View-" + layout_type+"-"+layout_num)1973 }1974 1975 if ((layout_num < 0) && $('#canvas').data("preview") > -1) {1976 1977 1978 1979 $('#canvas').data("preview", -1)1980 $('#canvas').data("preview_image").hide()1981 $('#canvas').data("preview_image").getLayer().draw()1982 $('#canvas').data("overlap_layer").show()1983 1984 var selected=$('.selectedPreview')1985 1986 var canvas = selected[0];1987 var ctx = canvas.getContext("2d")1988 var image = selected.data("preview_image")1989 var sugg_stage= $('#canvas').data("sugg_stage")1990 1991 ctx.drawImage(image, 0, 0, sugg_stage.attrs.width / 3, sugg_stage.attrs.height / 3);1992 1993 selected.removeClass("selectedPreview")1994 1995 1996 1997 } else if ($('#' + layout_type + '_layout' + layout_num).data("layout") != undefined) {1998 $('#' + layout_type + '_layout' + layout_num).addClass("selectedPreview")1999 $('#canvas').data("overlap_layer").hide()2000 $('#canvas').data("preview", layout_num)2001 $('#canvas').data("preview_image").show()2002 $('#canvas').data("preview_image").attrs.fillPatternImage = $('#' + layout_type + '_layout' + layout_num).data("preview_image")2003 2004 $('#canvas').data("preview_image").attrs.stroke='#0F0'2005 $('#canvas').data("preview_image").attrs.strokeEnabled=true2006 $('#canvas').data("preview_image").attrs.strokeWidth=42007 2008 $('#canvas').data("preview_image").moveToTop()2009 $('#canvas').data("preview_image").getLayer().draw()2010 2011 var canvas = $('#' + layout_type + '_layout' + layout_num)[0];2012 var ctx = canvas.getContext("2d")2013 var image = $('#canvas').data("images")['accept_suggestion']; 2014 2015 var sugg_stage= $('#canvas').data("sugg_stage")2016 if (sugg_stage.attrs.width>sugg_stage.attrs.height)2017 ctx.drawImage(image, 30, 0);2018 else 2019 ctx.drawImage(image, 0, 30); 2020 2021 2022 2023 }2024}2025function sendDesign() {2026 var elements = $('#canvas').data("design").elements;2027 console.log('sendInitialDesign');2028 for (var j = 0; j < elements.length; j++) {2029 if (elements[j].loaded == false) {2030 setTimeout(sendDesign, 500);2031 return;2032 }2033 }2034 sendCurrentLayout();2035 sendCurrentDesign();2036}2037function updateTextElement(elem) {2038 var old_text_chars = elem.old_text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');2039 var new_text_chars = elem.text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');2040 var old_num_lines = elem.old_text.split("\n").length;2041 var new_num_lines = elem.text.split("\n").length;2042 //var old_text_lines = elem.old_text.replaceAll(',', '').replaceAll(' ', '');2043 //var new_text_lines = elem.text.replaceAll(',', '').replaceAll(' ', '');2044 console.log("old_text: " + old_text_chars)2045 console.log("new_text: " + new_text_chars)2046 /*2047 Cases:2048 1) The new text is identical to the old text2049 - re-render alternates, but use the current texts2050 2) The new text is significantly different than the old text (new words, etc)2051 - get text alternates and re-render everything from scratch2052 3) The new text differs from the old text by the number of lines2053 - render the new text, set that as a new alternate, and update the selection2054 4) The new text only differs from the old text by commas or spaces (tweaking the current)2055 - re-render only this element2056 */2057 // Case 12058 if (elem.old_text == elem.text) {2059 console.log("updateTextElement: Re-rendering existing alternates")2060 renderTextAlts(elem, false)2061 }2062 //Case 22063 else if (old_text_chars != new_text_chars) {2064 console.log("updateTextElement: Completely re-rendering & finding new alternates")2065 renderTextAlts(elem, true)2066 }2067 //Case 32068 else if ((old_num_lines != new_num_lines)) {2069 console.log("updateTextElement: Setting a new alternate with different #s of lines")2070 var alts = $('#canvas').data("design").element_alts[elem.id];2071 if ( new_num_lines in alts) {2072 //selectAlternateElement(new_num_lines)2073 //renderTextElement(elem,true)2074 alts[new_num_lines].text = elem.text2075 elem.text = elem.old_text;2076 renderTextElement(alts[new_num_lines], false)2077 setTimeout(function() {2078 setAlternate(elem, alts[new_num_lines])2079 }, 100)2080 $("#num_lines_select").val(new_num_lines).attr('selected', true);2081 } else {2082 var new_elem = jQuery.extend(true, {}, elem)2083 new_elem.text = elem.text2084 new_elem.num_lines = new_num_lines2085 new_elem.fixed_amount = 12086 elem.text = elem.old_text2087 elem.img.remove()2088 new_elem.loaded = false2089 delete new_elem["img"]2090 renderTextElement(new_elem, true)2091 var max_cnt = 0;2092 $.each(alts, function(i, alt) {2093 max_cnt = Math.max(max_cnt, alt.alternate_id);2094 });2095 new_elem.alternate_id = max_cnt + 12096 alts[new_num_lines] = new_elem2097 //selectElement(new_elem)2098 $("#num_lines_select").val(new_num_lines).attr('selected', true);2099 //return;2100 }2101 }2102 //Case 4: tweaking2103 else {2104 console.log("updateTextElement: Tweaking current")2105 renderTextElement(elem, true)2106 }2107 selectElement(elem)2108}2109function updateTextElementOld(elem) {2110 var old_text = elem.old_text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');2111 var new_text = elem.text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');2112 console.log("old_text: " + old_text)2113 console.log("new_text: " + new_text)2114 //only update the current alternate, don't replace everything...2115 if (old_text == new_text) {2116 var alts = $('#canvas').data("design").element_alts[elem.id];2117 var old_num_lines = elem.old_text.split("\n").length;2118 var new_num_lines = elem.text.split("\n").length;2119 if (old_num_lines == new_num_lines) {2120 renderTextElement(elem, true)2121 } else {2122 if ( new_num_lines in alts) {2123 alts[new_num_lines].text = elem.text2124 elem.text = elem.old_text;2125 renderTextElement(alts[new_num_lines], true)2126 setAlternate(elem, alts[new_num_lines])2127 } else {2128 var new_elem = jQuery.extend(true, {}, elem)2129 new_elem.text = elem.text2130 new_elem.num_lines = new_num_lines2131 new_elem.fixed_amount = 12132 elem.text = elem.old_text2133 elem.img.remove()2134 new_elem.loaded = false2135 delete new_elem["img"]2136 renderTextElement(new_elem, true)2137 //renderTextElement(elem,false)2138 var max_cnt = 0;2139 $.each(alts, function(i, alt) {2140 max_cnt = Math.max(max_cnt, alt.alternate_id);2141 });2142 new_elem.alternate_id = max_cnt + 12143 alts[new_num_lines] = new_elem2144 setTimeout(function() {2145 selectElement(new_elem)2146 }, 500)2147 }2148 $("#num_lines_select").val(new_num_lines).attr('selected', true);2149 }2150 } else {2151 delete $('#canvas').data("design").element_alts[String(elem.id)]2152 renderTextAlts(elem, true)2153 //selectElement(elem)2154 }2155}2156function fixElementImages() {2157 2158 2159 var design=$('#canvas').data("design");2160 var layer = $('#canvas').data("stage").get('#layer')[0];2161 2162 2163 $.each(design.elements, function (i, elem){2164 2165 2166 elem.img.remove()2167 2168 console.log(design.element_alts[elem.id])2169 2170 if (design.element_alts[elem.id]!= undefined)2171 {2172 $.each(design.element_alts[elem.id], function(i, e) {2173 e.img.remove()2174 2175 console.log(e.alignment_imgs)2176 $.each(e.alignment_imgs, function(j, ai) {2177 ai.remove()2178 });2179 $.each(e.anchors, function(i, a) {2180 a.hide()2181 });2182 });2183 }2184 2185 if ((elem.num_lines > 1) && (elem.img != elem.alignment_imgs[elem.align])) {2186 elem.img = elem.alignment_imgs[elem.align];2187 }2188 2189 elem.img.setPosition(elem.x, elem.y)2190 //elem.img.attrs.strokeEnabled = elem.selected2191 elem.img.setHeight(elem.height)2192 elem.img.setWidth(elem.height * elem.aspect_ratio)2193 elem.img.setOpacity(1)2194 2195 layer.add(elem.img)2196 elem.img.show()2197 2198 });2199}2200function renderTextAlts(elem, createAlternates) {2201 console.log("rendering text alts for element text: " + elem.text)2202 elem.orig_text = elem.text.trim()2203 var idx = $('#canvas').data("design").elements.indexOf(elem);2204 var text_alts = {};2205 if (elem.id in $('#canvas').data("design").element_alts) {2206 var elem_alts = $('#canvas').data("design").element_alts[elem.id];2207 $.each(elem_alts, function(i, alt) {2208 var num_lines = alt.text.split("\n").length2209 text_alts[num_lines] = alt.text2210 if ((alt.img != undefined) && ( typeof (alt.img) != 'string')) {2211 console.log("typeof(alt.img) " + typeof (alt.img))2212 alt.img.remove()2213 alt.sugg_img.remove()2214 $.each(alt.anchors, function(i, a) {2215 a.destroy();2216 });2217 }2218 })2219 }2220 if ((!(elem.id in $('#canvas').data("design").element_alts)) || (createAlternates))2221 text_alts = findTextAlternates(elem.text)2222 var alts = {}2223 var cnt = 0;2224 $.each(text_alts, function(i, text) {2225 //console.log("rendering text with num_lines "+elem.num_lines+" \n"+)2226 text_trim=text.trim()2227 console.log("text alt "+i+" has text "+text_trim)2228 var new_elem;2229 if (text_trim == elem.orig_text) {2230 console.log("matching orig")2231 new_elem = elem2232 $('#canvas').data("design").elements[idx] = new_elem2233 } else {2234 new_elem = jQuery.extend(true, {}, elem)2235 new_elem.text = text_trim2236 new_elem.num_lines = text_trim.split("\n").length2237 }2238 new_elem.state_img = elem.state_img;2239 new_elem.unlock_img = elem.unlock_img;2240 new_elem.tweakable_img = elem.tweakable_img;2241 new_elem.lock_img = elem.lock_img;2242 delete new_elem["img"];2243 delete new_elem["sugg_img"];2244 renderTextElement(new_elem, false)2245 alts[new_elem.num_lines] = new_elem2246 new_elem.alternate_id = cnt2247 cnt = cnt + 12248 });2249 $('#canvas').data("design").element_alts[elem.id] = alts;2250}2251function selectAlternateElement(elem, num_lines) {2252 console.log("setting element " + elem.id + " with num lines " + num_lines)2253 var alts = $('#canvas').data("design").element_alts[elem.id]2254 if ( num_lines in alts) {2255 setAlternate(elem, alts[num_lines])2256 }2257 //design.elements[idx].style=elem.style2258}2259function renderTextElement(elem, is_visible) {2260 var layer = $('#canvas').data("stage").get('#layer')[0];2261 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];2262 //var layer=elem.img.getLayer();2263 //var sugg_layer=elem.sugg_img.getLayer();2264 console.log("rendering text for element " + elem.text)2265 fontStyle = ''2266 if (elem.bold)2267 fontStyle = fontStyle + " bold";2268 if (elem.italic)2269 fontStyle = fontStyle + " italic";2270 var sugg_pos={}2271 sugg_pos.x=elem.x;2272 sugg_pos.y=elem.y;2273 sugg_pos.height=elem.height;2274 2275 2276 if ("img" in elem) {2277 console.log("removing img from element")2278 sugg_pos.x = elem.sugg_img.getAbsolutePosition().x2279 sugg_pos.y = elem.sugg_img.getAbsolutePosition().y2280 sugg_pos.height = elem.sugg_img.getHeight()2281 elem.x = elem.img.getAbsolutePosition().x2282 elem.y = elem.img.getAbsolutePosition().y2283 elem.height = elem.img.getHeight()2284 elem.width = elem.img.getWidth()2285 elem.img.destroy()2286 elem.sugg_img.destroy()2287 $.each(elem.alignment_imgs, function(i, ai) {2288 ai.destroy()2289 });2290 $.each(elem.anchors, function(i, a) {2291 a.destroy()2292 });2293 }2294 var alignments;2295 elem.num_lines = elem.text.split("\n").length;2296 // wierd...look into this fixed_alignment2297 if ((elem.num_lines > 1) && ((!("fixed_alignment" in elem)) || (elem.fixed_alignment == false)))2298 alignments = ["left", "center", "right"];2299 else2300 alignments = [elem.align]2301 console.log("alignments: " + (alignments))2302 elem.max_line_length = 0;2303 $.each(elem.text.split("\n"), function(i, t) {2304 elem.max_line_length = Math.max(elem.max_line_length, t.length)2305 });2306 console.log("max line length: " + elem.max_line_length)2307 //elem.num_align=alignments.length2308 elem.alignment_imgs = {}2309 elem.alignment_sugg_imgs = {}2310 console.log("font: " + elem.font)2311 console.log("fontStyle: " + fontStyle)2312 2313 2314 $('#canvas').data("images_rendering",$('#canvas').data("images_rendering")+alignments.length)2315 $.each(alignments, function(index, curr_alignment) {2316 elem.init_font_size= (60 / elem.num_lines + 10);2317 2318 2319 var text2320 if (elem.shadow)2321 text = new Kinetic.Text({2322 x : 0,2323 y : 0,2324 text : elem.text,2325 fill : elem.color,2326 fontSize : (60 / elem.num_lines + 10),2327 fontStyle : fontStyle,2328 fontFamily : elem.font,2329 align : curr_alignment,2330 shadowColor: 'black',2331 shadowBlur: 10,2332 shadowOffset: {x:5,y:5},2333 shadowOpacity: 0.52334 });2335 else2336 text = new Kinetic.Text({2337 x : 0,2338 y : 0,2339 text : elem.text,2340 fill : elem.color,2341 fontSize : (60 / elem.num_lines + 10),2342 fontStyle : fontStyle,2343 fontFamily : elem.font,2344 align : curr_alignment2345 });2346 2347 2348 2349 if ($('#canvas').data("hideContent"))2350 {2351 elem.aspect_ratio = text.getWidth() / text.getHeight()2352 2353 2354 text = new Kinetic.Text({2355 x : 0,2356 y : 0,2357 text : '',2358 fill : 'black',2359 height : Math.round(elem.height),2360 width : Math.round(elem.height * elem.aspect_ratio),2361 fontSize : 20,2362 fontFamily : 'Calibri',2363 align : 'center'2364 });2365 }2366 2367 /*2368 var sans_serif_width=text.getWidth()2369 console.log("sans serif width:"+sans_serif_width)2370 2371 text.attrs.fontFamily=elem.font2372 var font_width=text.getWidth()2373 console.log("font width:"+font_width)2374 2375 if ((elem.font!= 'sans-serif') && (font_width==sans_serif_width))2376 {2377 console.log("ERROR. Font not loaded. Rendering as sans-serif. Wait till loaded") 2378 2379 2380 var callback = function (){textToImage(text,curr_alignment, sugg_pos,elem,layer,is_visible)};2381 2382 var interval;2383 var cnt=0;2384 2385 var checkFontWidth=function()2386 {2387 text.attrs.fontFamily=elem.font2388 var width=text.getWidth()2389 console.log("checkFontWidth "+width+ ", sans_serif_width "+sans_serif_width+", cnt "+cnt)2390 console.log(interval)2391 if (width!=sans_serif_width)2392 {2393 console.log("clearing interval and textToImage ")2394 clearInterval(interval)2395 callback()2396 } 2397 cnt+=1;2398 }2399 2400 //interval= setInterval(checkFontWidth,1000)2401 2402 }2403 //else2404 */2405 textToImage(text,curr_alignment, sugg_pos,elem,layer,sugg_layer,is_visible)2406 2407 /*2408 if (gup('hideContent') == '1')2409 text = new Kinetic.Text({2410 x : 0,2411 y : 0,2412 text : 'Text',2413 fill : 'black',2414 height : text.getHeight(),2415 width : text.getWidth(),2416 fontSize : 30,2417 fontFamily : 'Calibri',2418 align : 'center'2419 });2420 */2421 2422 });2423}2424function textToImage(text, curr_alignment,sugg_pos, elem, layer,sugg_layer,is_visible)2425{2426 elem.anchors = createAnchors(elem, layer, false)2427 elem.aspect_ratio = text.getWidth() / text.getHeight()2428 //elem.aspect_ratio=img.width/img.height2429 console.log("text: " + elem.text + " \n aspect ratio " + elem.aspect_ratio)2430 2431 if (elem.text.trim().split("\n").length!=elem.num_lines)2432 {2433 console.log("ERROR. doesnt match num lines"+elem.num_lines)2434 }2435 2436 var w=text.getWidth()2437 var h=text.getHeight()2438 text.toImage({2439 x : 0,2440 y : 0,2441 width : (text.getWidth()+5),2442 height : (text.getHeight()+5),2443 callback : function(img) {2444 2445 $('#canvas').data("images_rendering",$('#canvas').data("images_rendering")-1)2446 /*2447 var canvas = document.createElement('canvas');2448 canvas.width=img.width2449 canvas.height=img.height2450 var context = canvas.getContext('2d');2451 context.drawImage(img, 0, 0 );2452 var data = context.getImageData(0, 0, img.width, img.height).data;2453 //console.log(data)2454 var min_x=img.width, max_x=-1;2455 var min_y=img.height, max_y=-1;2456 for(var y = 0; y < img.height; y++)2457 for(var x = 0; x < img.width; x++)2458 {2459 if (data[((img.width * y) + x) * 4 + 3]!=0)2460 {2461 min_x=Math.min(min_x,x)2462 min_y=Math.min(min_y,y)2463 max_x=Math.max(max_x,x)2464 max_y=Math.max(max_y,y)2465 }2466 }2467 */2468 var add_background = ''2469 if ($('#canvas').data("hideContent")) {2470 2471 2472 add_background = function(pixels) {2473 var d = pixels.data;2474 for (var i = 0; i < d.length; i += 4) {2475 //if ((i<4*img.width-20) || (i>d.length-4*img.width+20) || (i%(4*img.width-20)<4 ) || (i%(4*img.width-20)> 4*img.width-28 ))2476 //{2477 // d[i] =02478 // d[i+1] =02479 // d[i+2] =02480 //}2481 //else2482 //{2483 var alpha = (d[i + 3] / 255)2484 2485 d[i] += alpha * d[i] + (1 - alpha) * 109;2486 d[i + 1] += alpha * d[i + 1] + (1 - alpha) * 229;2487 d[i + 2] += alpha * d[i + 2] + (1 - alpha) * 114;2488 //}2489 d[i + 3] = 255;2490 }2491 return pixels;2492 };2493 }2494 var text_img = new Kinetic.Image({2495 image : img,2496 x : elem.x,2497 y : elem.y,2498 width : img.width, //max_x-min_x,2499 height : img.height, //max_y-min_y,2500 strokeEnabled : $('#canvas').data("hideContent"),2501 stroke : 'Black',2502 strokeWidth : 2,2503 lineJoin : 'round',2504 //dashArray : [7, 5],2505 name : String(elem.id),2506 draggable : true,2507 visible : false,2508 filter : add_background2509 //crop: {2510 //x: min_x,2511 //y: min_y,2512 //width: max_x-min_x,2513 // height: max_y-min_y2514 //}2515 });2516 2517 //if (gup('hideContent') == '1')2518 2519 elem.init_height= img.height;2520 var scale = 1.0;2521 if (elem.old_text.length > 0) {2522 var old_num_lines = elem.old_text.split("\n").length;2523 scale = elem.num_lines / old_num_lines;2524 }2525 elem.alignment_imgs[curr_alignment] = text_img2526 text_img.setHeight(elem.height * scale);2527 text_img.setWidth(elem.height * scale * elem.aspect_ratio);2528 var sugg_text_img = text_img.clone();2529 sugg_text_img.setX(sugg_pos.x);2530 sugg_text_img.setY(sugg_pos.x);2531 sugg_text_img.setHeight(sugg_pos.height)2532 sugg_text_img.setWidth(sugg_pos.height * elem.aspect_ratio)2533 sugg_text_img.attrs.strokeEnabled = false;2534 elem.alignment_imgs[curr_alignment] = text_img2535 elem.alignment_sugg_imgs[curr_alignment] = sugg_text_img2536 console.log("create text with num_lines " + elem.num_lines + " with alignment:" + curr_alignment + " " + elem.align)2537 if ((elem.num_lines == 1) || (elem.align == curr_alignment)) {2538 //console.log("\nadding image to element\n "+elem.text)2539 2540 //console.log("\norig text\n"+elem.orig_text)2541 elem.img = text_img;2542 layer.add(text_img);2543 if ((is_visible) || (elem.text.trim() == elem.orig_text.trim())) {2544 console.log('matched elem text\n: ' + elem.orig_text)2545 //$.each(elem.anchors, function(i,a){2546 // layer.add(a)2547 //a.moveToTop()2548 //});2549 //moveAnchors(elem)2550 elem.img.show()2551 layer.draw()2552 }2553 }2554 if ((elem.num_lines == 1) || (elem.sugg_align == curr_alignment)) {2555 elem.sugg_img = sugg_text_img;2556 sugg_layer.add(sugg_text_img);2557 if ((is_visible) || (elem.text == elem.orig_text)) {2558 sugg_layer.draw()2559 elem.sugg_img.show()2560 }2561 }2562 setupElementCallbacks(text_img, elem);2563 elem.loaded = true;2564 }2565 });2566}2567function findTextAlternates(text) {2568 var alts = {};2569 var one_line = text.split("\n").join(" ");2570 var num_words = one_line.split(" ").length;2571 alts[1] = one_line;2572 var init_num_lines = text.split("\n").length;2573 console.log("one line: " + one_line);2574 console.log("num words:" + num_words);2575 //console.log("init_num_lines "+init_num_lines)2576 for (var n = 2; n <= Math.min(num_words, 7); n++) {2577 var line_size = one_line.length / n;2578 console.log('line size' + line_size)2579 var new_text = ''2580 var curr_idx = 0;2581 var check_idx = curr_idx + line_size;2582 for (var i = 0; i < n - 1; i++) {2583 var idx1 = one_line.indexOf(' ', check_idx);2584 var idx2 = one_line.substring(0, check_idx).lastIndexOf(' ');2585 if ((idx1 == -1) && (idx2 == -1)) {2586 console.log("index ==-1 ")2587 continue2588 }2589 var idx = 02590 if ((((idx1 - check_idx) < (check_idx - idx2)) || (idx2 >= one_line.length - 1) || (idx2 == -1)) && (idx1 != -1))2591 idx = idx1;2592 else2593 idx = idx2;2594 console.log('n' + n + ' i ' + i + " curr idx " + curr_idx + " idx " + idx)2595 console.log(" idx1 " + idx1 + " " + " idx2 " + idx2)2596 new_text += one_line.substring(curr_idx, idx + 1) + "\n"2597 curr_idx = idx;2598 check_idx += line_size;2599 }2600 new_text += one_line.substring(curr_idx, one_line.length)2601 console.log('new_text: ' + new_text)2602 var lines = new_text.split("\n")2603 var text2 = ''2604 var max_len = 0;2605 for (var j = 0; j < lines.length; j++) {2606 if (lines[j].length > 0) {2607 var trimmed = lines[j].trim()2608 text2 += trimmed + "\n"2609 max_len = Math.max(max_len, trimmed.length)2610 }2611 }2612 text2 = text2.substring(0, text2.length - 1)2613 var num_lines = text2.split("\n").length;2614 var ratio = (max_len) / (num_lines)2615 console.log('Creating text alt ' + n + ' with num_lines ' + num_lines + ", ratio: " + ratio + "\n" + text2)2616 //if ((num_lines>2) && (ratio<5))2617 // continue;2618 alts[num_lines] = text2;2619 }2620 alts[init_num_lines] = text;2621 return alts;2622}2623function deselectAll(elem) {2624 var other;2625 if ((elem != undefined) && (elem.type == 'region'))2626 other = $('#canvas').data("design").regions2627 else2628 other = $('#canvas').data("design").elements2629 2630 $('#canvas').data("selected", elem);2631 if (elem==undefined)2632 $('#canvas').data("selected", 0);2633 2634 console.log('selected: '+$('#canvas').data("selected"))2635 $.each($('#canvas').data("align_lines"), function(i, al) {2636 al[0].destroy()2637 });2638 $('#canvas').data("align_lines", [])2639 $.each(other, function(i, e) {2640 if ((e != elem)) {2641 e.state_img.hide()2642 //if (e.selected) {2643 //e.img.attrs.strokeEnabled = false;2644 $.each(e.anchors, function(i, a) {2645 a.hide();2646 });2647 e.selected = false;2648 2649 }2650 });2651}2652function selectMultipleElements(p1, p2) {2653 console.log('p1:' + p1.x + ' ' + p1.y)2654 console.log('p2: ' + p2.x + ' ' + p2.y)2655 var x = Math.min(p1.x, p2.x)2656 var y = Math.min(p1.y, p2.y)2657 var width = Math.max(p1.x, p2.x) - x2658 var height = Math.max(p1.y, p2.y) - y2659 var selected = []2660 $.each($('#canvas').data("design").elements, function(i, e) {2661 if (!((x + width < e.x) || (e.x + e.width < x) || (y + height < e.y) || (e.y + e.height < y)))2662 selected.push(e)2663 });2664 if (selected.length > 0) {2665 deselectAll()2666 $.each(selected, function(i, e) {2667 console.log('e:' + e.x + ' ' + e.y + " w/h: " + e.width + ' ' + e.height)2668 console.log("selected element " + e.id)2669 selectElement(e, true)2670 });2671 }2672}2673function selectElement(elem, multiple) {2674 multiple = typeof multiple !== 'undefined' ? multiple : false;2675 console.log("setting selected to " + elem.id + " with type " + elem.type + " and multiple " + multiple)2676 //if (elem.selected)2677 // return;2678 if (elem.img == undefined) {2679 console.log("no image. try again in 200 ms")2680 setTimeout(function() {2681 selectElement(elem, multiple);2682 }, 200)2683 return2684 }2685 2686 removeSuggestions()2687 2688 2689 $("#canvas").data("last_selected", $('#canvas').data("selected")) 2690 if (!multiple) {2691 deselectAll(elem)2692 //if ($('#canvas').data("selected")!=elem)2693 setControls(elem)2694 if (elem.type != 'background')2695 drawAlignmentLines(elem, 'dragging')2696 2697 2698 console.log("setting anchors")2699 $.each(elem.anchors, function(i, a) {2700 //if ($('#canvas').data("region_mode"))2701 a.moveToTop()2702 //layer.add(a)2703 a.show()2704 });2705 moveAnchors(elem);2706 2707 ///$('#size_constraint').prop("checked",false)2708 //$('#alignment_constraint').prop("checked",false)2709 2710 $('#group_constraints').css("visibility",'hidden')2711 2712 } 2713 2714 else {2715 if (elem.selected) {2716 elem.selected = false;2717 //elem.img.attrs.strokeEnabled = false;2718 elem.img.getLayer().draw();2719 return;2720 }2721 if ($('#canvas').data("selected")!=0)2722 {2723 $.each($('#canvas').data("selected").anchors, function(i, a) {2724 a.hide();2725 });2726 }2727 2728 var size_constraint=true;2729 var alignment_constraint=true;2730 2731 var selected_others=0;2732 2733 $.each($('#canvas').data("design").elements, function(i, e) {2734 if ((e.selected) && (e.id!=elem.id))2735 {2736 selected_others++;2737 2738 if (e.constraints['size'].indexOf(elem.id)==-1)2739 size_constraint=false2740 2741 if (e.constraints['alignment'].indexOf(elem.id)==-1)2742 alignment_constraint=false 2743 2744 2745 }2746 2747 });2748 2749 if (selected_others==0){2750 size_constraint=false;2751 alignment_constraint=false;2752 }2753 else2754 $('#group_constraints').css("visibility",'visible')2755 2756 $('#size_constraint').prop("checked",size_constraint)2757 $('#alignment_constraint').prop("checked",alignment_constraint)2758 2759 2760 }2761 if ($('#canvas').data("region_mode"))2762 elem.img.moveToTop();2763 var layer = elem.img.getLayer()2764 $.each($('#canvas').data("design").elements, function(i, e) {2765 if (elem.type != 'background') {2766 e.state_img.show()2767 e.state_img.setPosition(e.x + e.width, e.y)2768 } else2769 e.state_img.hide()2770 });2771 //elem.curr_pos=elem.img.getStage().getPointerPosition()2772 elem.last_x = elem.img.getPosition().x;2773 elem_last_y = elem.img.getPosition().y;2774 elem.selected = true;2775 2776 if (elem.type!='background')2777 elem.img.attrs.strokeEnabled = false;//true;2778 $('#canvas').data("selected", elem);2779 console.log("finished selecting")2780 //setCurrentRules()2781 layer.draw();2782}2783function getDistance(p1, p2) {2784 return Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));2785}2786function setupStageCallbacks(stage) {2787 stage.getContent().addEventListener('touchmove', function(evt) {2788 var touch1 = evt.touches[0];2789 var touch2 = evt.touches[1];2790 if (touch1 && touch2) {2791 var dist = getDistance({2792 x : touch1.clientX,2793 y : touch1.clientY2794 }, {2795 x : touch2.clientX,2796 y : touch2.clientY2797 });2798 var lastDist = $('#canvas').data("lastDist");2799 var lastScale = $('#canvas').data("lastScale");2800 $('#canvas').data("lastDist", dist);2801 var scale = ((dist + 50 ) / (lastDist + 50));2802 scale = Math.min(Math.max(scale, 0.95), 1.05)2803 if ((lastScale != undefined) && (((lastScale > 1) && (scale > 1)) || ((lastScale < 1) && (scale < 1))))2804 scale = scale * 0.25 + lastScale * 0.75;2805 $('#canvas').data("lastScale", scale);2806 scaleCurrentElement(scale)2807 }2808 }, false);2809 stage.getContent().addEventListener('touchend', function() {2810 $('#canvas').data("lastDist", 0);2811 }, false);2812}2813function setupElementCallbacks(elem_img, elem) {2814 2815 2816 elem_img.on('mouseover', function(evt) {2817 if ($("#mouseover_alignment_select").prop("checked"))2818 drawAlignmentLines(elem, 'mouseover')2819 });2820 2821 elem_img.on('dragstart',function(evt) {dragStartEvent(evt, elem, elem_img)});2822 elem_img.on('dragmove',function(evt) {dragMoveEvent(evt, elem, elem_img)});2823 elem_img.on('dragend',function(evt) {dragEndEvent(evt, elem, elem_img)});2824 elem_img.on('dblclick dbltap', function(evt) {2825 console.log("double click");2826 if (elem.type != 'background')2827 showElementControls();2828 else2829 showBackgroundControls();2830 });2831 elem_img.on("click tap",function(evt) {clickEvent(evt, elem, elem_img)});2832 2833 elem_img.on("mousedown",function(evt) {mouseDownEvent(evt, elem, elem_img)});2834 elem_img.on("mousemove",function(evt) {mouseMoveEvent(evt, elem, elem_img)}); 2835 elem_img.on("mouseup",function(evt) {mouseUpEvent(evt, elem, elem_img)});2836}2837function dragStartEvent(evt,elem,elem_img)2838{2839 $('#canvas').data("dragging", true)2840 console.log("dragstart")2841 evt.preventDefault();2842 if (elem.type != 'background')2843 $('#canvas').data("select_start", false)2844 $.each($('#canvas').data("design").elements, function(i, e) {2845 e.last_x=e.x;2846 e.last_y=e.y; 2847 });2848 if (elem.type=='background')2849 console.log("background drag")2850 if (!elem.selected)2851 selectElement(elem, evt.shiftKey == 1)2852 elem.curr_pos = elem_img.getStage().getPointerPosition();2853 $('#canvas').data("user_input_log").push("M")2854 $('#canvas').data("status_log").push("M")2855 2856 2857 stopSuggestionsUntilUserInput()2858 2859}2860function dragMoveEvent(evt,elem,elem_img)2861{2862 2863 console.log("dragmove")2864 //$('#canvas').data("select_start",undefined)2865 evt.preventDefault();2866 if ((elem.resizing))2867 return;2868 //elem.selected=true;2869 $('#canvas').data("select_start", false)2870 //allowUpdates()2871 var stage = elem_img.getStage()2872 //console.log("stage:"+stage)2873 if (stage == undefined) {2874 console.log("layer:")2875 console.log(elem_img.getLayer())2876 $('#suggestion_status').text("stage undefined");2877 return;2878 }2879 moveAnchors(elem)2880 elem.x = elem_img.getPosition().x2881 elem.y = elem_img.getPosition().y2882 elem.state_img.setPosition(elem.x + elem.width, elem.y)2883 drawAlignmentLines(elem, 'dragging')2884 //var curr_pos=stage.getPointerPosition()2885 var diff_x = elem.x - elem.last_x;2886 var diff_y = elem.y - elem.last_y;2887 console.log("x:"+elem.x)2888 console.log("y:"+elem.y)2889 console.log("last_x:"+elem.last_x)2890 console.log("last_y:"+elem.last_y)2891 console.log("diff_x:"+diff_x)2892 console.log("diff_y:"+diff_y)2893 elem.last_x = elem.x2894 elem.last_y = elem.y2895 var num_other_selected = 02896 $.each($('#canvas').data("design").elements, function(i, e) {2897 if ((e != elem) && (e.selected)) {2898 if (e.img.attrs.strokeEnabled == false) {2899 $('#error_message').text("Element selected by mistake")2900 e.selected = false2901 return2902 }2903 e.curr_pos += diff_x2904 e.curr_pos += diff_y2905 e.x += diff_x2906 e.y += diff_y2907 e.img.setPosition(e.x, e.y)2908 e.state_img.setPosition(e.x + e.width, e.y)2909 e.fixed_amount = elem.fixed_amount2910 num_other_selected += 12911 }2912 });2913 //console.log("setting state")2914 //if ($("#infer_locking_select").prop("checked") && (elem.fixed_amount !=1) && (elem.fixed_amount != 0.5) && (num_other_selected == 0))2915 // setElementState(elem.id, 'tweakable')2916 //else2917 elem.state_img.show()2918 $.each($('#canvas').data("design").elements, function(i, e) {2919 if ((e != elem) && (!(e.selected))) {2920 var new_opacity = 0;2921 if ($("#fixed_opacity_select").prop("checked")) {2922 console.log("fixed opacity")2923 new_opacity = 0.6;2924 } else if (e.fixed_amount == 0)2925 new_opacity = 0.3;2926 else2927 new_opacity = 0.6;2928 e.img.attrs.opacity = new_opacity2929 e.state_img.attrs.opacity = new_opacity2930 if ($("#lock_icon_select").prop("checked"))2931 e.state_img.show()2932 else2933 e.state_img.hide()2934 } else2935 e.img.attrs.opacity = 1.0;2936 });2937 //sendCurrentLayout();2938 //console.log("end dragmove")2939 elem_img.getLayer().draw();2940}2941function dragEndEvent(evt,elem,elem_img)2942{2943 2944 evt.preventDefault();2945 2946 allowUpdates()2947 //if (elem.type != 'region') {2948 2949 $.each($('#canvas').data("design").elements, function(i, e) {2950 if ((e != elem)) {2951 //setStroke(e.img, false, 1.5, e.fixed_amount)2952 if ($("#infer_locking_select").prop("checked")) {2953 var overlap = getOverlap(e.img, elem.img)2954 if ((overlap > 0.1) && (e.fixed_amount != 1)&& (!e.allow_overlap)&& (!elem.allow_overlap)) {2955 setElementState(e.id, 'unlocked')2956 //e.img.attrs.strokeEnabled=false2957 if (e.fix_alignment)2958 {2959 e.fix_alignment=false2960 2961 sendCurrentDesign()2962 }2963 2964 }2965 }2966 //console.log('overlap: '+overlap)2967 e.state_img.attrs.opacity = 12968 //if (!e.selected)2969 // e.state_img.hide()2970 }2971 e.img.attrs.opacity = 12972 });2973 //$.each($('#canvas').data("align_lines"), function(i, al){2974 // al.destroy()2975 //});2976 elem_img.getLayer().draw();2977 sendCurrentLayout('Move');2978 2979 $('#canvas').data("dragging", false)2980 2981}2982function clickEvent(evt,elem,elem_img)2983{2984 console.log("click, text mode " + $('#canvas').data("text_mode")+", "+$('#canvas').data("dragging"))2985 2986 if ($('#canvas').data("text_mode")) {2987 console.log("create text element")2988 createNewElement('text')2989 document.body.style.cursor = "default";2990 $('#canvas').data("text_mode", false)2991 return2992 }2993 2994 if ($('#canvas').data("dragging"))2995 return;2996 2997 selectElement(elem, evt.shiftKey == 1)2998 if (elem.type == 'background') {2999 $('#element_controls').hide()3000 var last_selected = $("#canvas").data("last_selected")3001 if ($('#background_controls').is(":visible"))3002 hideBackgroundControls()3003 else if (("type" in last_selected) && (last_selected.type == "background") && ($('#canvas').data("modificationsEnabled")))3004 {3005 showBackgroundControls()3006 }3007 3008 } else {3009 hideBackgroundControls()3010 sendCurrentLayout('Select')3011 }3012 3013}3014function mouseMoveEvent(evt,elem,elem_img)3015{3016 var start_pos = $('#canvas').data("select_start")3017 3018 console.log("mouse move")3019 var stage = elem_img.getStage();3020 var curr_pos = stage.getPointerPosition()3021 3022 console.log("curr_pos")3023 console.log(curr_pos)3024 3025 console.log(elem_img.getHeight())3026 //evt.preventDefault();3027 if ((start_pos != false)&& $('#canvas').data("mousedown")) {3028 3029 3030 var select_rect = $('#canvas').data("select_rect")3031 3032 var dist = getDistance(start_pos, curr_pos)3033 if (dist > 10) {3034 selectMultipleElements($('#canvas').data("select_start"), stage.getPointerPosition())3035 select_rect.setWidth(curr_pos.x - start_pos.x)3036 select_rect.setHeight(curr_pos.y - start_pos.y)3037 select_rect.show()3038 select_rect.getLayer().draw()3039 }3040 }3041}3042function mouseUpEvent(evt,elem,elem_img)3043{3044 $('#canvas').data("mousedown",false)3045 //evt.preventDefault();3046 $('#canvas').data("select_rect").hide()3047 $('#canvas').data("select_rect").getLayer().draw()3048 3049 var stage = elem_img.getStage();3050 console.log("mouse up: " + $('#canvas').data("select_start"))3051 //console.log(elem_img)3052 //console.log(elem)3053 if ($('#canvas').data("select_start") != false) {3054 console.log("mouse up")3055 var curr_pos = stage.getPointerPosition()3056 var dist = getDistance($('#canvas').data("select_start"), curr_pos)3057 if (dist > 10) {3058 selectMultipleElements($('#canvas').data("select_start"), stage.getPointerPosition())3059 }3060 }3061 $('#canvas').data("select_start", false)3062 3063}3064function mouseDownEvent(evt,elem,elem_img)3065{3066 var stage = elem_img.getStage();3067 3068 $('#canvas').data("mousedown",true)3069 3070 console.log("mouse down: " + $('#canvas').data("select_start"))3071 console.log(elem_img)3072 console.log(elem) 3073 if (elem.type=='background')3074 {3075 $('#canvas').data("select_start", stage.getPointerPosition())3076 $('#canvas').data("select_rect").setPosition($('#canvas').data("select_start"));3077 }3078}3079function drawAlignmentLines(elem, call_type) {3080 $.each($('#canvas').data("align_lines"), function(i, al) {3081 al[0].destroy()3082 });3083 $('#canvas').data("align_lines", [])3084 if (elem.type == 'background') {3085 elem.img.getLayer().draw()3086 return;3087 }3088 elem.width = elem.img.getWidth()3089 elem.height = elem.img.getHeight()3090 //console.log("drawAlignmentLines")3091 elem.mid_x = elem.x + elem.width / 2.03092 elem.mid_y = elem.y + elem.height / 2.03093 var min_x_amount = 99993094 var min_y_amount = 99993095 var x_line = [min_x_amount, 0, 0, 0, 0, 0, -99, []]3096 var y_line = [0, min_y_amount, 0, 0, 0, 0, -99, []]3097 var align_thresh = 103098 var design_x_center = $('#canvas').data("design").width / 2.03099 var design_y_center = $('#canvas').data("design").height / 2.03100 var align_x_center = Math.abs(elem.mid_x - design_x_center)3101 var align_y_center = Math.abs(elem.mid_y - design_y_center)3102 //var global_x_align=false;3103 if (align_x_center < align_thresh) {3104 //global_x_align=true;3105 min_x_amount = align_x_center3106 x_line = ([design_x_center - elem.mid_x, 0, design_x_center, 0, design_x_center, design_y_center * 2, 10, []])3107 }3108 //var global_y_align=false;3109 if (align_y_center < align_thresh) {3110 //global_y_align=true;3111 min_y_amount = align_y_center3112 y_line = ([0, design_y_center - elem.mid_y, 0, design_y_center, design_x_center * 2, design_y_center, 11, []])3113 }3114 $.each($('#canvas').data("design").elements, function(i, e) {3115 if ((e != elem) && (!(e.selected))) {3116 e.width = e.img.getWidth()3117 e.height = e.img.getHeight()3118 var mid_x = e.x + e.width / 2.0;3119 var mid_y = e.y + e.height / 2.0;3120 var align_left = Math.abs(elem.x - e.x)3121 var align_right = Math.abs(elem.x + elem.width - (e.x + e.width))3122 var align_x_center = Math.abs(elem.mid_x - mid_x)3123 var align_x_min = Math.min(align_left, Math.min(align_x_center, align_right))3124 var align_bottom = Math.abs(elem.y - e.y)3125 var align_top = Math.abs(elem.y + elem.height - (e.y + e.height))3126 var align_y_center = Math.abs(elem.mid_y - mid_y)3127 var align_y_min = Math.min(align_top, Math.min(align_y_center, align_bottom))3128 if (call_type.indexOf('Left') > -1) {3129 align_x_center = align_thresh + 13130 align_right = align_thresh + 13131 }3132 if (call_type.indexOf('Right') > -1) {3133 align_x_center = align_thresh + 13134 align_left = align_thresh + 13135 }3136 if (call_type.indexOf('top') > -1) {3137 align_y_center = align_thresh + 13138 align_bottom = align_thresh + 13139 }3140 if (call_type.indexOf('bottom') > -1) {3141 align_y_center = align_thresh + 13142 align_top = align_thresh + 13143 }3144 var y_start = Math.min(e.y, elem.y)3145 var y_end = Math.max(e.y + e.height, elem.y + elem.height)3146 var x_start = Math.min(e.x, elem.x)3147 var x_end = Math.max(e.x + e.width, elem.x + elem.width)3148 //&& (y_end-y_start >x_line[5]-x_line[3])3149 if ((align_x_min < align_thresh)) {3150 var prev_line = x_line;3151 //global_x_align=false;3152 var new_x_line = -1;3153 if ((align_left < align_thresh) && (align_left == align_x_min)) {3154 x_line = ([e.x - elem.x, 0, e.x, y_start, e.x, y_end, 0, [e.id]])3155 } else if ((align_x_center < align_thresh) && (align_x_center == align_x_min)) {3156 x_line = ([mid_x - elem.mid_x, 0, mid_x, y_start, mid_x, y_end, 1, [e.id]])3157 } else if ((align_right < align_thresh) && (align_right == align_x_min)) {3158 x_line = ([(e.x + e.width) - (elem.x + elem.width), 0, e.x + e.width, y_start, e.x + e.width, y_end, 2, [e.id]])3159 }3160 //if they are the same type, then concatente the other elements3161 if (prev_line[6] == x_line[6]) {3162 //console.log("same type")3163 if (align_x_min > min_x_amount) {3164 //var prev_align=prev_line[7]3165 var temp = jQuery.extend(true, {}, prev_line);3166 prev_line = x_line3167 x_line = temp3168 //x_line[7]=prev_align3169 //console.log("prev_line:"+prev_line)3170 //console.log("x_line:"+x_line)3171 }3172 x_line[3] = Math.min(x_line[3], prev_line[3])3173 x_line[5] = Math.max(x_line[5], prev_line[5])3174 x_line[7] = x_line[7].concat(prev_line[7])3175 } else {3176 if (align_x_min > min_x_amount)3177 x_line = prev_line3178 }3179 min_x_amount = Math.min(align_x_min, min_x_amount);3180 }3181 //(x_end-x_start >x_line[4]-x_line[2]) &&3182 if ((align_y_min < align_thresh)) {3183 //console.log("matched element: "+e.id)3184 var prev_line = y_line;3185 //console.log("prev_line"+prev_line)3186 //global_y_align=false;3187 if ((align_bottom < align_thresh) && (align_bottom == align_y_min)) {3188 y_line = ([0, e.y - elem.y, x_start, e.y, x_end, e.y, 3, [e.id]])3189 } else if ((align_y_center < align_thresh) && (align_y_center == align_y_min)) {3190 y_line = ([0, mid_y - elem.mid_y, x_start, mid_y, x_end, mid_y, 4, [e.id]])3191 } else if ((align_top < align_thresh) && (align_top == align_y_min)) {3192 y_line = ([0, (e.y + e.height) - (elem.y + elem.height), x_start, e.y + e.height, x_end, e.y + e.height, 5, [e.id]])3193 }3194 //if they are the same type, then concatente the other elements3195 if (prev_line[6] == y_line[6]) {3196 //console.log("same type")3197 if (align_y_min > min_y_amount) {3198 //var prev_align=prev_line[7]3199 var temp = jQuery.extend(true, {}, prev_line);3200 prev_line = y_line3201 y_line = temp3202 //y_line[7]=prev_align3203 //console.log("prev_line:"+prev_line)3204 //console.log("y_line:"+y_line)3205 }3206 y_line[7] = y_line[7].concat(prev_line[7])3207 y_line[2] = Math.min(y_line[2], prev_line[2])3208 y_line[4] = Math.max(y_line[4], prev_line[4])3209 } else {3210 if (align_y_min > min_y_amount)3211 y_line = prev_line3212 }3213 min_y_amount = Math.min(align_y_min, min_y_amount);3214 }3215 }3216 });3217 //}3218 var lines = [];3219 if (x_line[0] < 9999)3220 lines.push(x_line)3221 if (y_line[1] < 9999)3222 lines.push(y_line)3223 if ((lines.length > 0) && ($("#alignment_select").prop("checked"))) {3224 $.each(lines, function(i, line) {3225 var stroke_color = 'black'3226 var stroke_opacity = 0.353227 if ($('#canvas').data("invert")) {3228 stroke_color = 'white'3229 stroke_opacity = 0.53230 }3231 3232 3233 //console.log("creating line "+line)3234 var draw_line = new Kinetic.Line({3235 points : [line[2], line[3], line[4], line[5]],3236 stroke : stroke_color,3237 strokeWidth : 1,3238 lineJoin : 'round',3239 dashArray : [3, 2],3240 opacity : stroke_opacity3241 });3242 //var global_align= Number(((line[2]==line[4]) && global_x_align) || ((line[2]!=line[4]) && global_y_align))3243 $('#canvas').data("align_lines").push([draw_line, elem.id, line[6], line[7]])3244 elem.img.getLayer().add(draw_line)3245 if ((line[0] != 0) || (line[1] != 0)) {3246 /*3247 $.each($('#canvas').data("design").elements, function(i, e) {3248 if (e.selected)3249 {3250 if (call_type=='dragging')3251 {3252 e.x+=line[0];3253 e.y+=line[1];3254 }3255 e.img.setPosition(e.x,e.y)3256 //elem.img.setWidth(elem.width,elem.height)3257 e.state_img.setPosition(e.x+e.width,e.y)3258 moveAnchors(e)3259 }3260 });3261 */3262 if ((call_type == 'dragging')) {3263 elem.x += line[0];3264 elem.y += line[1];3265 } 3266 /*3267 else if (call_type == 'topLeft') {3268 elem.x += line[0];3269 elem.y += line[1];3270 elem.height += Math.max(line[1], line[0] / elem.aspect_ratio)3271 elem.width += Math.max(line[0], line[1] * elem.aspect_ratio)3272 }3273 */3274 elem.img.setPosition(elem.x, elem.y)3275 //elem.img.setWidth(elem.width,elem.height)3276 elem.state_img.setPosition(elem.x + elem.width, elem.y)3277 moveAnchors(elem)3278 }3279 });3280 $.each(elem.anchors, function(i, a) {3281 a.moveToTop()3282 });3283 3284 elem.img.getLayer().draw()3285 }3286}3287function setStroke(shape, enabled, width, color_blend) {3288 shape.attrs.strokeEnabled = enabled3289 shape.setStrokeWidth(width)3290 shape.setStrokeR(Math.round(255 * (1 - color_blend)))3291 shape.setStrokeG(0)3292 shape.setStrokeB(Math.round(255 * (color_blend)))3293}3294function getOverlap(shape1, shape2) {3295 var p1 = shape1.getPosition()3296 var p2 = shape2.getPosition()3297 var x11 = p1.x, y11 = p1.y, x12 = p1.x + shape1.getWidth(), y12 = p1.y + shape1.getHeight(), x21 = p2.x, y21 = p2.y, x22 = p2.x + shape2.getWidth(), y22 = p2.y + shape2.getHeight()3298 x_overlap = Math.max(0, Math.min(x12, x22) - Math.max(x11, x21))3299 y_overlap = Math.max(0, Math.min(y12, y22) - Math.max(y11, y21));3300 var ol1 = (x_overlap * y_overlap) / (shape1.getWidth() * shape1.getHeight())3301 var ol2 = (x_overlap * y_overlap) / (shape2.getWidth() * shape2.getHeight())3302 return Math.max(ol1, ol2)3303}3304function showBackgroundControls() {3305 if ($('#canvas').data("modificationsEnabled")) {3306 $('#background_controls').show()3307 //$('#canvas').data("design").background_elem.img.attrs.draggable=true3308 //$('#canvas').data("design").background_elem.img.attrs.strokeEnabled=true3309 $('#element_controls').hide()3310 3311 //if ($('#canvas').data("design").background_fname=='')3312 // $('#offset_controls').hide()3313 3314 $('#canvas').data("design").background_elem.img.getLayer().draw()3315 }3316}3317function hideBackgroundControls() {3318 if ($('#canvas').data("modificationsEnabled")) {3319 console.log("hideBackgroundControls")3320 //$('#canvas').data("design").background_elem.img.attrs.strokeEnabled=false3321 $('#background_controls').hide()3322 //$('#canvas').data("design").background_elem.img.attrs.draggable=false3323 3324 $('#canvas').data("design").background_elem.img.getLayer().draw()3325 3326 }3327}3328function showElementControls() {3329 if ($('#canvas').data("modificationsEnabled")) {3330 hideBackgroundControls() 3331 $('#element_controls').show()3332 }3333}3334function moveAnchors(elem) {3335 $.each(elem.anchors, function(i, a) {3336 if (a.attrs.name == 'bottomLeft') {3337 a.setX(elem.img.getAbsolutePosition().x)3338 a.setY(elem.img.getAbsolutePosition().y)3339 }3340 if (a.attrs.name == 'bottomRight') {3341 a.setX(elem.img.getAbsolutePosition().x + elem.img.getWidth())3342 a.setY(elem.img.getAbsolutePosition().y)3343 }3344 if (a.attrs.name == 'topLeft') {3345 a.setX(elem.img.getAbsolutePosition().x)3346 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight())3347 }3348 if (a.attrs.name == 'topRight') {3349 a.setX(elem.img.getAbsolutePosition().x + elem.img.getWidth())3350 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight())3351 }3352 if (a.attrs.name == 'midRight') {3353 a.setX(elem.img.getAbsolutePosition().x + elem.img.getWidth() - 6)3354 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight() / 2)3355 }3356 if (a.attrs.name == 'midLeft') {3357 a.setX(elem.img.getAbsolutePosition().x - 6)3358 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight() / 2)3359 }3360 });3361}3362function createNewElement(type, img, fname) {3363 if ((type == 'text') && $('#user_text').val() == '') {3364 alert("Please enter the text before clicking to position")3365 return3366 }3367 console.log("Creating new element")3368 var mousePos = $('#canvas').data("stage").getPointerPosition()3369 var elem = {}3370 elem.loaded = false3371 elem.resizing = false3372 elem.fixed = false3373 elem.align_type = -13374 elem.num_lines = 03375 //elem.num_align=-13376 elem.selected = true3377 elem.old_text = ''3378 elem.type = type3379 elem.id = -13380 elem.fixed_amount = 0.53381 elem.alternate_id = 03382 elem.optional = false3383 if (mousePos == undefined) {3384 elem.x = 03385 elem.y = 03386 } else {3387 elem.x = mousePos.x3388 elem.y = mousePos.y3389 }3390 if (fname != undefined)3391 elem.fname = fname3392 elem.group_id = $("#group_select").val()3393 elem.importance = $("#importance_select").val()3394 var max_id = 0;3395 $.each($('#canvas').data("design").elements, function(i, e) {3396 max_id = Math.max(max_id, parseInt(e.id))3397 });3398 elem.id = max_id + 13399 $('#canvas').data("design").elements.push(elem)3400 //design.elements.sort(function(e1,e2){return e1.importance-e2.importance})3401 //var max_id=-1;3402 //$.each($('#canvas').data("design").elements, function(i,e){3403 // max_id3404 //});3405 var layer = $('#canvas').data("stage").get('#layer')[0];3406 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];3407 //if ($('#canvas').data("suggestionsEnabled"))3408 setupLockingCallbacks(elem, layer)3409 if (elem.type == 'graphic') {3410 $('#canvas').data("user_input_log").push("Add Graphic")3411 $('#canvas').data("status_log").push("Add Graphic")3412 elem.type_id = 2;3413 elem.height = 100;3414 setupImageElement(elem, img, layer, sugg_layer, false);3415 overlap = {}3416 overlap.elem_id = elem.id3417 overlap.x_min = 03418 overlap.y_min = 03419 overlap.x_max = 13420 overlap.y_max = 13421 $('#canvas').data("design").overlap_regions.push(overlap)3422 sendCurrentDesign();3423 }3424 if (elem.type == 'text') {3425 $('#canvas').data("user_input_log").push("Add Text")3426 $('#canvas').data("status_log").push("Add Text")3427 elem.type_id = 1;3428 elem.font = $('#font_select').data("font");3429 elem.bold = $("#bold_select").attr("checked") == 'checked';3430 elem.italic = $("#italic_select").attr("checked") == 'checked';3431 elem.shadow = $("#shadow_select").attr("checked") == 'checked';3432 elem.fix_alignment = $("#fix_select").attr("checked") == 'checked';3433 elem.fix_alternate = $("#num_lines_fix_select").attr("checked") == 'checked';3434 elem.color = $('#color_select').val();3435 elem.text = $('#user_text').val();3436 if (elem.text == '')3437 return;3438 elem.align = ""3439 $(".align_select.active").each(function() {3440 console.log(this);3441 elem.align = this.value3442 });3443 elem.sugg_align = elem.align;3444 console.log("Creating with alignment: " + elem.align)3445 elem.num_lines = elem.text.split("\n").length;3446 console.log('num_lines ' + elem.num_lines)3447 elem.height = 25 * (elem.num_lines);3448 //renderTextElement(elem,true,true);3449 renderTextAlts(elem, true)3450 setTimeout(function() {3451 sendCurrentDesign();3452 resumeSuggestions();3453 }, 500)3454 }3455 console.log("setting element id to " + elem.id)3456 deleteGallery()3457 //deselectAll(elem)3458 //$('#canvas').data("selected",elem)3459 layer.draw();3460 sugg_layer.draw();3461 //$('#canvas').data("selected",elem);3462 //elem.img.attrs.strokeEnabled=true;3463 selectElement(elem, false);3464}3465function setControls(elem) {3466 $('#canvas').data("settingControls", true);3467 if (elem.type == 'region') {3468 console.log("Setting controls for region: " + elem.id);3469 $("#region_text_select").prop("checked", elem.allow_text)3470 $("#region_graphic_select").prop("checked", elem.allow_graphic)3471 $("#region_overlap_select").prop("checked", elem.allow_overlap)3472 } else {3473 console.log("Setting controls for element: " + elem.id + " with type " + elem.type);3474 //$("#font_select").val(elem.font);3475 $("#font_select").data("font", elem.font)3476 $("#font_select").find('span').html(elem.font);3477 $("#font_select").css('font-family', elem.font);3478 console.log("setting font:" + elem.font)3479 $("#group_select").val(elem.group_id).attr('selected', true);3480 $("#importance_select").val(elem.importance).attr('selected', true);3481 $("#bold_select").prop("checked", elem.bold)3482 $("#italic_select").prop("checked", elem.italic)3483 $("#shadow_select").prop("checked", elem.shadow)3484 $("#fix_select").prop("checked", elem.fix_alignment)3485 $("#num_lines_fix_select").prop("checked", elem.fix_alternate)3486 3487 3488 if (elem.color!=undefined)3489 {3490 $('#color_select').val(cutHex(elem.color));3491 $('#color_select').css("background-color",'#'+cutHex(elem.color))3492 3493 3494 if (hexToV(elem.color)<100)3495 $('#color_select').css("color",'#FFF')3496 else3497 $('#color_select').css("color",'#000')3498 }3499 3500 $("#optional_select").prop("checked", elem.optional)3501 $("#hidden_select").prop("checked", elem.hidden)3502 $('#user_text').val(elem.text);3503 $("#overlap_select").prop("checked", elem.allow_overlap)3504 if (elem.type=='text')3505 $("#overlap_mod").hide()3506 else3507 $("#overlap_mod").show()3508 /*3509 if (elem.type=='graphic')3510 $('#user_text').hide()3511 else3512 $('#user_text').show()3513 */3514 if (elem.type=='text')3515 $("#fontSizeInput").val((elem.height/elem.init_height)*elem.init_font_size)3516 3517 $("#num_lines_select").val(elem.num_lines).attr('selected', true);3518 $(".align_select").each(function() {3519 //console.log(this);3520 if (this.value == elem.align)3521 this.click()3522 });3523 }3524 console.log("Finished setting controls for element: " + elem.id);3525 $('#canvas').data("settingControls", false);3526}3527function regionControlsChanged() {3528 console.log("region controls changed")3529 if ($('#canvas').data("settingControls"))3530 return;3531 var elem = $('#canvas').data("selected")3532 elem.allow_text = $("#region_text_select").attr("checked") == 'checked'3533 elem.allow_graphic = $("#region_graphic_select").attr("checked") == 'checked'3534 elem.allow_overlap = $("#region_overlap_select").attr("checked") == 'checked'3535 elem.img.setFill(getRegionColor(elem))3536 elem.img.getLayer().draw()3537 sendCurrentDesign();3538}3539function numLinesChanged() {3540 selectAlternateElement($('#canvas').data("selected"), $("#num_lines_select").val())3541}3542function fontSelected(font) {3543 var splt = font.split(",")3544 var fontName = splt[0]3545 fontName = fontName.split("'").join('');3546 console.log("clicked: " + fontName)3547 $('#font_select').data("font", fontName)3548 controlsChanged()3549}3550function controlsChanged(new_val) {3551 console.log("controls changed")3552 if ($('#canvas').data("settingControls"))3553 return;3554 var elem = $('#canvas').data("selected")3555 if ((elem == undefined) || (elem.type == "background"))3556 return;3557 if (new_val != undefined) {3558 $('#canvas').data("user_input_log").push("Align-" + new_val)3559 $('#canvas').data("status_log").push("Align-" + new_val)3560 }3561 console.log("selected " + elem.id)3562 var changed_design = false;3563 var changed_text = false;3564 var changed_alignment = false;3565 var alignments = ["left", "center", "right"];3566 elem.old_text = elem.text;3567 if (elem.type == 'text') {3568 var bold = $("#bold_select").attr("checked") == 'checked'3569 var italic = $("#italic_select").attr("checked") == 'checked'3570 var shadow = $("#shadow_select").attr("checked") == 'checked'3571 var fix_alignment = $("#fix_select").attr("checked") == 'checked'3572 var fix_alternate = $("#num_lines_fix_select").attr("checked") == 'checked'3573 var optional = $("#optional_select").attr("checked") == 'checked'3574 var hidden = $("#hidden_select").attr("checked") == 'checked'3575 if (bold != elem.bold) {3576 console.log("bold changed from " + elem.bold + " to " + bold)3577 elem.bold = bold;3578 changed_text = true;3579 changed_design = true;3580 }3581 if (shadow != elem.shadow) {3582 console.log("shadow changed from " + elem.shadow + " to " + shadow)3583 elem.shadow = shadow;3584 changed_text = true;3585 }3586 if (fix_alternate != elem.fix_alternate) {3587 console.log("fix_alternate changed from " + elem.fix_alternate + " to " + fix_alternate)3588 elem.fix_alternate = fix_alternate;3589 changed_design = true;3590 }3591 if (optional != elem.optional) {3592 console.log("optional changed from " + elem.optional + " to " + optional)3593 elem.optional = optional;3594 changed_design = true;3595 }3596 if (hidden != elem.hidden) {3597 console.log("hidden changed from " + elem.hidden + " to " + hidden)3598 elem.hidden = hidden;3599 //changed_design=true;3600 if (elem.hidden) {3601 elem.hidden_img = elem.img.getImage()3602 elem.img.setImage(0)3603 //elem.img.setFillEnabled(false)3604 //elem.img.hide()3605 } else {3606 //console.log(elem.hidden_img)3607 elem.img.setImage(elem.hidden_img)3608 elem.hidden_img = 03609 //elem.img.show()3610 //elem.img.setFillEnabled(true)3611 }3612 elem.img.getLayer().draw();3613 changed_design = true;3614 }3615 if ($("#color_select").val() != elem.color) {3616 console.log("color changed from " + elem.color + " to " + $("#color_select").val())3617 elem.color = $("#color_select").val();3618 changed_text = true;3619 }3620 if ($('#font_select').data("font") != elem.font) {3621 console.log("font changed from " + elem.font + " to " + $('#font_select').data("font"))3622 elem.font = $('#font_select').data("font");3623 changed_text = true;3624 }3625 if ($("#user_text").val() != elem.text) {3626 console.log("text changed from " + elem.text + " to " + $("#user_text").val())3627 elem.text = $("#user_text").val();3628 changed_text = true;3629 }3630 if (fix_alignment != elem.fix_alignment) {3631 console.log("fix_alignment changed from " + elem.fix_alignment + " to " + fix_alignment)3632 elem.fix_alignment = fix_alignment;3633 $(".align_select.active").each(function() {3634 //console.log(this);3635 elem.align_type = alignments.indexOf(this.value)3636 elem.align=this.value3637 //console.log("setting alternate to "+elem.alternate)3638 });3639 changed_design = true;3640 }3641 if ((elem.num_lines > 1) && (new_val != undefined) && (new_val != elem.align)) {3642 elem.align = new_val3643 console.log("Setting new alignment: " + elem.align);3644 var layer = elem.img.getLayer();3645 var orig_img = elem.img;3646 elem.img.remove();3647 elem.img = elem.alignment_imgs[new_val];3648 elem.img.show();3649 //elem.alternate=alignments.indexOf(new_val)3650 elem.align_type = alignments.indexOf(new_val)3651 elem.img.setX(orig_img.getAbsolutePosition().x)3652 elem.img.setY(orig_img.getAbsolutePosition().y)3653 elem.img.setHeight(orig_img.getHeight())3654 elem.img.setWidth(orig_img.getWidth())3655 //elem.img.attrs.strokeEnabled = orig_img.attrs.strokeEnabled3656 layer.add(elem.img);3657 $.each(elem.anchors, function(i, a) {3658 a.moveToTop();3659 });3660 layer.draw();3661 //changed_text=true;3662 changed_alignment = true;3663 elem.fix_alignment = true;3664 changed_design = true;3665 $("#fix_select").prop("checked", true)3666 }3667 if (changed_text) {3668 updateTextElement(elem)3669 }3670 }3671 //graphical elements3672 else3673 {3674 console.log("allow_overlap for element "+elem.id)3675 3676 var allow_overlap = $("#overlap_select").attr("checked") == 'checked'3677 if (allow_overlap != elem.allow_overlap) 3678 {3679 elem.allow_overlap = allow_overlap;3680 3681 var design=$('#canvas').data("design")3682 var or_idx=-1;3683 $.each(design.overlap_regions , function (i,or) {3684 if (or.elem_id==elem.id)3685 {3686 or_idx=i;3687 console.log("matched "+or.elem_id+ " at index "+or_idx) 3688 }3689 3690 });3691 3692 if (or_idx>-1)3693 {3694 console.log(design.overlap_regions[or_idx]) 3695 design.overlap_regions.splice(or_idx,1)3696 3697 }3698 3699 if (!allow_overlap)3700 {3701 console.log("!allow_overlap")3702 overlap = {}3703 overlap.elem_id = elem.id3704 overlap.x_min = 03705 overlap.y_min = 03706 overlap.x_max = 13707 overlap.y_max = 13708 design.overlap_regions.push(overlap)3709 3710 console.log(design.overlap_regions)3711 }3712 3713 3714 //overlap = overlap + or.elem_id + "," + Math.round(or.x_min * 1000) / 1000 + "," + Math.round(or.x_max * 1000) / 1000 + "," + Math.round(or.y_min * 1000) / 1000 + "," + Math.round(or.y_max * 1000) / 1000 + "\n"3715 3716 sendCurrentDesign();3717 }3718 3719 3720 3721 }3722 if ($("#group_select").val() != elem.group_id) {3723 elem.group_id = $("#group_select").val();3724 sendCurrentDesign();3725 }3726 if ($("#importance_select").val() != elem.importance) {3727 elem.importance = $("#importance_select").val();3728 sendCurrentDesign();3729 }3730 3731 3732 3733 3734 if ((changed_design) || (changed_text))3735 setTimeout(function() {3736 sendCurrentDesign();3737 }, 200)3738 if (changed_alignment)3739 sendCurrentLayout('Align');3740}3741function checkForSuggestions() {3742 var runs = $('#canvas').data("runs")3743 var design=$('#canvas').data("design")3744 var dir_name=design.name+"_"+design.width+"_"+design.height3745 $.each(runs, function(i, run) {3746 if (run.id > -1)3747 {3748 3749 if (run.type=='gallery')3750 {3751 var last_gallery_check=$('#canvas').data("last_gallery_check")3752 var curr_time=new Date().getTime()3753 3754 if ((last_gallery_check!=undefined) && (curr_time-last_gallery_check<2000))3755 return3756 3757 $('#canvas').data("last_gallery_check",curr_time)3758 3759 }3760 3761 getLayoutFromServer(run.id, run.type,dir_name);3762 3763 }3764 });3765 /*3766 if ($('#suggLayout').data('runID')>=0)3767 {3768 getLayoutFromServer($('#canvas').data("design").name,$('input[name=userID]').val());3769 }3770 */3771}3772function getCurrentLayout(reset) {3773 var design = $('#canvas').data("design")3774 var layout = design.name+'\n';3775 3776 var scale = 1.0;3777 layout += Math.round(design.width / scale) + "," + Math.round(design.height / scale) +'\n'+ (design.elements.length) + "\n";3778 3779 var constraints={}3780 3781 var type_map={'size':10,'alignment':11}3782 3783 var cons_str=''3784 for (var i = 0; i < design.elements.length; i++) {3785 var elem = design.elements[i];3786 //var fixed=(elem.fixed);3787 //var fixed=(elem.fixed || elem.selected);3788 if (elem.alternate_id == -1)3789 elem.alternate_id = 03790 var fix_amount = (Math.round((elem.fixed_amount) * 1000) / 1000)3791 3792 if (elem.hidden)3793 fix_amount = -1;3794 3795 // && $('#canvas').data("automaticUpdate")3796 if ((elem.selected))3797 if (fix_amount==1)3798 fix_amount = 1.05;3799 else3800 fix_amount = 0.95;3801 3802 //if ((!reset) &&(fix_amount==0) &&($('#canvas').data("automaticUpdate")))3803 // fix_amount=0.013804 3805 if ((!reset) &&(fix_amount==0))3806 fix_amount=0.53807 3808 3809 $.each(elem.constraints,function(type,cons){3810 if (cons.length>0)3811 {3812 console.log("constraint ")3813 console.log(cons)3814 3815 cons_str+=elem.id+","+type_map[type]+","+cons.length+","3816 for (var j=0;j<cons.length;j++)3817 cons_str+=cons[j]+","3818 cons_str=cons_str.substring(0,cons_str.length-1)+"\n"3819 }3820 3821 });3822 3823 3824 //if ((fix_amount<0.05) &&(!$('#canvas').data("automaticUpdate")))3825 // fix_amount=0.03826 layout += Math.round(elem.x / scale) + "," + Math.round(elem.y / scale) + "," + Math.round(elem.height / scale) + "," + elem.align_type + "," + fix_amount + ",-1," + (elem.hidden ? -1 : elem.alternate_id) + "\n"3827 }3828 var lines = $('#canvas').data("align_lines");3829 if (lines.length >= 1) {3830 var selected_element = false;3831 for (var i = 0; i < design.elements.length; i++) {3832 if ((design.elements[i].id == lines[0][1]) && (design.elements[i].selected))3833 selected_element = true;3834 }3835 if (selected_element) {3836 //layout += lines.length + ' lines\n'3837 $.each(lines, function(i, al) {3838 var aligned_elem = al[3];3839 //console.log("al:"+al)3840 cons_str += al[1] + "," + al[2] + "," + aligned_elem.length + ","3841 for (var i = 0; i < aligned_elem.length; i++)3842 cons_str += aligned_elem[i] + ","3843 cons_str = cons_str.slice(0, -1) + "\n"3844 });3845 } //else3846 // layout += '0 lines\n'3847 } //else3848 // layout += '0 lines\n'3849 //console.log("constraints:\n"+cons_str)3850 var num_constraints=cons_str.split("\n").length-13851 layout += num_constraints+' constraints\n'3852 layout += cons_str3853 3854 3855 if (reset==true)3856 layout += '-2 regions\n'3857 else3858 layout += '-1 regions\n'3859 return layout3860 //console.log("layout:\n"+layout);3861}3862function sendCurrentLayout(user_input, reset,run_id) {3863 console.log("sendCurrentLayout "+user_input)3864 var layout = getCurrentLayout(reset)3865 3866 if (user_input!=undefined)3867 {3868 $('#canvas').data("layout_log").push(['user-'+user_input,new Date().getTime(),layout,";"])3869 makeSuggestions()3870 }3871 3872 3873 console.log("curr_layout: "+layout) 3874 $('#report').hide()3875 $('#reportStatus').text("")3876 3877 //addLayoutToStack(layout,'user')3878 addLayoutToStack(layout)3879 //console.log("curr layout:" + layout)3880 var layout_counter=$('#canvas').data("layout_counter")3881 if (layout_counter==undefined)3882 layout_counter=0;3883 $('#canvas').data("layout_counter",layout_counter+1)3884 3885 layout=layout_counter+"\n"+layout3886 3887 3888 console.log("new counter: "+layout_counter)3889 3890 $('#userLayout').val(layout)3891 3892 if (run_id==undefined){3893 console.log("sending to all");3894 $.each($('#canvas').data("runs"), function(i, run) {3895 if (run.id > -1) {3896 sendLayoutToServer(run.id, layout);3897 }3898 });3899 3900 $('#canvas').data("energy", 9999)3901 $('#canvas_energy').text(9999)3902 }3903 else3904 sendLayoutToServer(run_id, layout);3905 3906 allowUpdates()3907 3908}3909function sendCurrentDesign() {3910 console.log("sendCurrentDesign")3911 var design = getCurrentDesign();3912 $.each($('#canvas').data("runs"), function(i, run) {3913 updateDesignOnServer(run.id, design)3914 run.energy = 99999;3915 });3916}3917function getCurrentDesign() {3918 //console.log('getCurrentDesign')3919 var design = $('#canvas').data("design")3920 var dstring = design.name+'\n';3921 3922 3923 var scale = 1.0;3924 dstring += Math.round(design.width / scale) + "," + Math.round(design.height / scale) +'\n'+ (design.elements.length) + "\n";3925 dstring = dstring + "0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,background\n";3926 var graphic_ids=[]3927 for (var i = 0; i < design.elements.length; i++) {3928 var elem = design.elements[i];3929 3930 if (elem.type=='graphic')3931 graphic_ids.push(elem.id)3932 if (elem.alternate_id == -1)3933 elem.alternate_id = 03934 /*3935 var fix_amount = (Math.round((elem.fixed_amount) * 100) / 100)3936 if (elem.hidden)3937 fix_amount = -1;3938 if ((elem.anchors["topLeft"].attrs != undefined) && (elem.anchors["topLeft"].attrs.visible))3939 fix_amount = 1;3940 */3941 fix_amount = 0;3942 3943 var alignments = ["left", "center", "right"];3944 var a_type= alignments.indexOf(elem.align)3945 dstring = dstring + (elem.id) + ",";3946 dstring = dstring + elem.type_id + ",";3947 dstring = dstring + elem.importance + ",";3948 dstring = dstring + elem.num_lines + ",";3949 dstring = dstring + elem.group_id + ",";3950 dstring = dstring + (Math.round((1 / elem.aspect_ratio) * 1000) / 1000) + ',';3951 dstring = dstring + Math.round(elem.x / scale) + ',';3952 dstring = dstring + Math.round(elem.y / scale) + ',';3953 dstring = dstring + Math.round(elem.height / scale) + ',';3954 dstring = dstring + a_type + ",";3955 dstring = dstring + fix_amount + ",";3956 dstring = dstring + (elem.fix_alternate ? 0 : elem.alternate_id ) + ",";3957 dstring = dstring + (elem.fix_alignment ? 1 : 0 ) + ",";3958 dstring = dstring + (elem.optional ? 1 : 0 ) + ",";3959 dstring = dstring + "0,1,0,1," + elem.fname + "\n";3960 //console.log("aspect ratio "+(Math.round((1/elem.aspect_ratio)*1000)/1000))3961 //if (elem.img)3962 // console.log('element +'+i+' x: '+elem.img.getPosition().x+ ' y: '+elem.img.getPosition().y)3963 }3964 var overlap = '';3965 var overlap_cnt=0;3966 for (var i = 0; i < design.overlap_regions.length; i++) {3967 var or = design.overlap_regions[i];3968 if ($.inArray(or.elem_id,graphic_ids)>-1)3969 {3970 overlap = overlap + or.elem_id + "," + Math.round(or.x_min * 1000) / 1000 + "," + Math.round(or.x_max * 1000) / 1000 + "," + Math.round(or.y_min * 1000) / 1000 + "," + Math.round(or.y_max * 1000) / 1000 + "\n"3971 overlap_cnt++;3972 }3973 }3974 dstring += (overlap_cnt) + " overlap regions\n" + overlap;3975 var num_alts = 0;3976 var alt_string = ''3977 $.each(design.element_alts, function(id, alts) {3978 var alt_str = id + "," + Object.keys(alts).length + ","3979 $.each(design.elements, function(i, elem) {3980 if ((id == elem.id) && (!elem.fix_alternate)) {3981 num_alts++3982 $.each(alts, function(num_lines, alt_elem) {3983 alt_str += alt_elem.num_lines + "," + (Math.round((1 / alt_elem.aspect_ratio) * 1000) / 1000) + "," + alt_elem.max_line_length + ","3984 });3985 alt_string += alt_str + "\n"3986 }3987 });3988 });3989 dstring += num_alts + " alternates\n"3990 dstring += alt_string;3991 //console.log("sending current design:\n "+dstring);3992 return dstring3993}3994function setSuggestionLayout(run_id, new_layout, new_energy) {3995 var design = $('#canvas').data("design");3996 var run = $('#canvas').data("runs")[run_id]3997 //var gallery_layouts=$('#canvas').data("gallery_layouts");3998 //var gallery_images=$('#canvas').data("gallery_images");3999 //var gallery_designs=$('#canvas').data("gallery_designs");4000 4001 var sequence=((run.type.search("gallery") > -1) ||(run.type.search("nio") > -1))4002 if ((run.layout != new_layout) && (new_energy<9999) &&((run.energy != new_energy ) ||sequence )) {4003 //console.log("setting new layout for run_id "+run_id)//+" new_layout: "+new_layout)4004 //console.log("old energy "+run.energy+" new energy "+new_energy)4005 4006 //console.log("canvas id:"+run.canvas_id )4007 if (run.canvas_id < 0)4008 {4009 return;4010 4011 }4012 var alignments = ["left", "center", "right"];4013 var elements = new_layout.split("\n");4014 var elem_cnt = parseInt(elements[3])4015 if (elem_cnt != design.elements.length)4016 {4017 console.log("count mismatch")4018 return;4019 }4020 4021 var design_sizes = elements[2].split(",")4022 var layout_width=parseInt(design_sizes[0])4023 var layout_height=parseInt(design_sizes[1])4024 4025 if ((layout_width!= design.width) || (layout_height!=design.height))4026 {4027 console.log("layout_width:"+ layout_width)4028 console.log("layout_height:"+ layout_height)4029 console.log("design.width:"+ design.width)4030 console.log("design.height:"+ design.height)4031 return;4032 }4033 4034 var curr_time=new Date().getTime()4035 var start_time=$('#canvas').data("startRenderTime")4036 4037 if ((curr_time!=undefined)&& (curr_time!=0) && (curr_time-start_time<5000))4038 {4039 console.log("still rendering. check back later...")4040 setTimeout(function(){setSuggestionLayout(run_id,new_layout,new_energy);}, 500);4041 return4042 }4043 else4044 $('#canvas').data("startRenderTime",curr_time)4045 4046 4047 4048 4049 console.log("setting new layout for run "+run_id)4050 4051 run.layout = new_layout4052 run.energy = new_energy4053 if (run.type != 'gallery')4054 $('#suggestion_layout' + String(run.canvas_id)).data("layout", new_layout)4055 4056 4057 4058 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];4059 for (var i = 4; i < design.elements.length + 4; i++) {4060 var elem = design.elements[i - 4];4061 var elem_split = elements[i].split(',');4062 var alt_id = parseInt(elem_split[6]);4063 var alt_elem = elem;4064 4065 if ("sugg_img" in alt_elem)4066 alt_elem.sugg_img.remove();4067 if ((!elem.fix_alternate) && (elem.id in design.element_alts)) {4068 $.each(design.element_alts[elem.id], function(num_lines, ae) {4069 if (alt_id == ae.alternate_id) {4070 alt_elem = ae;4071 //console.log("found "+(i)+" num_lines "+num_lines+ " alt id "+ae.alternate_id)4072 }4073 ae.sugg_img.remove();4074 });4075 }4076 if (alt_elem.num_lines > 1) {4077 var a = parseInt(elem_split[3])4078 var align;4079 if (a > -1)4080 align = alignments[a]4081 else4082 align = elem.align4083 alt_elem.sugg_align = align;4084 alt_elem.sugg_img = alt_elem.alignment_sugg_imgs[align];4085 }4086 if (alt_id < 0) {4087 continue;4088 }4089 //console.log("added "+(i))4090 sugg_layer.add(alt_elem.sugg_img);4091 var height = parseInt(elem_split[2]);4092 var width = height * alt_elem.aspect_ratio;4093 alt_elem.sugg_img.setX(parseInt(elem_split[0]));4094 alt_elem.sugg_img.setY(parseInt(elem_split[1]));4095 alt_elem.sugg_img.setHeight(height);4096 alt_elem.sugg_img.setWidth(width);4097 //if (alt_id!=-1)4098 alt_elem.sugg_img.show()4099 //else4100 // alt_elem.sugg_img.hide()4101 //console.log("setting "+i+ " "+parseInt(elem_split[0])*4.0+ " "+ parseInt(elem_split[1])*4.0+" "+height+" "+width+" "+elem.aspect_ratio);4102 }4103 sugg_layer.draw();4104 //console.log("draw")4105 var sugg_stage = sugg_layer.getStage();4106 sugg_stage.toDataURL({4107 callback : function(dataUrl) {4108 var img = new Image();4109 img.onload = function() {4110 run.image = img;4111 if ($("#canvas").data("preview") == run.canvas_id) {4112 $('#canvas').data("preview_image").attrs.fillPatternImage = img4113 $('#canvas').data("preview_image").getLayer().draw()4114 }4115 if ((run.type == 'gallery')|| (run.type == 'nio')) {4116 4117 4118 4119 var count = $("#gallery_table").children().children().length;4120 var new_layout_elem = $('#gallery_layout0').clone()4121 new_layout_elem.show()4122 new_layout_elem.data("preview_image", img);4123 new_layout_elem.data("layout", new_layout);4124 new_layout_elem.attr("id", "gallery_layout" + count)4125 4126 new_layout_elem.attr("width",sugg_stage.attrs.width / 3)4127 new_layout_elem.attr("height",sugg_stage.attrs.height / 3)4128 4129 new_layout_elem.mouseover(function() {4130 viewLayout('gallery', count)4131 })4132 new_layout_elem.click(function() {4133 setFixedLayout('gallery', count)4134 })4135 //new_layout_elem.dblclick(function() {setFixedLayout('gallery',count)})4136 var canvas = new_layout_elem[0];4137 var ctx = canvas.getContext("2d")4138 ctx.drawImage(img, 0, 0, sugg_stage.attrs.width / 3, sugg_stage.attrs.height / 3);4139 $('#gallery_table').append($('<tr>').append($('<td>').append(new_layout_elem)))4140 new_layout_elem.parent().addClass("suggestion")4141 } else {4142 4143 $('#suggestion_layout' + run.canvas_id).data("preview_image", img)4144 4145 var canvas = $('#suggestion_layout'+(run.canvas_id));4146 canvas.attr("width",sugg_stage.attrs.width/3)4147 canvas.attr("height",sugg_stage.attrs.height/3)4148 canvas.show()4149 4150 var ctx = canvas[0].getContext("2d")4151 ctx.clearRect(0, 0, sugg_stage.attrs.width / 3, sugg_stage.attrs.height / 3);4152 ctx.drawImage(img, 0, 0, sugg_stage.attrs.width / 3, sugg_stage.attrs.height / 3);4153 4154 4155 if ($('#suggestion_layout' + run.canvas_id).hasClass("selectedPreview")) 4156 { 4157 if (sugg_stage.attrs.width>sugg_stage.attrs.height)4158 ctx.drawImage($('#canvas').data("images")['accept_suggestion'], 30,0);4159 else 4160 ctx.drawImage($('#canvas').data("images")['accept_suggestion'], 0, 30);4161 }4162 4163 }4164 4165 $('#canvas').data("startRenderTime",0) 4166 }4167 img.src = dataUrl4168 }4169 });4170 }4171}4172function createNewRegion(x, y, w, h, graphic, text, overlap) {4173 region = {}4174 region.type = 'region'4175 region.id = 'region'4176 region.x = x4177 region.y = y4178 region.width = w4179 region.height = h4180 region.allow_graphic = graphic4181 region.allow_text = text4182 region.allow_overlap = overlap4183 region.selected = false4184 region.fixed_amount = 04185 return region4186}4187function getLayoutDiff(layout1, layout2) {4188 if ((layout1 == undefined) || (layout2 == undefined) || (layout1 == '') || (layout2 == ''))4189 return 10000;4190 4191 var idx1=layout1.indexOf("design_")4192 var idx2=layout2.indexOf("design_")4193 4194 layout1=layout1.slice(idx1,layout1.length)4195 layout2=layout2.slice(idx2,layout2.length)4196 4197 var elements1 = layout1.split("\n");4198 var elements2 = layout2.split("\n");4199 var num_elements = parseInt(elements1[2])4200 if (num_elements != parseInt(elements2[2]))4201 return 10000;4202 //console.log("layout1:"+layout1)4203 //console.log("layout2:"+layout2)4204 4205 4206 var diff_sum = 0;4207 for (var i = 3; i < num_elements + 3; i++) {4208 4209 var elem1_split = elements1[i].split(',');4210 var elem2_split = elements2[i].split(',');4211 //console.log(elem1_split)4212 //console.log(elem2_split)4213 for (var j = 0; j < 3; j++)4214 diff_sum += Math.abs(elem1_split[j] - elem2_split[j])4215 //diff_sum+=5*Math.abs(elem1_split[3]-elem2_split[3])4216 }4217 //console.log("diff_sum:"+diff_sum)4218 return diff_sum;4219}4220function addLayoutToStack(new_layout,stack_type) {4221 var idx;4222 var stack;4223 //console.log("addLayoutToStack "+new_layout)4224 if (stack_type=='user')4225 {4226 idx = $('#canvas').data("user_layout_stack_idx");4227 stack = $('#canvas').data("user_layout_stack");4228 //console.log("user_layout_stack")4229 }4230 else4231 {4232 idx = $('#canvas').data("layout_stack_idx");4233 stack = $('#canvas').data("layout_stack");4234 //console.log("layout_stack")4235 }4236 4237 4238 if ((stack.length>0) && (getLayoutDiff(stack[stack.length-1][0],new_layout)<1))4239 {4240 //console.log("duplicate layout, not added to stack")4241 return; 4242 }4243 4244 4245 //console.log("pre stack length:"+stack.length)4246 //stack.push([new_layout, getCurrentDesign()])4247 4248 if (idx != stack.length - 1)4249 {4250 //console.log("slicing stack from 0 to "+(idx+1))4251 stack = stack.slice(0, idx+1);4252 4253 }4254 4255 4256 4257 if (stack_type=='user')4258 {4259 var elem_info=[]4260 $.each($('#canvas').data("design").elements, function(i, elem) {4261 elem_info.push({'fixed_amount':elem.fixed_amount,'selected':elem.selected })4262 });4263 stack.push([new_layout, elem_info])4264 4265 $('#canvas').data("user_layout_stack_idx", stack.length - 1)4266 $('#canvas').data("user_layout_stack", stack)4267 }4268 else4269 {4270 4271 console.log("new idx:"+(stack.length - 1))4272 stack.push([new_layout, undefined])4273 4274 $('#canvas').data("layout_stack_idx", stack.length - 1)4275 $('#canvas').data("layout_stack", stack)4276 }4277 if (stack.length > 1)4278 {4279 if (stack_type=='user')4280 $('#reportUndoButton').fadeTo(0, 1)4281 else 4282 $('#undoButton').fadeTo(0, 1)4283 }4284 4285}4286function setCurrentLayout(new_layout, set_fixed, undoing,render_info,playback) {4287 if (undoing==undefined)4288 undoing=false4289 4290 console.log("setCurrentLayout")4291 4292 if (new_layout==undefined)4293 {4294 console.log("ERROR. layout undefined.")4295 return4296 }4297 if (((set_fixed == false)) || ($('#canvas').data("dragging")))4298 return4299 var design = $('#canvas').data("design")4300 var layout = $('#canvas').data("layout");4301 var alignments = ["left", "center", "right"];4302 if (layout != new_layout) {4303 if (!undoing) {4304 addLayoutToStack(new_layout)4305 }4306 //console.log("setting new layout")4307 console.log("setting current layout:" + new_layout)4308 4309 var idx=new_layout.indexOf("design_")4310 //console.log("idx:"+idx)4311 if (idx==0)4312 new_layout='0\n'+new_layout4313 //console.log("here")4314 var elements = new_layout.split("\n");4315 var elem_cnt = parseInt(elements[3])4316 //console.log("elem_cnt "+elem_cnt+" design.elements.length "+design.elements.length)4317 if (elem_cnt != design.elements.length)4318 return;4319 4320 4321 var design_sizes = elements[2].split(",")4322 var layout_width=parseInt(design_sizes[0])4323 var layout_height=parseInt(design_sizes[1])4324 4325 if ((layout_width!= design.width) || (layout_height!=design.height))4326 {4327 console.log("layout_width:"+ layout_width)4328 console.log("layout_height:"+ layout_height)4329 console.log("design.width:"+ design.width)4330 console.log("design.height:"+ design.height)4331 return;4332 }4333 4334 if (undoing)4335 $('#canvas').data("layout_log").push(['user-Undo/Redo',new Date().getTime(),new_layout,";"])4336 else4337 $('#canvas').data("layout_log").push(['sugg',new Date().getTime(),new_layout,";"])4338 var layer = $('#canvas').data("stage").get('#layer')[0];4339 //layer.removeChildren()4340 4341 var fixed_count=0;4342 for (var i = 0; i < design.elements.length; i++) {4343 //console.log("design.elements.length: "+design.elements.length)4344 var elem = design.elements[i];4345 //console.log("elem id: "+elem.id+" selected?"+elem.selected)4346 4347 if (elem.fixed_amount==1)4348 fixed_count+=1;4349 4350 4351 //console.log("elem id: "+elem.id+" selected?"+elem.selected+ " fix_amount:"+fixed_count)4352 var elem_split = elements[i+4].split(',');4353 if (elem.img == undefined)4354 console.log("ERROR on element " + i + " with layout " + elements[i])4355 4356 var new_height = parseInt(elem_split[2]);4357 var new_x = parseInt(elem_split[0])4358 var new_y = parseInt(elem_split[1])4359 var new_alt_id = parseInt(elem_split[6]);4360 var new_align_id=parseInt(elem_split[3])4361 4362 4363 //elem.img.attrs.strokeEnabled=false4364 4365 if (elem.selected){4366 4367 4368 fixed_count+=1;4369 //continue4370 4371 var str= sprintf("checking selected %f %f %f %f %f, %f %f %f %f %f",elem.x,elem.y,elem.height,elem.alternate_id, elem.align_type, new_x,new_y, new_height, new_alt_id, new_align_id )4372 4373 console.log(str)4374 4375 if ((elem.type=='graphic') || (Math.round(elem.height)!=new_height) || (Math.round(elem.x)!=new_x) || (Math.round(elem.y)!=new_y) || (new_alt_id!= elem.alternate_id) || (new_align_id ==elem.align_type))4376 {4377 elem.img.attrs.strokeEnabled=false//true4378 continue4379 }4380 4381 //console.log("updating selected to new align type "+String(new_align_id)+" from type "+String(elem.align_type))4382 }4383 4384 if ((!elem.fix_alternate) && (elem.id in design.element_alts)) {4385 $.each(design.element_alts[elem.id], function(num_lines, ae) {4386 ae.img.remove()4387 //fadeOutImage(ae.img)4388 if ((new_alt_id == ae.alternate_id)) {4389 4390 4391 var last_img=elem.img;4392 last_img.remove()4393 //fadeOutImage(last_img)4394 4395 ae.fixed_amount = elem.fixed_amount4396 ae.state_img = elem.state_img4397 design.elements[i] = ae4398 4399 ae.selected=elem.selected4400 //ae.img.attrs.strokeEnabled = false;4401 ae.img.show()4402 ae.img.setPosition(last_img.getPosition())4403 4404 if (new_alt_id!= elem.alternate_id)4405 ae.img.setOpacity(0)4406 4407 layer.add(ae.img)4408 4409 elem = ae;4410 }4411 });4412 }4413 4414 4415 4416 4417 4418 4419 var new_width = new_height * elem.aspect_ratio;4420 elem.height = new_height4421 elem.width = new_width4422 elem.x = new_x4423 elem.y = new_y4424 4425 //elem.state_img.show()4426 4427 4428 4429 if (undoing)4430 {4431 setElementState(elem.id,'unlocked')4432 elem.state_img.hide()4433 }4434 4435 4436 if ((render_info!= undefined) || (playback!=undefined)){4437 4438 4439 4440 if (render_info!= undefined)4441 {4442 fix_amount = render_info[i].fixed_amount4443 selected = render_info[i].selected4444 }4445 else4446 {4447 fix_amount=parseFloat(elem_split[4]);4448 selected= ((fix_amount==0.95) || (fix_amount==1.05))4449 4450 console.log("fix_amount:"+fix_amount)4451 console.log("selected:"+selected)4452 }4453 4454 elem.img.attrs.strokeEnabled=false//selected4455 4456 elem.state_img.hide()4457 4458 if (fix_amount<0.5)4459 elem.state_img=elem.unlock_img4460 else if (fix_amount<1.0)4461 elem.state_img=elem.tweakable_img4462 else4463 elem.state_img=elem.lock_img4464 4465 elem.state_img.setPosition(elem.x + elem.width, elem.y) 4466 4467 elem.state_img.show()4468 4469 }4470 if (elem.num_lines > 1) {4471 elem.align_type = new_align_id4472 var align;4473 if (new_align_id > -1)4474 align = alignments[new_align_id]4475 else4476 align = elem.align4477 if (elem.img != elem.alignment_imgs[align]) {4478 var layer = elem.img.getLayer();4479 4480 var last_img=elem.img4481 4482 4483 elem.state_img.setPosition(last_img.attrs.x + last_img.getWidth(), last_img.attrs.y) 4484 4485 elem.align = align;4486 elem.img = elem.alignment_imgs[align];4487 //elem.img.attrs.strokeEnabled=elem.selected4488 elem.img.setHeight(last_img.getHeight())4489 elem.img.setWidth(last_img.getWidth())4490 elem.img.setPosition(last_img.getPosition())4491 elem.img.setOpacity(0)4492 elem.img.show()4493 layer.add(elem.img);4494 4495 4496 fadeOutImage(last_img,undoing)4497 }4498 }4499 4500 //else4501 //if (playback==undefined)4502 // elem.img.attrs.strokeEnabled=false4503 if ((elem.selected) && $('#canvas').data("automaticUpdate"))4504 {4505 elem.img.attrs.strokeEnabled=true4506 console.log("drawing selected")4507 } 4508 fadeInElement(elem,undoing)4509 setHidden(elem, new_alt_id < 0)4510 4511 elem.region_id = parseInt(elem_split[5])4512 4513 4514 }4515 //set regions4516 design.regions = []4517 for (var i = elem_cnt + 4; i < elements.length; i++) {4518 var reg = elements[i].split(",")4519 if (reg.length < 6)4520 continue;4521 $.each(reg, function(i, r) {4522 reg[i] = parseInt(r)4523 })4524 var region = createNewRegion(reg[1], reg[2], reg[3], reg[4], reg[0] == 2, reg[0] == 1, false)4525 console.log('region. ' + elements[i] + ' x ' + region.x + ' y ' + region.y + ' w ' + region.width + ' h ' + region.height + ' ' + region.allow_text + ' ')4526 design.regions.push(region);4527 }4528 console.log("finished setting new layout")4529 4530 4531 if (fixed_count<design.elements.length)4532 $('#canvas').data("status_log").push("U"+(design.elements.length-fixed_count))4533 $('#canvas').data("layout", new_layout);4534 }4535 design.elements[0].img.getLayer().draw();4536 //double check each element is correct4537 $.each(design.elements, function(i, e) {4538 if ((e.img.getStage() == undefined) || (e.img.getLayer() == undefined)) {4539 console.log("error for element " + e.id)4540 console.log("stage: ")4541 console.log(e.img.getStage())4542 console.log("layer: ")4543 console.log(e.img.getLayer())4544 console.log("new_layout:")4545 console.log(new_layout)4546 $('#suggestion_status').text("stage undefined");4547 }4548 });4549}4550function fadeInElement(elem,undoing)4551{4552 4553 var time=0.34554 if (undoing)4555 time=0.24556 //var visible=elem.state_img.isVisible()4557 if (elem.state_img.isVisible())4558 {4559 var tween = new Kinetic.Tween({4560 node:elem.state_img,4561 duration:time, 4562 opacity:1,4563 x:(elem.x + elem.width),4564 y:elem.y,4565 });4566 tween.play()4567 }4568 else4569 elem.state_img.setPosition(elem.x + elem.width, elem.y)4570 4571 elem.img.attrs.draggable=false4572 var tween = new Kinetic.Tween({4573 node:elem.img,4574 duration:time,4575 opacity:1,4576 x:elem.x,4577 y:elem.y,4578 height:elem.height,4579 width:elem.width,4580 easing:Kinetic.Easings.Linear,4581 onFinish: function(element){4582 elem.img.attrs.draggable=true4583 moveAnchors(elem) 4584 }4585 4586 })4587 tween.play()4588}4589function fadeOutImage(img,undoing)4590{4591 /*4592 console.log("fadeout img")4593 console.log(img) 4594 console.log(img.getLayer())4595 if ((img==undefined)||(img.getLayer()==undefined))4596 return4597 */4598 var time=0.34599 if (undoing)4600 time=0.24601 var tween = new Kinetic.Tween({4602 node:img,4603 duration:time, 4604 opacity:0,4605 onFinish: function(){4606 //console.log(img)4607 if (img!=undefined)4608 img.remove()4609 }4610 });4611 tween.play()4612 4613 4614}4615function setHidden(elem, state) {4616 elem.hidden = state4617 if (state) {4618 if (elem.hidden_img == 0) {4619 elem.hidden_img = elem.img.getImage()4620 elem.img.setImage(0)4621 }4622 } else {4623 if (elem.hidden_img != 0) {4624 elem.img.setImage(elem.hidden_img)4625 elem.hidden_img = 04626 }4627 }4628}4629function loadImages(sources, callback) {4630 4631 if ($('#canvas').data("loadedImages"))4632 return4633 4634 $('#canvas').data("loadedImages",true)4635 console.log("loading images")4636 var images = {};4637 var loadedImages = 0;4638 var numImages = 0;4639 for (var src in sources) {4640 numImages++;4641 }4642 for (var src in sources) {4643 console.log("loading image " + sources[src])4644 images[src] = new Image();4645 images[src].onload = function() {4646 if (++loadedImages >= numImages) {4647 $('#canvas').data("images", images);4648 callback();4649 }4650 };4651 images[src].src = sources[src];4652 }4653}4654function loadDesignFile(designName) {4655 $('#canvas').data("images_rendering",-1)4656 4657 console.log("loading design " + designName)4658 var jsonLoad = $.getJSON(sprintf('/design/static/designs/%s.json', designName), function(design) {4659 console.log('design.json obtained');4660 var idx=designName.indexOf('new')4661 if (idx>-1) {4662 design.name = "design_" + String(new Date().getTime());4663 console.log("Created design " + design.name)4664 }4665 4666 idx=designName.lastIndexOf('/')4667 4668 if (idx>-1)4669 {4670 var design_dir=designName.substring(0,idx+1)4671 var name=designName.substring(idx+1,designName.length)4672 4673 4674 console.log("design dir: "+design_dir)4675 console.log("design name: "+name)4676 4677 design.directory=design_dir;4678 design.name=name; 4679 4680 }4681 design.elements.sort(function(e1, e2) {4682 return e2.importance - e1.importance4683 })4684 $('#canvas').data("design", design);4685 sources = {};4686 sources['unlocked'] = '/design/static/icons/unlocked.png'4687 sources['tweakable'] = '/design/static/icons/tweakable.png'4688 sources['locked'] = '/design/static/icons/locked.png'4689 4690 sources['accept_suggestion'] = '/design/static/img/select_suggestion.png'4691 if (design.background_fname.length > 1)4692 sources['background'] = sprintf('/design/static/images/%s', design.background_fname);4693 font_list=[]4694 $.each(design.elements, function(i, elem) {4695 if ("fname" in elem) {4696 console.log("elem.fname " + elem.fname)4697 sources[elem.fname] = sprintf('/design/static/images/%s', elem.fname);4698 }4699 else{4700 if ($.inArray(elem.font,font_list)==-1)4701 {4702 $('#updateText').css("font-family",elem.font)4703 4704 var fdiv=$('#initFont').clone()4705 fdiv.css("font-family",elem.font)4706 fdiv.attr("id",elem.font)4707 $('#initFont').parent().append(fdiv)4708 font_list.push(elem.font)4709 }4710 4711 }4712 4713 });4714 4715 console.log("loading fonts "+String(font_list))4716 4717 $('#canvas').data("loadedImages",false)4718 4719 4720 var callback = function(){loadImages(sources, setupCanvas);}4721 4722 if (font_list.length>0)4723 waitForWebfonts(font_list,callback)4724 else4725 callback()4726 //loadImages(sources, setupCanvas);4727 4728 }).done(function() {4729 console.log('success');4730 }).fail(function() {4731 console.error('JSON load failure.');4732 });4733}4734function selectImage(type) {4735 console.log("selectImage")4736 deselectAll()4737 $('#canvas').data('inputType', type)4738 $('#fileInput').click();4739}4740function handleFiles(files) {4741 console.log("handling files " + files);4742 var file = files[0];4743 var reader = new FileReader();4744 reader.onload = onFileReadComplete;4745 reader.readAsDataURL(file);4746 4747 $("#canvas").data("load_filename", file.name)4748}4749function onFileReadComplete(event) {4750 console.log(event.target.result)4751 var img = new Image();4752 var fname = "graphic_" + String(new Date().getTime()) + ".png";4753 var fname = $("#canvas").data("load_filename");4754 img.onload = function() {4755 if ($('#canvas').data('inputType') == 'graphic')4756 createNewElement('graphic', img, fname)4757 else {4758 var background = $('#canvas').data('design').background;4759 background.attrs.fillPatternImage = img4760 background.attrs.fill = undefined4761 $("#canvas").data("design").background_fname = fname;4762 background.getLayer().draw()4763 background = $('#canvas').data('design').sugg_background;4764 background.attrs.fillPatternImage = img4765 background.attrs.fill = undefined4766 background.getLayer().draw()4767 }4768 };4769 img.src = event.target.result4770 saveImageOnServer(fname, event.target.result)4771}4772function backgroundOffsetChanged() {4773 console.log("backgroundOffsetChanged")4774 var design=$('#canvas').data("design");4775 if (design.background_fname != ''){4776 4777 var offset_x=parseInt($('#background_offset_x').val())4778 var offset_y=parseInt($('#background_offset_y').val())4779 4780 var pos = design.background_elem.img.getPosition();4781 4782 design.background_elem.offset_x=offset_x4783 design.background_elem.offset_y=offset_y4784 4785 design.background_elem.img.attrs.fillPatternOffsetX=offset_x4786 design.background_elem.img.attrs.fillPatternOffsetY=offset_y4787 4788 design.background_elem.img.getLayer().draw() 4789 }4790}4791function backgroundColorChanged() {4792 console.log("backgroundColorChanged")4793 var background = $('#canvas').data('design').background;4794 background.attrs.fillPatternImage = ''4795 background.attrs.fill = $('#background_color_select').val();4796 $("#canvas").data("design").background_fname = '';4797 $('#canvas').data('design').background_color = $('#background_color_select').val();4798 background.getLayer().draw()4799 background = $('#canvas').data('design').sugg_background;4800 background.attrs.fillPatternImage = ''4801 background.attrs.fill = $('#background_color_select').val();4802 background.getLayer().draw()4803 4804 4805 4806 setupSelectRectangle($('#canvas').data('design'),$('#canvas').data("stage").get('#layer')[0])4807 4808 4809}4810function setupSliders() {4811 $('#whitespace_slider').slider({4812 min : 0,4813 step : 1,4814 max : 100,4815 value : 50,4816 change : function(event, ui) {4817 updateParameters('whitespace', ui.value);4818 }4819 });4820 $('#text_size_slider').slider({4821 min : 0,4822 step : 1,4823 max : 100,4824 value : 50,4825 change : function(event, ui) {4826 updateParameters('text_size', ui.value);4827 }4828 });4829 $('#graphic_size_slider').slider({4830 min : 0,4831 step : 1,4832 max : 100,4833 value : 50,4834 change : function(event, ui) {4835 updateParameters('graphic_size', ui.value);4836 }4837 });4838 $('#symmetry_slider').slider({4839 min : 0,4840 step : 1,4841 max : 100,4842 value : 50,4843 change : function(event, ui) {4844 updateParameters('symmetry', ui.value);4845 }4846 });4847}4848function createNewDesign() {4849 window.location.replace("/design/create&design=new")4850}4851function openExistingDesign() {4852 window.location.replace("/design/select/"+$('#canvas').data("design").directory)4853}4854function duplicateDesign() {4855 $('#canvas').data("design").name = "design_" + String(new Date().getTime());4856 saveDesign()4857 alert("Design duplicated")4858 startSuggestions()4859}4860function deleteDesign() {4861 if (confirm("Warning! This will permanentely delete this design and send you back to the selection menu. Are you sure you want to delete this design?")) {4862 deleteDesignOnServer($('#canvas').data("design"))4863 }4864}4865function startSuggestions(run_offset) {4866 if (run_offset == undefined)4867 {4868 run_offset = 04869 if (gup("run_offset")!='')4870 run_offset=parseInt(gup("run_offset"))4871 }4872 4873 console.log("Starting suggestions")4874 if ($('#canvas').data("design").elements.length <= 1) {4875 console.log("Not enough elements")4876 //return4877 }4878 $('#canvas').data("status_log").push("Start")4879 $('#canvas').data('killed', false)4880 $('#canvas').data('paused', false)4881 $('#restartButton').hide()4882 $('#suggestion_status').text("")4883 var design_string = getCurrentDesign();4884 var layout_counter=$('#canvas').data("layout_counter")4885 if (layout_counter==undefined)4886 layout_counter=0;4887 $('#canvas').data("layout_counter",layout_counter+1)4888 4889 design_string=layout_counter+"\n"+design_string4890 4891 $('#design_out').val(design_string);4892 var runs = [];4893 var run_id = -1;4894 //var run_types;4895 //var run_types=['near','mid','far','gallery']4896 4897 4898 //var run_types=['near','mid','far','gallery']4899 4900 if ($('#canvas').data("automaticUpdate"))4901 run_types=['autoupdate','gallery']4902 else4903 run_types=['near']4904 if (getURLParameter("brainstorm") == 1){4905 run_types=['gallery']4906 console.log("do gallery suggestions")4907 }4908 if (getURLParameter("nio") == 1)4909 run_types=['nio']4910 4911 var run_dict={}4912 for (var i = 0; i < run_types.length; i++) {4913 run = {}4914 //run.id=Math.floor(Math.random()*65000);4915 run.id = i + run_offset4916 run.canvas_id = i4917 run.image = new Image()4918 run.type = run_types[i]4919 run.layout = ''4920 run.energy = 99999994921 run.converged=false4922 //stopRun(run.id, run_types[i]);4923 4924 runs.push(run)4925 4926 run_dict[run.id]=run4927 if ('gallery' == run_types[i])4928 $('#gallery_layout0').data("run_idx", i)4929 else4930 $('#suggestion_layout' + String(run.canvas_id)).data("run_idx", i)4931 4932 }4933 $('#canvas').data("runs", run_dict)4934 4935 sendRun(0,runs,design_string)4936 4937 4938}4939function sendRun(i,runs,design_string)4940{4941 if (i>=runs.length)4942 return4943 startNewRun(runs[i].id, runs[i].type, design_string)4944 setTimeout(function(){sendCurrentLayout( 'start', false,runs[i].id); sendRun(i+1,runs, design_string)}, 1000);4945}4946 4947function startText() {4948 console.log("adding new text. deselecting")4949 deselectAll()4950 var layer = $('#canvas').data("stage").get('#layer')[0];4951 layer.draw()4952 $('#user_text').val('')4953 //if ($('#canvas').data("text_mode") == false) {4954 document.body.style.cursor = "url('/design/static/img/text_cursor2.png'), auto"4955 $('#canvas').data("text_mode", true)4956 showElementControls()4957 //} else {4958 // document.body.style.cursor = "default";4959 // $('#canvas').data("text_mode", false)4960 //}4961}4962function createRegion() {4963 var region = createNewRegion(0, 0, 100, 100, $("#region_graphic_select").attr("checked") == 'checked', $("#region_text_select").attr("checked") == 'checked', $("#region_overlap_select").attr("checked") == 'checked')4964 $('#canvas').data("design").regions.push(region)4965 toggleRegionMode()4966 toggleRegionMode()4967 deselectAll(region)4968 region.img.getLayer().draw()4969}4970function regionProposalChanged() {4971 var design = $('#canvas').data("design");4972 design.region_proposals = $("#region_proposal_select").attr("checked") == 'checked';4973 sendCurrentLayout();4974}4975function testSendLayout(num) {4976 $('#canvas').data("sendLayoutToServerTimes", [])4977 for (var i = 0; i < num; i++) {4978 sendCurrentLayout()4979 }4980}4981function toggleInvert() {4982 $('#canvas').data("invert", $("#invert_select").attr("checked") == 'checked')4983 /*4984 $.each($('#canvas').data("design").elements, function(i,elem){4985 var filt=04986 if ($('#canvas').data("invert"))4987 filt=Kinetic.Filters.Invert4988 elem.lock_img.attrs.filter=filt4989 elem.tweakable_img.attrs.filter=filt4990 elem.unlock_img.attrs.filter=filt4991 elem.state_img.attrs.filter=filt4992 });4993 */4994 $('#canvas').data("stage").get('#layer')[0].draw()4995}4996function validateFormResults() {4997 var saved_canvases = $("#saved_table").find("canvas")4998 console.log("saved_canvases.length:" + saved_canvases.length)4999 var min_layouts = gup('numLayouts')5000 if ((min_layouts != '') && (saved_canvases.length - 1 < parseInt(min_layouts)))5001 alert("You must create (and save) at least " + min_layouts + " layouts.")5002 else {5003 $("#final_design").val(getCurrentDesign())5004 $.each(saved_canvases, function(i, saved_img) {5005 var saved_layout = $(saved_img).data("layout")5006 var new_inp = $('<input>')5007 new_inp.attr("type", "hidden")5008 new_inp.attr("id", "saved_layout" + i)5009 new_inp.attr("name", "saved_layout" + i)5010 new_inp.val(saved_layout)5011 $("#final_layouts").append(new_inp)5012 });5013 //$("#studySubmit").click()5014 }5015}5016function setSuggestionIndex(shift) {5017 var idx = $('#canvas').data("layout_stack_idx")5018 var stack = $('#canvas').data("layout_stack")5019 console.log("setSuggestionIndex idx: " + idx + " shift: " + shift + " stack.len: " + stack.length)5020 if ((idx + shift < 0) || (idx + shift > stack.length - 1))5021 return5022 if (shift == -1) {5023 $('#canvas').data("user_input_log").push("Undo")5024 $('#canvas').data("status_log").push("Undo")5025 } else if (shift == 1) {5026 $('#canvas').data("user_input_log").push("Redo")5027 $('#canvas').data("status_log").push("Redo")5028 }5029 deselectAll()5030 //pauseSuggestions()5031 setCurrentLayout(stack[idx+shift][0], true, true)5032 if ((idx + shift) == 0)5033 $('#undoButton').fadeTo(0, 0.4)5034 else5035 $('#undoButton').fadeTo(0, 1)5036 if ((idx + shift) == stack.length - 1)5037 $('#redoButton').fadeTo(0, 0.4)5038 else5039 $('#redoButton').fadeTo(0, 1)5040 $('#canvas').data("layout_stack_idx", idx + shift)5041}5042function setUserLayoutIndex(shift) {5043 var idx = $('#canvas').data("user_layout_stack_idx")5044 var stack = $('#canvas').data("user_layout_stack")5045 console.log("setUserLayoutIndex idx: " + idx + " shift: " + shift + " stack.len: " + stack.length)5046 if ((idx + shift < 0) || (idx + shift > stack.length - 1))5047 return5048 deselectAll()5049 5050 setReportBeforeImage(stack[idx+shift])5051 if ((idx + shift) == 0)5052 $('#reportUndoButton').fadeTo(0, 0.4)5053 else5054 $('#reportUndoButton').fadeTo(0, 1)5055 if ((idx + shift) == stack.length - 1)5056 $('#reportRedoButton').fadeTo(0, 0.4)5057 else5058 $('#reportRedoButton').fadeTo(0, 1)5059 $('#canvas').data("user_layout_stack_idx", idx + shift)5060}5061function plotEnergy(sugg_energy, user_energy) {5062 var curr_energy = $('#canvas').data("energy")5063 if (curr_energy == 0)5064 return;5065 var plot_energy = $('#canvas').data("plot_energy_list")5066 plot_energy.push([user_energy, sugg_energy])5067 var data1 = [];5068 var data2 = [];5069 for (var i = Math.max(0, plot_energy.length - 25); i < plot_energy.length; i++) {5070 data1.push([i, plot_energy[i][0]]);5071 data2.push([i, plot_energy[i][1]]);5072 }5073 $.plot("#energy_plot", [data1, data2], {5074 series : {5075 shadowSize : 0 // Drawing is faster without shadows5076 },5077 xaxis : {5078 show : false5079 }5080 });5081}5082function fontSizeChanged(new_size)5083{5084 5085 var elem=$('#canvas').data("selected")5086 if (elem.type=="text")5087 {5088 5089 $('#canvas').data("user_input_log").push("Scale-Dropdown")5090 $('#canvas').data("status_log").push("Scale-Dropdown")5091 5092 5093 console.log('user field:'+$('#fontSizeInput'))5094 if (new_size==undefined)5095 new_size=parseFloat($('#fontSizeInput').val())5096 else5097 $('#fontSizeInput').val(new_size)5098 5099 console.log('new size:'+new_size)5100 elem.height=(new_size/elem.init_font_size)*elem.init_height5101 elem.width=elem.height*elem.aspect_ratio5102 5103 console.log('setting new height:'+elem.height)5104 5105 elem.img.setHeight(elem.height)5106 elem.img.setWidth(elem.width)5107 5108 moveAnchors(elem)5109 elem.state_img.setPosition(elem.x + elem.width, elem.y)5110 drawAlignmentLines(elem, 'dragging')5111 elem.img.getLayer().draw()5112 5113 }5114 5115 5116}5117function initializeReport(positive)5118{5119 5120 5121 5122 if (positive)5123 $('#reportInstructions').text("Please describe what you liked about the update (optional)")5124 else5125 $('#reportInstructions').text("Please describe the problem. What was the expected behaviour? What was wrong with the automatic update?")5126 5127 5128 5129 5130 5131 $('#report').show()5132 $('#reportStatus').text("")5133 $('#report').data("running",$('#canvas').data("started"))5134 $('#report').data("positive",positive)5135 5136 5137 5138 $('#report').data("afterLayout",getCurrentLayout())5139 5140 stopSuggestionsUntilUserInput()5141 5142 5143 var stage=$('#canvas').data("stage")5144 5145 $.each($('#canvas').data("design").elements, function(i, elem) {5146 elem.state_img.show();5147 });5148 5149 5150 stage.get('#layer')[0].draw();5151 5152 stage.toDataURL({5153 callback : function(dataUrl) {5154 var img = new Image();5155 img.onload = function() {5156 5157 $('#report_after_img').attr("width",stage.attrs.width / 2)5158 $('#report_after_img').attr("height",stage.attrs.height / 2)5159 $('#report_after_img').attr("src",dataUrl)5160 }5161 img.src = dataUrl;5162 }5163 });5164 5165 var stack = $('#canvas').data("user_layout_stack")5166 5167 if (stack.length==0)5168 return5169 5170 5171 setReportBeforeImage( stack[stack.length-1])5172 5173 5174 5175 5176 $('#canvas').data("sugg_stage").toDataURL({5177 callback : function(dataUrl) {5178 var img = new Image();5179 img.onload = function() {5180 $('#report_sugg_img').attr("width",stage.attrs.width / 2)5181 $('#report_sugg_img').attr("height",stage.attrs.height / 2)5182 $('#report_sugg_img').attr("src",dataUrl)5183 }5184 img.src = dataUrl;5185 }5186 });5187 5188 5189}5190function setReportBeforeImage(layout_info)5191{5192 5193 var layout=layout_info[0] 5194 var curr_layout=getCurrentLayout()5195 5196 $('#report').data("beforeLayout",layout)5197 5198 5199 deselectAll()5200 5201 setCurrentLayout(layout,true,true,layout_info[1]) 5202 5203 var stage=$('#canvas').data("stage")5204 stage.toDataURL({5205 callback : function(dataUrl) {5206 var img = new Image();5207 img.onload = function() {5208 $('#report_before_img').attr("width",stage.attrs.width / 2)5209 $('#report_before_img').attr("height",stage.attrs.height / 2)5210 $('#report_before_img').attr("src",dataUrl)5211 }5212 img.src = dataUrl;5213 }5214 });5215 5216 setCurrentLayout(curr_layout,true,true) 5217 5218 $.each($('#canvas').data("design").elements, function(i, elem) {5219 elem.state_img.hide();5220 });5221 stage.get('#layer')[0].draw();5222 5223}5224function cancelReport()5225{5226 5227 $('#report').hide()5228 5229 $('#reportStatus').text("")5230 $('#reportText').val('')5231}5232function submitReport()5233{5234 5235 // 5236 if (($('#reportText').val()=='')&& (!$('#report').data("positive")))5237 {5238 alert("You must provide some explanation for your response")5239 return;5240 }5241 5242 5243 if ($('#report').data("positive"))5244 $('#numLikes').text(parseInt($('#numLikes').text())+1)5245 else5246 $('#numDislikes').text(parseInt($('#numDislikes').text())+1)5247 5248 $('#report').hide()5249 5250 $('#reportStatus').text("Response Submitted")5251 5252 var report={}5253 5254 report['text']=$('#reportText').val()5255 report['workerId']=gup('workerId')5256 report['hitId']=gup('hitId')5257 report['assignmentId']=gup('assignmentId')5258 report['userId']=$('input[name=userID]').val()5259 report['design']=$('#canvas').data("design").name5260 report['date']=String(new Date())5261 report['errorMessage']=$('#error_message').text()5262 report['optimizerRunning']=$('#report').data("running")5263 report['afterLayout']=$('#report').data("afterLayout")5264 report['beforeLayout']=$('#report').data("beforeLayout")5265 report['positive']=$('#report').data("positive")5266 5267 5268 report['userLayoutFeatures']=$('#userLayoutFeatures').val()5269 report['suggestionLayoutFeatures']=$('#suggLayoutFeatures').val()5270 5271 var report_name=report['design']+ "-"+String(new Date().getTime());5272 5273 saveReportOnServer(report_name, $('#report_before_img').attr("src"), $('#report_after_img').attr("src"), $('#report_sugg_img').attr("src"),report)5274 5275 5276 if ($('#report').data("names")==undefined)5277 $('#report').data("names",[])5278 5279 $('#report').data("names").push([$('#report').data("positive"),report_name])5280 5281 $('#reportText').val('')5282}5283function startStudy()5284{5285 5286 $('#canvas').data("layoutStartTime", new Date())5287 5288 var sequence=$('#canvas').data("design_sequence")5289 5290 $('#startStudyButton').hide()5291 $('#nextDesignButton').show()5292 5293 $('#canvas').data("sequence_index",0)5294 loadDesignFile(design_sequence[0].design)5295 5296 5297 if ($('#canvas').data("suggestionsEnabled"))5298 $('.suggestions').show()5299 5300 5301 if($('#canvas').data("automaticUpdate"))5302 $('#suggestion_td').hide()5303 5304 5305 5306 if ($('#canvas').data("sequence_type")=="retarget")5307 {5308 executeAfterTextRendering(function(){5309 setMatchDesign(design_sequence[0].match_design);5310 setupRetargetting();5311 resetLayout()})5312 }5313}5314function moveToNextDesign()5315{5316 5317 console.log("moveToNextDesign")5318 var curr_design_idx=$('#canvas').data("sequence_index")5319 var sequence=$('#canvas').data("design_sequence")5320 5321 var curr_design=sequence[curr_design_idx].design5322 5323 if ($('#canvas').data("loading"))5324 return5325 else5326 $('#canvas').data("loading",true)5327 5328 //$("#layout"+curr_design_idx).val(getCurrentLayout())5329 $("#layout"+curr_design_idx).val(getCurrentLayout())5330 5331 var last_time=$('#canvas').data("designTime") 5332 if (last_time==undefined)5333 last_time=$('#canvas').data("layoutStartTime") 5334 5335 console.log($('#canvas').data("designTime"))5336 5337 var curr_time=new Date()5338 5339 if ($('#layoutTimes').data('times')==undefined)5340 $('#layoutTimes').data('times',[curr_time-last_time])5341 else5342 $('#layoutTimes').data('times').push(curr_time-last_time)5343 5344 console.log(curr_time-last_time)5345 5346 5347 $('#layoutTimes').val(String($('#layoutTimes').data('times')))5348 $('#canvas').data("designTime",curr_time)5349 5350 $("#layout_input"+curr_design_idx).val($('#canvas').data("user_input_log"))5351 $("#layout_log"+curr_design_idx).val($('#canvas').data("layout_log"))5352 5353 5354 $('#studyOrder').val(String(sequence))5355 5356 5357 $.each($('#canvas').data("design").elements, function(i, elem) {5358 elem.state_img.hide();5359 //elem.img.attrs.strokeEnabled=false5360 $.each(elem.anchors, function(i, a) {5361 a.hide();5362 });5363 });5364 $.each($('#canvas').data("align_lines"), function(i, al) {5365 al[0].destroy()5366 });5367 //$('#canvas').data("stage").get('#layer')[0].draw()5368 5369 $('#canvas').data("stage").toDataURL({5370 callback : function(dataUrl) {5371 var img = new Image();5372 img.onload = function() {5373 5374 5375 $('#canvas').data("layout_stack", [])5376 $('#canvas').data("layout_stack_idx", -1)5377 $('#undoButton').fadeTo(0, 0.4)5378 $('#redoButton').fadeTo(0, 0.4)5379 5380 var hit_id = gup('hitId')5381 var fname = 'layouts/' + $('#canvas').data("design").name + '-' + gup('workerId') + "-" + hit_id + "-" + String(curr_design_idx) + '.png'5382 saveImageOnServer(fname, dataUrl)5383 5384 5385 $('#canvas').data("sequence_index",curr_design_idx+1) 5386 5387 var next_design=sequence[curr_design_idx+1].design5388 5389 5390 if (next_design!=curr_design) 5391 {5392 deleteGallery()5393 }5394 5395 5396 5397 if (next_design.indexOf("direct")>-1)5398 $('#canvas').data("suggestionsEnabled",false)5399 if (next_design.indexOf("sugg")>-1)5400 $('#canvas').data("suggestionsEnabled",true)5401 5402 var next_str=""5403 5404 if (next_design.indexOf("tut")>-1)5405 next_str+="Tutorial-"5406 else5407 next_str+="Normal-"5408 5409 5410 5411 5412 if ($('#canvas').data("suggestionsEnabled"))5413 {5414 5415 next_str+="Suggestions"5416 5417 $('.suggestions').show()5418 5419 if($('#canvas').data("automaticUpdate"))5420 {5421 $('#suggestion_td').hide()5422 $('#interface').data("interface").push('adaptive') 5423 }5424 else5425 $('#interface').data("interface").push('suggestions')5426 }5427 else5428 {5429 $('#interface').data("interface").push('baseline')5430 next_str+="Baseline" 5431 5432 $('.suggestions').hide()5433 stopSuggestionsUntilUserInput() 5434 }5435 5436 5437 $('#canvas').data("user_input_log",[next_str])5438 $('#canvas').data("status_log").push(next_str)5439 $('#canvas').data("layout_log",[next_str,new Date().getTime(),''])5440 5441 5442 5443 5444 5445 loadDesignFile(next_design)5446 5447 5448 if ("match_design" in sequence[curr_design_idx+1])5449 setMatchDesign(sequence[curr_design_idx+1].match_design)5450 5451 5452 executeAfterTextRendering(5453 function(){5454 $('#canvas').data("loading",false)5455 5456 if (gup("retarget")!='')5457 setupRetargetting();5458 5459 resetLayout();5460 5461 });5462 5463 5464 5465 }5466 img.src = dataUrl;5467 }5468 }); 5469 5470 if (curr_design_idx+1==sequence.length)5471 {5472 $('#nextDesignButton').hide()5473 5474 $('.mturkQuestionnaire').show()5475 5476 $('#canvas').hide()5477 5478 $('#mainTable').hide()5479 5480 $('#study_status').text("HIT complete. Please submit after providing suggestions/comments.")5481 $('#study_status').css("background-color",'#5F5')5482 $('#study_status').show()5483 5484 return5485 }5486 5487 5488 5489}5490function setMatchDesign(match_design)5491{5492 var stage=$('#canvas').data("stage")5493 console.log("setMatchDesign")5494 $('#retarget_img').css("width",stage.attrs.width / 2)5495 $('#retarget_img').css("height",stage.attrs.height / 2)5496 $('#retarget_img').attr("src","/design/static/designs/"+match_design+".png")5497}5498function setupRetargetting()5499{ 5500 5501 var retarget=gup('retarget')5502 5503 5504 5505 if (retarget!='')5506 {5507 5508 console.log("setupRetargetting. retarget: "+retarget)5509 5510 $('#canvas').data("started", true)5511 5512 //var stage=$('#canvas').data("stage")5513 5514 //stage.toDataURL({5515 // callback : function(dataUrl) {5516 // var img = new Image();5517 // img.onload = function() {5518 // 5519 // $('#retarget_img').attr("width",stage.attrs.width / 2)5520 // $('#retarget_img').attr("height",stage.attrs.height / 2)5521 // $('#retarget_img').attr("src",dataUrl)5522 5523 var splt=retarget.split("_")5524 var new_width=parseInt(splt[0])5525 var new_height=parseInt(splt[1]) 5526 5527 $('#design_width').val(new_width)5528 $('#design_height').val(new_height)5529 5530 designSizeChanged()5531 5532 // }5533 // img.src = dataUrl;5534 5535 // }5536 //}); 5537 }5538 5539}5540function waitForWebfonts(fonts, callback) {5541 var loadedFonts = 0;5542 for(var i = 0, l = fonts.length; i < l; ++i) {5543 (function(font) {5544 var node = document.createElement('span');5545 // Characters that vary significantly among different fonts5546 node.innerHTML = 'giItT1WQy@!-/#';5547 // Visible - so we can measure it - but not on the screen5548 node.style.position = 'absolute';5549 node.style.left = '-10000px';5550 node.style.top = '-10000px';5551 // Large font size makes even subtle changes obvious5552 node.style.fontSize = '300px';5553 // Reset any font properties5554 5555 5556 if ((font=='sans-serif') || (font=='Helvetica'))5557 node.style.fontFamily = 'Eater Caps';5558 else5559 node.style.fontFamily = 'sans-serif';5560 node.style.fontVariant = 'normal';5561 node.style.fontStyle = 'normal';5562 node.style.fontWeight = 'normal';5563 node.style.letterSpacing = '0';5564 document.body.appendChild(node);5565 // Remember width with no applied web font5566 var width = node.offsetWidth;5567 node.style.fontFamily = font;5568 5569 console.log("font "+font+ " start. sans-serif width "+width)5570 var interval;5571 var cnt=0;5572 function checkFont() {5573 5574 if (node)5575 {5576 console.log("font "+font+ " has offset width "+node.offsetWidth+"sans-serif width "+width)5577 5578 }5579 console.log("loaded fonts "+loadedFonts+ " array len "+fonts.length+ " at cnt"+cnt)5580 // Compare current width with original width5581 if((node!=null) && (node.offsetWidth != width)) {5582 ++loadedFonts;5583 node.parentNode.removeChild(node);5584 5585 node = null;5586 }5587 5588 if (cnt>10)5589 {5590 clearInterval(interval);5591 callback()5592 return true5593 }5594 cnt+=15595 5596 5597 // If all fonts have been loaded5598 if(loadedFonts >= fonts.length) {5599 if(interval) {5600 clearInterval(interval);5601 }5602 if(loadedFonts == fonts.length) {5603 callback();5604 return true;5605 }5606 }5607 };5608 5609 if(!checkFont()) {5610 interval = setInterval(checkFont, 50);5611 5612 }5613 })(fonts[i]);5614 }5615};5616function toggleSuggestionInterface()5617{5618 var url=document.URL5619 5620 if (url.indexOf("?automaticUpdate=1")>-1)5621 window.location.replace(url.replace("?automaticUpdate=1",""))5622 else5623 window.location.replace(url+"?automaticUpdate=1")5624 5625}5626/*5627function acceptOrRejectSuggestion(event, layout_num)5628{5629 console.log(event.clientX)5630 console.log(event.clientY)5631 5632 var offset=$('#suggestion_layout' + layout_num).offset()5633 console.log(offset)5634 5635 var width=$('#suggestion_layout' + layout_num).width()5636 5637 var mid_pt=offset.left+width/2.05638 if (event.clientX>mid_pt)5639 console.log("reject suggestion")5640 else5641 {5642 console.log("accept suggestion")5643 setFixedLayout("suggestion",layout_num)5644 5645 }5646 5647 5648}5649*/5650function showMoreSimilarLayouts()5651{5652 $('#suggestion_lk').click()5653}5654function showMoreDifferentLayouts()5655{5656 $('#suggestion_lk').click()5657 5658 5659 //if (gup("testing")=="1")5660 resetRuns()5661 //else5662 // resetLayout(false)5663 5664 5665}5666function removeSuggestions()5667{5668 $.each($('#canvas').data("suggestion"),function(i,sugg){5669 5670 sugg.img.destroy()5671 })5672 5673 $('#canvas').data("suggestion",[])5674}5675function acceptSuggestion(s)5676{5677 5678 console.log(s.element)5679 console.log("sugg:"+s.element.text)5680 5681 setElementPosition(s.element,s.x,s.y,s.height)5682 s.img.destroy()5683 5684 //drawAlignmentLines(s.element, 'dragging')5685 5686}5687function setElementPosition(element, x, y,height)5688{5689 element.img.setPosition(x, y)5690 element.img.setHeight(height)5691 element.img.setWidth(height*element.aspect_ratio)5692 element.x=x5693 element.y=y5694 element.height=height5695 element.width=height*element.aspect_ratio5696 5697 element.state_img.setPosition(element.x + element.width, element.y)5698}5699function findSuggestion(selected, elem,type)5700{5701 5702 var shape1=selected.img5703 var shape2=elem.img5704 var p1 = shape1.getPosition()5705 var p2 = shape2.getPosition()5706 var x11 = p1.x, y11 = p1.y, x12 = p1.x + shape1.getWidth(), y12 = p1.y + shape1.getHeight(), x21 = p2.x, y21 = p2.y, x22 = p2.x + shape2.getWidth(), y22 = p2.y + shape2.getHeight()5707 x_overlap = Math.max(0, Math.min(x12, x22) - Math.max(x11, x21))5708 y_overlap = Math.max(0, Math.min(y12, y22) - Math.max(y11, y21));5709 5710 sugg={}5711 5712 5713 sugg.element=elem5714 5715 5716 console.log("x_overlap: "+x_overlap)5717 console.log("y_overlap: "+y_overlap)5718 5719 var offset_x=0;5720 var offset_y=0;5721 5722 //try to shift horizontally5723 if (x_overlap<y_overlap)5724 {5725 5726 //shift left5727 if (elem.x+elem.width-selected.x < selected.x+selected.width-(elem.x))5728 {5729 offset_x=selected.x-(elem.x+elem.width) - 3 5730 }5731 //shift right5732 else5733 {5734 offset_x=(selected.x+selected.width)-elem.x + 35735 }5736 5737 }5738 //try to shift vertically5739 else5740 {5741 if (elem.y+elem.height-selected.y < selected.y+selected.height-(elem.y))5742 {5743 offset_y=selected.y-(elem.y+elem.height) - 35744 }5745 else5746 {5747 offset_y=(selected.y+selected.height)-elem.y +35748 }5749 5750 }5751 5752 sugg.x=elem.x+offset_x5753 sugg.y=elem.y+offset_y5754 sugg.height=elem.height5755 5756 5757 return sugg5758}5759function makeSuggestions()5760{5761 5762 if ((gup("makeSuggestions")=='1') && (gup("automaticUpdate")=='0'))5763 {5764 5765 var design=$('#canvas').data("design")5766 5767 var selected=$('#canvas').data("selected")5768 5769 5770 console.log("selected:")5771 console.log(selected)5772 5773 if ((selected==0)||(selected.type=='background'))5774 return5775 5776 removeSuggestions()5777 5778 5779 var suggs=[]5780 5781 $.each(design.elements, function(i,e){5782 5783 5784 var overlap = getOverlap(selected.img, e.img)5785 5786 5787 if ((e!=selected) && (overlap > 0.02) && (e.fixed_amount != 1)) {5788 sugg=findSuggestion(selected, e,'overlap')5789 5790 suggs.push(sugg)5791 }5792 5793 5794 })5795 5796 5797 $.each(suggs, function (i, sugg)5798 {5799 5800 var img=sugg.element.img5801 sugg.img=img.clone()5802 sugg.img.setOpacity(0.5),5803 img.getLayer().add(sugg.img)5804 5805 5806 var tween = new Kinetic.Tween({5807 node:sugg.img,5808 duration:0.3,5809 opacity:0.15,5810 x:sugg.x,5811 y:sugg.y,5812 scaleX:sugg.element.height/sugg.height,5813 scaleY:sugg.element.height/sugg.height,5814 easing:Kinetic.Easings.Linear5815 5816 })5817 tween.play()5818 5819 5820 sugg.img.off("click tap")5821 5822 sugg.img.on("click tap", function(){acceptSuggestion(sugg)})5823 5824 });5825 5826 $('#canvas').data("suggestion",suggs)5827 5828 5829 }5830 5831}5832function removeAllConstraints()5833{5834 $.each($('#canvas').data("design").elements, function (i,e){5835 e.constraints = {'size':[],'alignment':[]}5836 e.state_img.hide()5837 e.fixed_amount = 0.05838 e.state_img = e.unlock_img5839 5840 }); 5841 5842}5843function constraintsChanged(type)5844{5845 5846 console.log("constraintsChanged-"+type)5847 5848 var selected_ids=[]5849 var selected_types=[]5850 5851 var design = $('#canvas').data('design')5852 5853 $.each(design.elements, function (i,e){5854 5855 if (e.selected)5856 {5857 selected_ids.push(e.id)5858 selected_types.push(e.type)5859 }5860 });5861 5862 var adding_constraint=$("#size_constraint").prop("checked")5863 5864 console.log("adding_constraint: "+adding_constraint)5865 5866 var changed=false;5867 var set_height=0;5868 if ($('#canvas').data('selected').type=='graphic')5869 set_height=$('#canvas').data('selected').height5870 else5871 set_height=$('#canvas').data('selected').height/$('#canvas').data('selected').num_lines5872 5873 $.each(design.elements, function (i,e){5874 5875 if (e.selected)5876 {5877 5878 var cons=e.constraints[type]5879 5880 for (var i=0;i<selected_ids.length;i++){5881 if ((e.id!=selected_ids[i])&&(e.type==selected_types[i])){5882 5883 var idx=cons.indexOf(selected_ids[i])5884 if (idx==-1){ 5885 cons.push(selected_ids[i])5886 changed=true5887 5888 5889 if (type=='size')5890 {5891 5892 var new_height=set_height*Math.max(e.num_lines,1)5893 console.log("set new height "+new_height)5894 e.height=new_height5895 e.width=new_height*e.aspect_ratio5896 5897 e.img.setHeight(e.height)5898 e.img.setWidth(e.width) 5899 5900 }5901 5902 5903 }5904 5905 else if (!adding_constraint){5906 cons.splice(idx, 1); 5907 }5908 5909 }5910 }5911 5912 }5913 });5914 5915 5916 $('#canvas').data("stage").get('#layer')[0].draw()5917 5918 if (changed)5919 sendCurrentLayout(type+" constraint")5920 5921 5922}5923function showGalleryLayouts()5924{5925 $('#gallery_text').show()5926 $('#saved_text').hide()5927 $('#style_lk').click()5928 5929 $('#showGalleryButton').hide()5930 5931 5932 //$('#gallery_text').show()5933 //$('#style_lk').click()5934 5935}5936function deleteGallery()5937{5938 var gallery_elem = $('#gallery_layout0')5939 $("#gallery_table").empty()5940 $('#gallery_table').append($('<tr>').append($('<td>').append(gallery_elem)))5941 gallery_elem.hide()...

Full Screen

Full Screen

design#OnDisk.js

Source:design#OnDisk.js Github

copy

Full Screen

1String.prototype.replaceAll = function(find, replace) {2 var str = this;3 return str.replace(new RegExp(find, 'g'), replace);4};5if ( typeof (String.prototype.trim) === "undefined") {6 String.prototype.trim = function() {7 return String(this).replace(/^\s+|\s+$/g, '');8 };9}10function isiPhonePad() {11 return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) || (navigator.userAgent.match(/iPad/i) != null)12 );13}14function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}15function hexToV(h) {16 var r= parseInt((cutHex(h)).substring(0,2),16)17 var g= parseInt((cutHex(h)).substring(2,4),16)18 var b= parseInt((cutHex(h)).substring(4,6),16)19 return (r+g+b)/3.020}21function setupCanvas() {22 var design = $('#canvas').data("design");23 var images = $('#canvas').data("images");24 $('#canvas').data("sendLayoutToServerTimes", [])25 design.region_proposals = false;26 if ($('#canvas').data("stage") != undefined)27 $('#canvas').data("stage").destroy();28 if ($('#canvas').data("latencyTimes") == undefined)29 $('#canvas').data("latencyTimes",[]);30 $('#canvas').hide(); 31 $('#canvas').data("mousePos", 0)32 $('#canvas').data("dragging", false)33 $('#canvas').data("lastDist", 1);34 $('#canvas').data("show_lock_icons", true);35 $('#canvas').data("show_fixed_opacity", false);36 $('#canvas').data("align_lines", [])37 $('#canvas').data("energy", 9999)38 $('#canvas').data("energy_lists", {})39 $('#canvas').data("plot_energy_list", [])40 $('#canvas').data("layout_stack", [])41 $('#canvas').data("layout_stack_idx", -1)42 43 $('#canvas').data("user_layout_stack", [])44 $('#canvas').data("user_layout_stack_idx", -1)45 if ($('#canvas').data("user_input_log")==undefined)46 $('#canvas').data("user_input_log", [])47 48 if ($('#canvas').data("status_log")==undefined)49 $('#canvas').data("status_log", ['Setup'])50 51 52 if ($('#canvas').data("layout_log")==undefined)53 $('#canvas').data("layout_log", [])54 //$('#canvas').data("paused", false)55 $('#canvas').data('killed', false)56 $('#canvas').data("overlap_mode", false)57 $('#canvas').data("region_mode", false)58 $('#canvas').data("text_mode", false)59 if (!("saved_layouts" in design))60 design.saved_layouts = []61 if (!("overlap_regions" in design))62 design.overlap_regions = []63 if (!("regions" in design))64 design.regions = []65 66 if (!("element_alts" in design))67 design.element_alts = {}68 69 if (!("rules" in design)) 70 design.rules=[]71 72 if (!("directory" in design)) 73 design.directory=''74 75 76 $('#design_width').val(design.width)77 $('#design_height').val(design.height)78 var stage = new Kinetic.Stage({79 container : 'canvas',80 width : design.width,81 height : design.height82 });83 var layer = new Kinetic.Layer({84 id : 'layer',85 });86 stage.add(layer);87 88 $('#canvas').data("mousedown",false)89 $(document).mousedown(function(evt){$('#canvas').data("mousedown",true)})90 $(document).mouseup( function(evt){91 console.log("stage mouseup")92 $('#canvas').data("mousedown",false)93 $('#canvas').data("select_rect").hide()94 $('#canvas').data("select_rect").getLayer().draw()95 $('#canvas').data("select_start", false) 96 })97 var previewRect = new Kinetic.Rect({98 x : 0,99 y : 0,100 width : design.width,101 height : design.height,102 name : 'preview',103 fillPatternImage : images.background104 });105 layer.add(previewRect);106 previewRect.hide();107 $('#canvas').data("preview_image", previewRect);108 $('#canvas').data("preview", -1);109 var col = design.background_color110 if ((col != undefined) && (col.indexOf('#') == -1))111 col = '#' + col;112 if (!("background_elem" in design))113 {114 back_elem = {}115 back_elem.id = '0';116 back_elem.type = "background";117 back_elem.text = '';118 back_elem.font = 'Garamond';119 back_elem.color = design.background_color;120 back_elem.group_id = 0;121 back_elem.importance = 0;122 back_elem.anchors = [];123 back_elem.loaded = false;124 back_elem.resizing = false;125 back_elem.selected = false;126 back_elem.bold = false;127 back_elem.italic = false;128 back_elem.shadow = false;129 back_elem.align = "center"130 back_elem.x = 0131 back_elem.y = 0132 back_elem.fname=design.background_fname 133 134 135 back_elem.offset_x=0136 back_elem.offset_y=0137 design.background_elem=back_elem138 }139 else140 {141 $('#background_offset_x').val(design.background_elem.offset_x)142 $('#background_offset_y').val(design.background_elem.offset_y)143 }144 var backgroundRect = new Kinetic.Rect({145 x : 0,146 y : 0,147 width : design.width,148 height : design.height,149 fill : col,150 name : 'background',151 stroke : 'Red',152 strokeWidth : 4,153 strokeEnabled: false,154 fillPatternImage : images.background,155 fillPatternOffset: {x:design.background_elem.offset_x, y:design.background_elem.offset_y}156 });157 layer.add(backgroundRect);158 backgroundRect.moveToBottom()159 design.background = backgroundRect;160 console.log('design.background_color:'+design.background_color)161 console.log('design.background_fname:'+design.background_fname)162 163 164 design.background_elem.img = backgroundRect165 166 setupSelectRectangle(design,layer)167 168 $('#canvas').data("selected", design.background_elem)169 setupElementCallbacks(backgroundRect, design.background_elem);170 var sugg_stage = new Kinetic.Stage({171 container : 'suggestion_canvas',172 width : design.width,173 height : design.height174 });175 var sugg_layer = new Kinetic.Layer({176 id : 'sugg_layer',177 });178 var backgroundRect2 = new Kinetic.Rect({179 x : 0,180 y : 0,181 width : design.width,182 height : design.height,183 fill : design.background_color,184 fillPatternImage : images.background185 });186 sugg_layer.add(backgroundRect2);187 design.sugg_background = backgroundRect2;188 //console.log("background color: "+design.background_color)189 sugg_stage.add(sugg_layer);190 var overlap_layer = new Kinetic.Layer();191 stage.add(overlap_layer);192 $('#canvas').data("overlap_layer", overlap_layer);193 var region_layer = new Kinetic.Layer();194 stage.add(region_layer);195 $('#canvas').data("region_layer", region_layer);196 $('#canvas').data("stage", stage);197 $('#canvas').data("sugg_stage", sugg_stage);198 console.log("stage:" + stage)199 var max_group_id = 0;200 var max_id = 0;201 $.each(design.elements, function(i, elem) {202 if ("group_id" in elem)203 max_group_id = Math.max(max_group_id, elem.group_id);204 if (("id" in elem))205 max_id = Math.max(max_id, elem.id)206 });207 $('#canvas').data("images_rendering",0)208 $.each(design.elements, function(i, elem) {209 elem.loaded = false;210 elem.resizing = false;211 elem.fixed = false;212 elem.align_type = -1;213 elem.num_lines = 0;214 //elem.num_align=-1;215 elem.selected = false;216 elem.old_text = '';217 218 if (elem.color=='black')219 elem.color='000'220 elem.fixed_amount = 0.5;221 if ($('#canvas').data("init_fixed_amount")!=undefined)222 elem.fixed_amount =$('#canvas').data("init_fixed_amount");223 224 elem.hidden_img = 0;225 elem.hidden = false;226 delete elem["img"];227 delete elem["sugg_img"];228 if (!("group_id" in elem)) {229 max_group_id = max_group_id + 1;230 elem.group_id = max_group_id;231 }232 if (!("id" in elem)) {233 max_id = max_id + 1;234 elem.id = max_id;235 }236 237 if (!("shadow" in elem)) { 238 elem.shadow =false239 }240 if (!("allow_overlap" in elem))241 elem.allow_overlap = false;242 if (!("fix_alignment" in elem))243 elem.fix_alignment = false;244 if (!("fix_alternate" in elem))245 elem.fix_alternate = false;246 if (!("optional" in elem))247 elem.optional = false;248 if (elem.type == 'graphic')249 elem.type_id = 2;250 if (elem.type == 'text')251 elem.type_id = 1;252 if (elem.id in design.element_alts) {253 var alt_id = 0;254 $.each(design.element_alts[elem.id], function(i, e) {255 e.alternate_id = alt_id;256 alt_id += 1;257 });258 }259 260 261 if ($('#canvas').data("randomizeInit"))262 {263 264 var new_height265 if (elem.type == 'graphic') 266 new_height = 80267 else if (elem.type == 'text')268 new_height = 20 * elem.text.split("\n").length269 270 271 elem.height = new_height272 elem.width = elem.height * elem.aspect_ratio273 274 var new_x = Math.random() * (design.width - elem.width)275 var new_y = Math.random() * (design.height - elem.height)276 277 elem.x = new_x278 elem.y = new_y279 }280 281 282 //if ($('#canvas').data("suggestionsEnabled"))283 setupLockingCallbacks(elem, layer)284 if ("fname" in elem) {285 elem.alternate_id = 0;286 setupImageElement(elem, images[elem.fname], layer, sugg_layer, false)287 var missing_or = true;288 $.each(design.overlap_regions, function(j, or) {289 if (or.elem_id == elem.id)290 missing_or = false;291 });292 if ((missing_or) && (!elem.allow_overlap)) {293 overlap = {}294 overlap.elem_id = elem.id295 overlap.x_min = 0296 overlap.y_min = 0297 overlap.x_max = 1298 overlap.y_max = 1299 design.overlap_regions.push(overlap)300 }301 } else if (elem.type == 'text') {302 if (elem.color == undefined)303 elem.color = '#000'304 if (elem.color.indexOf('#') == -1)305 elem.color = '#' + elem.color;306 elem.text = elem.text.trim()307 elem.sugg_align = elem.align;308 renderTextAlts(elem, false)309 }310 elem.last_x = elem.x;311 elem.last_y = elem.y;312 });313 window.addEventListener('keydown', keyPressed);314 layer.draw();315 sugg_layer.draw();316 //$('#suggestion_canvas').data("stage",sugg_stage);317 //setTimeout(sendDesign,500);318 //sendCurrentDesign();319 $.each(design.elements, function(i, elem) {320 var found_other = false;321 $.each(design.elements, function(j, elem2) {322 if ((i != j) && (elem.group_id == elem2.group_id))323 found_other = true;324 });325 if (!found_other)326 elem.group_id = -1;327 });328 setupStageCallbacks(stage);329 var curr_layout=getCurrentLayout()330 addLayoutToStack(curr_layout)331 $('#canvas').data("runs", [])332 if ($('#canvas').data("suggestionsEnabled")) {333 startSuggestions()334 }335 //design.elements.sort(function(e1,e2){return e1.importance-e2.importance})336 console.log("text to render: "+$('#canvas').data("images_rendering"))337 if ((design.saved_layouts.length>0) && ($('#canvas').data("sequence_index")==undefined))338 {339 var func = function(){340 renderSavedLayouts(design.saved_layouts,curr_layout)341 }342 executeAfterTextRendering(func)343 }344 else345 $('#canvas').show()346 $('#canvas').data("started", false)347}348function executeAfterTextRendering(func)349{350 var images_remaining = $('#canvas').data("images_rendering")351 if ((images_remaining != undefined) && (images_remaining==0))352 {353 console.log("executing function")354 func()355 }356 else357 {358 setTimeout(function (){359 executeAfterTextRendering(func) 360 },100)361 }362 363 364}365function renderSavedLayouts(layouts,curr_layout)366{367 368 //console.log("rendering saved layouts: "+layouts)369 370 if (layouts.length==0)371 {372 setCurrentLayout(curr_layout)373 $('#canvas').show()374 return375 376 }377 378 if (layouts[0]==null)379 {380 renderSavedLayouts(layouts.slice(1),curr_layout)381 return 382 }383 384 385 console.log("rendering saved layout: "+layouts[0])386 387 setCurrentLayout(layouts[0],true,true)388 389 $('#canvas').data("stage").toDataURL({390 callback : function(data_url) {391 var img = new Image();392 393 img.onload = function() {394 395 var sugg_id = Math.round(Math.random() * 100000) 396 addSavedLayout(img,data_url,layouts[0],sugg_id,false) 397 renderSavedLayouts(layouts.slice(1),curr_layout)398 399 }400 img.src=data_url401 }402 });403 404}405function setupSelectRectangle(design,layer)406{407 408 console.log("setupSelectRectangle\n, background col:"+design.background_color)409 410 $('#canvas').data("invert", false)411 var select_color = 'black'412 var select_opacity = 0.1413 414 var background_val;415 if (design.background_color!=undefined)416 background_val=hexToV(design.background_color)417 418 if ((design.background_fname.indexOf("black") > -1) || ((design.background_fname=='') && (background_val<50)))419 {420 console.log('inverting selector')421 $('#canvas').data("invert", true)422 $("#invert_select").prop("checked", true)423 select_color = 'white'424 select_opacity = 0.2425 }426 var select_rect = new Kinetic.Rect({427 x : 0,428 y : 0,429 width : 100,430 height : 100,431 fill : 'blue',432 stroke : select_color,433 opacity : select_opacity,434 strokeWidth : 1,435 visible : false436 });437 layer.add(select_rect);438 $('#canvas').data("select_rect", select_rect)439 $('#canvas').data("select_start", false)440 441 442 443}444function allowUpdates() {445 $('#canvas').data("started", true)446 $('#canvas').data("energy_lists", {})447 if ($('#canvas').data("layoutStartTime") == undefined)448 $('#canvas').data("layoutStartTime", new Date())449 450 451 452 var sug_check=$('#canvas').data("suggestion_check");453 if ((sug_check==undefined) || (sug_check==-1))454 {455 console.log("adding checkForSuggestions"+$('#canvas').data("suggestion_check"))456 457 if ($('#canvas').data("automaticUpdate"))458 suggestion_check=setInterval(checkForSuggestions, 100);459 else460 suggestion_check=setInterval(checkForSuggestions, 300); 461 462 $('#canvas').data("suggestion_check",suggestion_check)463 }464}465function setupLockingCallbacks(elem, layer) {466 //console.log("background color:"+$('#canvas').data("design").background_color)467 //var filt=Kinetic.Filters.Invert;468 var filt = 0;469 //if ($('#canvas').data("invert"))470 // filt=Kinetic.Filters.Invert471 var images = $('#canvas').data("images");472 var size = 20473 if (!$('#canvas').data("suggestionsEnabled"))474 size =0.1475 476 if ($('#canvas').data("playback"))477 size = 20478 elem.unlock_img = new Kinetic.Image({479 x : elem.x + elem.width,480 y : elem.y,481 image : images['unlocked'],482 height : size,483 width : size,484 draggable : false,485 visible : false,486 filter : filt,487 opacity : 0.75488 });489 elem.tweakable_img = new Kinetic.Image({490 x : elem.x + elem.width,491 y : elem.y,492 image : images['tweakable'],493 height : size,494 width : size,495 draggable : false,496 visible : false,497 filter : filt,498 opacity : 0.75499 });500 elem.lock_img = new Kinetic.Image({501 x : elem.x + elem.width,502 y : elem.y,503 image : images['locked'],504 height : size,505 width : size,506 draggable : false,507 visible : false,508 filter : filt,509 opacity : 0.75510 });511 layer.add(elem.unlock_img)512 layer.add(elem.tweakable_img)513 layer.add(elem.lock_img)514 if (elem.fixed_amount<0.5)515 elem.state_img = elem.unlock_img;516 else if (elem.fixed_amount<1)517 elem.state_img = elem.tweakable_img;518 else519 elem.state_img = elem.lock_img;520 elem.unlock_img.on("click tap", function(evt) {521 setElementState(elem.id, 'tweakable')522 $('#canvas').data("user_input_log").push("St-"+String(elem.id)+"-twk")523 $('#canvas').data("status_log").push("St-"+String(elem.id)+"-twk")524 sendCurrentLayout('State Change')525 526 });527 528 elem.tweakable_img.on("click tap", function(evt) {529 setElementState(elem.id, 'locked')530 531 $('#canvas').data("user_input_log").push("St-"+String(elem.id)+"-lk" )532 $('#canvas').data("status_log").push("St-"+String(elem.id)+"-lk" )533 sendCurrentLayout('State Change')534 });535 elem.lock_img.on("click tap", function(evt) {536 setElementState(elem.id, 'unlocked')537 538 $('#canvas').data("user_input_log").push("St-"+String(elem.id)+"-ulk")539 $('#canvas').data("status_log").push("St-"+String(elem.id)+"-ulk")540 sendCurrentLayout('State Change')541 });542}543function setElementState(elem_id, new_state,fix_amount) {544 $.each($('#canvas').data("design").elements, function(i, elem) {545 if (elem.id == elem_id) {546 var old_state_img = elem.state_img;547 elem.unlock_img.hide()548 elem.tweakable_img.hide()549 elem.lock_img.hide()550 if (new_state == 'unlocked') {551 elem.fix_alignment=false552 elem.state_img = elem.unlock_img553 elem.fixed_amount = 0554 }555 if (new_state == 'tweakable') {556 elem.state_img = elem.tweakable_img557 elem.fixed_amount = 0.5558 }559 if (new_state == 'locked') {560 elem.state_img = elem.lock_img561 elem.fixed_amount = 1562 }563 564 if (fix_amount !=undefined)565 elem.fixed_amount=fix_amount566 console.log("elem " + elem.id + " is " + new_state + " with fixed amount " + elem.fixed_amount)567 elem.state_img.setPosition(old_state_img.getPosition())568 elem.state_img.show()569 elem.state_img.getLayer().draw()570 }571 });572}573function changeElementStates(new_state) {574 $('#canvas').data("user_input_log").push("State-" + new_state)575 $('#canvas').data("status_log").push("State-" + new_state)576 $.each($('#canvas').data("design").elements, function(i, e) {577 if (e.selected) {578 setElementState(e.id, new_state)579 }580 });581 582 sendCurrentLayout('State Change')583 allowUpdates()584}585function designSizeChanged() {586 var design = $('#canvas').data("design")587 var new_width = parseInt($('#design_width').val())588 var new_height = parseInt($('#design_height').val())589 if ((new_width > 0) && (new_height > 0)) {590 console.log("designSizeChanged")591 retargetElements(new_height,new_width)592 593 design.width = new_width594 design.height = new_height595 596 $('#canvas').data("stage").setWidth(new_width)597 $('#canvas').data("stage").setHeight(new_height)598 599 600 design.background_elem.img.attrs.width=new_width601 design.background_elem.img.attrs.height=new_height602 603 $('#canvas').data("sugg_stage").attrs.width=new_width604 $('#canvas').data("sugg_stage").attrs.height=new_height605 606 design.sugg_background.attrs.width=new_width607 design.sugg_background.attrs.height=new_height608 609 $('#canvas').data("preview_image").attrs.width=new_width610 $('#canvas').data("preview_image").attrs.height=new_height611 612 design.background_elem.img.getLayer().draw()613 614 615 $.each(design.elements, function(i, elem) {616 setElementState(elem.id, 'unlocked',0.05)617 elem.state_img.hide()618 })619 620 621 if ($('#canvas').data("suggestionsEnabled")) 622 startSuggestions()623 624 allowUpdates()625 }626}627function retargetElements(new_height, new_width)628{629 var design = $('#canvas').data("design")630 var new_diag =Math.sqrt(new_height*new_height + new_width*new_width)631 var curr_diag=Math.sqrt(design.height*design.height + design.width*design.width )632 633 var scale = (new_diag/ curr_diag);634 635 $.each(design.elements, function(i, elem) {636 elem.aspect_ratio=elem.img.getWidth()/elem.img.getHeight()637 var width = elem.height * elem.aspect_ratio638 var mid_x = (elem.x + width / 2) / design.width;639 var mid_y = (elem.y + elem.height / 2) / design.height;640 elem.height = elem.height * scale641 elem.width = elem.height * elem.aspect_ratio642 elem.x = Math.max(0, mid_x * new_width - elem.width / 2);643 elem.y = Math.max(0, mid_y * new_height - elem.height / 2);644 645 //console.log("elem.text: "+elem.text)646 //console.log("element "+elem.id +" exceed by "+(elem.x+elem.width-design.width))647 //console.log("elem.x: "+elem.x)648 649 650 elem.x = elem.x - Math.max(0,(elem.x+elem.width)-new_width) 651 elem.y = elem.y - Math.max(0,(elem.y+elem.height)-new_height)652 653 elem.img.setPosition(elem.x, elem.y)654 655 });656 657}658function setupImageElement(elem, image, layer, sugg_layer, selected) {659 var design = $('#canvas').data("design");660 var scale = 1;661 while (Math.max(image.height * scale, image.height * scale) > Math.max(design.width, design.height) * 0.5) {662 scale = scale * 0.9;663 }664 if (gup('hideContent') != '1') {665 img = new Kinetic.Image({666 x : elem.x,667 y : elem.y,668 image : image,669 height : Math.round(image.height * scale),670 width : Math.round(image.width * scale),671 name : elem.id,672 strokeEnabled : selected,673 stroke : 'Red',674 strokeWidth : 2,675 lineJoin : 'round',676 dashArray : [7, 5],677 name : elem.id,678 draggable : true679 });680 layer.add(img);681 img.moveToBottom()682 img.moveUp()683 elem.img = img;684 elem.aspect_ratio = image.width / image.height;685 elem.img.setHeight(elem.height);686 elem.img.setWidth(elem.height * elem.aspect_ratio);687 //console.log("setting up image with height "+elem.height)688 var img2 = img.clone();689 img2.attrs.strokeEnabled = false;690 sugg_layer.add(img2);691 elem.sugg_img = img2;692 setupElementCallbacks(img, elem);693 elem.anchors = createAnchors(elem, layer, selected)694 moveAnchors(elem)695 elem.loaded = true;696 } else {697 var text = new Kinetic.Text({698 x : 0,699 y : 0,700 text : 'Image',701 fill : 'black',702 height : Math.round(image.height * scale),703 width : Math.round(image.width * scale),704 fontSize : 30,705 fontFamily : 'Calibri',706 align : 'center'707 });708 text.toImage({709 x : 0,710 y : 0,711 width : (text.getWidth()),712 height : (text.getHeight()),713 callback : function(text_img) {714 var add_background = function(pixels) {715 var d = pixels.data;716 for (var i = 0; i < d.length; i += 4) {717 var alpha = (d[i + 3] / 255)718 d[i] += alpha * d[i] + (1 - alpha) * 135;719 d[i + 1] += alpha * d[i + 1] + (1 - alpha) * 206;720 d[i + 2] += alpha * d[i + 2] + (1 - alpha) * 235;721 d[i + 3] = 255;722 }723 return pixels;724 };725 img = new Kinetic.Image({726 x : elem.x,727 y : elem.y,728 image : text_img,729 height : Math.round(image.height * scale),730 width : Math.round(image.width * scale),731 name : elem.id,732 strokeEnabled : selected,733 stroke : 'Red',734 strokeWidth : 2,735 lineJoin : 'round',736 dashArray : [7, 5],737 name : elem.id,738 draggable : true,739 filter : add_background740 });741 layer.add(img);742 elem.img = img;743 elem.aspect_ratio = image.width / image.height;744 elem.img.setHeight(elem.height);745 elem.img.setWidth(elem.height * elem.aspect_ratio);746 //console.log("setting up image with height "+elem.height)747 var img2 = img.clone();748 img2.attrs.strokeEnabled = false;749 sugg_layer.add(img2);750 elem.sugg_img = img2;751 setupElementCallbacks(img, elem);752 elem.anchors = createAnchors(elem, layer, selected)753 moveAnchors(elem)754 elem.loaded = true;755 }756 });757 }758}759function createAnchors(elem, layer, visible) {760 var anchors = {}761 anchors["topLeft"] = createScaleAnchor(0, 0, "topLeft", layer, elem, visible)762 anchors["topRight"] = createScaleAnchor(0, 0, "topRight", layer, elem, visible)763 anchors["bottomLeft"] = createScaleAnchor(0, 0, "bottomLeft", layer, elem, visible)764 anchors["bottomRight"] = createScaleAnchor(0, 0, "bottomRight", layer, elem, visible)765 //766 if ((elem.type == 'text') && ((elem.text.indexOf(" ") > -1) || (elem.text.indexOf("\n") > -1))) {767 anchors["midRight"] = createAspectRatioAnchor(0, 0, "midRight", layer, elem, visible)768 anchors["midLeft"] = createAspectRatioAnchor(0, 0, "midLeft", layer, elem, visible)769 }770 return anchors;771}772function createAspectRatioAnchor(x, y, name, layer, elem, selected) {773 var anchor = new Kinetic.Rect({774 x : x,775 y : y,776 width : 8,777 height : 8,778 fill : 'red',779 opacity : 1,780 name : name,781 draggable : true,782 visible : selected783 });784 anchor.rotate(150)785 layer.add(anchor);786 anchor.on('dragstart', function() {787 elem.anchor_pos = layer.getStage().getPointerPosition()788 $('#canvas').data("user_input_log").push("AR")789 $('#canvas').data("status_log").push("AR")790 console.log("ar dragstart")791 });792 anchor.on('dragmove', function() {793 $('#canvas').data("select_start", false)794 795 console.log("ar dragmove")796 if ((elem.anchor_pos == 0) || (elem.fix_alternate))797 return;798 799 elem.resizing = true;800 //anchorImageUpdate(this,element);801 //console.log("layer "+anchor.getLayer())802 var alts = $('#canvas').data("design").element_alts[elem.id];803 var next_pos = layer.getStage().getPointerPosition()804 805 var pos_diff=elem.anchor_pos.x - next_pos.x806 console.log("pos_diff:"+pos_diff)807 var flip = 1;808 if (name == 'midLeft')809 flip = -1;810 if (flip * (pos_diff) > 5) {811 console.log("checking")812 if ((elem.num_lines + 1) in alts) {813 console.log("setting "+(elem.num_lines + 1))814 selectAlternateElement(elem, elem.num_lines + 1)815 elem.anchor_pos = 0;816 }817 moveAnchors(elem)818 layer.draw();819 } else if (flip * (-1*pos_diff) > 5) {820 console.log("checking")821 822 if ((elem.num_lines - 1) in alts) {823 selectAlternateElement(elem, elem.num_lines - 1)824 elem.anchor_pos = 0;825 }826 moveAnchors(elem)827 layer.draw();828 }829 });830 anchor.on('dragend', function() {831 elem.resizing = false832 moveAnchors(elem)833 layer.draw();834 });835 return anchor;836}837function createScaleAnchor(x, y, name, layer, element, selected) {838 var anchor = new Kinetic.Circle({839 x : x,840 y : y,841 fill : 'red',842 opacity : 1,843 radius : 6,844 name : name,845 draggable : true,846 visible : selected847 });848 layer.add(anchor);849 anchor.on('dragstart', function() {850 $('#canvas').data("user_input_log").push("S")851 $('#canvas').data("status_log").push("S")852 });853 anchor.on('dragmove', function() {854 console.log("dragmove scale")855 $('#canvas').data("select_start", false)856 element.resizing = true;857 allowUpdates()858 anchorImageUpdate(this, element);859 drawAlignmentLines(element, name)860 if ($("#infer_locking_select").prop("checked") && (element.fixed_amount == 0))861 setElementState(element.id, 'tweakable')862 //863 layer.draw();864 });865 anchor.on('dragend', function() {866 867 $.each($('#canvas').data("design").elements, function(i, e) {868 if ((e != element)) {869 if ($("#infer_locking_select").prop("checked")) {870 var overlap = getOverlap(e.img, element.img)871 if ((overlap > 0.1) && (e.fixed_amount != 1)&& (!e.allow_overlap)&& (!element.allow_overlap)) {872 873 setElementState(e.id, 'unlocked')874 875 /*876 if (e.fix_alignment)877 {878 e.fix_alignment=false879 sendCurrentDesign()880 }881 */882 }883 }884 }885 });886 element.resizing = false887 888 sendCurrentLayout('Scale')889 });890 return anchor;891}892function anchorImageAspectRatioUpdate(anchor, elem) {893 var anchor_pos = anchor.getAbsolutePosition()894 //console.log("element "+ elem.id+" anchor "+ anchor.attrs.name+" has position: "+anchor_pos.x + " "+ anchor_pos.y )895 var new_height = 1;896 var new_width = 1;897 if (anchor.attrs.name == "topLeft") {898 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y899 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x900 }901 if (anchor.attrs.name == "bottomLeft") {902 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y903 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x904 }905 if (anchor.attrs.name == "bottomRight") {906 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y907 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x908 }909 if (anchor.attrs.name == "topRight") {910 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y911 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x912 }913 var aspect_ratio = new_width / new_height;914 var nearest_elem = elem;915 var min_dist = 999;916 $.each($('#canvas').data("design").element_alts[elem.id], function(i, e) {917 var dist = Math.abs(aspect_ratio - e.aspect_ratio)918 if (dist < min_dist) {919 nearest_elem = e920 min_dist = dist921 }922 });923 if (elem != nearest_elem) {924 setAlternate(elem, nearest_elem);925 if (anchor.attrs.name.indexOf("Left") > -1) {926 nearest_elem.img.setX(anchor_pos.x)927 }928 return true929 }930 /*931 new_height=Math.max(new_height,10);932 elem.img.setHeight(new_height)933 elem.height=new_height934 if ("aspect_ratio" in elem)935 elem.img.setWidth(new_height*elem.aspect_ratio)936 else937 {938 new_width=Math.max(new_width,10)939 elem.img.setWidth(new_width)940 elem.width=new_width941 }942 if ((anchor.attrs.name=="topLeft") || (anchor.attrs.name=="bottomLeft") )943 {944 var right_pos=elem.anchors["bottomRight"].getAbsolutePosition().x;945 elem.img.setX(right_pos-elem.img.getWidth())946 }947 */948 //moveAnchors(elem)949}950function setAlternate(elem, alt_elem) {951 console.log("setAlternate for element " + elem.id)952 var layer = $('#canvas').data("stage").get('#layer')[0];953 var design = $('#canvas').data("design")954 var scale = alt_elem.num_lines / elem.num_lines955 console.log("setting alternate text :" + alt_elem.text)956 console.log("orig element selected? " + elem.selected)957 console.log("alternate id :" + alt_elem.alternate_id)958 alt_elem.x = elem.x959 alt_elem.y = elem.y960 alt_elem.height = elem.height * scale961 alt_elem.align_type = elem.align_type962 alt_elem.align = elem.align963 alt_elem.group_id = elem.group_id964 alt_elem.importance = elem.importance965 alt_elem.selected = elem.selected966 alt_elem.fix_alignment = elem.fix_alignment967 alt_elem.fixed_amount = elem.fixed_amount968 //alt_elem.unlock_img=elem.unlock_img969 //alt_elem.tweakable_img=elem.tweakable_img970 //alt_elem.lock_img=elem.lock_img971 alt_elem.optional = elem.optional972 elem.img.remove()973 elem.sugg_img.remove();974 $.each(design.element_alts[elem.id], function(i, e) {975 e.img.remove()976 $.each(e.alignment_imgs, function(j, ai) {977 ai.remove()978 });979 $.each(e.anchors, function(i, a) {980 a.hide()981 });982 });983 if (alt_elem.num_lines > 1) {984 if (alt_elem.img != alt_elem.alignment_imgs[alt_elem.align]) {985 alt_elem.img = alt_elem.alignment_imgs[alt_elem.align];986 }987 }988 alt_elem.img.setPosition(elem.img.attrs.x, elem.img.attrs.y)989 alt_elem.img.attrs.strokeEnabled = elem.selected990 alt_elem.img.setHeight(elem.img.getHeight() * scale)991 alt_elem.img.setWidth(alt_elem.img.getHeight() * alt_elem.aspect_ratio)992 alt_elem.img.setOpacity(1)993 alt_elem.width=alt_elem.img.getWidth()994 alt_elem.height=alt_elem.img.getHeight()995 alt_elem.state_img = elem.state_img996 alt_elem.state_img.setPosition(alt_elem.x + alt_elem.width, alt_elem.y)997 layer.add(alt_elem.img)998 alt_elem.img.show()999 setHidden(alt_elem, elem.hidden)1000 1001 1002 $.each(alt_elem.anchors, function(i, a) {1003 //layer.add(a)1004 1005 a.moveToTop()1006 if (elem.selected)1007 a.show();1008 });1009 1010 moveAnchors(alt_elem)1011 layer.draw()1012 var idx = design.elements.indexOf(elem);1013 design.elements[idx] = alt_elem;1014 if ($('#canvas').data("selected") == elem) {1015 console.log("element was selected already")1016 $("#num_lines_select").val(alt_elem.num_lines).attr('selected', true);1017 $("#user_text").val(alt_elem.text);1018 $('#canvas').data("selected", alt_elem)1019 }1020 if (alt_elem.fixed_amount < 0.5)1021 setElementState(alt_elem.id, 'unlocked')1022 else if ((alt_elem.fixed_amount >0) && (alt_elem.fixed_amount <1))1023 setElementState(alt_elem.id, 'tweakable')1024 else1025 setElementState(alt_elem.id, 'locked')1026 1027 sendCurrentLayout('Aspect Ratio')1028}1029function anchorImageUpdate(anchor, elem) {1030 var anchor_pos = anchor.getAbsolutePosition()1031 //console.log("element "+ elem.id+" anchor "+ anchor.attrs.name+" has position: "+anchor_pos.x + " "+ anchor_pos.y )1032 var new_height = 1;1033 var new_width = 1;1034 if (anchor.attrs.name == "topLeft") {1035 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y1036 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x1037 }1038 if (anchor.attrs.name == "bottomLeft") {1039 new_height = elem.anchors["topLeft"].getAbsolutePosition().y - elem.anchors["bottomLeft"].getAbsolutePosition().y1040 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x1041 elem.img.setY(anchor_pos.y)1042 }1043 if (anchor.attrs.name == "bottomRight") {1044 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y1045 new_width = elem.anchors["bottomRight"].getAbsolutePosition().x - elem.anchors["bottomLeft"].getAbsolutePosition().x1046 elem.img.setY(anchor_pos.y)1047 }1048 if (anchor.attrs.name == "topRight") {1049 new_height = elem.anchors["topRight"].getAbsolutePosition().y - elem.anchors["bottomRight"].getAbsolutePosition().y1050 new_width = elem.anchors["topRight"].getAbsolutePosition().x - elem.anchors["topLeft"].getAbsolutePosition().x1051 }1052 new_height = Math.max(new_height, 10);1053 elem.img.setHeight(new_height)1054 elem.height = new_height1055 if ("aspect_ratio" in elem)1056 elem.img.setWidth(new_height * elem.aspect_ratio)1057 else {1058 new_width = Math.max(new_width, 10)1059 elem.img.setWidth(new_width)1060 elem.width = new_width1061 }1062 if ((anchor.attrs.name == "topLeft") || (anchor.attrs.name == "bottomLeft")) {1063 var right_pos = elem.anchors["bottomRight"].getAbsolutePosition().x;1064 elem.img.setX(right_pos - elem.img.getWidth())1065 }1066 elem.x = elem.img.attrs.x1067 elem.y = elem.img.attrs.y1068 elem.width = elem.img.getWidth()1069 elem.height = elem.img.getHeight()1070 elem.state_img.setPosition(elem.x + elem.width, elem.y)1071 moveAnchors(elem)1072 1073 if (elem.type=='text')1074 $("#fontSizeInput").val((elem.height/elem.init_height)*elem.init_font_size)1075}1076function keyPressed(evt) {1077 console.log("Key pressed: " + evt.keyCode)1078 var input_focused = $("*:focus").length > 0;1079 if (input_focused)1080 return;1081 if (evt.keyCode == 49)1082 saveCurrentLayout()1083 if (evt.keyCode == 67) {1084 if ($('#canvas').data("overlap_mode")) {1085 $('#canvas').data("design").overlap_regions = [];1086 toggleOverlapMode();1087 toggleOverlapMode();1088 sendCurrentDesign();1089 }1090 }1091 if (evt.keyCode == 65 && evt.shiftKey)1092 selectAllElements()1093 if (evt.keyCode == 189 && evt.shiftKey)1094 scaleCurrentElement(0.9)1095 if (evt.keyCode == 187 && evt.shiftKey)1096 scaleCurrentElement(1.1)1097 if ((evt.keyCode == 68) || (evt.keyCode == 46))1098 deleteCurrentElement()1099 //if (evt.keyCode == 80)1100 // toggleOverlapMode()1101 //if (evt.keyCode == 82)1102 // toggleRegionMode()1103 /*1104 if (evt.keyCode == 32) {1105 switchPauseState();1106 evt.preventDefault();1107 }1108 if (evt.keyCode==70)1109 {1110 $.each($('#canvas').data("design").elements, function(i, elem){1111 if (elem.selected)1112 {1113 if (elem.fixed_amount<1)1114 elem.fixed_amount=11115 else1116 elem.fixed_amount=0.251117 //setStroke(elem.img,true, 1.5,elem.fixed_amount );1118 //elem.img.attrs.opacity=elem.fixed_amount1119 }1120 });1121 $('#canvas').data("design").elements[0].img.getLayer().draw();1122 sendCurrentLayout();1123 }1124 */1125}1126function toggleRegionMode() {1127 var stage = $('#canvas').data("stage");1128 var design = $('#canvas').data("design");1129 var region_layer = $('#canvas').data("region_layer");1130 var layer = stage.get('#layer')[0];1131 if ($('#canvas').data("region_mode")) {1132 //layer.show();1133 console.log("disabling region mode")1134 region_layer.removeChildren();1135 region_layer.draw()1136 $('#canvas').data("region_mode", false)1137 $('#region_controls').hide()1138 } else {1139 console.log("enabling region mode")1140 deselectAll(design.background_elem)1141 design.background_elem.img.getLayer().draw();1142 var backgroundRect = new Kinetic.Rect({1143 x : 0,1144 y : 0,1145 fill : 'black',1146 opacity : 0.25,1147 width : design.width,1148 height : design.height1149 });1150 region_layer.add(backgroundRect)1151 backgroundRect.moveToTop()1152 $.each(design.regions, function(i, reg) {1153 var fill_color = getRegionColor(reg)1154 var rect = new Kinetic.Rect({1155 x : reg.x,1156 y : reg.y,1157 fill : fill_color,1158 opacity : 0.25,1159 width : reg.width,1160 height : reg.height,1161 draggable : true,1162 stroke : 'Red',1163 strokeWidth : 2,1164 lineJoin : 'round',1165 dashArray : [7, 5],1166 strokeEnabled : false1167 });1168 reg.img = rect1169 region_layer.add(rect)1170 reg.anchors = createAnchors(reg, region_layer, false)1171 moveAnchors(reg)1172 setupElementCallbacks(rect, reg)1173 });1174 region_layer.draw()1175 $('#canvas').data("region_mode", true)1176 $('#region_controls').show()1177 hideBackgroundControls()1178 $('#element_controls').hide()1179 }1180}1181function getRegionColor(reg) {1182 if (reg.allow_text && (!reg.allow_graphic))1183 return '#5F5'1184 else if (reg.allow_graphic && (!reg.allow_text))1185 return '#55F'1186 else if (reg.allow_graphic && (reg.allow_text))1187 return '#5FF'1188 else1189 return 'white'1190}1191function toggleOverlapMode() {1192 var stage = $('#canvas').data("stage");1193 var design = $('#canvas').data("design");1194 var overlap_layer = $('#canvas').data("overlap_layer");1195 var layer = stage.get('#layer')[0];1196 if ($('#canvas').data("overlap_mode")) {1197 //layer.show();1198 console.log("disabling overlap mode")1199 overlap_layer.removeChildren();1200 overlap_layer.draw()1201 $('#canvas').data("overlap_mode", false)1202 } else {1203 //layer.hide();1204 console.log("enabling overlap mode")1205 var backgroundRect = new Kinetic.Rect({1206 x : 0,1207 y : 0,1208 fill : 'black',1209 opacity : 0.25,1210 width : design.width,1211 height : design.height1212 });1213 overlap_layer.add(backgroundRect)1214 backgroundRect.moveToTop()1215 //var elem_list=design.elements1216 //elem_list.push(design.back_elem)1217 $.each(design.elements, function(i, elem) {1218 var x = elem.x1219 var y = elem.y1220 var w = elem.img.getWidth()1221 var h = elem.img.getHeight()1222 var draw_overlap = false;1223 if (elem.type == 'text')1224 draw_overlap = true1225 else1226 $.each(design.overlap_regions, function(i, or) {1227 if (or.elem_id == elem.id) {1228 draw_overlap = true;1229 x = x + w * or.x_min;1230 y = y + h * or.y_min;1231 w = w * (or.x_max - or.x_min);1232 h = h * (or.y_max - or.y_min);1233 }1234 });1235 if (draw_overlap) {1236 var rect = new Kinetic.Rect({1237 x : x,1238 y : y,1239 fill : 'white',1240 opacity : 0.25,1241 width : w,1242 height : h1243 });1244 overlap_layer.add(rect)1245 }1246 });1247 for (var i = 0; i < design.overlap_regions.length; i++) {1248 var or = design.overlap_regions[i]1249 console.log("or.elem_id " + or.elem_id)1250 if (or.elem_id == 0) {1251 var rect = new Kinetic.Rect({1252 x : or.x_min * design.width,1253 y : or.y_min * design.height,1254 fill : 'white',1255 opacity : 0.25,1256 width : design.width * (or.x_max - or.x_min),1257 height : design.height * (or.y_max - or.y_min)1258 });1259 overlap_layer.add(rect)1260 console.log("adding rectangle " + rect.attrs.x + " " + rect.attrs.y + " ")1261 }1262 }1263 overlap_layer.draw()1264 overlap_layer.on("mousedown", function(evt) {1265 console.log("mouse down")1266 var mousePos = stage.getPointerPosition();1267 var overlapRect = new Kinetic.Rect({1268 x : mousePos.x,1269 y : mousePos.y,1270 fill : 'white',1271 opacity : 0.25,1272 width : 0,1273 height : 0,1274 id : "current_overlap"1275 });1276 overlap_layer.add(overlapRect)1277 overlap_layer.draw()1278 $('#canvas').data("mousePos", mousePos)1279 console.log("down")1280 console.log($('#canvas').data("mousePos"))1281 });1282 overlap_layer.on("mousemove", function() {1283 var mousePos0 = $('#canvas').data("mousePos")1284 if (mousePos0 == 0)1285 return;1286 var mousePos = stage.getPointerPosition();1287 var overlapRect = stage.get('#current_overlap')[0];1288 //if (overlapRect!=undefined)1289 //{1290 if (mousePos.y < mousePos0.y)1291 overlapRect.setY(mousePos.y)1292 if (mousePos.x < mousePos0.x)1293 overlapRect.setX(mousePos.x)1294 overlapRect.setHeight(Math.abs(mousePos.y - mousePos0.y))1295 overlapRect.setWidth(Math.abs(mousePos.x - mousePos0.x))1296 //console.log(overlapRect.getWidth()+" "+overlapRect.getHeight())1297 //overlap_layer.draw()1298 //}1299 });1300 overlap_layer.on("mouseup", function() {1301 console.log("mouse up (overlap)")1302 if (($('#canvas').data("mousePos") == 0))1303 return;1304 $('#canvas').data("mousePos", 0)1305 console.log($('#canvas').data("mousePos"))1306 var overlapRect = stage.get('#current_overlap')[0];1307 //var elem=findElement(overlapRect.attrs.x,overlapRect.attrs.y,overlapRect.getWidth(),overlapRect.getHeight())1308 var elem = design.background_elem;1309 overlap = {}1310 overlap.elem_id = elem.id1311 console.log("Creating new OR with elem id " + elem.id)1312 overlap.x_min = (overlapRect.attrs.x - elem.x) / elem.img.getWidth()1313 overlap.y_min = (overlapRect.attrs.y - elem.y) / elem.img.getHeight()1314 overlap.x_max = overlap.x_min + overlapRect.getWidth() / elem.img.getWidth()1315 overlap.y_max = overlap.y_min + overlapRect.getHeight() / elem.img.getHeight()1316 if ((overlap.x_max - overlap.x_min > 0.01) && (overlap.y_max - overlap.y_min > 0.01)) {1317 console.log("")1318 design.overlap_regions.push(overlap)1319 overlap_layer.draw()1320 sendCurrentDesign()1321 }1322 });1323 $('#canvas').data("overlap_mode", true)1324 }1325}1326function selectAllElements() {1327 console.log("select all")1328 var elements = $('#canvas').data("design").elements;1329 $.each(elements, function(i, e) {1330 e.img.attrs.strokeEnabled = true;1331 $.each(e.anchors, function(i, a) {1332 a.hide();1333 });1334 e.selected = true;1335 });1336 elements[0].img.getLayer().draw();1337}1338/*1339function switchPauseState() {1340 if ($('#canvas').data("paused") == false)1341 pauseSuggestions()1342 else1343 resumeSuggestions()1344}1345function pauseSuggestions() {1346 //$('#pauseButton').text("Resume")1347 //$('#pauseButton').removeClass("btn-warning")1348 //$('#pauseButton').addClass("btn-success")1349 $('#pauseButton').hide()1350 $('#startButton').show()1351 $('#canvas').data("paused", true)1352}1353*/1354function resumeSuggestions() {1355 if (!$('#canvas').data("suggestionsEnabled"))1356 return1357 if ($('#canvas').data("design").elements.length <= 1) {1358 console.log("not enough elements to start suggestions")1359 //return1360 }1361 if (($('#suggestion_status').text() == "Inactive"))1362 startSuggestions()1363 $('#canvas').data("status_log").push("Resume")1364 sendCurrentLayout('Resume')1365 /*1366 $('#pauseButton').show()1367 $('#startButton').hide()1368 $('#canvas').data("paused", false)1369 */1370}1371function deleteCurrentElement() {1372 $('#element_controls').hide()1373 document.body.style.cursor = "default";1374 $('#canvas').data("text_mode", false)1375 $('#canvas').data("user_input_log").push("Remove")1376 $('#canvas').data("status_log").push("Remove")1377 var layer = $('#canvas').data("stage").get('#layer')[0];1378 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];1379 var elements;1380 if ($('#canvas').data("region_mode"))1381 elements = $('#canvas').data("design").regions1382 else1383 elements = $('#canvas').data("design").elements1384 if ($('#canvas').data("selected").type == 'background')1385 return;1386 var rem = elements.indexOf($('#canvas').data("selected"));1387 console.log("removing element " + rem)1388 elements[rem].img.destroy();1389 if ("sugg_img" in elements[rem]) {1390 elements[rem].sugg_img.destroy();1391 }1392 console.log(elements)1393 $.each(elements[rem].anchors, function(i, a) {1394 a.destroy();1395 });1396 elements[rem].lock_img.destroy()1397 elements[rem].unlock_img.destroy()1398 elements[rem].tweakable_img.destroy()1399 $.each($('#canvas').data("align_lines"), function(i, al) {1400 al[0].destroy()1401 });1402 $('#canvas').data("align_lines", [])1403 elements.splice(rem, 1);1404 sendCurrentDesign();1405 sendCurrentLayout('Delete');1406 layer.draw()1407 sugg_layer.draw()1408 $('#canvas').data("selected", $('#canvas').data("design").background_elem)1409}1410function scaleCurrentElement(scale_factor) {1411 var elem = $('#canvas').data("selected");1412 if ((elem != undefined) && (elem.type != "background")) {1413 var curr_height = elem.img.getHeight()1414 var new_height = Math.max(curr_height * scale_factor, 5);1415 elem.height = new_height;1416 elem.img.setHeight(new_height)1417 if (elem.type == 'region') {1418 elem.img.setWidth(elem.img.getWidth() * scale_factor)1419 elem.width = elem.img.getWidth();1420 } else1421 elem.img.setWidth(new_height * elem.aspect_ratio)1422 elem.width = elem.img.getWidth();1423 moveAnchors(elem)1424 elem.img.getLayer().draw()1425 }1426}1427/*1428 function setCurrentSuggestion(evt)1429 {1430 setCurrentLayout($('#suggestion_canvas').data("layout"))1431 elements[0].img.getLayer().draw();1432 }1433 */1434function copyCurrentDesign() {1435 var design = $('#canvas').data("design");1436 var design_copy = jQuery.extend(true, {}, design);1437 //$.each(design_copy, function (i, elem){1438 //});1439 return design_copy;1440}1441function addSavedLayout(img,data_url,curr_layout,sugg_id,save_to_server){1442 console.log("addSavedLayout")1443 1444 var new_layout_elem = $('#saved_layout0').clone()1445 new_layout_elem.data("preview_image", img);1446 new_layout_elem.data("layout", curr_layout);1447 new_layout_elem.data("time", new Date());1448 new_layout_elem.data("sugg_id", sugg_id);1449 new_layout_elem.attr("id", "saved_layout" + sugg_id)1450 new_layout_elem.mouseover(function() {1451 viewLayout('saved', sugg_id)1452 })1453 new_layout_elem.click(function() {1454 setFixedLayout('saved', sugg_id)1455 })1456 //new_layout_elem.dblclick(function() {setFixedLayout('saved',count)})1457 var stage = $('#canvas').data("stage");1458 var canvas = new_layout_elem[0];1459 var ctx = canvas.getContext("2d")1460 ctx.drawImage(img, 0, 0, stage.attrs.width / 3, stage.attrs.height / 3);1461 var remove_layout_elem = $('#remove_saved_layout0').clone()1462 remove_layout_elem.click(function() {1463 removeSavedLayout(sugg_id)1464 })1465 1466 1467 $('#saved_table').append($('<tr>').append($('<td>').append(new_layout_elem), $('<td>').append(remove_layout_elem)))1468 1469 1470 if (save_to_server)1471 {1472 var hit_id = gup('hitId')1473 var fname = 'layouts/' + $('#canvas').data("design").name + '-' + gup('workerId') + "-" + hit_id + "-" + String(sugg_id) + '.png'1474 saveImageOnServer(fname, data_url)1475 }1476 1477 1478 1479 var retarget=gup('retarget')1480 if (retarget!='')1481 {1482 var splt=retarget.split("_")1483 var new_width=parseInt(splt[0])1484 var new_height=parseInt(splt[1]) 1485 retargetElements(new_height,new_width) 1486 var retarget_layout =getCurrentLayout()1487 1488 setCurrentLayout(curr_layout)1489 1490 new_layout_elem.data("retarget_layout", retarget_layout);1491 1492 console.log("retarget_layout:"+retarget_layout)1493 }1494 1495 1496 1497 1498}1499function saveCurrentLayout() {1500 var stage = $('#canvas').data("stage");1501 var curr_layout = getCurrentLayout()1502 1503 1504 var num_saved = $('#saved_table').find("tr").length - 1;1505 var max_saved = 100;1506 if (gup("maxSaved") != undefined)1507 max_saved = parseInt(gup("maxSaved"))1508 if (num_saved >= max_saved) {1509 alert("You have reached the maximum number of saved layouts: " + max_saved + ". Remove other layouts before saving.")1510 return;1511 }1512 $('#canvas').data("user_input_log").push("Save")1513 $('#canvas').data("status_log").push("Save")1514 $.each($('#canvas').data("design").elements, function(i, e) {1515 e.state_img.show()1516 });1517 1518 1519 stage.toDataURL({1520 1521 callback: function(data_url2) {1522 1523 var sugg_id = Math.round(Math.random() * 100000)1524 1525 1526 console.log("rendering first time")1527 var fname='layouts/states/'+$('#canvas').data("design").name+'-'+gup('workerId')+"-"+gup('hitId')+"-"+String(sugg_id)1528 saveDesignOnServer(data_url2,'',fname)1529 1530 $.each($('#canvas').data("design").elements, function(i, e) {1531 e.img.attrs.strokeEnabled = false;1532 e.state_img.hide()1533 $.each(e.anchors, function(i, a) {1534 a.hide();1535 });1536 });1537 1538 $.each($('#canvas').data("align_lines"), function(i, al) {1539 al[0].hide()1540 }); 1541 1542 stage.toDataURL({1543 callback : function(data_url) {1544 var img = new Image();1545 1546 img.onload = function() {1547 1548 console.log("rendering second time")1549 //$('#canvas').data("saved_images").push(img);1550 //$('#canvas').data("saved_layouts").push(curr_layout);1551 //$('#canvas').data("saved_designs").push(copyCurrentDesign());1552 1553 //var count = $("#saved_table").children().children().length;1554 1555 //$("#saved_row").parent().css("padding",1)1556 1557 addSavedLayout(img,data_url,curr_layout,sugg_id,true)1558 1559 /*1560 for (var i=0;i < Math.min(saved_layouts.length,9);i++)1561 {1562 1563 $('#saved_layout'+i).data("preview_image",saved_images[i]);1564 $('#saved_layout'+i).data("layout",saved_layouts[i]);1565 var canvas=$('#saved_layout'+i)[0];1566 var ctx=canvas.getContext("2d")1567 ctx.drawImage(saved_images[i],0,0,stage.attrs.width/3,stage.attrs.height/3);1568 1569 }1570 */1571 1572 $.each($('#canvas').data("design").elements, function(i, e) {1573 if (e.selected) {1574 e.img.attrs.strokeEnabled = true;1575 e.state_img.show()1576 $.each(e.anchors, function(i, a) {1577 a.show();1578 });1579 }1580 });1581 $.each($('#canvas').data("align_lines"), function(i, al) {1582 al[0].show()1583 });1584 1585 //resetLayout() 1586 1587 }1588 img.src = data_url;1589 1590 }1591 });1592 1593 1594 }1595 });1596 1597 1598 1599}1600function removeSavedLayout(id) {1601 console.log("id to remove:" + id)1602 $("#saved_layout" + id).parent().parent().remove()1603 $('#canvas').data("user_input_log").push("Rm Layout")1604 $('#canvas').data("status_log").push("Rm Layout")1605}1606function saveDesign() {1607 1608 console.log("saveDesign")1609 var stage = $('#canvas').data("stage");1610 var design = $('#canvas').data("design");1611 $.each(design.elements, function(i, e) {1612 e.img.attrs.strokeEnabled = false;1613 e.state_img.hide()1614 $.each(e.anchors, function(i, a) {1615 a.hide();1616 });1617 });1618 $.each($('#canvas').data("align_lines"), function(i, al) {1619 al[0].hide()1620 });1621 console.log("height " + design.elements[0].height)1622 1623 1624 1625 var saved_canvases = $("#saved_table").find("canvas")1626 console.log("saved_canvases.length:" + saved_canvases.length)1627 design.saved_layouts=[]1628 $.each(saved_canvases, function(i, saved_img) {1629 design.saved_layouts.push($(saved_img).data("layout"))1630 });1631 1632 1633 stage.toDataURL({1634 callback : function(data_url) {1635 saveDesignOnServer(data_url, design)1636 $.each(design.elements, function(i, e) {1637 if (e.selected) {1638 e.img.attrs.strokeEnabled = true;1639 e.state_img.show()1640 $.each(e.anchors, function(i, a) {1641 a.show();1642 });1643 }1644 });1645 $.each($('#canvas').data("align_lines"), function(i, al) {1646 al[0].show()1647 });1648 }1649 });1650}1651function setFixedLayout(layout_type, layout_num) {1652 viewLayout('interactive', -1);1653 deselectAll()1654 console.log("setting " + layout_type + " layout: " + layout_num)1655 //setCurrentLayout($('#canvas').data("saved_layouts")[i],true)1656 setCurrentLayout($('#' + layout_type + '_layout' + layout_num).data("layout"), true);1657 //pauseSuggestions();1658 sendCurrentLayout('set-'+layout_type);1659 $('#canvas').data("user_input_log").push("Load-" + layout_type)1660 $('#canvas').data("status_log").push("Load-" + layout_type)1661 //if (!$('#canvas').data("noSuggestions"))1662 // $('#suggestion_lk').click()1663 if ($('#canvas').data("overlap_mode")) {1664 toggleOverlapMode();1665 toggleOverlapMode();1666 }1667 if ($('#canvas').data("region_mode")) {1668 toggleRegionMode();1669 toggleRegionMode();1670 }1671}1672function resetLayout() {1673 deselectAll()1674 var design = $('#canvas').data("design");1675 var run_offset = $('#canvas').data("run_offset");1676 if (run_offset == undefined)1677 run_offset = 0;1678 run_offset = 0;1679 $('#canvas').data("run_offset", run_offset)1680 $('#canvas').data("user_input_log").push("Reset")1681 $('#canvas').data("status_log").push("Reset")1682 var curr_layout = getCurrentLayout()1683 $('#canvas').data("ignore_layout", curr_layout)1684 console.log("resetting from layout:" + $('#canvas').data("ignore_layout"))1685 //$.each($('#canvas').data("design").elements,function (i,e){e.fixed_amount=0.01})1686 //return1687 $.each(design.elements, function(i, e) {1688 1689 1690 var new_height = 01691 1692 1693 e.state_img.hide()1694 e.state_img = e.unlock_img1695 e.fixed_amount = 0.011696 1697 1698 if (e.type == 'graphic') {1699 new_height = 801700 } else if (e.type == 'text') {1701 1702 if (e.num_lines<=3)1703 {1704 var num_lines=Math.round(Math.random()*2+1)1705 console.log(num_lines)1706 selectAlternateElement(e,num_lines)1707 1708 }1709 new_height = 20 * e.num_lines1710 }1711 console.log("design height " + design.height + ", e height " + e.height)1712 e.height = new_height1713 e.width = e.height * e.aspect_ratio1714 var new_x = Math.random() * (design.width - e.width)1715 var new_y = Math.random() * (design.height - e.height)1716 e.x = new_x1717 e.y = new_y1718 e.last_x = new_x1719 e.last_y = new_y1720 e.img.setPosition(new_x, new_y)1721 e.img.setWidth(e.width)1722 e.img.setHeight(e.height)1723 e.state_img.hide()1724 e.fixed_amount = 0.011725 e.state_img = e.unlock_img1726 1727 e.state_img.setPosition(e.x + e.width, e.y)1728 1729 1730 });1731 1732 design.elements[0].img.getLayer().draw()1733 addLayoutToStack(getCurrentLayout())1734 sendCurrentLayout('Reset',true)1735 $('#canvas').data("energy_lists", {})1736 $('#checkingImage').css("visibility","hidden");1737 $('#canvas').data("started", true)1738 //stopSuggestions()1739 allowUpdates()1740 //startSuggestions(run_offset)1741}1742function viewLayout(layout_type, layout_num) {1743 console.log("view " + layout_type + " layout " + layout_num)1744 if ((layout_num < 0) && $('#canvas').data("preview") > -1) {1745 $('#canvas').data("preview", -1)1746 $('#canvas').data("preview_image").hide()1747 $('#canvas').data("preview_image").getLayer().draw()1748 $('#canvas').data("overlap_layer").show()1749 $('.selectedPreview').removeClass("selectedPreview")1750 1751 1752 } else if ($('#' + layout_type + '_layout' + layout_num).data("layout") != undefined) {1753 $('#' + layout_type + '_layout' + layout_num).addClass("selectedPreview")1754 $('#canvas').data("overlap_layer").hide()1755 $('#canvas').data("preview", layout_num)1756 $('#canvas').data("preview_image").show()1757 $('#canvas').data("preview_image").attrs.fillPatternImage = $('#' + layout_type + '_layout' + layout_num).data("preview_image")1758 1759 $('#canvas').data("preview_image").attrs.stroke='#0F0'1760 $('#canvas').data("preview_image").attrs.strokeEnabled=true1761 $('#canvas').data("preview_image").attrs.strokeWidth=41762 1763 $('#canvas').data("preview_image").moveToTop()1764 $('#canvas').data("preview_image").getLayer().draw()1765 1766 /*1767 var canvas = $('#' + layout_type + '_layout' + layout_num)[0];1768 var ctx = canvas.getContext("2d")1769 var image = $('#canvas').data("images")['checkmark'];1770 var sugg_stage= $('#canvas').data("sugg_stage")1771 1772 //var sugg_stage.attrs.width / 31773 ctx.drawImage(image, 0, 0);1774 */1775 1776 }1777}1778function sendDesign() {1779 var elements = $('#canvas').data("design").elements;1780 console.log('sendInitialDesign');1781 for (var j = 0; j < elements.length; j++) {1782 if (elements[j].loaded == false) {1783 setTimeout(sendDesign, 500);1784 return;1785 }1786 }1787 sendCurrentLayout();1788 sendCurrentDesign();1789}1790function updateTextElement(elem) {1791 var old_text_chars = elem.old_text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');1792 var new_text_chars = elem.text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');1793 var old_num_lines = elem.old_text.split("\n").length;1794 var new_num_lines = elem.text.split("\n").length;1795 //var old_text_lines = elem.old_text.replaceAll(',', '').replaceAll(' ', '');1796 //var new_text_lines = elem.text.replaceAll(',', '').replaceAll(' ', '');1797 console.log("old_text: " + old_text_chars)1798 console.log("new_text: " + new_text_chars)1799 /*1800 Cases:1801 1) The new text is identical to the old text1802 - re-render alternates, but use the current texts1803 2) The new text is significantly different than the old text (new words, etc)1804 - get text alternates and re-render everything from scratch1805 3) The new text differs from the old text by the number of lines1806 - render the new text, set that as a new alternate, and update the selection1807 4) The new text only differs from the old text by commas or spaces (tweaking the current)1808 - re-render only this element1809 */1810 // Case 11811 if (elem.old_text == elem.text) {1812 console.log("updateTextElement: Re-rendering existing alternates")1813 renderTextAlts(elem, false)1814 }1815 //Case 21816 else if (old_text_chars != new_text_chars) {1817 console.log("updateTextElement: Completely re-rendering & finding new alternates")1818 renderTextAlts(elem, true)1819 }1820 //Case 31821 else if ((old_num_lines != new_num_lines)) {1822 console.log("updateTextElement: Setting a new alternate with different #s of lines")1823 var alts = $('#canvas').data("design").element_alts[elem.id];1824 if ( new_num_lines in alts) {1825 //selectAlternateElement(new_num_lines)1826 //renderTextElement(elem,true)1827 alts[new_num_lines].text = elem.text1828 elem.text = elem.old_text;1829 renderTextElement(alts[new_num_lines], false)1830 setTimeout(function() {1831 setAlternate(elem, alts[new_num_lines])1832 }, 100)1833 $("#num_lines_select").val(new_num_lines).attr('selected', true);1834 } else {1835 var new_elem = jQuery.extend(true, {}, elem)1836 new_elem.text = elem.text1837 new_elem.num_lines = new_num_lines1838 new_elem.fixed_amount = 11839 elem.text = elem.old_text1840 elem.img.remove()1841 new_elem.loaded = false1842 delete new_elem["img"]1843 renderTextElement(new_elem, true)1844 var max_cnt = 0;1845 $.each(alts, function(i, alt) {1846 max_cnt = Math.max(max_cnt, alt.alternate_id);1847 });1848 new_elem.alternate_id = max_cnt + 11849 alts[new_num_lines] = new_elem1850 //selectElement(new_elem)1851 $("#num_lines_select").val(new_num_lines).attr('selected', true);1852 //return;1853 }1854 }1855 //Case 4: tweaking1856 else {1857 console.log("updateTextElement: Tweaking current")1858 renderTextElement(elem, true)1859 }1860 selectElement(elem)1861}1862function updateTextElementOld(elem) {1863 var old_text = elem.old_text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');1864 var new_text = elem.text.replaceAll('\n', '').replaceAll(',', '').replaceAll(' ', '');1865 console.log("old_text: " + old_text)1866 console.log("new_text: " + new_text)1867 //only update the current alternate, don't replace everything...1868 if (old_text == new_text) {1869 var alts = $('#canvas').data("design").element_alts[elem.id];1870 var old_num_lines = elem.old_text.split("\n").length;1871 var new_num_lines = elem.text.split("\n").length;1872 if (old_num_lines == new_num_lines) {1873 renderTextElement(elem, true)1874 } else {1875 if ( new_num_lines in alts) {1876 alts[new_num_lines].text = elem.text1877 elem.text = elem.old_text;1878 renderTextElement(alts[new_num_lines], true)1879 setAlternate(elem, alts[new_num_lines])1880 } else {1881 var new_elem = jQuery.extend(true, {}, elem)1882 new_elem.text = elem.text1883 new_elem.num_lines = new_num_lines1884 new_elem.fixed_amount = 11885 elem.text = elem.old_text1886 elem.img.remove()1887 new_elem.loaded = false1888 delete new_elem["img"]1889 renderTextElement(new_elem, true)1890 //renderTextElement(elem,false)1891 var max_cnt = 0;1892 $.each(alts, function(i, alt) {1893 max_cnt = Math.max(max_cnt, alt.alternate_id);1894 });1895 new_elem.alternate_id = max_cnt + 11896 alts[new_num_lines] = new_elem1897 setTimeout(function() {1898 selectElement(new_elem)1899 }, 500)1900 }1901 $("#num_lines_select").val(new_num_lines).attr('selected', true);1902 }1903 } else {1904 delete $('#canvas').data("design").element_alts[String(elem.id)]1905 renderTextAlts(elem, true)1906 //selectElement(elem)1907 }1908}1909function fixElementImages() {1910 1911 1912 var design=$('#canvas').data("design");1913 var layer = $('#canvas').data("stage").get('#layer')[0];1914 1915 1916 $.each(design.elements, function (i, elem){1917 1918 1919 elem.img.remove()1920 1921 console.log(design.element_alts[elem.id])1922 1923 if (design.element_alts[elem.id]!= undefined)1924 {1925 $.each(design.element_alts[elem.id], function(i, e) {1926 e.img.remove()1927 1928 console.log(e.alignment_imgs)1929 $.each(e.alignment_imgs, function(j, ai) {1930 ai.remove()1931 });1932 $.each(e.anchors, function(i, a) {1933 a.hide()1934 });1935 });1936 }1937 1938 if ((elem.num_lines > 1) && (elem.img != elem.alignment_imgs[elem.align])) {1939 elem.img = elem.alignment_imgs[elem.align];1940 }1941 1942 elem.img.setPosition(elem.x, elem.y)1943 elem.img.attrs.strokeEnabled = elem.selected1944 elem.img.setHeight(elem.height)1945 elem.img.setWidth(elem.height * elem.aspect_ratio)1946 elem.img.setOpacity(1)1947 1948 layer.add(elem.img)1949 elem.img.show()1950 1951 });1952}1953function renderTextAlts(elem, createAlternates) {1954 console.log("rendering text alts for element text: " + elem.text)1955 elem.orig_text = elem.text1956 var idx = $('#canvas').data("design").elements.indexOf(elem);1957 var text_alts = {};1958 if (elem.id in $('#canvas').data("design").element_alts) {1959 var elem_alts = $('#canvas').data("design").element_alts[elem.id];1960 $.each(elem_alts, function(i, alt) {1961 var num_lines = alt.text.split("\n").length1962 text_alts[num_lines] = alt.text1963 if ((alt.img != undefined) && ( typeof (alt.img) != 'string')) {1964 console.log("typeof(alt.img) " + typeof (alt.img))1965 alt.img.remove()1966 alt.sugg_img.remove()1967 $.each(alt.anchors, function(i, a) {1968 a.destroy();1969 });1970 }1971 })1972 }1973 if ((!(elem.id in $('#canvas').data("design").element_alts)) || (createAlternates))1974 text_alts = findTextAlternates(elem.text)1975 var alts = {}1976 var cnt = 0;1977 $.each(text_alts, function(i, text) {1978 //console.log("rendering text with num_lines "+elem.num_lines+" \n"+)1979 var new_elem;1980 if (text == elem.orig_text) {1981 console.log("matching orig")1982 new_elem = elem1983 $('#canvas').data("design").elements[idx] = new_elem1984 } else {1985 new_elem = jQuery.extend(true, {}, elem)1986 new_elem.text = text1987 new_elem.num_lines = text.split("\n").length1988 }1989 new_elem.state_img = elem.state_img;1990 new_elem.unlock_img = elem.unlock_img;1991 new_elem.tweakable_img = elem.tweakable_img;1992 new_elem.lock_img = elem.lock_img;1993 delete new_elem["img"];1994 delete new_elem["sugg_img"];1995 renderTextElement(new_elem, false)1996 alts[new_elem.num_lines] = new_elem1997 new_elem.alternate_id = cnt1998 cnt = cnt + 11999 });2000 $('#canvas').data("design").element_alts[elem.id] = alts;2001}2002function selectAlternateElement(elem, num_lines) {2003 console.log("setting element " + elem.id + " with num lines " + num_lines)2004 var alts = $('#canvas').data("design").element_alts[elem.id]2005 if ( num_lines in alts) {2006 setAlternate(elem, alts[num_lines])2007 }2008 //design.elements[idx].style=elem.style2009}2010function renderTextElement(elem, is_visible) {2011 var layer = $('#canvas').data("stage").get('#layer')[0];2012 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];2013 //var layer=elem.img.getLayer();2014 //var sugg_layer=elem.sugg_img.getLayer();2015 console.log("rendering text for element " + elem.text)2016 fontStyle = ''2017 if (elem.bold)2018 fontStyle = fontStyle + " bold";2019 if (elem.italic)2020 fontStyle = fontStyle + " italic";2021 var sugg_pos={}2022 sugg_pos.x=elem.x;2023 sugg_pos.y=elem.y;2024 sugg_pos.height=elem.height;2025 2026 2027 if ("img" in elem) {2028 console.log("removing img from element")2029 sugg_pos.x = elem.sugg_img.getAbsolutePosition().x2030 sugg_pos.y = elem.sugg_img.getAbsolutePosition().y2031 sugg_pos.height = elem.sugg_img.getHeight()2032 elem.x = elem.img.getAbsolutePosition().x2033 elem.y = elem.img.getAbsolutePosition().y2034 elem.height = elem.img.getHeight()2035 elem.width = elem.img.getWidth()2036 elem.img.destroy()2037 elem.sugg_img.destroy()2038 $.each(elem.alignment_imgs, function(i, ai) {2039 ai.destroy()2040 });2041 $.each(elem.anchors, function(i, a) {2042 a.destroy()2043 });2044 }2045 var alignments;2046 elem.num_lines = elem.text.split("\n").length;2047 // wierd...look into this fixed_alignment2048 if ((elem.num_lines > 1) && ((!("fixed_alignment" in elem)) || (elem.fixed_alignment == false)))2049 alignments = ["left", "center", "right"];2050 else2051 alignments = [elem.align]2052 console.log("alignments: " + (alignments))2053 elem.max_line_length = 0;2054 $.each(elem.text.split("\n"), function(i, t) {2055 elem.max_line_length = Math.max(elem.max_line_length, t.length)2056 });2057 console.log("max line length: " + elem.max_line_length)2058 //elem.num_align=alignments.length2059 elem.alignment_imgs = {}2060 elem.alignment_sugg_imgs = {}2061 console.log("font: " + elem.font)2062 console.log("fontStyle: " + fontStyle)2063 2064 2065 $('#canvas').data("images_rendering",$('#canvas').data("images_rendering")+alignments.length)2066 $.each(alignments, function(index, curr_alignment) {2067 elem.init_font_size= (60 / elem.num_lines + 10);2068 var text2069 if (elem.shadow)2070 text = new Kinetic.Text({2071 x : 0,2072 y : 0,2073 text : elem.text,2074 fill : elem.color,2075 fontSize : (60 / elem.num_lines + 10),2076 fontStyle : fontStyle,2077 fontFamily : elem.font,2078 align : curr_alignment,2079 shadowColor: 'black',2080 shadowBlur: 10,2081 shadowOffset: {x:5,y:5},2082 shadowOpacity: 0.52083 });2084 else2085 text = new Kinetic.Text({2086 x : 0,2087 y : 0,2088 text : elem.text,2089 fill : elem.color,2090 fontSize : (60 / elem.num_lines + 10),2091 fontStyle : fontStyle,2092 fontFamily : elem.font,2093 align : curr_alignment2094 });2095 2096 /*2097 var sans_serif_width=text.getWidth()2098 console.log("sans serif width:"+sans_serif_width)2099 2100 text.attrs.fontFamily=elem.font2101 var font_width=text.getWidth()2102 console.log("font width:"+font_width)2103 2104 if ((elem.font!= 'sans-serif') && (font_width==sans_serif_width))2105 {2106 console.log("ERROR. Font not loaded. Rendering as sans-serif. Wait till loaded") 2107 2108 2109 var callback = function (){textToImage(text,curr_alignment, sugg_pos,elem,layer,is_visible)};2110 2111 var interval;2112 var cnt=0;2113 2114 var checkFontWidth=function()2115 {2116 text.attrs.fontFamily=elem.font2117 var width=text.getWidth()2118 console.log("checkFontWidth "+width+ ", sans_serif_width "+sans_serif_width+", cnt "+cnt)2119 console.log(interval)2120 if (width!=sans_serif_width)2121 {2122 console.log("clearing interval and textToImage ")2123 clearInterval(interval)2124 callback()2125 } 2126 cnt+=1;2127 }2128 2129 //interval= setInterval(checkFontWidth,1000)2130 2131 }2132 //else2133 */2134 textToImage(text,curr_alignment, sugg_pos,elem,layer,sugg_layer,is_visible)2135 2136 /*2137 if (gup('hideContent') == '1')2138 text = new Kinetic.Text({2139 x : 0,2140 y : 0,2141 text : 'Text',2142 fill : 'black',2143 height : text.getHeight(),2144 width : text.getWidth(),2145 fontSize : 30,2146 fontFamily : 'Calibri',2147 align : 'center'2148 });2149 */2150 2151 });2152}2153function textToImage(text, curr_alignment,sugg_pos, elem, layer,sugg_layer,is_visible)2154{2155 elem.anchors = createAnchors(elem, layer, false)2156 elem.aspect_ratio = text.getWidth() / text.getHeight()2157 //elem.aspect_ratio=img.width/img.height2158 console.log("text: " + elem.text + " \n aspect ratio " + elem.aspect_ratio)2159 text.toImage({2160 x : 0,2161 y : 0,2162 width : (text.getWidth()+5),2163 height : (text.getHeight()+5),2164 callback : function(img) {2165 2166 $('#canvas').data("images_rendering",$('#canvas').data("images_rendering")-1)2167 /*2168 var canvas = document.createElement('canvas');2169 canvas.width=img.width2170 canvas.height=img.height2171 var context = canvas.getContext('2d');2172 context.drawImage(img, 0, 0 );2173 var data = context.getImageData(0, 0, img.width, img.height).data;2174 //console.log(data)2175 var min_x=img.width, max_x=-1;2176 var min_y=img.height, max_y=-1;2177 for(var y = 0; y < img.height; y++)2178 for(var x = 0; x < img.width; x++)2179 {2180 if (data[((img.width * y) + x) * 4 + 3]!=0)2181 {2182 min_x=Math.min(min_x,x)2183 min_y=Math.min(min_y,y)2184 max_x=Math.max(max_x,x)2185 max_y=Math.max(max_y,y)2186 }2187 }2188 */2189 var add_background = ''2190 if (gup('hideContent') == '1') {2191 add_background = function(pixels) {2192 var d = pixels.data;2193 for (var i = 0; i < d.length; i += 4) {2194 var alpha = (d[i + 3] / 255)2195 //d[i] += alpha*d[i]+(1-alpha)*135;2196 // d[i+1] += alpha*d[i+1]+(1-alpha)*206;2197 //d[i+2] += alpha*d[i+2]+(1-alpha)*235;2198 d[i] += alpha * d[i] + (1 - alpha) * 0;2199 d[i + 1] += alpha * d[i + 1] + (1 - alpha) * 255;2200 d[i + 2] += alpha * d[i + 2] + (1 - alpha) * 127;2201 d[i + 3] = 255;2202 }2203 return pixels;2204 };2205 }2206 var text_img = new Kinetic.Image({2207 image : img,2208 x : elem.x,2209 y : elem.y,2210 width : img.width, //max_x-min_x,2211 height : img.height, //max_y-min_y,2212 strokeEnabled : is_visible,2213 stroke : 'Red',2214 strokeWidth : 2,2215 lineJoin : 'round',2216 dashArray : [7, 5],2217 name : String(elem.id),2218 draggable : true,2219 visible : false,2220 filter : add_background2221 //crop: {2222 //x: min_x,2223 //y: min_y,2224 //width: max_x-min_x,2225 // height: max_y-min_y2226 //}2227 });2228 2229 elem.init_height= img.height;2230 var scale = 1.0;2231 if (elem.old_text.length > 0) {2232 var old_num_lines = elem.old_text.split("\n").length;2233 scale = elem.num_lines / old_num_lines;2234 }2235 elem.alignment_imgs[curr_alignment] = text_img2236 text_img.setHeight(elem.height * scale);2237 text_img.setWidth(elem.height * scale * elem.aspect_ratio);2238 var sugg_text_img = text_img.clone();2239 sugg_text_img.setX(sugg_pos.x);2240 sugg_text_img.setY(sugg_pos.x);2241 sugg_text_img.setHeight(sugg_pos.height)2242 sugg_text_img.setWidth(sugg_pos.height * elem.aspect_ratio)2243 sugg_text_img.attrs.strokeEnabled = false;2244 elem.alignment_imgs[curr_alignment] = text_img2245 elem.alignment_sugg_imgs[curr_alignment] = sugg_text_img2246 console.log("create text with num_lines " + elem.num_lines + " with alignment:" + curr_alignment + " " + elem.align)2247 if ((elem.num_lines == 1) || (elem.align == curr_alignment)) {2248 elem.img = text_img;2249 layer.add(text_img);2250 if ((is_visible) || (elem.text == elem.orig_text)) {2251 console.log('matched elem text: ' + elem.orig_text)2252 //$.each(elem.anchors, function(i,a){2253 // layer.add(a)2254 //a.moveToTop()2255 //});2256 //moveAnchors(elem)2257 elem.img.show()2258 layer.draw()2259 }2260 }2261 if ((elem.num_lines == 1) || (elem.sugg_align == curr_alignment)) {2262 elem.sugg_img = sugg_text_img;2263 sugg_layer.add(sugg_text_img);2264 if ((is_visible) || (elem.text == elem.orig_text)) {2265 sugg_layer.draw()2266 elem.sugg_img.show()2267 }2268 }2269 setupElementCallbacks(text_img, elem);2270 elem.loaded = true;2271 }2272 });2273}2274function findTextAlternates(text) {2275 var alts = {};2276 var one_line = text.split("\n").join(" ");2277 var num_words = one_line.split(" ").length;2278 alts[1] = one_line;2279 var init_num_lines = text.split("\n").length;2280 console.log("one line: " + one_line);2281 console.log("num words:" + num_words);2282 //console.log("init_num_lines "+init_num_lines)2283 for (var n = 2; n <= Math.min(num_words, 8); n++) {2284 var line_size = one_line.length / n;2285 console.log('line size' + line_size)2286 var new_text = ''2287 var curr_idx = 0;2288 var check_idx = curr_idx + line_size;2289 for (var i = 0; i < n - 1; i++) {2290 var idx1 = one_line.indexOf(' ', check_idx);2291 var idx2 = one_line.substring(0, check_idx).lastIndexOf(' ');2292 if ((idx1 == -1) && (idx2 == -1)) {2293 console.log("index ==-1 ")2294 continue2295 }2296 var idx = 02297 if ((((idx1 - check_idx) < (check_idx - idx2)) || (idx2 >= one_line.length - 1) || (idx2 == -1)) && (idx1 != -1))2298 idx = idx1;2299 else2300 idx = idx2;2301 console.log('n' + n + ' i ' + i + " curr idx " + curr_idx + " idx " + idx)2302 console.log(" idx1 " + idx1 + " " + " idx2 " + idx2)2303 new_text += one_line.substring(curr_idx, idx + 1) + "\n"2304 curr_idx = idx;2305 check_idx += line_size;2306 }2307 new_text += one_line.substring(curr_idx, one_line.length)2308 console.log('new_text: ' + new_text)2309 var lines = new_text.split("\n")2310 var text2 = ''2311 var max_len = 0;2312 for (var j = 0; j < lines.length; j++) {2313 if (lines[j].length > 0) {2314 var trimmed = lines[j].trim()2315 text2 += trimmed + "\n"2316 max_len = Math.max(max_len, trimmed.length)2317 }2318 }2319 text2 = text2.substring(0, text2.length - 1)2320 var num_lines = text2.split("\n").length;2321 var ratio = (max_len) / (num_lines)2322 console.log('Creating text alt ' + n + ' with num_lines ' + num_lines + ", ratio: " + ratio + "\n" + text2)2323 //if ((num_lines>2) && (ratio<5))2324 // continue;2325 alts[num_lines] = text2;2326 }2327 alts[init_num_lines] = text;2328 return alts;2329}2330function deselectAll(elem) {2331 var other;2332 if ((elem != undefined) && (elem.type == 'region'))2333 other = $('#canvas').data("design").regions2334 else2335 other = $('#canvas').data("design").elements2336 2337 $('#canvas').data("selected", elem);2338 if (elem==undefined)2339 $('#canvas').data("selected", 0);2340 2341 console.log('selected: '+$('#canvas').data("selected"))2342 $.each($('#canvas').data("align_lines"), function(i, al) {2343 al[0].destroy()2344 });2345 $('#canvas').data("align_lines", [])2346 $.each(other, function(i, e) {2347 if ((e != elem)) {2348 e.state_img.hide()2349 if (e.selected) {2350 e.img.attrs.strokeEnabled = false;2351 $.each(e.anchors, function(i, a) {2352 a.hide();2353 });2354 e.selected = false;2355 }2356 }2357 });2358}2359function selectMultipleElements(p1, p2) {2360 console.log('p1:' + p1.x + ' ' + p1.y)2361 console.log('p2: ' + p2.x + ' ' + p2.y)2362 var x = Math.min(p1.x, p2.x)2363 var y = Math.min(p1.y, p2.y)2364 var width = Math.max(p1.x, p2.x) - x2365 var height = Math.max(p1.y, p2.y) - y2366 var selected = []2367 $.each($('#canvas').data("design").elements, function(i, e) {2368 if (!((x + width < e.x) || (e.x + e.width < x) || (y + height < e.y) || (e.y + e.height < y)))2369 selected.push(e)2370 });2371 if (selected.length > 0) {2372 deselectAll()2373 $.each(selected, function(i, e) {2374 console.log('e:' + e.x + ' ' + e.y + " w/h: " + e.width + ' ' + e.height)2375 console.log("selected element " + e.id)2376 selectElement(e, true)2377 });2378 }2379}2380function selectElement(elem, multiple) {2381 multiple = typeof multiple !== 'undefined' ? multiple : false;2382 console.log("setting selected to " + elem.id + " with type " + elem.type + " and multiple " + multiple)2383 //if (elem.selected)2384 // return;2385 if (elem.img == undefined) {2386 console.log("no image. try again in 200 ms")2387 setTimeout(function() {2388 selectElement(elem, multiple);2389 }, 200)2390 return2391 }2392 2393 2394 2395 $("#canvas").data("last_selected", $('#canvas').data("selected")) 2396 if (!multiple) {2397 deselectAll(elem)2398 //if ($('#canvas').data("selected")!=elem)2399 setControls(elem)2400 if (elem.type != 'background')2401 drawAlignmentLines(elem, 'dragging')2402 } else {2403 if (elem.selected) {2404 elem.selected = false;2405 elem.img.attrs.strokeEnabled = false;2406 elem.img.getLayer().draw();2407 return;2408 }2409 if ($('#canvas').data("selected")!=0)2410 {2411 $.each($('#canvas').data("selected").anchors, function(i, a) {2412 a.hide();2413 });2414 }2415 }2416 if ($('#canvas').data("region_mode"))2417 elem.img.moveToTop();2418 var layer = elem.img.getLayer()2419 if (!multiple) {2420 console.log("setting anchors")2421 $.each(elem.anchors, function(i, a) {2422 //if ($('#canvas').data("region_mode"))2423 a.moveToTop()2424 //layer.add(a)2425 a.show()2426 });2427 moveAnchors(elem);2428 }2429 $.each($('#canvas').data("design").elements, function(i, e) {2430 if (elem.type != 'background') {2431 e.state_img.show()2432 e.state_img.setPosition(e.x + e.width, e.y)2433 } else2434 e.state_img.hide()2435 });2436 //elem.curr_pos=elem.img.getStage().getPointerPosition()2437 elem.last_x = elem.img.getPosition().x;2438 elem_last_y = elem.img.getPosition().y;2439 elem.selected = true;2440 2441 if (elem.type!='background')2442 elem.img.attrs.strokeEnabled = true;2443 2444 $('#canvas').data("selected", elem);2445 console.log("finished selecting")2446 /*2447 var children=layer.getChildren()2448 console.log("num children "+children.length)2449 for (var i=0;i< children.length;i++)2450 {2451 var pos =children[i].getAbsolutePosition()2452 console.log('element '+ String(children[i].attrs.name) + " has position "+ pos.x + " "+pos.y)2453 console.log(children[i])2454 }2455 */2456 2457 setCurrentRules()2458 layer.draw();2459}2460function getDistance(p1, p2) {2461 return Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));2462}2463function setupStageCallbacks(stage) {2464 stage.getContent().addEventListener('touchmove', function(evt) {2465 var touch1 = evt.touches[0];2466 var touch2 = evt.touches[1];2467 if (touch1 && touch2) {2468 var dist = getDistance({2469 x : touch1.clientX,2470 y : touch1.clientY2471 }, {2472 x : touch2.clientX,2473 y : touch2.clientY2474 });2475 var lastDist = $('#canvas').data("lastDist");2476 var lastScale = $('#canvas').data("lastScale");2477 $('#canvas').data("lastDist", dist);2478 var scale = ((dist + 50 ) / (lastDist + 50));2479 scale = Math.min(Math.max(scale, 0.95), 1.05)2480 if ((lastScale != undefined) && (((lastScale > 1) && (scale > 1)) || ((lastScale < 1) && (scale < 1))))2481 scale = scale * 0.25 + lastScale * 0.75;2482 $('#canvas').data("lastScale", scale);2483 scaleCurrentElement(scale)2484 }2485 }, false);2486 stage.getContent().addEventListener('touchend', function() {2487 $('#canvas').data("lastDist", 0);2488 }, false);2489}2490function setupElementCallbacks(elem_img, elem) {2491 2492 2493 elem_img.on('mouseover', function(evt) {2494 if ($("#mouseover_alignment_select").prop("checked"))2495 drawAlignmentLines(elem, 'mouseover')2496 });2497 2498 elem_img.on('dragstart',function(evt) {dragStartEvent(evt, elem, elem_img)});2499 elem_img.on('dragmove',function(evt) {dragMoveEvent(evt, elem, elem_img)});2500 elem_img.on('dragend',function(evt) {dragEndEvent(evt, elem, elem_img)});2501 elem_img.on('dblclick dbltap', function(evt) {2502 console.log("double click");2503 if (elem.type != 'background')2504 showElementControls();2505 else2506 showBackgroundControls();2507 });2508 elem_img.on("click tap",function(evt) {clickEvent(evt, elem, elem_img)});2509 2510 elem_img.on("mousedown",function(evt) {mouseDownEvent(evt, elem, elem_img)});2511 elem_img.on("mousemove",function(evt) {mouseMoveEvent(evt, elem, elem_img)}); 2512 elem_img.on("mouseup",function(evt) {mouseUpEvent(evt, elem, elem_img)});2513}2514function dragStartEvent(evt,elem,elem_img)2515{2516 $('#canvas').data("dragging", true)2517 console.log("dragstart")2518 evt.preventDefault();2519 if (elem.type != 'background')2520 $('#canvas').data("select_start", false)2521 $.each($('#canvas').data("design").elements, function(i, e) {2522 e.last_x=e.x;2523 e.last_y=e.y; 2524 });2525 if (elem.type=='background')2526 console.log("background drag")2527 if (!elem.selected)2528 selectElement(elem, evt.shiftKey == 1)2529 elem.curr_pos = elem_img.getStage().getPointerPosition();2530 $('#canvas').data("user_input_log").push("M")2531 $('#canvas').data("status_log").push("M")2532 2533}2534function dragMoveEvent(evt,elem,elem_img)2535{2536 2537 console.log("dragmove")2538 //$('#canvas').data("select_start",undefined)2539 evt.preventDefault();2540 if ((elem.resizing))2541 return;2542 //elem.selected=true;2543 $('#canvas').data("select_start", false)2544 allowUpdates()2545 var stage = elem_img.getStage()2546 //console.log("stage:"+stage)2547 if (stage == undefined) {2548 console.log("layer:")2549 console.log(elem_img.getLayer())2550 $('#suggestion_status').text("stage undefined");2551 return;2552 }2553 moveAnchors(elem)2554 elem.x = elem_img.getPosition().x2555 elem.y = elem_img.getPosition().y2556 elem.state_img.setPosition(elem.x + elem.width, elem.y)2557 drawAlignmentLines(elem, 'dragging')2558 //var curr_pos=stage.getPointerPosition()2559 var diff_x = elem.x - elem.last_x;2560 var diff_y = elem.y - elem.last_y;2561 console.log("x:"+elem.x)2562 console.log("y:"+elem.y)2563 console.log("last_x:"+elem.last_x)2564 console.log("last_y:"+elem.last_y)2565 console.log("diff_x:"+diff_x)2566 console.log("diff_y:"+diff_y)2567 elem.last_x = elem.x2568 elem.last_y = elem.y2569 var num_other_selected = 02570 $.each($('#canvas').data("design").elements, function(i, e) {2571 if ((e != elem) && (e.selected)) {2572 if (e.img.attrs.strokeEnabled == false) {2573 $('#error_message').text("Element selected by mistake")2574 e.selected = false2575 return2576 }2577 e.curr_pos += diff_x2578 e.curr_pos += diff_y2579 e.x += diff_x2580 e.y += diff_y2581 e.img.setPosition(e.x, e.y)2582 e.state_img.setPosition(e.x + e.width, e.y)2583 e.fixed_amount = elem.fixed_amount2584 num_other_selected += 12585 }2586 });2587 //console.log("setting state")2588 if ($("#infer_locking_select").prop("checked") && (elem.fixed_amount !=1) && (elem.fixed_amount != 0.5) && (num_other_selected == 0))2589 setElementState(elem.id, 'tweakable')2590 else2591 elem.state_img.show()2592 $.each($('#canvas').data("design").elements, function(i, e) {2593 if ((e != elem) && (!(e.selected))) {2594 var new_opacity = 0;2595 if ($("#fixed_opacity_select").prop("checked")) {2596 console.log("fixed opacity")2597 new_opacity = 0.6;2598 } else if (e.fixed_amount == 0)2599 new_opacity = 0.3;2600 else2601 new_opacity = 0.6;2602 e.img.attrs.opacity = new_opacity2603 e.state_img.attrs.opacity = new_opacity2604 if ($("#lock_icon_select").prop("checked"))2605 e.state_img.show()2606 else2607 e.state_img.hide()2608 } else2609 e.img.attrs.opacity = 1.0;2610 });2611 //sendCurrentLayout();2612 //console.log("end dragmove")2613 elem_img.getLayer().draw();2614}2615function dragEndEvent(evt,elem,elem_img)2616{2617 2618 evt.preventDefault();2619 //if (elem.type != 'region') {2620 2621 $.each($('#canvas').data("design").elements, function(i, e) {2622 if ((e != elem)) {2623 //setStroke(e.img, false, 1.5, e.fixed_amount)2624 if ($("#infer_locking_select").prop("checked")) {2625 var overlap = getOverlap(e.img, elem.img)2626 if ((overlap > 0.1) && (e.fixed_amount != 1)&& (!e.allow_overlap)&& (!elem.allow_overlap)) {2627 setElementState(e.id, 'unlocked')2628 e.img.attrs.strokeEnabled=false2629 if (e.fix_alignment)2630 {2631 e.fix_alignment=false2632 2633 sendCurrentDesign()2634 }2635 2636 }2637 }2638 //console.log('overlap: '+overlap)2639 e.state_img.attrs.opacity = 12640 //if (!e.selected)2641 // e.state_img.hide()2642 }2643 e.img.attrs.opacity = 12644 });2645 //$.each($('#canvas').data("align_lines"), function(i, al){2646 // al.destroy()2647 //});2648 elem_img.getLayer().draw();2649 sendCurrentLayout('Move');2650 2651 $('#canvas').data("dragging", false)2652 2653}2654function clickEvent(evt,elem,elem_img)2655{2656 console.log("click, text mode " + $('#canvas').data("text_mode"))2657 if ($('#canvas').data("dragging"))2658 return;2659 2660 if ($('#canvas').data("text_mode")) {2661 createNewElement('text')2662 document.body.style.cursor = "default";2663 $('#canvas').data("text_mode", false)2664 return2665 }2666 selectElement(elem, evt.shiftKey == 1)2667 if (elem.type == 'background') {2668 $('#element_controls').hide()2669 var last_selected = $("#canvas").data("last_selected")2670 if ($('#background_controls').is(":visible"))2671 hideBackgroundControls()2672 else if (("type" in last_selected) && (last_selected.type == "background") && ($('#canvas').data("modificationsEnabled")))2673 {2674 showBackgroundControls()2675 }2676 2677 } else {2678 hideBackgroundControls()2679 sendCurrentLayout('Select')2680 }2681 2682}2683function mouseMoveEvent(evt,elem,elem_img)2684{2685 var start_pos = $('#canvas').data("select_start")2686 2687 console.log("mouse move")2688 //evt.preventDefault();2689 if ((start_pos != false)&& $('#canvas').data("mousedown")) {2690 2691 var stage = elem_img.getStage();2692 var select_rect = $('#canvas').data("select_rect")2693 var curr_pos = stage.getPointerPosition()2694 var dist = getDistance(start_pos, curr_pos)2695 if (dist > 10) {2696 selectMultipleElements($('#canvas').data("select_start"), stage.getPointerPosition())2697 select_rect.setWidth(curr_pos.x - start_pos.x)2698 select_rect.setHeight(curr_pos.y - start_pos.y)2699 select_rect.show()2700 select_rect.getLayer().draw()2701 }2702 }2703}2704function mouseUpEvent(evt,elem,elem_img)2705{2706 $('#canvas').data("mousedown",false)2707 //evt.preventDefault();2708 $('#canvas').data("select_rect").hide()2709 $('#canvas').data("select_rect").getLayer().draw()2710 2711 var stage = elem_img.getStage();2712 console.log("mouse up: " + $('#canvas').data("select_start"))2713 console.log(elem_img)2714 console.log(elem)2715 if ($('#canvas').data("select_start") != false) {2716 console.log("mouse up")2717 var curr_pos = stage.getPointerPosition()2718 var dist = getDistance($('#canvas').data("select_start"), curr_pos)2719 if (dist > 10) {2720 selectMultipleElements($('#canvas').data("select_start"), stage.getPointerPosition())2721 }2722 }2723 $('#canvas').data("select_start", false)2724 2725}2726function mouseDownEvent(evt,elem,elem_img)2727{2728 var stage = elem_img.getStage();2729 2730 $('#canvas').data("mousedown",true)2731 2732 console.log("mouse down: " + $('#canvas').data("select_start"))2733 console.log(elem_img)2734 console.log(elem) 2735 if (elem.type=='background')2736 {2737 $('#canvas').data("select_start", stage.getPointerPosition())2738 $('#canvas').data("select_rect").setPosition($('#canvas').data("select_start"));2739 }2740}2741function drawAlignmentLines(elem, call_type) {2742 $.each($('#canvas').data("align_lines"), function(i, al) {2743 al[0].destroy()2744 });2745 $('#canvas').data("align_lines", [])2746 if (elem.type == 'background') {2747 elem.img.getLayer().draw()2748 return;2749 }2750 elem.width = elem.img.getWidth()2751 elem.height = elem.img.getHeight()2752 //console.log("drawAlignmentLines")2753 elem.mid_x = elem.x + elem.width / 2.02754 elem.mid_y = elem.y + elem.height / 2.02755 var min_x_amount = 99992756 var min_y_amount = 99992757 var x_line = [min_x_amount, 0, 0, 0, 0, 0, -99, []]2758 var y_line = [0, min_y_amount, 0, 0, 0, 0, -99, []]2759 var align_thresh = 102760 var design_x_center = $('#canvas').data("design").width / 2.02761 var design_y_center = $('#canvas').data("design").height / 2.02762 var align_x_center = Math.abs(elem.mid_x - design_x_center)2763 var align_y_center = Math.abs(elem.mid_y - design_y_center)2764 //var global_x_align=false;2765 if (align_x_center < align_thresh) {2766 //global_x_align=true;2767 min_x_amount = align_x_center2768 x_line = ([design_x_center - elem.mid_x, 0, design_x_center, 0, design_x_center, design_y_center * 2, 10, []])2769 }2770 //var global_y_align=false;2771 if (align_y_center < align_thresh) {2772 //global_y_align=true;2773 min_y_amount = align_y_center2774 y_line = ([0, design_y_center - elem.mid_y, 0, design_y_center, design_x_center * 2, design_y_center, 11, []])2775 }2776 $.each($('#canvas').data("design").elements, function(i, e) {2777 if ((e != elem) && (!(e.selected))) {2778 e.width = e.img.getWidth()2779 e.height = e.img.getHeight()2780 var mid_x = e.x + e.width / 2.0;2781 var mid_y = e.y + e.height / 2.0;2782 var align_left = Math.abs(elem.x - e.x)2783 var align_right = Math.abs(elem.x + elem.width - (e.x + e.width))2784 var align_x_center = Math.abs(elem.mid_x - mid_x)2785 var align_x_min = Math.min(align_left, Math.min(align_x_center, align_right))2786 var align_bottom = Math.abs(elem.y - e.y)2787 var align_top = Math.abs(elem.y + elem.height - (e.y + e.height))2788 var align_y_center = Math.abs(elem.mid_y - mid_y)2789 var align_y_min = Math.min(align_top, Math.min(align_y_center, align_bottom))2790 if (call_type.indexOf('Left') > -1) {2791 align_x_center = align_thresh + 12792 align_right = align_thresh + 12793 }2794 if (call_type.indexOf('Right') > -1) {2795 align_x_center = align_thresh + 12796 align_left = align_thresh + 12797 }2798 if (call_type.indexOf('top') > -1) {2799 align_y_center = align_thresh + 12800 align_bottom = align_thresh + 12801 }2802 if (call_type.indexOf('bottom') > -1) {2803 align_y_center = align_thresh + 12804 align_top = align_thresh + 12805 }2806 var y_start = Math.min(e.y, elem.y)2807 var y_end = Math.max(e.y + e.height, elem.y + elem.height)2808 var x_start = Math.min(e.x, elem.x)2809 var x_end = Math.max(e.x + e.width, elem.x + elem.width)2810 //&& (y_end-y_start >x_line[5]-x_line[3])2811 if ((align_x_min < align_thresh)) {2812 var prev_line = x_line;2813 //global_x_align=false;2814 var new_x_line = -1;2815 if ((align_left < align_thresh) && (align_left == align_x_min)) {2816 x_line = ([e.x - elem.x, 0, e.x, y_start, e.x, y_end, 0, [e.id]])2817 } else if ((align_x_center < align_thresh) && (align_x_center == align_x_min)) {2818 x_line = ([mid_x - elem.mid_x, 0, mid_x, y_start, mid_x, y_end, 1, [e.id]])2819 } else if ((align_right < align_thresh) && (align_right == align_x_min)) {2820 x_line = ([(e.x + e.width) - (elem.x + elem.width), 0, e.x + e.width, y_start, e.x + e.width, y_end, 2, [e.id]])2821 }2822 //if they are the same type, then concatente the other elements2823 if (prev_line[6] == x_line[6]) {2824 //console.log("same type")2825 if (align_x_min > min_x_amount) {2826 //var prev_align=prev_line[7]2827 var temp = jQuery.extend(true, {}, prev_line);2828 prev_line = x_line2829 x_line = temp2830 //x_line[7]=prev_align2831 //console.log("prev_line:"+prev_line)2832 //console.log("x_line:"+x_line)2833 }2834 x_line[3] = Math.min(x_line[3], prev_line[3])2835 x_line[5] = Math.max(x_line[5], prev_line[5])2836 x_line[7] = x_line[7].concat(prev_line[7])2837 } else {2838 if (align_x_min > min_x_amount)2839 x_line = prev_line2840 }2841 min_x_amount = Math.min(align_x_min, min_x_amount);2842 }2843 //(x_end-x_start >x_line[4]-x_line[2]) &&2844 if ((align_y_min < align_thresh)) {2845 //console.log("matched element: "+e.id)2846 var prev_line = y_line;2847 //console.log("prev_line"+prev_line)2848 //global_y_align=false;2849 if ((align_bottom < align_thresh) && (align_bottom == align_y_min)) {2850 y_line = ([0, e.y - elem.y, x_start, e.y, x_end, e.y, 3, [e.id]])2851 } else if ((align_y_center < align_thresh) && (align_y_center == align_y_min)) {2852 y_line = ([0, mid_y - elem.mid_y, x_start, mid_y, x_end, mid_y, 4, [e.id]])2853 } else if ((align_top < align_thresh) && (align_top == align_y_min)) {2854 y_line = ([0, (e.y + e.height) - (elem.y + elem.height), x_start, e.y + e.height, x_end, e.y + e.height, 5, [e.id]])2855 }2856 //if they are the same type, then concatente the other elements2857 if (prev_line[6] == y_line[6]) {2858 //console.log("same type")2859 if (align_y_min > min_y_amount) {2860 //var prev_align=prev_line[7]2861 var temp = jQuery.extend(true, {}, prev_line);2862 prev_line = y_line2863 y_line = temp2864 //y_line[7]=prev_align2865 //console.log("prev_line:"+prev_line)2866 //console.log("y_line:"+y_line)2867 }2868 y_line[7] = y_line[7].concat(prev_line[7])2869 y_line[2] = Math.min(y_line[2], prev_line[2])2870 y_line[4] = Math.max(y_line[4], prev_line[4])2871 } else {2872 if (align_y_min > min_y_amount)2873 y_line = prev_line2874 }2875 min_y_amount = Math.min(align_y_min, min_y_amount);2876 }2877 }2878 });2879 //}2880 var lines = [];2881 if (x_line[0] < 9999)2882 lines.push(x_line)2883 if (y_line[1] < 9999)2884 lines.push(y_line)2885 if ((lines.length > 0) && ($("#alignment_select").prop("checked"))) {2886 $.each(lines, function(i, line) {2887 var stroke_color = 'black'2888 var stroke_opacity = 0.352889 if ($('#canvas').data("invert")) {2890 stroke_color = 'white'2891 stroke_opacity = 0.52892 }2893 //console.log("creating line "+line)2894 var draw_line = new Kinetic.Line({2895 points : [line[2], line[3], line[4], line[5]],2896 stroke : stroke_color,2897 strokeWidth : 1,2898 lineJoin : 'round',2899 dashArray : [3, 2],2900 opacity : stroke_opacity2901 });2902 //var global_align= Number(((line[2]==line[4]) && global_x_align) || ((line[2]!=line[4]) && global_y_align))2903 $('#canvas').data("align_lines").push([draw_line, elem.id, line[6], line[7]])2904 elem.img.getLayer().add(draw_line)2905 if ((line[0] != 0) || (line[1] != 0)) {2906 /*2907 $.each($('#canvas').data("design").elements, function(i, e) {2908 if (e.selected)2909 {2910 if (call_type=='dragging')2911 {2912 e.x+=line[0];2913 e.y+=line[1];2914 }2915 e.img.setPosition(e.x,e.y)2916 //elem.img.setWidth(elem.width,elem.height)2917 e.state_img.setPosition(e.x+e.width,e.y)2918 moveAnchors(e)2919 }2920 });2921 */2922 if ((call_type == 'dragging')) {2923 elem.x += line[0];2924 elem.y += line[1];2925 } else if (call_type == 'topLeft') {2926 elem.x += line[0];2927 elem.y += line[1];2928 elem.height += Math.max(line[1], line[0] / elem.aspect_ratio)2929 elem.width += Math.max(line[0], line[1] * elem.aspect_ratio)2930 }2931 elem.img.setPosition(elem.x, elem.y)2932 //elem.img.setWidth(elem.width,elem.height)2933 elem.state_img.setPosition(elem.x + elem.width, elem.y)2934 moveAnchors(elem)2935 }2936 });2937 $.each(elem.anchors, function(i, a) {2938 a.moveToTop()2939 });2940 2941 elem.img.getLayer().draw()2942 }2943}2944function setStroke(shape, enabled, width, color_blend) {2945 shape.attrs.strokeEnabled = enabled2946 shape.setStrokeWidth(width)2947 shape.setStrokeR(Math.round(255 * (1 - color_blend)))2948 shape.setStrokeG(0)2949 shape.setStrokeB(Math.round(255 * (color_blend)))2950}2951function getOverlap(shape1, shape2) {2952 var p1 = shape1.getPosition()2953 var p2 = shape2.getPosition()2954 var x11 = p1.x, y11 = p1.y, x12 = p1.x + shape1.getWidth(), y12 = p1.y + shape1.getHeight(), x21 = p2.x, y21 = p2.y, x22 = p2.x + shape2.getWidth(), y22 = p2.y + shape2.getHeight()2955 x_overlap = Math.max(0, Math.min(x12, x22) - Math.max(x11, x21))2956 y_overlap = Math.max(0, Math.min(y12, y22) - Math.max(y11, y21));2957 var ol1 = (x_overlap * y_overlap) / (shape1.getWidth() * shape1.getHeight())2958 var ol2 = (x_overlap * y_overlap) / (shape2.getWidth() * shape2.getHeight())2959 return Math.max(ol1, ol2)2960}2961function showBackgroundControls() {2962 if ($('#canvas').data("modificationsEnabled")) {2963 $('#background_controls').show()2964 //$('#canvas').data("design").background_elem.img.attrs.draggable=true2965 //$('#canvas').data("design").background_elem.img.attrs.strokeEnabled=true2966 $('#element_controls').hide()2967 2968 //if ($('#canvas').data("design").background_fname=='')2969 // $('#offset_controls').hide()2970 2971 $('#canvas').data("design").background_elem.img.getLayer().draw()2972 }2973}2974function hideBackgroundControls() {2975 if ($('#canvas').data("modificationsEnabled")) {2976 console.log("hideBackgroundControls")2977 //$('#canvas').data("design").background_elem.img.attrs.strokeEnabled=false2978 $('#background_controls').hide()2979 //$('#canvas').data("design").background_elem.img.attrs.draggable=false2980 2981 $('#canvas').data("design").background_elem.img.getLayer().draw()2982 2983 }2984}2985function showElementControls() {2986 if ($('#canvas').data("modificationsEnabled")) {2987 hideBackgroundControls() 2988 $('#element_controls').show()2989 }2990}2991function moveAnchors(elem) {2992 $.each(elem.anchors, function(i, a) {2993 if (a.attrs.name == 'bottomLeft') {2994 a.setX(elem.img.getAbsolutePosition().x)2995 a.setY(elem.img.getAbsolutePosition().y)2996 }2997 if (a.attrs.name == 'bottomRight') {2998 a.setX(elem.img.getAbsolutePosition().x + elem.img.getWidth())2999 a.setY(elem.img.getAbsolutePosition().y)3000 }3001 if (a.attrs.name == 'topLeft') {3002 a.setX(elem.img.getAbsolutePosition().x)3003 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight())3004 }3005 if (a.attrs.name == 'topRight') {3006 a.setX(elem.img.getAbsolutePosition().x + elem.img.getWidth())3007 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight())3008 }3009 if (a.attrs.name == 'midRight') {3010 a.setX(elem.img.getAbsolutePosition().x + elem.img.getWidth() - 6)3011 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight() / 2)3012 }3013 if (a.attrs.name == 'midLeft') {3014 a.setX(elem.img.getAbsolutePosition().x - 6)3015 a.setY(elem.img.getAbsolutePosition().y + elem.img.getHeight() / 2)3016 }3017 });3018}3019function createNewElement(type, img, fname) {3020 if ((type == 'text') && $('#user_text').val() == '') {3021 alert("Please enter the text before clicking to position")3022 return3023 }3024 console.log("Creating new element")3025 var mousePos = $('#canvas').data("stage").getPointerPosition()3026 var elem = {}3027 elem.loaded = false3028 elem.resizing = false3029 elem.fixed = false3030 elem.align_type = -13031 elem.num_lines = 03032 //elem.num_align=-13033 elem.selected = true3034 elem.old_text = ''3035 elem.type = type3036 elem.id = -13037 elem.fixed_amount = 0.53038 elem.alternate_id = 03039 elem.optional = false3040 if (mousePos == undefined) {3041 elem.x = 03042 elem.y = 03043 } else {3044 elem.x = mousePos.x3045 elem.y = mousePos.y3046 }3047 if (fname != undefined)3048 elem.fname = fname3049 elem.group_id = $("#group_select").val()3050 elem.importance = $("#importance_select").val()3051 var max_id = 0;3052 $.each($('#canvas').data("design").elements, function(i, e) {3053 max_id = Math.max(max_id, parseInt(e.id))3054 });3055 elem.id = max_id + 13056 $('#canvas').data("design").elements.push(elem)3057 //design.elements.sort(function(e1,e2){return e1.importance-e2.importance})3058 //var max_id=-1;3059 //$.each($('#canvas').data("design").elements, function(i,e){3060 // max_id3061 //});3062 var layer = $('#canvas').data("stage").get('#layer')[0];3063 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];3064 //if ($('#canvas').data("suggestionsEnabled"))3065 setupLockingCallbacks(elem, layer)3066 if (elem.type == 'graphic') {3067 $('#canvas').data("user_input_log").push("Add Graphic")3068 $('#canvas').data("status_log").push("Add Graphic")3069 elem.type_id = 2;3070 elem.height = 100;3071 setupImageElement(elem, img, layer, sugg_layer, false);3072 overlap = {}3073 overlap.elem_id = elem.id3074 overlap.x_min = 03075 overlap.y_min = 03076 overlap.x_max = 13077 overlap.y_max = 13078 $('#canvas').data("design").overlap_regions.push(overlap)3079 sendCurrentDesign();3080 }3081 if (elem.type == 'text') {3082 $('#canvas').data("user_input_log").push("Add Text")3083 $('#canvas').data("status_log").push("Add Text")3084 elem.type_id = 1;3085 elem.font = $('#font_select').data("font");3086 elem.bold = $("#bold_select").attr("checked") == 'checked';3087 elem.italic = $("#italic_select").attr("checked") == 'checked';3088 elem.shadow = $("#shadow_select").attr("checked") == 'checked';3089 elem.fix_alignment = $("#fix_select").attr("checked") == 'checked';3090 elem.fix_alternate = $("#num_lines_fix_select").attr("checked") == 'checked';3091 elem.color = $('#color_select').val();3092 elem.text = $('#user_text').val();3093 if (elem.text == '')3094 return;3095 elem.align = ""3096 $(".align_select.active").each(function() {3097 console.log(this);3098 elem.align = this.value3099 });3100 elem.sugg_align = elem.align;3101 console.log("Creating with alignment: " + elem.align)3102 elem.num_lines = elem.text.split("\n").length;3103 console.log('num_lines ' + elem.num_lines)3104 elem.height = 25 * (elem.num_lines);3105 //renderTextElement(elem,true,true);3106 renderTextAlts(elem, true)3107 setTimeout(function() {3108 sendCurrentDesign();3109 resumeSuggestions();3110 }, 500)3111 }3112 console.log("setting element id to " + elem.id)3113 //deselectAll(elem)3114 //$('#canvas').data("selected",elem)3115 layer.draw();3116 sugg_layer.draw();3117 //$('#canvas').data("selected",elem);3118 //elem.img.attrs.strokeEnabled=true;3119 selectElement(elem, false);3120}3121function setControls(elem) {3122 $('#canvas').data("settingControls", true);3123 if (elem.type == 'region') {3124 console.log("Setting controls for region: " + elem.id);3125 $("#region_text_select").prop("checked", elem.allow_text)3126 $("#region_graphic_select").prop("checked", elem.allow_graphic)3127 $("#region_overlap_select").prop("checked", elem.allow_overlap)3128 } else {3129 console.log("Setting controls for element: " + elem.id + " with type " + elem.type);3130 //$("#font_select").val(elem.font);3131 $("#font_select").data("font", elem.font)3132 $("#font_select").find('span').html(elem.font);3133 $("#font_select").css('font-family', elem.font);3134 console.log("setting font:" + elem.font)3135 $("#group_select").val(elem.group_id).attr('selected', true);3136 $("#importance_select").val(elem.importance).attr('selected', true);3137 $("#bold_select").prop("checked", elem.bold)3138 $("#italic_select").prop("checked", elem.italic)3139 $("#shadow_select").prop("checked", elem.shadow)3140 $("#fix_select").prop("checked", elem.fix_alignment)3141 $("#num_lines_fix_select").prop("checked", elem.fix_alternate)3142 3143 3144 if (elem.color!=undefined)3145 {3146 $('#color_select').val(cutHex(elem.color));3147 $('#color_select').css("background-color",'#'+cutHex(elem.color))3148 3149 3150 if (hexToV(elem.color)<100)3151 $('#color_select').css("color",'#FFF')3152 else3153 $('#color_select').css("color",'#000')3154 }3155 3156 $("#optional_select").prop("checked", elem.optional)3157 $("#hidden_select").prop("checked", elem.hidden)3158 $('#user_text').val(elem.text);3159 $("#overlap_select").prop("checked", elem.allow_overlap)3160 if (elem.type=='text')3161 $("#overlap_mod").hide()3162 else3163 $("#overlap_mod").show()3164 /*3165 if (elem.type=='graphic')3166 $('#user_text').hide()3167 else3168 $('#user_text').show()3169 */3170 if (elem.type=='text')3171 $("#fontSizeInput").val((elem.height/elem.init_height)*elem.init_font_size)3172 3173 $("#num_lines_select").val(elem.num_lines).attr('selected', true);3174 $(".align_select").each(function() {3175 //console.log(this);3176 if (this.value == elem.align)3177 this.click()3178 });3179 }3180 console.log("Finished setting controls for element: " + elem.id);3181 $('#canvas').data("settingControls", false);3182}3183function regionControlsChanged() {3184 console.log("region controls changed")3185 if ($('#canvas').data("settingControls"))3186 return;3187 var elem = $('#canvas').data("selected")3188 elem.allow_text = $("#region_text_select").attr("checked") == 'checked'3189 elem.allow_graphic = $("#region_graphic_select").attr("checked") == 'checked'3190 elem.allow_overlap = $("#region_overlap_select").attr("checked") == 'checked'3191 elem.img.setFill(getRegionColor(elem))3192 elem.img.getLayer().draw()3193 sendCurrentDesign();3194}3195function numLinesChanged() {3196 selectAlternateElement($('#canvas').data("selected"), $("#num_lines_select").val())3197}3198function fontSelected(font) {3199 var splt = font.split(",")3200 var fontName = splt[0]3201 fontName = fontName.split("'").join('');3202 console.log("clicked: " + fontName)3203 $('#font_select').data("font", fontName)3204 controlsChanged()3205}3206function controlsChanged(new_val) {3207 console.log("controls changed")3208 if ($('#canvas').data("settingControls"))3209 return;3210 var elem = $('#canvas').data("selected")3211 if ((elem == undefined) || (elem.type == "background"))3212 return;3213 if (new_val != undefined) {3214 $('#canvas').data("user_input_log").push("Align-" + new_val)3215 $('#canvas').data("status_log").push("Align-" + new_val)3216 }3217 console.log("selected " + elem.id)3218 var changed_design = false;3219 var changed_text = false;3220 var changed_alignment = false;3221 var alignments = ["left", "center", "right"];3222 elem.old_text = elem.text;3223 if (elem.type == 'text') {3224 var bold = $("#bold_select").attr("checked") == 'checked'3225 var italic = $("#italic_select").attr("checked") == 'checked'3226 var shadow = $("#shadow_select").attr("checked") == 'checked'3227 var fix_alignment = $("#fix_select").attr("checked") == 'checked'3228 var fix_alternate = $("#num_lines_fix_select").attr("checked") == 'checked'3229 var optional = $("#optional_select").attr("checked") == 'checked'3230 var hidden = $("#hidden_select").attr("checked") == 'checked'3231 if (bold != elem.bold) {3232 console.log("bold changed from " + elem.bold + " to " + bold)3233 elem.bold = bold;3234 changed_text = true;3235 changed_design = true;3236 }3237 if (shadow != elem.shadow) {3238 console.log("shadow changed from " + elem.shadow + " to " + shadow)3239 elem.shadow = shadow;3240 changed_text = true;3241 }3242 if (fix_alternate != elem.fix_alternate) {3243 console.log("fix_alternate changed from " + elem.fix_alternate + " to " + fix_alternate)3244 elem.fix_alternate = fix_alternate;3245 changed_design = true;3246 }3247 if (optional != elem.optional) {3248 console.log("optional changed from " + elem.optional + " to " + optional)3249 elem.optional = optional;3250 changed_design = true;3251 }3252 if (hidden != elem.hidden) {3253 console.log("hidden changed from " + elem.hidden + " to " + hidden)3254 elem.hidden = hidden;3255 //changed_design=true;3256 if (elem.hidden) {3257 elem.hidden_img = elem.img.getImage()3258 elem.img.setImage(0)3259 //elem.img.setFillEnabled(false)3260 //elem.img.hide()3261 } else {3262 //console.log(elem.hidden_img)3263 elem.img.setImage(elem.hidden_img)3264 elem.hidden_img = 03265 //elem.img.show()3266 //elem.img.setFillEnabled(true)3267 }3268 elem.img.getLayer().draw();3269 changed_design = true;3270 }3271 if ($("#color_select").val() != elem.color) {3272 console.log("color changed from " + elem.color + " to " + $("#color_select").val())3273 elem.color = $("#color_select").val();3274 changed_text = true;3275 }3276 if ($('#font_select').data("font") != elem.font) {3277 console.log("font changed from " + elem.font + " to " + $('#font_select').data("font"))3278 elem.font = $('#font_select').data("font");3279 changed_text = true;3280 }3281 if ($("#user_text").val() != elem.text) {3282 console.log("text changed from " + elem.text + " to " + $("#user_text").val())3283 elem.text = $("#user_text").val();3284 changed_text = true;3285 }3286 if (fix_alignment != elem.fix_alignment) {3287 console.log("fix_alignment changed from " + elem.fix_alignment + " to " + fix_alignment)3288 elem.fix_alignment = fix_alignment;3289 $(".align_select.active").each(function() {3290 //console.log(this);3291 elem.align_type = alignments.indexOf(this.value)3292 //console.log("setting alternate to "+elem.alternate)3293 });3294 changed_design = true;3295 }3296 if ((elem.num_lines > 1) && (new_val != undefined) && (new_val != elem.align)) {3297 elem.align = new_val3298 console.log("Setting new alignment: " + elem.align);3299 var layer = elem.img.getLayer();3300 var orig_img = elem.img;3301 elem.img.remove();3302 elem.img = elem.alignment_imgs[new_val];3303 elem.img.show();3304 //elem.alternate=alignments.indexOf(new_val)3305 elem.align_type = alignments.indexOf(new_val)3306 elem.img.setX(orig_img.getAbsolutePosition().x)3307 elem.img.setY(orig_img.getAbsolutePosition().y)3308 elem.img.setHeight(orig_img.getHeight())3309 elem.img.setWidth(orig_img.getWidth())3310 elem.img.attrs.strokeEnabled = orig_img.attrs.strokeEnabled3311 layer.add(elem.img);3312 $.each(elem.anchors, function(i, a) {3313 a.moveToTop();3314 });3315 layer.draw();3316 //changed_text=true;3317 changed_alignment = true;3318 elem.fix_alignment = true;3319 changed_design = true;3320 $("#fix_select").prop("checked", true)3321 }3322 if (changed_text) {3323 updateTextElement(elem)3324 }3325 }3326 //graphical elements3327 else3328 {3329 console.log("allow_overlap for element "+elem.id)3330 3331 var allow_overlap = $("#overlap_select").attr("checked") == 'checked'3332 if (allow_overlap != elem.allow_overlap) 3333 {3334 elem.allow_overlap = allow_overlap;3335 3336 var design=$('#canvas').data("design")3337 var or_idx=-1;3338 $.each(design.overlap_regions , function (i,or) {3339 if (or.elem_id==elem.id)3340 {3341 or_idx=i;3342 console.log("matched "+or.elem_id+ " at index "+or_idx) 3343 }3344 3345 });3346 3347 if (or_idx>-1)3348 {3349 console.log(design.overlap_regions[or_idx]) 3350 design.overlap_regions.splice(or_idx,1)3351 3352 }3353 3354 if (!allow_overlap)3355 {3356 console.log("!allow_overlap")3357 overlap = {}3358 overlap.elem_id = elem.id3359 overlap.x_min = 03360 overlap.y_min = 03361 overlap.x_max = 13362 overlap.y_max = 13363 design.overlap_regions.push(overlap)3364 3365 console.log(design.overlap_regions)3366 }3367 3368 3369 //overlap = overlap + or.elem_id + "," + Math.round(or.x_min * 1000) / 1000 + "," + Math.round(or.x_max * 1000) / 1000 + "," + Math.round(or.y_min * 1000) / 1000 + "," + Math.round(or.y_max * 1000) / 1000 + "\n"3370 3371 sendCurrentDesign();3372 }3373 3374 3375 3376 }3377 if ($("#group_select").val() != elem.group_id) {3378 elem.group_id = $("#group_select").val();3379 sendCurrentDesign();3380 }3381 if ($("#importance_select").val() != elem.importance) {3382 elem.importance = $("#importance_select").val();3383 sendCurrentDesign();3384 }3385 3386 3387 3388 3389 if ((changed_design) || (changed_text))3390 setTimeout(function() {3391 sendCurrentDesign();3392 }, 200)3393 if (changed_alignment)3394 sendCurrentLayout('Align');3395}3396function checkForSuggestions() {3397 var runs = $('#canvas').data("runs")3398 $.each(runs, function(i, run) {3399 if (run.id > -1)3400 getLayoutFromServer(run.id, run.type);3401 });3402 /*3403 if ($('#suggLayout').data('runID')>=0)3404 {3405 getLayoutFromServer($('#canvas').data("design").name,$('input[name=userID]').val());3406 }3407 */3408}3409function getCurrentLayout(reset) {3410 var design = $('#canvas').data("design")3411 var layout = design.name+'\n';3412 3413 var scale = 1.0;3414 layout += Math.round(design.width / scale) + "," + Math.round(design.height / scale) +'\n'+ (design.elements.length) + "\n";3415 for (var i = 0; i < design.elements.length; i++) {3416 var elem = design.elements[i];3417 //var fixed=(elem.fixed);3418 //var fixed=(elem.fixed || elem.selected);3419 if (elem.alternate_id == -1)3420 elem.alternate_id = 03421 var fix_amount = (Math.round((elem.fixed_amount) * 100) / 100)3422 3423 if (elem.hidden)3424 fix_amount = -1;3425 3426 if ((elem.selected) && $('#canvas').data("automaticUpdate"))3427 if (fix_amount==1)3428 fix_amount = 1.05;3429 else3430 fix_amount = 0.95;3431 3432 if ((!reset) &&(fix_amount==0))3433 fix_amount=0.013434 layout += Math.round(elem.x / scale) + "," + Math.round(elem.y / scale) + "," + Math.round(elem.height / scale) + "," + elem.align_type + "," + fix_amount + ",-1," + (elem.hidden ? -1 : elem.alternate_id) + "\n"3435 }3436 var lines = $('#canvas').data("align_lines");3437 if (lines.length >= 1) {3438 var selected_element = false;3439 for (var i = 0; i < design.elements.length; i++) {3440 if ((design.elements[i].id == lines[0][1]) && (design.elements[i].selected))3441 ;3442 selected_element = true;3443 }3444 if (selected_element) {3445 layout += lines.length + ' lines\n'3446 $.each(lines, function(i, al) {3447 var aligned_elem = al[3];3448 //console.log("al:"+al)3449 layout += al[1] + "," + al[2] + "," + aligned_elem.length + ","3450 for (var i = 0; i < aligned_elem.length; i++)3451 layout += aligned_elem[i] + ","3452 layout = layout.slice(0, -1) + "\n"3453 });3454 } else3455 layout += '0 lines\n'3456 } else3457 layout += '0 lines\n'3458 /*3459 if ($('#canvas').data("region_mode")) {3460 layout += design.regions.length + ' regions\n'3461 $.each(design.regions, function(i, reg) {3462 layout += (reg.allow_text ? 1 : 2) + "," + reg.x + "," + reg.y + "," + reg.width + "," + reg.height + "\n"3463 });3464 } else if (!design.region_proposals)3465 layout += '-1 regions\n'3466 else3467 layout += '0 regions\n'3468 */3469 if (reset==true)3470 layout += '-2 regions\n'3471 else3472 layout += '-1 regions\n'3473 return layout3474 //console.log("layout:\n"+layout);3475}3476function sendCurrentLayout(user_input, reset) {3477 console.log("sendCurrentLayout")3478 var layout = getCurrentLayout(reset)3479 3480 $('#canvas').data("layout_log").push(['user-'+user_input,new Date().getTime(),layout,";"])3481 3482 $('#report').hide()3483 $('#reportStatus').text("")3484 3485 addLayoutToStack(layout,'user')3486 console.log("curr layout:" + layout)3487 var layout_counter=$('#canvas').data("layout_counter")3488 if (layout_counter==undefined)3489 layout_counter=0;3490 $('#canvas').data("layout_counter",layout_counter+1)3491 3492 layout=layout_counter+"\n"+layout3493 3494 $('#userLayout').val(layout)3495 $.each($('#canvas').data("runs"), function(i, run) {3496 if (run.id > -1) {3497 sendLayoutToServer(run.id, layout);3498 }3499 });3500 $('#canvas').data("energy", 9999)3501 $('#canvas_energy').text(9999)3502 3503}3504function sendCurrentDesign() {3505 console.log("sendCurrentDesign")3506 var design = getCurrentDesign();3507 $.each($('#canvas').data("runs"), function(i, run) {3508 updateDesignOnServer(run.id, design)3509 run.energy = 99999;3510 });3511}3512function getCurrentDesign() {3513 //console.log('getCurrentDesign')3514 var design = $('#canvas').data("design")3515 var dstring = design.name+'\n';3516 3517 3518 var scale = 1.0;3519 dstring += Math.round(design.width / scale) + "," + Math.round(design.height / scale) +'\n'+ (design.elements.length) + "\n";3520 dstring = dstring + "0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,background\n";3521 var graphic_ids=[]3522 for (var i = 0; i < design.elements.length; i++) {3523 var elem = design.elements[i];3524 3525 if (elem.type=='graphic')3526 graphic_ids.push(elem.id)3527 if (elem.alternate_id == -1)3528 elem.alternate_id = 03529 var fix_amount = (Math.round((elem.fixed_amount) * 100) / 100)3530 if (elem.hidden)3531 fix_amount = -1;3532 if ((elem.anchors["topLeft"].attrs != undefined) && (elem.anchors["topLeft"].attrs.visible))3533 fix_amount = 1;3534 dstring = dstring + (elem.id) + ",";3535 dstring = dstring + elem.type_id + ",";3536 dstring = dstring + elem.importance + ",";3537 dstring = dstring + elem.num_lines + ",";3538 dstring = dstring + elem.group_id + ",";3539 dstring = dstring + (Math.round((1 / elem.aspect_ratio) * 1000) / 1000) + ',';3540 dstring = dstring + Math.round(elem.x / scale) + ',';3541 dstring = dstring + Math.round(elem.y / scale) + ',';3542 dstring = dstring + Math.round(elem.height / scale) + ',';3543 dstring = dstring + elem.align_type + ",";3544 dstring = dstring + fix_amount + ",";3545 dstring = dstring + (elem.fix_alternate ? 0 : elem.alternate_id ) + ",";3546 dstring = dstring + (elem.fix_alignment ? 1 : 0 ) + ",";3547 dstring = dstring + (elem.optional ? 1 : 0 ) + ",";3548 dstring = dstring + "0,1,0,1," + elem.fname + "\n";3549 //console.log("aspect ratio "+(Math.round((1/elem.aspect_ratio)*1000)/1000))3550 //if (elem.img)3551 // console.log('element +'+i+' x: '+elem.img.getPosition().x+ ' y: '+elem.img.getPosition().y)3552 }3553 var overlap = '';3554 var overlap_cnt=0;3555 for (var i = 0; i < design.overlap_regions.length; i++) {3556 var or = design.overlap_regions[i];3557 if ($.inArray(or.elem_id,graphic_ids)>-1)3558 {3559 overlap = overlap + or.elem_id + "," + Math.round(or.x_min * 1000) / 1000 + "," + Math.round(or.x_max * 1000) / 1000 + "," + Math.round(or.y_min * 1000) / 1000 + "," + Math.round(or.y_max * 1000) / 1000 + "\n"3560 overlap_cnt++;3561 }3562 }3563 dstring += (overlap_cnt) + " overlap regions\n" + overlap;3564 var num_alts = 0;3565 var alt_string = ''3566 $.each(design.element_alts, function(id, alts) {3567 var alt_str = id + "," + Object.keys(alts).length + ","3568 $.each(design.elements, function(i, elem) {3569 if ((id == elem.id) && (!elem.fix_alternate)) {3570 num_alts++3571 $.each(alts, function(num_lines, alt_elem) {3572 alt_str += alt_elem.num_lines + "," + (Math.round((1 / alt_elem.aspect_ratio) * 1000) / 1000) + "," + alt_elem.max_line_length + ","3573 });3574 alt_string += alt_str + "\n"3575 }3576 });3577 });3578 dstring += num_alts + " alternates\n"3579 dstring += alt_string;3580 //console.log("sending current design:\n "+dstring);3581 return dstring3582}3583function setSuggestionLayout(run_id, new_layout, new_energy) {3584 var design = $('#canvas').data("design");3585 var run = -1;3586 var runs = $('#canvas').data("runs")3587 for (var r = 0; r < runs.length; r++) {3588 if (run_id == runs[r].id)3589 run = runs[r];3590 }3591 if (run == -1)3592 return3593 //var gallery_layouts=$('#canvas').data("gallery_layouts");3594 //var gallery_images=$('#canvas').data("gallery_images");3595 //var gallery_designs=$('#canvas').data("gallery_designs");3596 if ((run.layout != new_layout) && ((run.energy != new_energy ) || (run.type.search("gallery") > -1))) {3597 //console.log("setting new layout for run_id "+run_id)//+" new_layout: "+new_layout)3598 //console.log("old energy "+run.energy+" new energy "+new_energy)3599 3600 run.layout = new_layout3601 run.energy = new_energy3602 3603 if (run.canvas_id < 0)3604 return;3605 if (run.type != 'gallery')3606 $('#suggestion_layout' + String(run.canvas_id)).data("layout", new_layout)3607 var alignments = ["left", "center", "right"];3608 var elements = new_layout.split("\n");3609 var elem_cnt = parseInt(elements[3])3610 //console.log(elements)3611 if (elem_cnt != design.elements.length)3612 return;3613 var sugg_layer = $('#canvas').data("sugg_stage").get('#sugg_layer')[0];3614 for (var i = 4; i < design.elements.length + 4; i++) {3615 var elem = design.elements[i - 4];3616 var elem_split = elements[i].split(',');3617 var alt_id = parseInt(elem_split[6]);3618 var alt_elem = elem;3619 alt_elem.sugg_img.remove();3620 if ((!elem.fix_alternate) && (elem.id in design.element_alts)) {3621 $.each(design.element_alts[elem.id], function(num_lines, ae) {3622 if (alt_id == ae.alternate_id) {3623 alt_elem = ae;3624 //console.log("found "+(i)+" num_lines "+num_lines+ " alt id "+ae.alternate_id)3625 }3626 ae.sugg_img.remove();3627 });3628 }3629 if (alt_elem.num_lines > 1) {3630 var a = parseInt(elem_split[3])3631 var align;3632 if (a > -1)3633 align = alignments[a]3634 else3635 align = elem.align3636 alt_elem.sugg_align = align;3637 alt_elem.sugg_img = alt_elem.alignment_sugg_imgs[align];3638 }3639 if (alt_id < 0) {3640 continue;3641 }3642 //console.log("added "+(i))3643 sugg_layer.add(alt_elem.sugg_img);3644 var height = parseInt(elem_split[2]);3645 var width = height * alt_elem.aspect_ratio;3646 alt_elem.sugg_img.setX(parseInt(elem_split[0]));3647 alt_elem.sugg_img.setY(parseInt(elem_split[1]));3648 alt_elem.sugg_img.setHeight(height);3649 alt_elem.sugg_img.setWidth(width);3650 //if (alt_id!=-1)3651 alt_elem.sugg_img.show()3652 //else3653 // alt_elem.sugg_img.hide()3654 //console.log("setting "+i+ " "+parseInt(elem_split[0])*4.0+ " "+ parseInt(elem_split[1])*4.0+" "+height+" "+width+" "+elem.aspect_ratio);3655 }3656 sugg_layer.draw();3657 //console.log("draw")3658 var sugg_stage = sugg_layer.getStage();3659 sugg_stage.toDataURL({3660 callback : function(dataUrl) {3661 var img = new Image();3662 img.onload = function() {3663 run.image = img;3664 if ($("#canvas").data("preview") == run.canvas_id) {3665 $('#canvas').data("preview_image").attrs.fillPatternImage = img3666 $('#canvas').data("preview_image").getLayer().draw()3667 }3668 if (run.type == 'gallery') {3669 var count = $("#gallery_table").children().children().length;3670 var new_layout_elem = $('#gallery_layout0').clone()3671 new_layout_elem.data("preview_image", img);3672 new_layout_elem.data("layout", new_layout);3673 new_layout_elem.attr("id", "gallery_layout" + count)3674 new_layout_elem.mouseover(function() {3675 viewLayout('gallery', count)3676 })3677 new_layout_elem.click(function() {3678 setFixedLayout('gallery', count)3679 })3680 //new_layout_elem.dblclick(function() {setFixedLayout('gallery',count)})3681 var canvas = new_layout_elem[0];3682 var ctx = canvas.getContext("2d")3683 ctx.drawImage(img, 0, 0, sugg_stage.attrs.width / 3, sugg_stage.attrs.height / 3);3684 $('#gallery_table').append($('<tr>').append($('<td>').append(new_layout_elem)))3685 } else {3686 $('#suggestion_layout' + run.canvas_id).data("preview_image", img)3687 var canvas = $('#suggestion_layout'+(run.canvas_id))[0];3688 var ctx = canvas.getContext("2d")3689 ctx.clearRect(0, 0, sugg_stage.attrs.width / 3, sugg_stage.attrs.height / 3);3690 ctx.drawImage(img, 0, 0, sugg_stage.attrs.width / 3, sugg_stage.attrs.height / 3);3691 }3692 3693 3694 }3695 img.src = dataUrl3696 }3697 });3698 }3699}3700function createNewRegion(x, y, w, h, graphic, text, overlap) {3701 region = {}3702 region.type = 'region'3703 region.id = 'region'3704 region.x = x3705 region.y = y3706 region.width = w3707 region.height = h3708 region.allow_graphic = graphic3709 region.allow_text = text3710 region.allow_overlap = overlap3711 region.selected = false3712 region.fixed_amount = 03713 return region3714}3715function getLayoutDiff(layout1, layout2) {3716 if ((layout1 == undefined) || (layout2 == undefined) || (layout1 == '') || (layout2 == ''))3717 return 10000;3718 var elements1 = layout1.split("\n");3719 var elements2 = layout2.split("\n");3720 var num_elements = parseInt(elements1[3])3721 if (num_elements != parseInt(elements2[3]))3722 return 10000;3723 //console.log("layout1:"+layout1)3724 //console.log("layout2:"+layout2)3725 var diff_sum = 0;3726 for (var i = 3; i < num_elements + 3; i++) {3727 var elem1_split = elements1[i].split(',');3728 var elem2_split = elements2[i].split(',');3729 //console.log(elem1_split)3730 //console.log(elem2_split)3731 for (var j = 0; j < 3; j++)3732 diff_sum += Math.abs(elem1_split[j] - elem2_split[j])3733 //diff_sum+=5*Math.abs(elem1_split[3]-elem2_split[3])3734 }3735 //console.log("diff_sum:"+diff_sum)3736 return diff_sum;3737}3738function addLayoutToStack(new_layout,stack_type) {3739 var idx;3740 var stack;3741 //console.log("addLayoutToStack "+stack_type)3742 if (stack_type=='user')3743 {3744 idx = $('#canvas').data("user_layout_stack_idx");3745 stack = $('#canvas').data("user_layout_stack");3746 console.log("user_layout_stack")3747 }3748 else3749 {3750 idx = $('#canvas').data("layout_stack_idx");3751 stack = $('#canvas').data("layout_stack");3752 console.log("layout_stack")3753 }3754 3755 3756 if (idx != stack.length - 1)3757 stack = stack.slice(0, idx);3758 /*3759 if ((stack.length>0) && (getLayoutDiff(stack[stack.length-1][0],new_layout)<3))3760 {3761 return;3762 }3763 */3764 //stack.push([new_layout, getCurrentDesign()])3765 3766 3767 if (stack_type=='user')3768 {3769 var elem_info=[]3770 $.each($('#canvas').data("design").elements, function(i, elem) {3771 elem_info.push({'fixed_amount':elem.fixed_amount,'selected':elem.selected })3772 });3773 stack.push([new_layout, elem_info])3774 3775 $('#canvas').data("user_layout_stack_idx", stack.length - 1)3776 $('#canvas').data("user_layout_stack", stack)3777 }3778 else3779 {3780 stack.push([new_layout, undefined])3781 3782 $('#canvas').data("layout_stack_idx", stack.length - 1)3783 $('#canvas').data("layout_stack", stack)3784 }3785 if (stack.length > 1)3786 {3787 if (stack_type=='user')3788 $('#reportUndoButton').fadeTo(0, 1)3789 else if ($('#canvas').data("suggestionsEnabled"))3790 $('#undoButton').fadeTo(0, 1)3791 }3792 3793}3794function setCurrentLayout(new_layout, set_fixed, undoing,render_info,playback) {3795 if (undoing==undefined)3796 undoing=false3797 3798 console.log("setCurrentLayout")3799 if (((set_fixed == false)) || ($('#canvas').data("dragging")))3800 return3801 var design = $('#canvas').data("design")3802 var layout = $('#canvas').data("layout");3803 var alignments = ["left", "center", "right"];3804 if (layout != new_layout) {3805 if (!undoing) {3806 addLayoutToStack(new_layout)3807 }3808 //console.log("setting new layout")3809 console.log("setting current layout:" + new_layout)3810 3811 var idx=new_layout.indexOf("design_")3812 console.log("idx:"+idx)3813 if (idx==0)3814 new_layout='0\n'+new_layout3815 //console.log("here")3816 var elements = new_layout.split("\n");3817 var elem_cnt = parseInt(elements[3])3818 console.log("elem_cnt "+elem_cnt+" design.elements.length"+design.elements.length)3819 if (elem_cnt != design.elements.length)3820 return;3821 3822 //console.log("elem_cnt "+elem_cnt+" design.elements.length"+design.elements.length) 3823 3824 var design_sizes = elements[2].split(",")3825 var layout_width=parseInt(design_sizes[0])3826 var layout_height=parseInt(design_sizes[1])3827 3828 if ((layout_width!= design.width) || (layout_height!=design.height))3829 {3830 console.log("layout_width:"+ layout_width)3831 console.log("layout_height:"+ layout_height)3832 console.log("design.width:"+ design.width)3833 console.log("design.height:"+ design.height)3834 return;3835 }3836 3837 $('#canvas').data("layout_log").push(['sugg',new Date().getTime(),new_layout,";"])3838 var layer = $('#canvas').data("stage").get('#layer')[0];3839 //layer.removeChildren()3840 3841 var fixed_count=0;3842 for (var i = 0; i < design.elements.length; i++) {3843 //console.log("design.elements.length: "+design.elements.length)3844 var elem = design.elements[i];3845 //console.log("elem id: "+elem.id+" selected?"+elem.selected)3846 3847 if (elem.fixed_amount==1)3848 fixed_count+=1;3849 3850 //console.log("elem id: "+elem.id+" selected?"+elem.selected+ " fix_amount:"+fixed_count)3851 var elem_split = elements[i+4].split(',');3852 if (elem.img == undefined)3853 console.log("ERROR on element " + i + " with layout " + elements[i])3854 3855 var new_height = parseInt(elem_split[2]);3856 var new_x = parseInt(elem_split[0])3857 var new_y = parseInt(elem_split[1])3858 var new_alt_id = parseInt(elem_split[6]);3859 var new_align_id=parseInt(elem_split[3])3860 3861 3862 if (elem.selected){3863 fixed_count+=1;3864 //continue3865 3866 var str= sprintf("checking selected %f %f %f %f %f, %f %f %f %f %f",elem.x,elem.y,elem.height,elem.alternate_id, elem.align_type, new_x,new_y, new_height, new_alt_id, new_align_id )3867 3868 console.log(str)3869 3870 if ((Math.round(elem.height)!=new_height) || (Math.round(elem.x)!=new_x) || (Math.round(elem.y)!=new_y) || (new_alt_id!= elem.alternate_id) || (new_align_id ==elem.align_type))3871 continue3872 3873 //console.log("updating selected to new align type "+String(new_align_id)+" from type "+String(elem.align_type))3874 }3875 3876 if ((!elem.fix_alternate) && (elem.id in design.element_alts)) {3877 $.each(design.element_alts[elem.id], function(num_lines, ae) {3878 ae.img.remove();3879 if (new_alt_id == ae.alternate_id) {3880 3881 elem.img.remove();3882 3883 ae.fixed_amount = elem.fixed_amount3884 ae.state_img = elem.state_img3885 design.elements[i] = ae3886 3887 ae.img.attrs.strokeEnabled = false;3888 ae.img.show()3889 layer.add(ae.img)3890 3891 elem = ae;3892 }3893 });3894 }3895 3896 3897 var new_width = new_height * elem.aspect_ratio;3898 elem.height = new_height3899 elem.width = new_width3900 elem.x = new_x3901 elem.y = new_y3902 elem.state_img.setPosition(elem.x + elem.width, elem.y)3903 //elem.state_img.show()3904 3905 if (elem.selected)3906 elem.img.attrs.strokeEnabled=true3907 3908 3909 3910 if ((render_info!= undefined) || (playback!=undefined)){3911 3912 3913 3914 if (render_info!= undefined)3915 {3916 fix_amount = render_info[i].fixed_amount3917 selected = render_info[i].selected3918 }3919 else3920 {3921 fix_amount=parseFloat(elem_split[4]);3922 selected= ((fix_amount==0.95) || (fix_amount==1.05))3923 3924 console.log("fix_amount:"+fix_amount)3925 console.log("selected:"+selected)3926 }3927 3928 elem.img.attrs.strokeEnabled=selected3929 3930 elem.state_img.hide()3931 3932 if (fix_amount<0.5)3933 elem.state_img=elem.unlock_img3934 else if (fix_amount<1.0)3935 elem.state_img=elem.tweakable_img3936 else3937 elem.state_img=elem.lock_img3938 3939 elem.state_img.setPosition(elem.x + elem.width, elem.y) 3940 3941 elem.state_img.show()3942 3943 }3944 3945 elem.region_id = parseInt(elem_split[5])3946 //console.log(elem_split)3947 //console.log("setting to "+elem.x+" "+elem.y+" "+elem.height)3948 if (elem.num_lines > 1) {3949 elem.align_type = new_align_id3950 var align;3951 if (new_align_id > -1)3952 align = alignments[new_align_id]3953 else3954 align = elem.align3955 if (elem.img != elem.alignment_imgs[align]) {3956 var layer = elem.img.getLayer();3957 elem.img.remove()3958 elem.align = align;3959 elem.img = elem.alignment_imgs[align];3960 elem.img.attrs.strokeEnabled=elem.selected3961 elem.img.show()3962 layer.add(elem.img);3963 }3964 }3965 elem.img.opacity = 1;3966 elem.img.setX(elem.x);3967 elem.img.setY(elem.y);3968 elem.img.setHeight(elem.height);3969 elem.img.setWidth(elem.width);3970 moveAnchors(elem)3971 setHidden(elem, new_alt_id < 0)3972 3973 3974 3975 3976 }3977 //set regions3978 design.regions = []3979 for (var i = elem_cnt + 4; i < elements.length; i++) {3980 var reg = elements[i].split(",")3981 if (reg.length < 6)3982 continue;3983 $.each(reg, function(i, r) {3984 reg[i] = parseInt(r)3985 })3986 var region = createNewRegion(reg[1], reg[2], reg[3], reg[4], reg[0] == 2, reg[0] == 1, false)3987 console.log('region. ' + elements[i] + ' x ' + region.x + ' y ' + region.y + ' w ' + region.width + ' h ' + region.height + ' ' + region.allow_text + ' ')3988 design.regions.push(region);3989 }3990 console.log("finished setting new layout")3991 3992 3993 if (fixed_count<design.elements.length)3994 $('#canvas').data("status_log").push("U"+(design.elements.length-fixed_count))3995 $('#canvas').data("layout", new_layout);3996 }3997 design.elements[0].img.getLayer().draw();3998 //double check each element is correct3999 $.each(design.elements, function(i, e) {4000 if ((e.img.getStage() == undefined) || (e.img.getLayer() == undefined)) {4001 console.log("error for element " + e.id)4002 console.log("stage: ")4003 console.log(e.img.getStage())4004 console.log("layer: ")4005 console.log(e.img.getLayer())4006 console.log("new_layout:")4007 console.log(new_layout)4008 $('#suggestion_status').text("stage undefined");4009 }4010 });4011}4012function setHidden(elem, state) {4013 elem.hidden = state4014 if (state) {4015 if (elem.hidden_img == 0) {4016 elem.hidden_img = elem.img.getImage()4017 elem.img.setImage(0)4018 }4019 } else {4020 if (elem.hidden_img != 0) {4021 elem.img.setImage(elem.hidden_img)4022 elem.hidden_img = 04023 }4024 }4025}4026function loadImages(sources, callback) {4027 4028 if ($('#canvas').data("loadedImages"))4029 return4030 4031 $('#canvas').data("loadedImages",true)4032 console.log("loading images")4033 var images = {};4034 var loadedImages = 0;4035 var numImages = 0;4036 for (var src in sources) {4037 numImages++;4038 }4039 for (var src in sources) {4040 console.log("loading image " + sources[src])4041 images[src] = new Image();4042 images[src].onload = function() {4043 if (++loadedImages >= numImages) {4044 $('#canvas').data("images", images);4045 callback();4046 }4047 };4048 images[src].src = sources[src];4049 }4050}4051function loadDesignFile(designName) {4052 $('#canvas').data("images_rendering",-1)4053 4054 console.log("loading design " + designName)4055 var jsonLoad = $.getJSON(sprintf('/design/static/designs/%s.json', designName), function(design) {4056 console.log('design.json obtained');4057 var idx=designName.indexOf('new')4058 if (idx>-1) {4059 design.name = "design_" + String(new Date().getTime());4060 console.log("Created design " + design.name)4061 }4062 4063 idx=designName.lastIndexOf('/')4064 4065 if (idx>-1)4066 {4067 var design_dir=designName.substring(0,idx+1)4068 var name=designName.substring(idx+1,designName.length)4069 4070 4071 console.log("design dir: "+design_dir)4072 console.log("design name: "+name)4073 4074 design.directory=design_dir;4075 design.name=name; 4076 4077 }4078 design.elements.sort(function(e1, e2) {4079 return e2.importance - e1.importance4080 })4081 $('#canvas').data("design", design);4082 sources = {};4083 sources['unlocked'] = '/design/static/icons/unlocked.png'4084 sources['tweakable'] = '/design/static/icons/tweakable.png'4085 sources['locked'] = '/design/static/icons/locked.png'4086 4087 //sources['checkmark'] = '/design/static/img/greencheck-transparent.png'4088 if (design.background_fname.length > 1)4089 sources['background'] = sprintf('/design/static/images/%s', design.background_fname);4090 font_list=[]4091 $.each(design.elements, function(i, elem) {4092 if ("fname" in elem) {4093 console.log("elem.fname " + elem.fname)4094 sources[elem.fname] = sprintf('/design/static/images/%s', elem.fname);4095 }4096 else{4097 if ($.inArray(elem.font,font_list)==-1)4098 {4099 $('#updateText').css("font-family",elem.font)4100 4101 var fdiv=$('#initFont').clone()4102 fdiv.css("font-family",elem.font)4103 fdiv.attr("id",elem.font)4104 $('#initFont').parent().append(fdiv)4105 font_list.push(elem.font)4106 }4107 4108 }4109 4110 });4111 4112 console.log("loading fonts "+String(font_list))4113 4114 $('#canvas').data("loadedImages",false)4115 4116 4117 var callback = function(){loadImages(sources, setupCanvas);}4118 4119 if (font_list.length>0)4120 waitForWebfonts(font_list,callback)4121 else4122 callback()4123 //loadImages(sources, setupCanvas);4124 4125 }).done(function() {4126 console.log('success');4127 }).fail(function() {4128 console.error('JSON load failure.');4129 });4130}4131function selectImage(type) {4132 console.log("selectImage")4133 deselectAll()4134 $('#canvas').data('inputType', type)4135 $('#fileInput').click();4136}4137function handleFiles(files) {4138 console.log("handling files " + files);4139 var file = files[0];4140 var reader = new FileReader();4141 reader.onload = onFileReadComplete;4142 reader.readAsDataURL(file);4143 4144 $("#canvas").data("load_filename", file.name)4145}4146function onFileReadComplete(event) {4147 console.log(event.target.result)4148 var img = new Image();4149 var fname = "graphic_" + String(new Date().getTime()) + ".png";4150 var fname = $("#canvas").data("load_filename");4151 img.onload = function() {4152 if ($('#canvas').data('inputType') == 'graphic')4153 createNewElement('graphic', img, fname)4154 else {4155 var background = $('#canvas').data('design').background;4156 background.attrs.fillPatternImage = img4157 background.attrs.fill = undefined4158 $("#canvas").data("design").background_fname = fname;4159 background.getLayer().draw()4160 background = $('#canvas').data('design').sugg_background;4161 background.attrs.fillPatternImage = img4162 background.attrs.fill = undefined4163 background.getLayer().draw()4164 }4165 };4166 img.src = event.target.result4167 saveImageOnServer(fname, event.target.result)4168}4169function backgroundOffsetChanged() {4170 console.log("backgroundOffsetChanged")4171 var design=$('#canvas').data("design");4172 if (design.background_fname != ''){4173 4174 var offset_x=parseInt($('#background_offset_x').val())4175 var offset_y=parseInt($('#background_offset_y').val())4176 4177 var pos = design.background_elem.img.getPosition();4178 4179 design.background_elem.offset_x=offset_x4180 design.background_elem.offset_y=offset_y4181 4182 design.background_elem.img.attrs.fillPatternOffsetX=offset_x4183 design.background_elem.img.attrs.fillPatternOffsetY=offset_y4184 4185 design.background_elem.img.getLayer().draw() 4186 }4187}4188function backgroundColorChanged() {4189 console.log("backgroundColorChanged")4190 var background = $('#canvas').data('design').background;4191 background.attrs.fillPatternImage = ''4192 background.attrs.fill = $('#background_color_select').val();4193 $("#canvas").data("design").background_fname = '';4194 $('#canvas').data('design').background_color = $('#background_color_select').val();4195 background.getLayer().draw()4196 background = $('#canvas').data('design').sugg_background;4197 background.attrs.fillPatternImage = ''4198 background.attrs.fill = $('#background_color_select').val();4199 background.getLayer().draw()4200 4201 4202 4203 setupSelectRectangle($('#canvas').data('design'),$('#canvas').data("stage").get('#layer')[0])4204 4205 4206}4207function setupSliders() {4208 $('#whitespace_slider').slider({4209 min : 0,4210 step : 1,4211 max : 100,4212 value : 50,4213 change : function(event, ui) {4214 updateParameters('whitespace', ui.value);4215 }4216 });4217 $('#text_size_slider').slider({4218 min : 0,4219 step : 1,4220 max : 100,4221 value : 50,4222 change : function(event, ui) {4223 updateParameters('text_size', ui.value);4224 }4225 });4226 $('#graphic_size_slider').slider({4227 min : 0,4228 step : 1,4229 max : 100,4230 value : 50,4231 change : function(event, ui) {4232 updateParameters('graphic_size', ui.value);4233 }4234 });4235 $('#symmetry_slider').slider({4236 min : 0,4237 step : 1,4238 max : 100,4239 value : 50,4240 change : function(event, ui) {4241 updateParameters('symmetry', ui.value);4242 }4243 });4244}4245function createNewDesign() {4246 window.location.replace("/design/create&design=new")4247}4248function openExistingDesign() {4249 window.location.replace("/design/select/"+$('#canvas').data("design").directory)4250}4251function duplicateDesign() {4252 $('#canvas').data("design").name = "design_" + String(new Date().getTime());4253 saveDesign()4254 alert("Design duplicated")4255 startSuggestions()4256}4257function deleteDesign() {4258 if (confirm("Warning! This will permanentely delete this design and send you back to the selection menu. Are you sure you want to delete this design?")) {4259 deleteDesignOnServer($('#canvas').data("design"))4260 }4261}4262function startSuggestions(run_offset) {4263 if (run_offset == undefined)4264 run_offset = 04265 console.log("Starting suggestions")4266 if ($('#canvas').data("design").elements.length <= 1) {4267 console.log("Not enough elements")4268 //return4269 }4270 $('#canvas').data("status_log").push("Start")4271 $('#canvas').data('killed', false)4272 $('#canvas').data('paused', false)4273 $('#restartButton').hide()4274 $('#suggestion_status').text("")4275 var design_string = getCurrentDesign();4276 var layout_counter=$('#canvas').data("layout_counter")4277 if (layout_counter==undefined)4278 layout_counter=0;4279 $('#canvas').data("layout_counter",layout_counter+1)4280 4281 design_string=layout_counter+"\n"+design_string4282 4283 $('#design_out').val(design_string);4284 var runs = [];4285 var run_id = -1;4286 var run_types;4287 //var run_types=['near','mid','far','gallery']4288 4289 if ($('#canvas').data("automaticUpdate"))4290 run_types=['near']4291 else4292 run_types=['near']4293 //var run_types = ['far']4294 if (getURLParameter("styles") == 1)4295 run_types.push("gallery")4296 for (var i = 0; i < run_types.length; i++) {4297 run = {}4298 //run.id=Math.floor(Math.random()*65000);4299 run.id = i + run_offset4300 run.canvas_id = i4301 run.image = new Image()4302 run.type = run_types[i]4303 run.layout = ''4304 run.energy = 9999999;4305 //stopRun(run.id, run_types[i]);4306 startNewRun(run.id, run_types[i], design_string)4307 runs.push(run)4308 if ('gallery' == run_types[i])4309 $('#gallery_layout0').data("run_idx", i)4310 else4311 $('#suggestion_layout' + String(run.canvas_id)).data("run_idx", i)4312 }4313 $('#canvas').data("runs", runs)4314 setTimeout(sendCurrentLayout, 500);4315}4316function startText() {4317 console.log("adding new text. deselecting")4318 deselectAll()4319 var layer = $('#canvas').data("stage").get('#layer')[0];4320 layer.draw()4321 $('#user_text').val('')4322 //if ($('#canvas').data("text_mode") == false) {4323 document.body.style.cursor = "url('/design/static/img/text_cursor2.png'), auto"4324 $('#canvas').data("text_mode", true)4325 showElementControls()4326 //} else {4327 // document.body.style.cursor = "default";4328 // $('#canvas').data("text_mode", false)4329 //}4330}4331function createRegion() {4332 var region = createNewRegion(0, 0, 100, 100, $("#region_graphic_select").attr("checked") == 'checked', $("#region_text_select").attr("checked") == 'checked', $("#region_overlap_select").attr("checked") == 'checked')4333 $('#canvas').data("design").regions.push(region)4334 toggleRegionMode()4335 toggleRegionMode()4336 deselectAll(region)4337 region.img.getLayer().draw()4338}4339function regionProposalChanged() {4340 var design = $('#canvas').data("design");4341 design.region_proposals = $("#region_proposal_select").attr("checked") == 'checked';4342 sendCurrentLayout();4343}4344function testSendLayout(num) {4345 $('#canvas').data("sendLayoutToServerTimes", [])4346 for (var i = 0; i < num; i++) {4347 sendCurrentLayout()4348 }4349}4350function toggleInvert() {4351 $('#canvas').data("invert", $("#invert_select").attr("checked") == 'checked')4352 /*4353 $.each($('#canvas').data("design").elements, function(i,elem){4354 var filt=04355 if ($('#canvas').data("invert"))4356 filt=Kinetic.Filters.Invert4357 elem.lock_img.attrs.filter=filt4358 elem.tweakable_img.attrs.filter=filt4359 elem.unlock_img.attrs.filter=filt4360 elem.state_img.attrs.filter=filt4361 });4362 */4363 $('#canvas').data("stage").get('#layer')[0].draw()4364}4365function validateFormResults() {4366 var saved_canvases = $("#saved_table").find("canvas")4367 console.log("saved_canvases.length:" + saved_canvases.length)4368 var min_layouts = gup('numLayouts')4369 if ((min_layouts != '') && (saved_canvases.length - 1 < parseInt(min_layouts)))4370 alert("You must create (and save) at least " + min_layouts + " layouts.")4371 else {4372 $("#final_design").val(getCurrentDesign())4373 $.each(saved_canvases, function(i, saved_img) {4374 var saved_layout = $(saved_img).data("layout")4375 var new_inp = $('<input>')4376 new_inp.attr("type", "hidden")4377 new_inp.attr("id", "saved_layout" + i)4378 new_inp.attr("name", "saved_layout" + i)4379 new_inp.val(saved_layout)4380 $("#final_layouts").append(new_inp)4381 });4382 //$("#studySubmit").click()4383 }4384}4385function setSuggestionIndex(shift) {4386 var idx = $('#canvas').data("layout_stack_idx")4387 var stack = $('#canvas').data("layout_stack")4388 console.log("setSuggestionIndex idx: " + idx + " shift: " + shift + " stack.len: " + stack.length)4389 if ((idx + shift < 0) || (idx + shift > stack.length - 1))4390 return4391 if (shift == -1) {4392 $('#canvas').data("user_input_log").push("Undo")4393 $('#canvas').data("status_log").push("Undo")4394 } else if (shift == 1) {4395 $('#canvas').data("user_input_log").push("Redo")4396 $('#canvas').data("status_log").push("Redo")4397 }4398 deselectAll()4399 //pauseSuggestions()4400 setCurrentLayout(stack[idx+shift][0], true, true)4401 if ((idx + shift) == 0)4402 $('#undoButton').fadeTo(0, 0.4)4403 else4404 $('#undoButton').fadeTo(0, 1)4405 if ((idx + shift) == stack.length - 1)4406 $('#redoButton').fadeTo(0, 0.4)4407 else4408 $('#redoButton').fadeTo(0, 1)4409 $('#canvas').data("layout_stack_idx", idx + shift)4410}4411function setUserLayoutIndex(shift) {4412 var idx = $('#canvas').data("user_layout_stack_idx")4413 var stack = $('#canvas').data("user_layout_stack")4414 console.log("setUserLayoutIndex idx: " + idx + " shift: " + shift + " stack.len: " + stack.length)4415 if ((idx + shift < 0) || (idx + shift > stack.length - 1))4416 return4417 deselectAll()4418 4419 setReportBeforeImage(stack[idx+shift])4420 if ((idx + shift) == 0)4421 $('#reportUndoButton').fadeTo(0, 0.4)4422 else4423 $('#reportUndoButton').fadeTo(0, 1)4424 if ((idx + shift) == stack.length - 1)4425 $('#reportRedoButton').fadeTo(0, 0.4)4426 else4427 $('#reportRedoButton').fadeTo(0, 1)4428 $('#canvas').data("user_layout_stack_idx", idx + shift)4429}4430function plotEnergy(sugg_energy, user_energy) {4431 var curr_energy = $('#canvas').data("energy")4432 if (curr_energy == 0)4433 return;4434 var plot_energy = $('#canvas').data("plot_energy_list")4435 plot_energy.push([user_energy, sugg_energy])4436 var data1 = [];4437 var data2 = [];4438 for (var i = Math.max(0, plot_energy.length - 25); i < plot_energy.length; i++) {4439 data1.push([i, plot_energy[i][0]]);4440 data2.push([i, plot_energy[i][1]]);4441 }4442 $.plot("#energy_plot", [data1, data2], {4443 series : {4444 shadowSize : 0 // Drawing is faster without shadows4445 },4446 xaxis : {4447 show : false4448 }4449 });4450}4451function fontSizeChanged(new_size)4452{4453 4454 var elem=$('#canvas').data("selected")4455 if (elem.type=="text")4456 {4457 4458 $('#canvas').data("user_input_log").push("Scale-Dropdown")4459 $('#canvas').data("status_log").push("Scale-Dropdown")4460 4461 4462 console.log('user field:'+$('#fontSizeInput'))4463 if (new_size==undefined)4464 new_size=parseFloat($('#fontSizeInput').val())4465 else4466 $('#fontSizeInput').val(new_size)4467 4468 console.log('new size:'+new_size)4469 elem.height=(new_size/elem.init_font_size)*elem.init_height4470 elem.width=elem.height*elem.aspect_ratio4471 4472 console.log('setting new height:'+elem.height)4473 4474 elem.img.setHeight(elem.height)4475 elem.img.setWidth(elem.width)4476 4477 moveAnchors(elem)4478 elem.state_img.setPosition(elem.x + elem.width, elem.y)4479 drawAlignmentLines(elem, 'dragging')4480 elem.img.getLayer().draw()4481 4482 }4483 4484 4485}4486function initializeReport(positive)4487{4488 4489 4490 4491 if (positive)4492 $('#reportInstructions').text("Please describe what you liked about the update (optional)")4493 else4494 $('#reportInstructions').text("Please describe the problem. What was the expected behaviour? What was wrong with the automatic update?")4495 4496 4497 4498 4499 4500 $('#report').show()4501 $('#reportStatus').text("")4502 $('#report').data("running",$('#canvas').data("started"))4503 $('#report').data("positive",positive)4504 4505 4506 4507 $('#report').data("afterLayout",getCurrentLayout())4508 4509 stopSuggestionsUntilUserInput()4510 4511 4512 var stage=$('#canvas').data("stage")4513 4514 $.each($('#canvas').data("design").elements, function(i, elem) {4515 elem.state_img.show();4516 });4517 4518 4519 stage.get('#layer')[0].draw();4520 4521 stage.toDataURL({4522 callback : function(dataUrl) {4523 var img = new Image();4524 img.onload = function() {4525 4526 $('#report_after_img').attr("width",stage.attrs.width / 2)4527 $('#report_after_img').attr("height",stage.attrs.height / 2)4528 $('#report_after_img').attr("src",dataUrl)4529 }4530 img.src = dataUrl;4531 }4532 });4533 4534 var stack = $('#canvas').data("user_layout_stack")4535 4536 if (stack.length==0)4537 return4538 4539 4540 setReportBeforeImage( stack[stack.length-1])4541 4542 4543 4544 4545 $('#canvas').data("sugg_stage").toDataURL({4546 callback : function(dataUrl) {4547 var img = new Image();4548 img.onload = function() {4549 $('#report_sugg_img').attr("width",stage.attrs.width / 2)4550 $('#report_sugg_img').attr("height",stage.attrs.height / 2)4551 $('#report_sugg_img').attr("src",dataUrl)4552 }4553 img.src = dataUrl;4554 }4555 });4556 4557 4558}4559function setReportBeforeImage(layout_info)4560{4561 4562 var layout=layout_info[0] 4563 var curr_layout=getCurrentLayout()4564 4565 $('#report').data("beforeLayout",layout)4566 4567 4568 deselectAll()4569 4570 setCurrentLayout(layout,true,true,layout_info[1]) 4571 4572 var stage=$('#canvas').data("stage")4573 stage.toDataURL({4574 callback : function(dataUrl) {4575 var img = new Image();4576 img.onload = function() {4577 $('#report_before_img').attr("width",stage.attrs.width / 2)4578 $('#report_before_img').attr("height",stage.attrs.height / 2)4579 $('#report_before_img').attr("src",dataUrl)4580 }4581 img.src = dataUrl;4582 }4583 });4584 4585 setCurrentLayout(curr_layout,true,true) 4586 4587 $.each($('#canvas').data("design").elements, function(i, elem) {4588 elem.state_img.hide();4589 });4590 stage.get('#layer')[0].draw();4591 4592}4593function cancelReport()4594{4595 4596 $('#report').hide()4597 4598 $('#reportStatus').text("")4599 $('#reportText').val('')4600}4601function submitReport()4602{4603 4604 // 4605 if (($('#reportText').val()=='')&& (!$('#report').data("positive")))4606 {4607 alert("You must provide some explanation for your response")4608 return;4609 }4610 4611 4612 if ($('#report').data("positive"))4613 $('#numLikes').text(parseInt($('#numLikes').text())+1)4614 else4615 $('#numDislikes').text(parseInt($('#numDislikes').text())+1)4616 4617 $('#report').hide()4618 4619 $('#reportStatus').text("Response Submitted")4620 4621 var report={}4622 4623 report['text']=$('#reportText').val()4624 report['workerId']=gup('workerId')4625 report['hitId']=gup('hitId')4626 report['assignmentId']=gup('assignmentId')4627 report['userId']=$('input[name=userID]').val()4628 report['design']=$('#canvas').data("design").name4629 report['date']=String(new Date())4630 report['errorMessage']=$('#error_message').text()4631 report['optimizerRunning']=$('#report').data("running")4632 report['afterLayout']=$('#report').data("afterLayout")4633 report['beforeLayout']=$('#report').data("beforeLayout")4634 report['positive']=$('#report').data("positive")4635 4636 4637 report['userLayoutFeatures']=$('#userLayoutFeatures').val()4638 report['suggestionLayoutFeatures']=$('#suggLayoutFeatures').val()4639 4640 var report_name=report['design']+ "-"+String(new Date().getTime());4641 4642 saveReportOnServer(report_name, $('#report_before_img').attr("src"), $('#report_after_img').attr("src"), $('#report_sugg_img').attr("src"),report)4643 4644 4645 if ($('#report').data("names")==undefined)4646 $('#report').data("names",[])4647 4648 $('#report').data("names").push([$('#report').data("positive"),report_name])4649 4650 $('#reportText').val('')4651}4652function startStudy()4653{4654 var sequence=$('#canvas').data("design_sequence")4655 4656 $('#startStudyButton').hide()4657 $('#nextDesignButton').show()4658 4659 $('#canvas').data("sequence_index",0)4660 loadDesignFile(design_sequence[0].design)4661 4662 executeAfterTextRendering(function(){4663 setMatchDesign(design_sequence[0].match_design);4664 setupRetargetting();4665 resetLayout()})4666}4667function moveToNextDesign()4668{4669 var curr_design_idx=$('#canvas').data("sequence_index")4670 var sequence=$('#canvas').data("design_sequence")4671 4672 var curr_design=sequence[curr_design_idx].design4673 4674 if ($('#canvas').data("loading"))4675 return4676 else4677 $('#canvas').data("loading",true)4678 4679 //$("#layout"+curr_design_idx).val(getCurrentLayout())4680 $("#layout"+curr_design_idx).val(getCurrentLayout())4681 4682 var last_time=$('#canvas').data("designTime") 4683 if (last_time==undefined)4684 last_time=$('#canvas').data("layoutStartTime") 4685 4686 var curr_time=new Date()4687 4688 if ($('#layoutTimes').data('times')==undefined)4689 $('#layoutTimes').data('times',[curr_time-last_time])4690 else4691 $('#layoutTimes').data('times').push(curr_time-last_time)4692 4693 $('#layoutTimes').val(String($('#layoutTimes').data('times')))4694 $('#canvas').data("designTime",curr_time)4695 4696 $("#layout_input"+curr_design_idx).val($('#canvas').data("user_input_log"))4697 $("#layout_log"+curr_design_idx).val($('#canvas').data("layout_log"))4698 4699 4700 $('#studyOrder').val(String(sequence))4701 4702 4703 $.each($('#canvas').data("design").elements, function(i, elem) {4704 elem.state_img.hide();4705 elem.img.attrs.strokeEnabled=false4706 $.each(elem.anchors, function(i, a) {4707 a.hide();4708 });4709 });4710 $.each($('#canvas').data("align_lines"), function(i, al) {4711 al[0].destroy()4712 });4713 //$('#canvas').data("stage").get('#layer')[0].draw()4714 4715 $('#canvas').data("stage").toDataURL({4716 callback : function(dataUrl) {4717 var img = new Image();4718 img.onload = function() {4719 4720 4721 4722 var hit_id = gup('hitId')4723 var fname = 'layouts/' + $('#canvas').data("design").name + '-' + gup('workerId') + "-" + hit_id + "-" + String(curr_design_idx) + '.png'4724 saveImageOnServer(fname, dataUrl)4725 4726 4727 $('#canvas').data("sequence_index",curr_design_idx+1) 4728 4729 var next_design=sequence[curr_design_idx+1].design4730 4731 4732 4733 if (next_design.indexOf("direct")>-1)4734 {4735 $('#canvas').data("suggestionsEnabled",false)4736 $('.suggestions').hide()4737 }4738 if (next_design.indexOf("sugg")>-1)4739 {4740 $('#canvas').data("suggestionsEnabled",true)4741 $('.suggestions').show()4742 4743 }4744 4745 var next_str=""4746 4747 if (next_design.indexOf("tut")>-1)4748 next_str+="Tutorial-"4749 else4750 next_str+="Normal-"4751 4752 4753 if ($('#canvas').data("suggestionsEnabled"))4754 {4755 $('#interface').data("interface").push('suggestions')4756 next_str+="Suggestions"4757 }4758 else4759 {4760 $('#interface').data("interface").push('baseline')4761 next_str+="Baseline" 4762 }4763 4764 4765 $('#canvas').data("user_input_log",[next_str])4766 $('#canvas').data("status_log").push(next_str)4767 $('#canvas').data("layout_log",[next_str,new Date().getTime(),''])4768 4769 4770 4771 4772 4773 4774 loadDesignFile(next_design)4775 4776 4777 if ("match_design" in sequence[curr_design_idx+1])4778 setMatchDesign(sequence[curr_design_idx+1].match_design)4779 4780 4781 executeAfterTextRendering(4782 function(){4783 $('#canvas').data("loading",false)4784 4785 if (gup("retarget")!='')4786 setupRetargetting();4787 4788 resetLayout();4789 4790 });4791 4792 4793 4794 }4795 img.src = dataUrl;4796 }4797 }); 4798 4799 if (curr_design_idx+1==sequence.length)4800 {4801 $('#nextDesignButton').hide()4802 4803 $('#mturkQuestionnaire').show()4804 4805 $('#canvas').hide()4806 4807 $('#suggestion_status').text("HIT complete. Please submit after providing suggestions/comments.")4808 $('#suggestion_status').css("background-color",'#5F5')4809 4810 return4811 }4812 4813 4814 4815}4816function setMatchDesign(match_design)4817{4818 var stage=$('#canvas').data("stage")4819 console.log("setMatchDesign")4820 $('#retarget_img').css("width",stage.attrs.width / 2)4821 $('#retarget_img').css("height",stage.attrs.height / 2)4822 $('#retarget_img').attr("src","/design/static/designs/"+match_design+".png")4823}4824function setupRetargetting()4825{ 4826 4827 var retarget=gup('retarget')4828 4829 4830 4831 if (retarget!='')4832 {4833 4834 console.log("setupRetargetting. retarget: "+retarget)4835 4836 $('#canvas').data("started", true)4837 4838 //var stage=$('#canvas').data("stage")4839 4840 //stage.toDataURL({4841 // callback : function(dataUrl) {4842 // var img = new Image();4843 // img.onload = function() {4844 // 4845 // $('#retarget_img').attr("width",stage.attrs.width / 2)4846 // $('#retarget_img').attr("height",stage.attrs.height / 2)4847 // $('#retarget_img').attr("src",dataUrl)4848 4849 var splt=retarget.split("_")4850 var new_width=parseInt(splt[0])4851 var new_height=parseInt(splt[1]) 4852 4853 $('#design_width').val(new_width)4854 $('#design_height').val(new_height)4855 4856 designSizeChanged()4857 4858 // }4859 // img.src = dataUrl;4860 4861 // }4862 //}); 4863 }4864 4865}4866function waitForWebfonts(fonts, callback) {4867 var loadedFonts = 0;4868 for(var i = 0, l = fonts.length; i < l; ++i) {4869 (function(font) {4870 var node = document.createElement('span');4871 // Characters that vary significantly among different fonts4872 node.innerHTML = 'giItT1WQy@!-/#';4873 // Visible - so we can measure it - but not on the screen4874 node.style.position = 'absolute';4875 node.style.left = '-10000px';4876 node.style.top = '-10000px';4877 // Large font size makes even subtle changes obvious4878 node.style.fontSize = '300px';4879 // Reset any font properties4880 4881 4882 if ((font=='sans-serif') || (font=='Helvetica'))4883 node.style.fontFamily = 'Eater Caps';4884 else4885 node.style.fontFamily = 'sans-serif';4886 node.style.fontVariant = 'normal';4887 node.style.fontStyle = 'normal';4888 node.style.fontWeight = 'normal';4889 node.style.letterSpacing = '0';4890 document.body.appendChild(node);4891 // Remember width with no applied web font4892 var width = node.offsetWidth;4893 node.style.fontFamily = font;4894 4895 console.log("font "+font+ " start. sans-serif width "+width)4896 var interval;4897 function checkFont() {4898 if (node)4899 {4900 console.log("font "+font+ " has offset width "+node.offsetWidth+"sans-serif width "+width)4901 4902 }4903 console.log("loaded fonts "+loadedFonts+ " array len "+fonts.length)4904 // Compare current width with original width4905 if((node!=null) && (node.offsetWidth != width)) {4906 ++loadedFonts;4907 node.parentNode.removeChild(node);4908 4909 node = null;4910 }4911 4912 // If all fonts have been loaded4913 if(loadedFonts >= fonts.length) {4914 if(interval) {4915 clearInterval(interval);4916 }4917 if(loadedFonts == fonts.length) {4918 callback();4919 return true;4920 }4921 }4922 };4923 if(!checkFont()) {4924 4925 interval = setInterval(checkFont, 50);4926 }4927 })(fonts[i]);4928 }...

Full Screen

Full Screen

auth.js

Source:auth.js Github

copy

Full Screen

1var loginURL = "/login_session";2var logoutURL = "/logoff_session";3var logout = "logoff"4var userAgent = navigator.userAgent.toLowerCase();5var firstLogIn = true;6 7var login = function() {8 var form = document.forms[0];9 var username = form.username.value;10 var password = form.password.value;11 var remember_me = form.remember_me.checked;12 var host = form.host.value;13 var path_name = window.location.pathname;14 15 var reshost = host.split("/");16 var res = path_name.split("/");17 if (reshost[reshost.length - 1] === res[1]) {18 path_name = path_name.replace("/"+res[1], "");19 }20 var _login = function(){21 22 $("#imgProgress").show(); 23 if (document.getElementById('myModalFormId') !== null ) {24 remove ('myModalFormId');25 }26 if (username === "" || password === "") {27 if (document.getElementById('myModalFormId') === null ) { 28 var newdiv = document.createElement('div');29 newdiv.innerHTML = "<br>Invalid Credentials</br>";30 newdiv.id = 'myModalFormId';31 document.getElementById("myModalForm").appendChild(newdiv);32 $("#imgProgress").hide();33 } 34 }else{ 35 36 //Instantiate HTTP Request37 var request = ((window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));38 //request.open("GET", host + loginURL, true, username, password);39 //request.send(null);40 request.open("POST", host + loginURL, true);41 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");42 request.send("username="+username+"&password="+password+"&remember_me="+remember_me);43 44 //Process Response45 request.onreadystatechange = function(){46 if (request.readyState == 2) {47 if (request.status==200) {48 window.location=host.concat(path_name);49 }50 else{51 if (navigator.userAgent.toLowerCase().indexOf("firefox") !==-1){ 52 }53 54 if (document.getElementById('myModalFormId') === null ) { 55 var newdiv = document.createElement('div');56 newdiv.innerHTML = "<br>Invalid Credentials</br>";57 newdiv.id = 'myModalFormId';58 document.getElementById("myModalForm").appendChild(newdiv);59 $("#imgProgress").hide(); 60 } 61 }62 }63 }64 }65 }66 67 var userAgent = navigator.userAgent.toLowerCase();68 if (userAgent.indexOf("firefox") !== -1){ //TODO: check version number69 if (firstLogIn) _login();70 else logoff(_login);71 }72 else{73 _login();74 }75 76 if (firstLogIn) firstLogIn = false;77};78var login_with_redirect = function() {79 var form = document.forms[0];80 var username = form.username.value;81 var password = form.password.value;82 var remember_me = form.remember_me.checked;83 var host = form.host.value;84 var _login = function(){85 var redirectURL = form.redirect && form.redirect.value || ""; 86 var reshost = host.split("/");87 var res = redirectURL.split("/");88 if (reshost[reshost.length - 1] === res[1]) {89 redirectURL = redirectURL.replace("/"+res[1], "");90 }91 $("#imgProgressRedirect").show(); 92 if (document.getElementById('myModalFormId') !== null ) {93 remove ('myModalFormId');94 }95 if (username === "" || password === "") {96 if (document.getElementById('myModalFormId') === null ) { 97 var newdiv = document.createElement('div');98 newdiv.innerHTML = "<br>Invalid Credentials</br>";99 newdiv.id = 'myModalFormId';100 document.getElementById("redirecLoginForm").appendChild(newdiv);101 $("#imgProgressRedirect").hide();102 } 103 }else{ 104 105 //Instantiate HTTP Request106 var request = ((window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));107 //request.open("GET", host.concat(loginURL), true, username, password);108 //request.send(null);109 110 request.open("POST", host + loginURL, true);111 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");112 request.send("username="+username+"&password="+password+"&remember_me="+remember_me);113 114 //Process Response115 request.onreadystatechange = function(){116 if (request.readyState == 2) {117 if (request.status==200) {118 if (redirectURL === "") { 119 window.location=host.concat("/");120 } else {121 window.location=host.concat(redirectURL);122 }123 }124 else{125 if (navigator.userAgent.toLowerCase().indexOf("firefox") !== -1){ 126 }127 128 if (document.getElementById('myModalFormId') === null ) { 129 var newdiv = document.createElement('div');130 newdiv.innerHTML = "<br>Invalid Credentials</br>";131 newdiv.id = 'myModalFormId';132 document.getElementById("redirecLoginForm").appendChild(newdiv);133 $("#imgProgressRedirect").hide(); 134 } 135 }136 }137 }138 }139 }140 141 var userAgent = navigator.userAgent.toLowerCase();142 if (userAgent.indexOf("firefox") !== -1){ //TODO: check version number143 if (firstLogIn) _login();144 else logoff(_login);145 }146 else{147 _login();148 }149 150 if (firstLogIn) firstLogIn = false;151};152var logoff = function(callback){153 var form = document.forms[0];154 var host = form.host.value;155 156 if (userAgent.indexOf("msie") !== -1) {157 document.execCommand("ClearAuthenticationCache");158 }159 else if (userAgent.indexOf("firefox") != -1){ //TODO: check version number160 161 var request1 = new XMLHttpRequest();162 var request2 = new XMLHttpRequest();163 164 //Logout. Tell the server not to return the "WWW-Authenticate" header165 request1.open("GET", host.concat(logoutURL) + "?prompt=false", true);166 request1.send("");167 request1.onreadystatechange = function(){168 if (request1.readyState === 4) {169 170 //Sign in with dummy credentials to clear the auth cache171 request2.open("GET", host.concat(logoutURL), true, "logout", "logout");172 request2.send("");173 174 request2.onreadystatechange = function(){175 if (request2.readyState == 4) {176 if (callback!=null) { callback.call(); } else { window.location=host.concat(logoutURL);}177 } 178 }179 180 }181 }182 }183 else {184 var request = ((window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));185 request.open("GET", host.concat(logoutURL), true, "logout", "logout");186 request.send("");187 request.onreadystatechange = function(){188 if (request.status==401 || request.status==403 ) { window.location=host.concat(logoutURL);189 } 190 }191 }192};193function remove(id)194{195 var element = document.getElementById(id);196 element.outerHTML = "";197 delete element;198 return;199};200$("#password").pressEnter( function() {201 login();202}); 203$("#password_redirect").pressEnter( function() {204 login_with_redirect();205}); 206$(document).ready(function() {207 progressive_loging();208 if (document.getElementById('guest_reports_page_size') !== null) {209 progressive_guest_page_resize();210 }211 if (document.getElementById('user_reports_page_size') !== null) {212 progressive_user_page_resize();213 }214 if (document.getElementById('responsible_reports_page_size') !== null) {215 progressive_responsible_page_resize();216 }217 218});219var progressive_loging = function () {220 var host = $('#host_pe').val();221 var user = $('#user_pe').val();222 console.log(host);223 console.log(user);224 var elem = '<li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown">';225 elem = elem.concat(user);226 elem = elem.concat('<b Class="caret"></b></a><ul class="dropdown-menu"><li><a href="');227 elem = elem.concat(host);228 elem = elem.concat('/account" itemprop="account_information" rel="account_information">Account Information</a></li><li class="divider"></li><li><a href="');229 elem = elem.concat(host);230 elem = elem.concat('/email" itemprop="change_email" rel="change_email">Change Email</li><li><a href="');231 elem = elem.concat(host);232 elem = elem.concat('/password" itemprop="change_password" rel="change_password">Change Password</a></li></ul></li>' );233 console.log (elem);234 $('#login_pe').after('<li><a class="login pull-right" data-toggle="modal" data-target="#myModalSignIn">Sign In</a></li>').remove();235 $('#logoff_pe').after('<li><a class="login pull-right" data-toggle="modal" data-target="#myModalSignOut" rel="logoff" itemprop="logoff">Sign Out</a></li>').remove();236 $('#dropdown_pe_2').remove();237 $('#dropdown_pe_3').remove();238 $('#dropdown_pe_4').remove();239 $('#dropdown_pe_1').after(elem).remove(); 240};241var progressive_guest_page_resize = function () {242 var host = $('#host_pe').val();243 var index = $('#page_pe').val();244 var category = $('#category_pe').val();245 var orderBy = $('#orderBy_pe').val();246 var dir = $('#dir_pe').val();247 var status = $('#status_pe').val();248 var filter = $('#filter_pe').val();249 var filter_content = $('#filter_content_pe').val();250 var pages = $('#pages_pe').val();251 var size = $('#size_pe').val();252 var count_bugs = $('#count_bugs_pe').val();253 console.log (host);254 console.log (index);255 console.log (category);256 console.log (orderBy);257 console.log (dir);258 console.log (status);259 console.log (filter);260 console.log (filter_content);261 console.log (pages);262 263 var elem = '<div class="col-xs-12"><div class="col-xs-2"><label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see.">Current page ';264 elem = elem.concat(index);265 elem = elem.concat(' of ');266 elem = elem.concat(pages);267 elem = elem.concat ('</label></div>'); 268 elem = elem.concat('<div class="col-xs-1"> <label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see.">Size</label> </div>') ; 269 elem = elem.concat('<div class="col-xs-1"> <input type="number" name="quantity" min="1" max="9999" value="');270 elem = elem.concat(size);271 elem = elem.concat ('" id="changesize"/>');272 elem = elem.concat('<input type="hidden" name="current" value="');273 elem = elem.concat (host);274 elem = elem.concat ('/reports?page=');275 elem = elem.concat (index);276 elem = elem.concat ('&amp;size=');277 elem = elem.concat (size);278 elem = elem.concat ('&amp;category=');279 elem = elem.concat (category);280 elem = elem.concat ('&amp;orderBy=');281 elem = elem.concat (orderBy);282 elem = elem.concat ('&amp;dir='); 283 elem = elem.concat (dir); 284 elem = elem.concat ('&amp;status='); 285 elem = elem.concat (status);286 elem = elem.concat ('&amp;filter='); 287 elem = elem.concat (filter);288 elem = elem.concat ('&amp;filter_content='); 289 elem = elem.concat (filter_content);290 elem = elem.concat ('" id="currentPage"/>');291 elem = elem.concat ('<img src="');292 elem = elem.concat (host);293 elem = elem.concat ('/static/images/ajax-loader.gif" alt="Loading..." style="display: none;" id="pageLoad" /> ');294 elem = elem.concat ('</div>' ); 295 elem = elem.concat('<div class="col-xs-1"><label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see."># of Bugs</label></div>') ; 296 elem = elem.concat('<div class="col-xs-1">');297 elem = elem.concat (count_bugs); 298 elem = elem.concat ('</div></div>' ); 299 300 console.log (elem);301 $('#guest_reports_page_size').after(elem).remove();302 303};304var progressive_user_page_resize = function () {305 var host = $('#host_pe').val();306 var user = $('#user_pe').val();307 var index = $('#page_pe').val();308 var category = $('#category_pe').val();309 var orderBy = $('#orderBy_pe').val();310 var dir = $('#dir_pe').val();311 var status = $('#status_pe').val();312 var filter = $('#filter_pe').val();313 var filter_content = $('#filter_content_pe').val();314 var pages = $('#pages_pe').val();315 var size = $('#size_pe').val();316 var count_bugs = $('#count_bugs_pe').val();317 console.log (host);318 console.log (index);319 console.log (category);320 console.log (orderBy);321 console.log (dir);322 console.log (status);323 console.log (filter);324 console.log (filter_content);325 console.log (pages);326 327 var elem = '<div class="col-xs-12"><div class="col-xs-2"><label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see.">Current page ';328 elem = elem.concat(index);329 elem = elem.concat(' of ');330 elem = elem.concat(pages);331 elem = elem.concat ('</label></div>'); 332 elem = elem.concat('<div class="col-xs-1"> <label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see.">Size</label> </div>') ; 333 elem = elem.concat('<div class="col-xs-1"> <input type="number" name="quantity" min="1" max="9999" value="');334 elem = elem.concat(size);335 elem = elem.concat ('" id="changesize"/>');336 elem = elem.concat('<input type="hidden" name="current" value="');337 elem = elem.concat (host);338 elem = elem.concat ('/user_reports/');339 elem = elem.concat (user);340 elem = elem.concat ('?page=');341 elem = elem.concat (index);342 elem = elem.concat ('&amp;size=');343 elem = elem.concat (size);344 elem = elem.concat ('&amp;category=');345 elem = elem.concat (category);346 elem = elem.concat ('&amp;orderBy=');347 elem = elem.concat (orderBy);348 elem = elem.concat ('&amp;dir='); 349 elem = elem.concat (dir); 350 elem = elem.concat ('&amp;status='); 351 elem = elem.concat (status);352 elem = elem.concat ('&amp;filter='); 353 elem = elem.concat (filter);354 elem = elem.concat ('&amp;filter_content='); 355 elem = elem.concat (filter_content);356 elem = elem.concat ('" id="currentPage"/>');357 elem = elem.concat ('<img src="');358 elem = elem.concat (host);359 elem = elem.concat ('/static/images/ajax-loader.gif" alt="Loading..." style="display: none;" id="pageLoad" /> ');360 elem = elem.concat ('</div>' ); 361 elem = elem.concat('<div class="col-xs-1"><label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see."># of Bugs</label></div>') ; 362 elem = elem.concat('<div class="col-xs-1">');363 elem = elem.concat (count_bugs); 364 elem = elem.concat ('</div></div>' ); 365 366 console.log (elem);367 $('#user_reports_page_size').after(elem).remove();368 369};370var progressive_responsible_page_resize = function () {371 var host = $('#host_pe').val();372 var user = $('#user_pe').val();373 var index = $('#page_pe').val();374 var category = $('#category_pe').val();375 var orderBy = $('#orderBy_pe').val();376 var dir = $('#dir_pe').val();377 var status = $('#status_pe').val();378 var filter = $('#filter_pe').val();379 var filter_content = $('#filter_content_pe').val();380 var pages = $('#pages_pe').val();381 var size = $('#size_pe').val();382 var submitter = $('#submitter_pe').val();383 var severity = $('#severity_pe').val();384 var priority = $('#priority_pe').val();385 var responsible = $('#responsible_pe').val();386 var count_bugs = $('#count_bugs_pe').val();387 console.log (host);388 console.log (index);389 console.log (category);390 console.log (orderBy);391 console.log (dir);392 console.log (status);393 console.log (filter);394 console.log (filter_content);395 console.log (pages);396 var elem = '<div class="col-xs-12"><div class="col-xs-2"><label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see.">Current page ';397 elem = elem.concat(index);398 elem = elem.concat(' of ');399 elem = elem.concat(pages);400 elem = elem.concat ('</label></div>'); 401 elem = elem.concat('<div class="col-xs-1"> <label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see.">Size</label> </div>') ; 402 elem = elem.concat('<div class="col-xs-1"> <input type="number" name="quantity" min="1" max="9999" value="');403 elem = elem.concat(size);404 elem = elem.concat ('" id="changesize"/>');405 elem = elem.concat('<input type="hidden" name="current" value="');406 elem = elem.concat (host);407 elem = elem.concat ('/reports?page=');408 elem = elem.concat (index);409 elem = elem.concat ('&amp;size=');410 elem = elem.concat (size);411 elem = elem.concat ('&amp;category=');412 elem = elem.concat (category);413 elem = elem.concat ('&amp;submitter=');414 elem = elem.concat (submitter);415 elem = elem.concat ('&amp;severity=');416 elem = elem.concat (severity);417 elem = elem.concat ('&amp;priority=');418 elem = elem.concat (priority);419 elem = elem.concat ('&amp;responsible=');420 elem = elem.concat (responsible);421 elem = elem.concat ('&amp;orderBy=');422 elem = elem.concat (orderBy);423 elem = elem.concat ('&amp;dir='); 424 elem = elem.concat (dir); 425 elem = elem.concat ('&amp;status='); 426 elem = elem.concat (status);427 elem = elem.concat ('&amp;filter='); 428 elem = elem.concat (filter);429 elem = elem.concat ('&amp;filter_content='); 430 elem = elem.concat (filter_content);431 elem = elem.concat ('" id="currentPage"/>');432 elem = elem.concat ('<img src="');433 elem = elem.concat (host);434 elem = elem.concat ('/static/images/ajax-loader.gif" alt="Loading..." style="display: none;" id="pageLoad" /> ');435 elem = elem.concat ('</div>' ); 436 437 elem = elem.concat('<div class="col-xs-1"><label class="control-label-api" itemprop="report_number" data-original-title="The number of reports you want to see."># of Bugs</label></div>') ; 438 elem = elem.concat('<div class="col-xs-1">');439 elem = elem.concat (count_bugs); 440 elem = elem.concat ('</div></div>' ); 441 console.log (elem);442 $('#responsible_reports_page_size').after(elem).remove();443 ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.get(function(err, resp) {4 if (err) {5 console.log(err);6 }7 else {8 console.log(resp);9 }10});11var wptools = require('wptools');12var page = wptools.page('Barack Obama');13page.get(function(err, resp) {14 if (err) {15 console.log(err);16 }17 else {18 console.log(resp);19 }20});21var wptools = require('wptools');22var page = wptools.page('Barack Obama');23page.get(function(err, resp) {24 if (err) {25 console.log(err);26 }27 else {28 console.log(resp);29 }30});31var wptools = require('wptools');32var page = wptools.page('Barack Obama');33page.get(function(err, resp) {34 if (err) {35 console.log(err);36 }37 else {38 console.log(resp);39 }40});41var wptools = require('wptools');42var page = wptools.page('Barack Obama');43page.get(function(err, resp) {44 if (err) {45 console.log(err);46 }47 else {48 console.log(resp);49 }50});51var wptools = require('wptools');52var page = wptools.page('Barack Obama');53page.get(function(err, resp) {54 if (err) {55 console.log(err);56 }57 else {58 console.log(resp);59 }60});61var wptools = require('wptools');62var page = wptools.page('Barack Obama');63page.get(function(err, resp) {64 if (err) {65 console.log(err);66 }67 else {68 console.log(resp);69 }70});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Albert Einstein');3page.get(function(err, info) {4 console.log(info);5});6var wptools = require('wptools');7var page = wptools.page('Albert Einstein');8page.get(function(err, info) {9 console.log(info);10});11var wptools = require('wptools');12var page = wptools.page('Albert Einstein');13page.get(function(err, info) {14 console.log(info);15});16var wptools = require('wptools');17var page = wptools.page('Albert Einstein');18page.get(function(err, info) {19 console.log(info);20});21var wptools = require('wptools');22var page = wptools.page('Albert Einstein');23page.get(function(err, info) {24 console.log(info);25});26var wptools = require('wptools');27var page = wptools.page('Albert Einstein');28page.get(function(err, info) {29 console.log(info);30});31var wptools = require('wptools');32var page = wptools.page('Albert Einstein');33page.get(function(err, info) {34 console.log(info);35});36var wptools = require('wptools');37var page = wptools.page('Albert Einstein');38page.get(function(err, info) {39 console.log(info);40});41var wptools = require('wptools');42var page = wptools.page('Albert Einstein');43page.get(function(err, info) {44 console.log(info);45});46var wptools = require('wptools');47var page = wptools.page('Albert Einstein');48page.get(function(err, info) {49 console.log(info);50});51var wptools = require('wptools');52var page = wptools.page('Albert Einstein');53page.get(function(err,

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt-api');2var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');3var options = {4};5wpt.runTest(options, function(err, data) {6 if (err) {7 return console.error(err);8 }9 console.log(data);10 wpt.getTestResults(data.data.testId, function(err, data) {11 if (err) {12 return console.error(err);13 }14 console.log(data);15 });16});17var wpt = require('wpt-api');18var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');19var options = {20};21wpt.runTest(options, function(err, data) {22 if (err) {23 return console.error(err);24 }25 console.log(data);26 wpt.getTestResults(data.data.testId, function(err, data) {27 if (err) {28 return console.error(err);29 }30 console.log(data);31 });32});33var wpt = require('wpt-api');34var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');35var options = {36};37wpt.runTest(options, function(err, data) {38 if (err) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt-api');2var assert = require('assert');3var elem = wpt.elem;4var test = elem("test");5var test2 = elem("test2");6var test3 = elem("test3");7test2.append(test3);8test.append(test2);9test.append("test4");10test.append("test5");11test.append("test6");12test.append("test7");13test.append("test8");14test.append("test9");15test.append("test10");16test.append("test11");17test.append("test12");18test.append("test13");19test.append("test14");20test.append("test15");21test.append("test16");22test.append("test17");23test.append("test18");24test.append("test19");25test.append("test20");26test.append("test21");27test.append("test22");28test.append("test23");29test.append("test24");30test.append("test25");31test.append("test26");32test.append("test27");33test.append("test28");34test.append("test29");35test.append("test30");36test.append("test31");37test.append("test32");38test.append("test33");39test.append("test34");40test.append("test35");41test.append("test36");42test.append("test37");43test.append("test38");44test.append("test39");45test.append("test40");46test.append("test41");47test.append("test42");48test.append("test43");49test.append("test44");50test.append("test45");51test.append("test46");52test.append("test47");53test.append("test48");54test.append("test49");55test.append("test50");56test.append("test51");57test.append("test52");58test.append("test53");59test.append("test54");60test.append("test55");61test.append("test56");62test.append("test57");63test.append("test58");64test.append("test59");65test.append("test60");66test.append("test61");67test.append("test62");68test.append("test63");69test.append("test64");70test.append("test65");71test.append("test66");72test.append("test67");73test.append("test68");74test.append("test69");75test.append("test70");76test.append("test71");77test.append("test72");78test.append("test73");79test.append("test74");80test.append("test75");81test.append("test76");

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2 console.log(data);3});4var wpt = require('wpt');5 console.log(data);6});7var wpt = require('wpt');8 console.log(data);9});10var wpt = require('wpt');11 console.log(data);12});13var wpt = require('wpt');14 console.log(data);15});16var wpt = require('wpt');17 console.log(data);18});19var wpt = require('wpt');20 console.log(data);21});22var wpt = require('wpt');23 console.log(data);24});25var wpt = require('wpt');26 console.log(data);27});28var wpt = require('wpt');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wikitools');2var fs = require('fs');3var data = fs.readFileSync('test.txt', 'utf8');4wptools.elem(data, function (err, data) {5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});11var wptools = require('wikitools');12var fs = require('fs');13var data = fs.readFileSync('test.txt', 'utf8');14wptools.elem(data, function (err, data) {15 if (err) {16 console.log(err);17 } else {18 console.log(data);19 }20});21var wptools = require('wikitools');22var fs = require('fs');23var data = fs.readFileSync('test.txt', 'utf8');24wptools.elem(data, function (err, data) {25 if (err) {26 console.log(err);27 } else {28 console.log(data);29 }30});31var wptools = require('wikitools');32var fs = require('fs');33var data = fs.readFileSync('test.txt', 'utf8');34wptools.elem(data, function (err, data) {35 if (err) {36 console.log(err);37 } else {38 console.log(data);39 }40});41var wptools = require('wikitools');42var fs = require('fs');43var data = fs.readFileSync('test.txt', 'utf8');44wptools.elem(data, function (err, data) {45 if (err) {46 console.log(err);47 } else {48 console.log(data);49 }50});51var wptools = require('wikitools');52var fs = require('fs');53var data = fs.readFileSync('test.txt', 'utf8');54wptools.elem(data, function (err,

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful