Add parsimony algorithm as quick hack; allow relationship merge in Stemweb. Fixes...
[scpubgit/stemmaweb.git] / root / js / componentload.js
CommitLineData
3f9d7ae5 1// Global state variables
2var selectedTextID;
3var selectedTextInfo;
6aabefa3 4var selectedTextEditable;
3f9d7ae5 5var selectedStemmaID = -1;
6var stemmata = [];
7
8// Load the names of the appropriate traditions into the directory div.
9function refreshDirectory () {
10 var lmesg = $('#loading_message').clone();
11 $('#directory').empty().append( lmesg.contents() );
12 $('#directory').load( _get_url(["directory"]),
13 function(response, status, xhr) {
14 if (status == "error") {
15 var msg = "An error occurred: ";
16 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
17 } else {
18 if( textOnLoad != "" ) {
19 // Call the click callback for the relevant text, if it is
20 // in the page.
21 $('#'+textOnLoad).click();
22 textOnLoad = "";
23 }
24 }
25 }
26 );
27}
28
29// Load a tradition with its information and stemmata into the tradition
30// view pane. Calls load_textinfo.
98a45925 31function loadTradition( textid, textname, editable ) {
32 selectedTextID = textid;
6aabefa3 33 selectedTextEditable = editable;
98a45925 34 // First insert the placeholder image and register an error handler
04469f3e 35 $('#textinfo_load_status').empty();
5f0eda3f 36 $('#stemma_graph').empty();
98a45925 37 $('#textinfo_waitbox').show();
75354c3a 38 $('#textinfo_container').hide().ajaxError(
39 function(event, jqXHR, ajaxSettings, thrownError) {
40 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET' ) {
41 $('#textinfo_waitbox').hide();
42 $('#textinfo_container').show();
43 display_error( jqXHR, $("#textinfo_load_status") );
98a45925 44 }
75354c3a 45 });
46
47 // Hide the functionality that is irrelevant
48 if( editable ) {
ce1c5863 49 $('#open_stemma_add').show();
ce1c5863 50 $('#open_textinfo_edit').show();
cbd23059 51 $('#relatebutton_label').text('View collation and edit relationships');
75354c3a 52 } else {
ce1c5863 53 $('#open_stemma_add').hide();
db234220 54 $('#open_stemweb_ui').hide();
c2b80bba 55 $('#query_stemweb_ui').hide();
ce1c5863 56 $('#open_textinfo_edit').hide();
cbd23059 57 $('#relatebutton_label').text('View collation and relationships');
75354c3a 58 }
59
62723740 60 // Then get and load the actual content.
98a45925 61 // TODO: scale #stemma_graph both horizontally and vertically
f6a8db89 62 // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
3f9d7ae5 63 $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
98a45925 64 // Add the scalar data
75354c3a 65 selectedTextInfo = textdata;
66 load_textinfo();
63378fe0 67 // Add the stemma(ta)
98a45925 68 stemmata = textdata.stemmata;
69 if( stemmata.length ) {
70 selectedStemmaID = 0;
65a0c9c6 71 } else {
57e3a008 72 selectedStemmaID = -1;
65a0c9c6 73 }
6aabefa3 74 load_stemma( selectedStemmaID );
98a45925 75 // Set up the relationship mapper button
3f9d7ae5 76 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
38627d20 77 // Set up the download button
78 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
79 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
98a45925 80 });
81}
82
3f9d7ae5 83// Load the metadata about a tradition into the appropriate div.
75354c3a 84function load_textinfo() {
85 $('#textinfo_waitbox').hide();
86 $('#textinfo_load_status').empty();
87 $('#textinfo_container').show();
88 $('.texttitle').empty().append( selectedTextInfo.name );
89 // Witnesses
90 $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
91 $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
92 // Who the owner is
93 $('#owner_id').empty().append('no one');
94 if( selectedTextInfo.owner ) {
897a22fc 95 var owneremail = selectedTextInfo.owner;
96 var chop = owneremail.indexOf( '@' );
97 if( chop > -1 ) {
98 owneremail = owneremail.substr( 0, chop + 1 ) + '...';
99 }
100 $('#owner_id').empty().append( owneremail );
75354c3a 101 }
102 // Whether or not it is public
103 $('#not_public').empty();
104 if( selectedTextInfo['public'] == false ) {
105 $('#not_public').append('NOT ');
106 }
107 // What language setting it has, if any
108 $('#marked_language').empty().append('no language set');
109 if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
110 $('#marked_language').empty().append( selectedTextInfo.language );
111 }
112}
113
3f9d7ae5 114// Enable / disable the appropriate buttons for paging through the stemma.
6aabefa3 115function show_stemmapager () {
bf81fb57 116 $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
117 $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
65a0c9c6 118 if( selectedStemmaID > 0 ) {
119 $('.pager_left_button').click( function () {
6aabefa3 120 load_stemma( selectedStemmaID - 1, selectedTextEditable );
bf81fb57 121 }).removeClass( 'greyed_out' );
65a0c9c6 122 }
123 if( selectedStemmaID + 1 < stemmata.length ) {
124 $('.pager_right_button').click( function () {
6aabefa3 125 load_stemma( selectedStemmaID + 1, selectedTextEditable );
bf81fb57 126 }).removeClass( 'greyed_out' );
65a0c9c6 127 }
128}
129
3f9d7ae5 130// Load a given stemma SVG into the stemmagraph box.
6aabefa3 131function load_stemma( idx ) {
65a0c9c6 132 // Load the stemma at idx
133 selectedStemmaID = idx;
6aabefa3 134 show_stemmapager( selectedTextEditable );
63378fe0 135 $('#open_stemma_edit').hide();
136 $('#run_stexaminer').hide();
137 $('#stemma_identifier').empty();
c2b80bba 138 // Add the relevant Stemweb functionality
6aabefa3 139 if( selectedTextEditable ) {
c2b80bba 140 if( selectedTextInfo.stemweb_jobid == 0 ) {
141 $('#open_stemweb_ui').show();
2c514a6f 142 $('#query_stemweb_ui').hide();
c2b80bba 143 } else {
144 $('#query_stemweb_ui').show();
2c514a6f 145 $('#open_stemweb_ui').hide();
c2b80bba 146 }
147 }
98a45925 148 if( idx > -1 ) {
63378fe0 149 // Load the stemma and its properties
ec2f89ff 150 var stemmadata = stemmata[idx];
6aabefa3 151 if( selectedTextEditable ) {
63378fe0 152 $('#open_stemma_edit').show();
153 }
154 if( stemmadata.directed ) {
155 // Stexaminer submit action
156 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
157 $('#run_stexaminer').attr( 'action', stexpath );
158 $('#run_stexaminer').show();
159 }
160 loadSVG( stemmadata.svg );
161 $('#stemma_identifier').text( stemmadata.name );
40803b80 162 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
98a45925 163 }
5ba6c2b4 164}
75354c3a 165
c2b80bba 166function query_stemweb_progress() {
167 var requrl = _get_url([ "stemweb", "query", selectedTextInfo.stemweb_jobid ]);
168 $.getJSON( requrl, function (data) {
3cb9d9c0 169 process_stemweb_result( data );
170 });
171}
172
173function process_stemweb_result(data) {
174 // Look for a status message, either success, running, or notfound.
175 if( data.status === 'success' ) {
176 // Add the new stemmata to the textinfo and tell the user.
177 selectedTextInfo.stemweb_jobid = 0;
178 if( data.stemmata.length > 0 ) {
179 stemmata = stemmata.concat( data.stemmata );
180 if( selectedStemmaID == -1 ) {
181 // We have a stemma for the first time; load the first one.
182 load_stemma( 0, true );
c2b80bba 183 } else {
3cb9d9c0 184 // Move to the index of the first added stemma.
185 var newIdx = stemmata.length - data.stemmata.length;
186 load_stemma( newIdx, true );
c2b80bba 187 }
3cb9d9c0 188 alert( 'You have one or more new stemmata!' );
189 } else {
190 alert( 'Stemweb run finished with no stemmata...huh?!' );
c2b80bba 191 }
3cb9d9c0 192 } else if( data.status === 'running' ) {
193 // Just tell the user.
194 alert( 'Your Stemweb query is still running!' );
195 } else if( data.status === 'notfound' ) {
196 // Ask the user to refresh, for now.
197 alert( 'Your Stemweb query probably finished and reported back. Please reload to check.' );
198 }
c2b80bba 199}
200
bd3ccd15 201// Load the SVG we are given
202function loadSVG(svgData) {
203 var svgElement = $('#stemma_graph');
204
205 $(svgElement).svg('destroy');
206
207 $(svgElement).svg({
208 loadURL: svgData,
209 onLoad : function () {
210 var theSVG = svgElement.find('svg');
211 var svgoffset = theSVG.offset();
bd3ccd15 212 var browseroffset = 1;
23f8bfc2 213 // Firefox needs a different offset, stupidly enough
bd3ccd15 214 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
23f8bfc2 215 browseroffset = 3; // works for tall images
216 // ...but if the SVG is wider than it is tall, Firefox treats
217 // the top as being the top of the graph, loaded into the middle
218 // of the canvas, but then the margin at the top of the canvas
219 // extends upward. So we have to find the actual top of the canvas
220 // and correct for *that* instead.
221 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
222 if( vbdim.height < vbdim.width ) {
223 var vbscale = svgElement.width() / vbdim.width;
224 var vbrealheight = vbdim.height * vbscale;
225 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
226 }
bd3ccd15 227 }
228 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
bd3ccd15 229 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
b63f3a77 230 set_stemma_interactive( theSVG );
bd3ccd15 231 }
232 });
233}
234
b63f3a77 235function set_stemma_interactive( svg_element ) {
6aabefa3 236 if( selectedTextEditable ) {
237 $( "#root_tree_dialog_button_ok" ).click( function() {
238 var requrl = _get_url([ "stemmaroot", selectedTextID, selectedStemmaID ]);
9f4b205a 239 var targetnode = $('#root_tree_dialog').data( 'selectedNode' );
6aabefa3 240 $.post( requrl, { root: targetnode }, function (data) {
241 // Reload the new stemma
242 stemmata[selectedStemmaID] = data;
243 load_stemma( selectedStemmaID );
244 // Put away the dialog
9f4b205a 245 $('#root_tree_dialog').data( 'selectedNode', null ).hide();
6aabefa3 246 } );
247 } ).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
248 if( ajaxSettings.url.indexOf( 'stemmaroot' ) > -1
249 && ajaxSettings.type == 'POST' ) {
250 display_error( jqXHR, $("#stemma_load_status") );
251 }
252 } );
253 // TODO Clear error at some appropriate point
254 $.each( $( 'ellipse', svg_element ), function(index) {
255 var ellipse = $(this);
256 var g = ellipse.parent( 'g' );
257 g.click( function(evt) {
258 if( typeof root_tree_dialog_timeout !== 'undefined' ) { clearTimeout( root_tree_dialog_timeout ) };
259 g.unbind( 'mouseleave' );
260 var dialog = $( '#root_tree_dialog' );
9f4b205a 261 // Note which node triggered the dialog
262 dialog.data( 'selectedNode', g.attr('id') );
263 // Position the dialog
6aabefa3 264 dialog.hide();
265 dialog.css( 'top', evt.pageY + 3 );
266 dialog.css( 'left', evt.pageX + 3 );
267 dialog.show();
268 root_tree_dialog_timeout = setTimeout( function() {
9f4b205a 269 $( '#root_tree_dialog' ).data( 'selectedNode', null ).hide();
6aabefa3 270 ellipse.removeClass( 'stemma_node_highlight' );
271 g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
272 }, 3000 );
273 } );
274 g.mouseenter( function() {
275 $( 'ellipse.stemma_node_highlight' ).removeClass( 'stemma_node_highlight' );
276 ellipse.addClass( 'stemma_node_highlight' )
277 } );
278 g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
279 } );
280 }
b63f3a77 281}
39b8b37b 282
3f9d7ae5 283// General-purpose error-handling function.
284// TODO make sure this gets used throughout, where appropriate.
75354c3a 285function display_error( jqXHR, el ) {
ce1c5863 286 var errmsg;
287 if( jqXHR.responseText == "" ) {
288 errmsg = "perhaps the server went down?"
75354c3a 289 } else {
ce1c5863 290 var errobj;
291 try {
292 errobj = jQuery.parseJSON( jqXHR.responseText );
293 errmsg = errobj.error;
294 } catch ( parse_err ) {
295 errmsg = "something went wrong on the server."
296 }
75354c3a 297 }
ce1c5863 298 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
75354c3a 299 $(el).empty().append( msghtml ).show();
3f9d7ae5 300}
301
e0b90236 302// Event to enable the upload button when a file has been selected
303function file_selected( e ) {
304 if( e.files.length == 1 ) {
305 $('#upload_button').button('enable');
ab0d1218 306 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
e0b90236 307 } else {
308 $('#upload_button').button('disable');
ab0d1218 309 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
e0b90236 310 }
311}
312
2ece58b3 313// Implement our own AJAX method that uses the features of XMLHttpRequest2
314// but try to let it have a similar interface to jquery.post
315// The data var needs to be a FormData() object.
316// The callback will be given a single argument, which is the response data
317// of the given type.
318
319function post_xhr2( url, data, cb, type ) {
320 if( !type ) {
321 type = 'json';
322 }
323 var xhr = new XMLHttpRequest();
324 // Set the expected response type
325 if( type === 'data' ) {
326 xhr.responseType = 'blob';
327 } else if( type === 'xml' ) {
328 xhr.responseType = 'document';
329 }
330 // Post the form
331 // Gin up an AJAX settings object
332 $.ajaxSetup({ url: url, type: 'POST' });
333 xhr.open( 'POST', url, true );
334 // Handle the results
335 xhr.onload = function( e ) {
336 // Get the response and parse it
337 // Call the callback with the response, whatever it was
338 var xhrs = e.target;
339 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
340 var resp;
341 if( type === 'json' ) {
342 resp = $.parseJSON( xhrs.responseText );
343 } else if ( type === 'xml' ) {
344 resp = xhrs.responseXML;
345 } else if ( type === 'text' ) {
346 resp = xhrs.responseText;
347 } else {
348 resp = xhrs.response;
349 }
350 cb( resp );
351 } else {
352 // Trigger the ajaxError...
353 _trigger_ajaxerror( e );
354 }
355 };
356 xhr.onerror = _trigger_ajaxerror;
357 xhr.onabort = _trigger_ajaxerror;
358 xhr.send( data );
359}
360
361function _trigger_ajaxerror( e ) {
362 var xhr = e.target;
363 var thrown = xhr.statusText || 'Request error';
364 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
365}
366
e0b90236 367function upload_new () {
368 // Serialize the upload form, get the file and attach it to the request,
369 // POST the lot and handle the response.
370 var newfile = $('#new_file').get(0).files[0];
371 var reader = new FileReader();
372 reader.onload = function( evt ) {
2ece58b3 373 var data = new FormData();
374 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
375 data.append( o.name, o.value );
376 });
377 data.append( 'file', newfile );
e0b90236 378 var upload_url = _get_url([ 'newtradition' ]);
2ece58b3 379 post_xhr2( upload_url, data, function( ret ) {
e0b90236 380 if( ret.id ) {
381 $('#upload-collation-dialog').dialog('close');
382 refreshDirectory();
383 loadTradition( ret.id, ret.name, 1 );
384 } else if( ret.error ) {
385 $('#upload_status').empty().append(
386 $('<span>').attr('class', 'error').append( ret.error ) );
387 }
2ece58b3 388 }, 'json' );
e0b90236 389 };
390 reader.onerror = function( evt ) {
391 var err_resp = 'File read error';
392 if( e.name == 'NotFoundError' ) {
393 err_resp = 'File not found';
394 } else if ( e.name == 'NotReadableError' ) {
395 err_resp == 'File unreadable - is it yours?';
396 } else if ( e.name == 'EncodingError' ) {
397 err_resp == 'File cannot be encoded - is it too long?';
398 } else if ( e.name == 'SecurityError' ) {
399 err_resp == 'File read security error';
400 }
401 // Fake a jqXHR object that we can pass to our generic error handler.
402 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
403 display_error( jqxhr, $('#upload_status') );
404 $('#upload_button').button('disable');
405 }
406
407 reader.readAsBinaryString( newfile );
3f9d7ae5 408}
409
410// Utility function to neatly construct an application URL
411function _get_url( els ) {
412 return basepath + els.join('/');
413}
414
6aabefa3 415// TODO Attach unified ajaxError handler to document
3f9d7ae5 416$(document).ready( function() {
50778a5d 417 // See if we have the browser functionality we need
418 // TODO Also think of a test for SVG readiness
7c25980f 419 if( !!window.FileReader && !!window.File ) {
50778a5d 420 $('#compatibility_check').empty();
421 }
b63f3a77 422
423 // hide dialog not yet in use
424 $('#root_tree_dialog').hide();
50778a5d 425
3f9d7ae5 426 // call out to load the directory div
427 $('#textinfo_container').hide();
428 $('#textinfo_waitbox').hide();
429 refreshDirectory();
430
431 // Set up the textinfo edit dialog
432 $('#textinfo-edit-dialog').dialog({
433 autoOpen: false,
434 height: 200,
435 width: 300,
436 modal: true,
437 buttons: {
438 Save: function (evt) {
439 $("#edit_textinfo_status").empty();
3cb9d9c0 440 $(evt.target).closest('button').button("disable");
3f9d7ae5 441 var requrl = _get_url([ "textinfo", selectedTextID ]);
442 var reqparam = $('#edit_textinfo').serialize();
443 $.post( requrl, reqparam, function (data) {
444 // Reload the selected text fields
445 selectedTextInfo = data;
446 load_textinfo();
447 // Reenable the button and close the form
3cb9d9c0 448 $(evt.target).closest('button').button("enable");
3f9d7ae5 449 $('#textinfo-edit-dialog').dialog('close');
450 }, 'json' );
451 },
452 Cancel: function() {
453 $('#textinfo-edit-dialog').dialog('close');
454 }
455 },
456 open: function() {
457 $("#edit_textinfo_status").empty();
458 // Populate the form fields with the current values
459 // edit_(name, language, public, owner)
460 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
461 var fname = '#edit_' + k;
462 // Special case: language Default is basically language null
463 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
464 $(fname).val( "" );
465 } else {
466 $(fname).val( selectedTextInfo[k] );
467 }
468 });
469 if( selectedTextInfo['public'] == true ) {
470 $('#edit_public').attr('checked','true');
471 } else {
472 $('#edit_public').removeAttr('checked');
473 }
474 },
475 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
476 $(event.target).parent().find('.ui-button').button("enable");
477 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
478 && ajaxSettings.type == 'POST' ) {
479 display_error( jqXHR, $("#edit_textinfo_status") );
480 }
481 });
482
483
484 // Set up the stemma editor dialog
485 $('#stemma-edit-dialog').dialog({
486 autoOpen: false,
487 height: 700,
488 width: 600,
489 modal: true,
490 buttons: {
491 Save: function (evt) {
492 $("#edit_stemma_status").empty();
3cb9d9c0 493 $(evt.target).closest('button').button("disable");
3f9d7ae5 494 var stemmaseq = $('#stemmaseq').val();
495 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
496 var reqparam = { 'dot': $('#dot_field').val() };
497 // TODO We need to stash the literal SVG string in stemmata
498 // somehow. Implement accept header on server side to decide
499 // whether to send application/json or application/xml?
500 $.post( requrl, reqparam, function (data) {
501 // We received a stemma SVG string in return.
502 // Update the current stemma sequence number
503 selectedStemmaID = data.stemmaid;
be536c89 504 delete data.stemmaid;
505 // Stash the answer in the appropriate spot in our stemma array
506 stemmata[selectedStemmaID] = data;
3f9d7ae5 507 // Display the new stemma
63378fe0 508 load_stemma( selectedStemmaID, true );
3f9d7ae5 509 // Reenable the button and close the form
3cb9d9c0 510 $(evt.target).closest('button').button("enable");
3f9d7ae5 511 $('#stemma-edit-dialog').dialog('close');
512 }, 'json' );
513 },
514 Cancel: function() {
515 $('#stemma-edit-dialog').dialog('close');
516 }
517 },
518 open: function(evt) {
519 $("#edit_stemma_status").empty();
520 var stemmaseq = $('#stemmaseq').val();
521 if( stemmaseq == 'n' ) {
522 // If we are creating a new stemma, populate the textarea with a
523 // bare digraph.
524 $(evt.target).dialog('option', 'title', 'Add a new stemma')
db234220 525 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
3f9d7ae5 526 } else {
527 // If we are editing a stemma, grab its stemmadot and populate the
528 // textarea with that.
529 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
530 $('#dot_field').val( 'Loading, please wait...' );
531 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
532 $.getJSON( doturl, function (data) {
533 // Re-insert the line breaks
534 var dotstring = data.dot.replace(/\|n/gm, "\n");
535 $('#dot_field').val( dotstring );
536 });
537 }
538 },
539 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
540 $(event.target).parent().find('.ui-button').button("enable");
541 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
542 && ajaxSettings.type == 'POST' ) {
543 display_error( jqXHR, $("#edit_stemma_status") );
544 }
545 });
db234220 546
547 $('#stemweb-ui-dialog').dialog({
548 autoOpen: false,
70744367 549 height: 160,
3cb9d9c0 550 width: 240,
db234220 551 modal: true,
552 buttons: {
553 Run: function (evt) {
554 $("#stemweb_run_status").empty();
3cb9d9c0 555 $(evt.target).closest('button').button("disable");
70744367 556 var requrl = _get_url([ "stemweb", "request" ]);
557 var reqparam = $('#call_stemweb').serialize();
db234220 558 // TODO We need to stash the literal SVG string in stemmata
559 // somehow. Implement accept header on server side to decide
560 // whether to send application/json or application/xml?
70744367 561 $.getJSON( requrl, reqparam, function (data) {
3cb9d9c0 562 $(evt.target).closest('button').button("enable");
e883f11b 563 $('#stemweb-ui-dialog').dialog('close');
3cb9d9c0 564 if( 'jobid' in data ) {
565 // There is a pending job.
566 selectedTextInfo.stemweb_jobid = data.jobid;
567 alert("Your request has been submitted to Stemweb.\nThe resulting tree will appear in due course.");
568 // Reload the current stemma to rejigger the buttons
569 load_stemma( selectedStemmaID, true );
570 } else {
571 // We appear to have an answer; process it.
572 process_stemweb_result( data );
573 }
db234220 574 }, 'json' );
575 },
576 Cancel: function() {
577 $('#stemweb-ui-dialog').dialog('close');
578 }
579 },
580 create: function(evt) {
581 // Call out to Stemweb to get the algorithm options, with which we
582 // populate the form.
583 var algorithmTypes = {};
584 var algorithmArgs = {};
66458003 585 var requrl = _get_url([ "stemweb", "available" ]);
586 $.getJSON( requrl, function( data ) {
587 $.each( data, function( i, o ) {
588 if( o.model === 'algorithms.algorithm' ) {
589 // it's an algorithm.
590 algorithmTypes[ o.pk ] = o.fields;
591 } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
592 // it's an option for an algorithm that we should display.
593 algorithmArgs[ o.pk ] = o.fields;
70744367 594 }
595 });
66458003 596 // TODO if it is an empty object, disable Stemweb entirely.
597 if( !jQuery.isEmptyObject( algorithmTypes ) ) {
598 $.each( algorithmTypes, function( pk, fields ) {
599 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
600 $('#stemweb_algorithm').append( algopt );
601 });
602 // Set up the relevant options for whichever algorithm is chosen.
603 // "key" -> form name, option ID "stemweb_$key_opt"
604 // "name" -> form label
605 $('#stemweb_algorithm').change( function() {
606 var pk = $(this).val();
607 $('#stemweb_runtime_options').empty();
608 $.each( algorithmTypes[pk].args, function( i, apk ) {
609 var argInfo = algorithmArgs[apk];
610 if( argInfo ) {
611 // Make the element ID
612 var optId = 'stemweb_' + argInfo.key + '_opt';
613 // Make the label
614 var optLabel = $('<label>').attr( 'for', optId )
615 .append( argInfo.name + ": " );
616 var optCtrl;
617 var argType = argInfo.value;
618 if( argType === 'positive_integer' ) {
619 // Make it an input field of smallish size.
620 optCtrl = $('<input>').attr( 'size', 4 );
621 } else if ( argType === 'boolean' ) {
622 // Make it a checkbox.
623 optCtrl = $('<checkbox>');
624 }
625 // Add the name and element ID
626 optCtrl.attr( 'name', argInfo.key ).attr( 'id', optId );
627 // Append the label and the option itself to the form.
628 $('#stemweb_runtime_options').append( optLabel )
629 .append( optCtrl ).append( $('<br>') );
630 }
631 });
632 });
633 $('#stemweb_algorithm').change();
634 }
70744367 635 });
636 // Prime the initial options
db234220 637 },
638 open: function(evt) {
70744367 639 $('#stemweb_run_status').empty();
b8f3a8c8 640 $('#stemweb_tradition').attr('value', selectedTextID );
3cb9d9c0 641 $('#stemweb_merge_reltypes').empty();
642 $.each( selectedTextInfo.reltypes, function( i, r ) {
643 var relation_opt = $('<option>').attr( 'value', r ).append( r );
644 $('#stemweb_merge_reltypes').append( relation_opt );
645 });
646 $('#stemweb_merge_reltypes').multiselect({
647 header: false,
648 selectedList: 3
649 });
db234220 650 },
651 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
652 $(event.target).parent().find('.ui-button').button("enable");
ed0ce314 653 if( ajaxSettings.url.indexOf( 'stemweb/request' ) > -1 ) {
db234220 654 display_error( jqXHR, $("#stemweb_run_status") );
655 }
656 });
3f9d7ae5 657
6cf17f04 658 // Set up the download dialog
659 $('#download-dialog').dialog({
660 autoOpen: false,
661 height: 150,
662 width: 300,
663 modal: true,
664 buttons: {
665 Download: function (evt) {
666 var dlurl = _get_url([ "download", $('#download_tradition').val(), $('#download_format').val() ]);
667 window.location = dlurl;
6cf17f04 668 },
8e26de0f 669 Done: function() {
6cf17f04 670 $('#download-dialog').dialog('close');
671 }
672 },
673 open: function() {
674 $('#download_tradition').attr('value', selectedTextID );
675 },
676 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
677 $(event.target).parent().find('.ui-button').button("enable");
678 if( ajaxSettings.url.indexOf( 'download' ) > -1
679 && ajaxSettings.type == 'POST' ) {
680 display_error( jqXHR, $("#download_status") );
681 }
682 });
683
3f9d7ae5 684 $('#upload-collation-dialog').dialog({
685 autoOpen: false,
e0b90236 686 height: 360,
3f9d7ae5 687 width: 480,
688 modal: true,
689 buttons: {
3f9d7ae5 690 upload: {
691 text: 'Upload',
692 id: 'upload_button',
693 click: function() {
694 $('#upload_status').empty();
e0b90236 695 $('#upload_button').button("disable");
696 upload_new();
3f9d7ae5 697 }
698 },
ab0d1218 699 pick_file: {
700 text: 'Pick File',
701 id: 'pick_file_button',
702 click: function() {
703 $('#new_file').click();
704 }
705 },
3f9d7ae5 706 Cancel: function() {
707 $('#upload-collation-dialog').dialog('close');
708 }
709 },
e0b90236 710 open: function() {
711 // Set the upload button to its correct state based on
712 // whether a file is loaded
713 file_selected( $('#new_file').get(0) );
2ece58b3 714 $('#upload_status').empty();
3f9d7ae5 715 }
e0b90236 716 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
717 // Reset button state
718 file_selected( $('#new_file').get(0) );
719 // Display error message if applicable
720 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
721 && ajaxSettings.type == 'POST' ) {
722 display_error( jqXHR, $("#upload_status") );
723 }
724 });;
3f9d7ae5 725
726 $('#stemma_graph').mousedown( function(evt) {
727 evt.stopPropagation();
728 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
729 $('body').mousemove( function(evt) {
730 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
731 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
732 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
733 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
734 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
735 var g = $('g.graph', svg_root).get(0);
736 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
737 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
738 g.setAttribute( 'transform', new_transform );
739 evt.returnValue = false;
740 evt.preventDefault();
741 return false;
742 });
743 $('body').mouseup( function(evt) {
744 $('body').unbind('mousemove');
745 $('body').unbind('mouseup');
746 });
747 });
748
749 $('#stemma_graph').mousewheel(function (event, delta) {
750 event.returnValue = false;
751 event.preventDefault();
752 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
753 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
754 if( delta < -9 ) { delta = -9 };
755 var z = 1 + delta/10;
756 z = delta > 0 ? 1 : -1;
757 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
758 var g = $('g.graph', svg_root).get(0);
759 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
760 var scaleLevel = z/10;
761 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
762 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
763 g.setAttribute( 'transform', new_transform );
764 }
765 });
766
767});