1 // Global state variables
4 var selectedStemmaID = -1;
7 // Load the names of the appropriate traditions into the directory div.
8 function refreshDirectory () {
9 var lmesg = $('#loading_message').clone();
10 $('#directory').empty().append( lmesg.contents() );
11 $('#directory').load( _get_url(["directory"]),
12 function(response, status, xhr) {
13 if (status == "error") {
14 var msg = "An error occurred: ";
15 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
17 if( textOnLoad != "" ) {
18 // Call the click callback for the relevant text, if it is
20 $('#'+textOnLoad).click();
28 // Load a tradition with its information and stemmata into the tradition
29 // view pane. Calls load_textinfo.
30 function loadTradition( textid, textname, editable ) {
31 selectedTextID = textid;
32 // First insert the placeholder image and register an error handler
33 $('#textinfo_load_status').empty();
34 $('#stemma_graph').empty();
35 $('#textinfo_waitbox').show();
36 $('#textinfo_container').hide().ajaxError(
37 function(event, jqXHR, ajaxSettings, thrownError) {
38 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET' ) {
39 $('#textinfo_waitbox').hide();
40 $('#textinfo_container').show();
41 display_error( jqXHR, $("#textinfo_load_status") );
45 // Hide the functionality that is irrelevant
47 $('#open_stemma_add').show();
48 $('#open_textinfo_edit').show();
49 $('#relatebutton_label').text('View collation and edit relationships');
51 $('#open_stemma_add').hide();
52 $('#open_stemweb_ui').hide();
53 $('#query_stemweb_ui').hide();
54 $('#open_textinfo_edit').hide();
55 $('#relatebutton_label').text('View collation and relationships');
58 // Then get and load the actual content.
59 // TODO: scale #stemma_graph both horizontally and vertically
60 // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
61 $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
62 // Add the scalar data
63 selectedTextInfo = textdata;
66 stemmata = textdata.stemmata;
67 if( stemmata.length ) {
70 selectedStemmaID = -1;
72 load_stemma( selectedStemmaID, editable );
73 // Set up the relationship mapper button
74 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
75 // Set up the download button
76 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
77 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
81 // Load the metadata about a tradition into the appropriate div.
82 function load_textinfo() {
83 $('#textinfo_waitbox').hide();
84 $('#textinfo_load_status').empty();
85 $('#textinfo_container').show();
86 $('.texttitle').empty().append( selectedTextInfo.name );
88 $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
89 $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
91 $('#owner_id').empty().append('no one');
92 if( selectedTextInfo.owner ) {
93 var owneremail = selectedTextInfo.owner;
94 var chop = owneremail.indexOf( '@' );
96 owneremail = owneremail.substr( 0, chop + 1 ) + '...';
98 $('#owner_id').empty().append( owneremail );
100 // Whether or not it is public
101 $('#not_public').empty();
102 if( selectedTextInfo['public'] == false ) {
103 $('#not_public').append('NOT ');
105 // What language setting it has, if any
106 $('#marked_language').empty().append('no language set');
107 if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
108 $('#marked_language').empty().append( selectedTextInfo.language );
112 // Enable / disable the appropriate buttons for paging through the stemma.
113 function show_stemmapager ( editable ) {
114 $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
115 $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
116 if( selectedStemmaID > 0 ) {
117 $('.pager_left_button').click( function () {
118 load_stemma( selectedStemmaID - 1, editable );
119 }).removeClass( 'greyed_out' );
121 if( selectedStemmaID + 1 < stemmata.length ) {
122 $('.pager_right_button').click( function () {
123 load_stemma( selectedStemmaID + 1, editable );
124 }).removeClass( 'greyed_out' );
128 // Load a given stemma SVG into the stemmagraph box.
129 function load_stemma( idx, editable ) {
130 // Load the stemma at idx
131 selectedStemmaID = idx;
132 show_stemmapager( editable );
133 $('#open_stemma_edit').hide();
134 $('#run_stexaminer').hide();
135 $('#stemma_identifier').empty();
136 // Add the relevant Stemweb functionality
138 if( selectedTextInfo.stemweb_jobid == 0 ) {
139 $('#open_stemweb_ui').show();
140 $('#query_stemweb_ui').hide();
142 $('#query_stemweb_ui').show();
143 $('#open_stemweb_ui').hide();
147 // Load the stemma and its properties
148 var stemmadata = stemmata[idx];
150 $('#open_stemma_edit').show();
152 if( stemmadata.directed ) {
153 // Stexaminer submit action
154 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
155 $('#run_stexaminer').attr( 'action', stexpath );
156 $('#run_stexaminer').show();
158 loadSVG( stemmadata.svg );
159 $('#stemma_identifier').text( stemmadata.name );
160 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
164 function query_stemweb_progress() {
165 var requrl = _get_url([ "stemweb", "query", selectedTextInfo.stemweb_jobid ]);
166 $.getJSON( requrl, function (data) {
167 // Look for a status message, either success, running, or notfound.
168 if( data.status === 'success' ) {
169 // Add the new stemmata to the textinfo and tell the user.
170 selectedTextInfo.stemweb_jobid = 0;
171 if( data.stemmata.length > 0 ) {
172 stemmata = stemmata.concat( data.stemmata );
173 if( selectedStemmaID == -1 ) {
174 // We have a stemma for the first time; load the first one.
175 load_stemma( 0, true );
177 alert( 'You have one or more new stemmata!' );
179 alert( 'Stemweb run finished with no stemmata...huh?!' );
181 } else if( data.status === 'running' ) {
182 // Just tell the user.
183 alert( 'Your Stemweb query is still running!' );
184 } else if( data.status === 'notfound' ) {
185 // Ask the user to refresh, for now.
186 alert( 'Your Stemweb query probably finished and reported back. Please reload to check.' );
191 // Load the SVG we are given
192 function loadSVG(svgData) {
193 var svgElement = $('#stemma_graph');
195 $(svgElement).svg('destroy');
199 onLoad : function () {
200 var theSVG = svgElement.find('svg');
201 var svgoffset = theSVG.offset();
202 var browseroffset = 1;
203 // Firefox needs a different offset, stupidly enough
204 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
205 browseroffset = 3; // works for tall images
206 // ...but if the SVG is wider than it is tall, Firefox treats
207 // the top as being the top of the graph, loaded into the middle
208 // of the canvas, but then the margin at the top of the canvas
209 // extends upward. So we have to find the actual top of the canvas
210 // and correct for *that* instead.
211 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
212 if( vbdim.height < vbdim.width ) {
213 var vbscale = svgElement.width() / vbdim.width;
214 var vbrealheight = vbdim.height * vbscale;
215 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
218 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
219 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
224 // General-purpose error-handling function.
225 // TODO make sure this gets used throughout, where appropriate.
226 function display_error( jqXHR, el ) {
228 if( jqXHR.responseText == "" ) {
229 errmsg = "perhaps the server went down?"
233 errobj = jQuery.parseJSON( jqXHR.responseText );
234 errmsg = errobj.error;
235 } catch ( parse_err ) {
236 errmsg = "something went wrong on the server."
239 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
240 $(el).empty().append( msghtml ).show();
243 // Event to enable the upload button when a file has been selected
244 function file_selected( e ) {
245 if( e.files.length == 1 ) {
246 $('#upload_button').button('enable');
247 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
249 $('#upload_button').button('disable');
250 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
254 // Implement our own AJAX method that uses the features of XMLHttpRequest2
255 // but try to let it have a similar interface to jquery.post
256 // The data var needs to be a FormData() object.
257 // The callback will be given a single argument, which is the response data
258 // of the given type.
260 function post_xhr2( url, data, cb, type ) {
264 var xhr = new XMLHttpRequest();
265 // Set the expected response type
266 if( type === 'data' ) {
267 xhr.responseType = 'blob';
268 } else if( type === 'xml' ) {
269 xhr.responseType = 'document';
272 // Gin up an AJAX settings object
273 $.ajaxSetup({ url: url, type: 'POST' });
274 xhr.open( 'POST', url, true );
275 // Handle the results
276 xhr.onload = function( e ) {
277 // Get the response and parse it
278 // Call the callback with the response, whatever it was
280 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
282 if( type === 'json' ) {
283 resp = $.parseJSON( xhrs.responseText );
284 } else if ( type === 'xml' ) {
285 resp = xhrs.responseXML;
286 } else if ( type === 'text' ) {
287 resp = xhrs.responseText;
289 resp = xhrs.response;
293 // Trigger the ajaxError...
294 _trigger_ajaxerror( e );
297 xhr.onerror = _trigger_ajaxerror;
298 xhr.onabort = _trigger_ajaxerror;
302 function _trigger_ajaxerror( e ) {
304 var thrown = xhr.statusText || 'Request error';
305 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
308 function upload_new () {
309 // Serialize the upload form, get the file and attach it to the request,
310 // POST the lot and handle the response.
311 var newfile = $('#new_file').get(0).files[0];
312 var reader = new FileReader();
313 reader.onload = function( evt ) {
314 var data = new FormData();
315 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
316 data.append( o.name, o.value );
318 data.append( 'file', newfile );
319 var upload_url = _get_url([ 'newtradition' ]);
320 post_xhr2( upload_url, data, function( ret ) {
322 $('#upload-collation-dialog').dialog('close');
324 loadTradition( ret.id, ret.name, 1 );
325 } else if( ret.error ) {
326 $('#upload_status').empty().append(
327 $('<span>').attr('class', 'error').append( ret.error ) );
331 reader.onerror = function( evt ) {
332 var err_resp = 'File read error';
333 if( e.name == 'NotFoundError' ) {
334 err_resp = 'File not found';
335 } else if ( e.name == 'NotReadableError' ) {
336 err_resp == 'File unreadable - is it yours?';
337 } else if ( e.name == 'EncodingError' ) {
338 err_resp == 'File cannot be encoded - is it too long?';
339 } else if ( e.name == 'SecurityError' ) {
340 err_resp == 'File read security error';
342 // Fake a jqXHR object that we can pass to our generic error handler.
343 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
344 display_error( jqxhr, $('#upload_status') );
345 $('#upload_button').button('disable');
348 reader.readAsBinaryString( newfile );
351 // Utility function to neatly construct an application URL
352 function _get_url( els ) {
353 return basepath + els.join('/');
357 $(document).ready( function() {
358 // See if we have the browser functionality we need
359 // TODO Also think of a test for SVG readiness
360 if( !!window.FileReader && !!window.File ) {
361 $('#compatibility_check').empty();
364 // call out to load the directory div
365 $('#textinfo_container').hide();
366 $('#textinfo_waitbox').hide();
369 // Set up the textinfo edit dialog
370 $('#textinfo-edit-dialog').dialog({
376 Save: function (evt) {
377 $("#edit_textinfo_status").empty();
378 $(evt.target).button("disable");
379 var requrl = _get_url([ "textinfo", selectedTextID ]);
380 var reqparam = $('#edit_textinfo').serialize();
381 $.post( requrl, reqparam, function (data) {
382 // Reload the selected text fields
383 selectedTextInfo = data;
385 // Reenable the button and close the form
386 $(evt.target).button("enable");
387 $('#textinfo-edit-dialog').dialog('close');
391 $('#textinfo-edit-dialog').dialog('close');
395 $("#edit_textinfo_status").empty();
396 // Populate the form fields with the current values
397 // edit_(name, language, public, owner)
398 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
399 var fname = '#edit_' + k;
400 // Special case: language Default is basically language null
401 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
404 $(fname).val( selectedTextInfo[k] );
407 if( selectedTextInfo['public'] == true ) {
408 $('#edit_public').attr('checked','true');
410 $('#edit_public').removeAttr('checked');
413 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
414 $(event.target).parent().find('.ui-button').button("enable");
415 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
416 && ajaxSettings.type == 'POST' ) {
417 display_error( jqXHR, $("#edit_textinfo_status") );
422 // Set up the stemma editor dialog
423 $('#stemma-edit-dialog').dialog({
429 Save: function (evt) {
430 $("#edit_stemma_status").empty();
431 $(evt.target).button("disable");
432 var stemmaseq = $('#stemmaseq').val();
433 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
434 var reqparam = { 'dot': $('#dot_field').val() };
435 // TODO We need to stash the literal SVG string in stemmata
436 // somehow. Implement accept header on server side to decide
437 // whether to send application/json or application/xml?
438 $.post( requrl, reqparam, function (data) {
439 // We received a stemma SVG string in return.
440 // Update the current stemma sequence number
441 selectedStemmaID = data.stemmaid;
442 delete data.stemmaid;
443 // Stash the answer in the appropriate spot in our stemma array
444 stemmata[selectedStemmaID] = data;
445 // Display the new stemma
446 load_stemma( selectedStemmaID, true );
447 // Reenable the button and close the form
448 $(evt.target).button("enable");
449 $('#stemma-edit-dialog').dialog('close');
453 $('#stemma-edit-dialog').dialog('close');
456 open: function(evt) {
457 $("#edit_stemma_status").empty();
458 var stemmaseq = $('#stemmaseq').val();
459 if( stemmaseq == 'n' ) {
460 // If we are creating a new stemma, populate the textarea with a
462 $(evt.target).dialog('option', 'title', 'Add a new stemma')
463 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
465 // If we are editing a stemma, grab its stemmadot and populate the
466 // textarea with that.
467 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
468 $('#dot_field').val( 'Loading, please wait...' );
469 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
470 $.getJSON( doturl, function (data) {
471 // Re-insert the line breaks
472 var dotstring = data.dot.replace(/\|n/gm, "\n");
473 $('#dot_field').val( dotstring );
477 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
478 $(event.target).parent().find('.ui-button').button("enable");
479 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
480 && ajaxSettings.type == 'POST' ) {
481 display_error( jqXHR, $("#edit_stemma_status") );
485 $('#stemweb-ui-dialog').dialog({
491 Run: function (evt) {
492 $("#stemweb_run_status").empty();
493 $(evt.target).button("disable");
494 var requrl = _get_url([ "stemweb", "request" ]);
495 var reqparam = $('#call_stemweb').serialize();
496 // TODO We need to stash the literal SVG string in stemmata
497 // somehow. Implement accept header on server side to decide
498 // whether to send application/json or application/xml?
499 $.getJSON( requrl, reqparam, function (data) {
500 // Job ID is in data.jobid. TODO do something with it.
501 $(evt.target).button("enable");
502 $('#stemma-edit-dialog').dialog('close');
503 // Reload the current stemma to rejigger the buttons
504 load_stemma( selectedStemmaID, true );
508 $('#stemweb-ui-dialog').dialog('close');
511 create: function(evt) {
512 // Call out to Stemweb to get the algorithm options, with which we
513 // populate the form.
514 var algorithmTypes = {};
515 var algorithmArgs = {};
516 $.each( stemwebAlgorithms, function( i, o ) {
517 if( o.model === 'algorithms.algorithm' ) {
518 // it's an algorithm.
519 algorithmTypes[ o.pk ] = o.fields;
520 } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
521 // it's an option for an algorithm that we should display.
522 algorithmArgs[ o.pk ] = o.fields;
525 $.each( algorithmTypes, function( pk, fields ) {
526 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
527 $('#stemweb_algorithm').append( algopt );
529 // Set up the relevant options for whichever algorithm is chosen.
530 // "key" -> form name, option ID "stemweb_$key_opt"
531 // "name" -> form label
532 $('#stemweb_algorithm').change( function() {
533 var pk = $(this).val();
534 $('#stemweb_runtime_options').empty();
535 $.each( algorithmTypes[pk].args, function( i, apk ) {
536 var argInfo = algorithmArgs[apk];
538 // Make the element ID
539 var optId = 'stemweb_' + argInfo.key + '_opt';
541 var optLabel = $('<label>').attr( 'for', optId )
542 .append( argInfo.name + ": " );
544 var argType = argInfo.value;
545 if( argType === 'positive_integer' ) {
546 // Make it an input field of smallish size.
547 optCtrl = $('<input>').attr( 'size', 4 );
548 } else if ( argType === 'boolean' ) {
549 // Make it a checkbox.
550 optCtrl = $('<checkbox>');
552 // Add the name and element ID
553 optCtrl.attr( 'name', argInfo.key ).attr( 'id', optId );
554 // Append the label and the option itself to the form.
555 $('#stemweb_runtime_options').append( optLabel )
556 .append( optCtrl ).append( $('<br>') );
560 // Prime the initial options
561 $('#stemweb_algorithm').change();
563 open: function(evt) {
564 $('#stemweb_run_status').empty();
565 $('#stemweb_tradition').attr('value', selectedTextID );
567 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
568 $(event.target).parent().find('.ui-button').button("enable");
569 if( ajaxSettings.url.indexOf( 'stemweb/request' ) > -1 ) {
570 display_error( jqXHR, $("#stemweb_run_status") );
574 $('#upload-collation-dialog').dialog({
584 $('#upload_status').empty();
585 $('#upload_button').button("disable");
591 id: 'pick_file_button',
593 $('#new_file').click();
597 $('#upload-collation-dialog').dialog('close');
601 // Set the upload button to its correct state based on
602 // whether a file is loaded
603 file_selected( $('#new_file').get(0) );
604 $('#upload_status').empty();
606 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
607 // Reset button state
608 file_selected( $('#new_file').get(0) );
609 // Display error message if applicable
610 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
611 && ajaxSettings.type == 'POST' ) {
612 display_error( jqXHR, $("#upload_status") );
616 $('#stemma_graph').mousedown( function(evt) {
617 evt.stopPropagation();
618 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
619 $('body').mousemove( function(evt) {
620 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
621 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
622 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
623 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
624 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
625 var g = $('g.graph', svg_root).get(0);
626 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
627 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
628 g.setAttribute( 'transform', new_transform );
629 evt.returnValue = false;
630 evt.preventDefault();
633 $('body').mouseup( function(evt) {
634 $('body').unbind('mousemove');
635 $('body').unbind('mouseup');
639 $('#stemma_graph').mousewheel(function (event, delta) {
640 event.returnValue = false;
641 event.preventDefault();
642 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
643 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
644 if( delta < -9 ) { delta = -9 };
645 var z = 1 + delta/10;
646 z = delta > 0 ? 1 : -1;
647 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
648 var g = $('g.graph', svg_root).get(0);
649 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
650 var scaleLevel = z/10;
651 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
652 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
653 g.setAttribute( 'transform', new_transform );