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();
141 $('#query_stemweb_ui').show();
145 // Load the stemma and its properties
146 var stemmadata = stemmata[idx];
148 $('#open_stemma_edit').show();
150 if( stemmadata.directed ) {
151 // Stexaminer submit action
152 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
153 $('#run_stexaminer').attr( 'action', stexpath );
154 $('#run_stexaminer').show();
156 loadSVG( stemmadata.svg );
157 $('#stemma_identifier').text( stemmadata.name );
158 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
162 function query_stemweb_progress() {
163 var requrl = _get_url([ "stemweb", "query", selectedTextInfo.stemweb_jobid ]);
164 $.getJSON( requrl, function (data) {
165 // Look for a status message, either success, running, or notfound.
166 if( data.status === 'success' ) {
167 // Add the new stemmata to the textinfo and tell the user.
168 if( data.stemmata.length > 0 ) {
169 stemmata = stemmata.concat( data.stemmata );
170 if( selectedStemmaID == -1 ) {
171 // We have a stemma for the first time; load the first one.
174 alert( 'You have one or more new stemmata!' );
176 alert( 'Stemweb run finished with no stemmata...huh?!' );
178 } else if( data.status === 'running' ) {
179 // Just tell the user.
180 alert( 'Your Stemweb query is still running!' );
181 } else if( data.status === 'notfound' ) {
182 // Ask the user to refresh, for now.
183 alert( 'Your Stemweb query probably finished and reported back. Please reload to check.' );
188 // Load the SVG we are given
189 function loadSVG(svgData) {
190 var svgElement = $('#stemma_graph');
192 $(svgElement).svg('destroy');
196 onLoad : function () {
197 var theSVG = svgElement.find('svg');
198 var svgoffset = theSVG.offset();
199 var browseroffset = 1;
200 // Firefox needs a different offset, stupidly enough
201 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
202 browseroffset = 3; // works for tall images
203 // ...but if the SVG is wider than it is tall, Firefox treats
204 // the top as being the top of the graph, loaded into the middle
205 // of the canvas, but then the margin at the top of the canvas
206 // extends upward. So we have to find the actual top of the canvas
207 // and correct for *that* instead.
208 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
209 if( vbdim.height < vbdim.width ) {
210 var vbscale = svgElement.width() / vbdim.width;
211 var vbrealheight = vbdim.height * vbscale;
212 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
215 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
216 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
221 // General-purpose error-handling function.
222 // TODO make sure this gets used throughout, where appropriate.
223 function display_error( jqXHR, el ) {
225 if( jqXHR.responseText == "" ) {
226 errmsg = "perhaps the server went down?"
230 errobj = jQuery.parseJSON( jqXHR.responseText );
231 errmsg = errobj.error;
232 } catch ( parse_err ) {
233 errmsg = "something went wrong on the server."
236 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
237 $(el).empty().append( msghtml ).show();
240 // Event to enable the upload button when a file has been selected
241 function file_selected( e ) {
242 if( e.files.length == 1 ) {
243 $('#upload_button').button('enable');
244 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
246 $('#upload_button').button('disable');
247 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
251 // Implement our own AJAX method that uses the features of XMLHttpRequest2
252 // but try to let it have a similar interface to jquery.post
253 // The data var needs to be a FormData() object.
254 // The callback will be given a single argument, which is the response data
255 // of the given type.
257 function post_xhr2( url, data, cb, type ) {
261 var xhr = new XMLHttpRequest();
262 // Set the expected response type
263 if( type === 'data' ) {
264 xhr.responseType = 'blob';
265 } else if( type === 'xml' ) {
266 xhr.responseType = 'document';
269 // Gin up an AJAX settings object
270 $.ajaxSetup({ url: url, type: 'POST' });
271 xhr.open( 'POST', url, true );
272 // Handle the results
273 xhr.onload = function( e ) {
274 // Get the response and parse it
275 // Call the callback with the response, whatever it was
277 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
279 if( type === 'json' ) {
280 resp = $.parseJSON( xhrs.responseText );
281 } else if ( type === 'xml' ) {
282 resp = xhrs.responseXML;
283 } else if ( type === 'text' ) {
284 resp = xhrs.responseText;
286 resp = xhrs.response;
290 // Trigger the ajaxError...
291 _trigger_ajaxerror( e );
294 xhr.onerror = _trigger_ajaxerror;
295 xhr.onabort = _trigger_ajaxerror;
299 function _trigger_ajaxerror( e ) {
301 var thrown = xhr.statusText || 'Request error';
302 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
305 function upload_new () {
306 // Serialize the upload form, get the file and attach it to the request,
307 // POST the lot and handle the response.
308 var newfile = $('#new_file').get(0).files[0];
309 var reader = new FileReader();
310 reader.onload = function( evt ) {
311 var data = new FormData();
312 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
313 data.append( o.name, o.value );
315 data.append( 'file', newfile );
316 var upload_url = _get_url([ 'newtradition' ]);
317 post_xhr2( upload_url, data, function( ret ) {
319 $('#upload-collation-dialog').dialog('close');
321 loadTradition( ret.id, ret.name, 1 );
322 } else if( ret.error ) {
323 $('#upload_status').empty().append(
324 $('<span>').attr('class', 'error').append( ret.error ) );
328 reader.onerror = function( evt ) {
329 var err_resp = 'File read error';
330 if( e.name == 'NotFoundError' ) {
331 err_resp = 'File not found';
332 } else if ( e.name == 'NotReadableError' ) {
333 err_resp == 'File unreadable - is it yours?';
334 } else if ( e.name == 'EncodingError' ) {
335 err_resp == 'File cannot be encoded - is it too long?';
336 } else if ( e.name == 'SecurityError' ) {
337 err_resp == 'File read security error';
339 // Fake a jqXHR object that we can pass to our generic error handler.
340 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
341 display_error( jqxhr, $('#upload_status') );
342 $('#upload_button').button('disable');
345 reader.readAsBinaryString( newfile );
348 // Utility function to neatly construct an application URL
349 function _get_url( els ) {
350 return basepath + els.join('/');
354 $(document).ready( function() {
355 // See if we have the browser functionality we need
356 // TODO Also think of a test for SVG readiness
357 if( !!window.FileReader && !!window.File ) {
358 $('#compatibility_check').empty();
361 // call out to load the directory div
362 $('#textinfo_container').hide();
363 $('#textinfo_waitbox').hide();
366 // Set up the textinfo edit dialog
367 $('#textinfo-edit-dialog').dialog({
373 Save: function (evt) {
374 $("#edit_textinfo_status").empty();
375 $(evt.target).button("disable");
376 var requrl = _get_url([ "textinfo", selectedTextID ]);
377 var reqparam = $('#edit_textinfo').serialize();
378 $.post( requrl, reqparam, function (data) {
379 // Reload the selected text fields
380 selectedTextInfo = data;
382 // Reenable the button and close the form
383 $(evt.target).button("enable");
384 $('#textinfo-edit-dialog').dialog('close');
388 $('#textinfo-edit-dialog').dialog('close');
392 $("#edit_textinfo_status").empty();
393 // Populate the form fields with the current values
394 // edit_(name, language, public, owner)
395 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
396 var fname = '#edit_' + k;
397 // Special case: language Default is basically language null
398 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
401 $(fname).val( selectedTextInfo[k] );
404 if( selectedTextInfo['public'] == true ) {
405 $('#edit_public').attr('checked','true');
407 $('#edit_public').removeAttr('checked');
410 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
411 $(event.target).parent().find('.ui-button').button("enable");
412 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
413 && ajaxSettings.type == 'POST' ) {
414 display_error( jqXHR, $("#edit_textinfo_status") );
419 // Set up the stemma editor dialog
420 $('#stemma-edit-dialog').dialog({
426 Save: function (evt) {
427 $("#edit_stemma_status").empty();
428 $(evt.target).button("disable");
429 var stemmaseq = $('#stemmaseq').val();
430 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
431 var reqparam = { 'dot': $('#dot_field').val() };
432 // TODO We need to stash the literal SVG string in stemmata
433 // somehow. Implement accept header on server side to decide
434 // whether to send application/json or application/xml?
435 $.post( requrl, reqparam, function (data) {
436 // We received a stemma SVG string in return.
437 // Update the current stemma sequence number
438 selectedStemmaID = data.stemmaid;
439 delete data.stemmaid;
440 // Stash the answer in the appropriate spot in our stemma array
441 stemmata[selectedStemmaID] = data;
442 // Display the new stemma
443 load_stemma( selectedStemmaID, true );
444 // Reenable the button and close the form
445 $(evt.target).button("enable");
446 $('#stemma-edit-dialog').dialog('close');
450 $('#stemma-edit-dialog').dialog('close');
453 open: function(evt) {
454 $("#edit_stemma_status").empty();
455 var stemmaseq = $('#stemmaseq').val();
456 if( stemmaseq == 'n' ) {
457 // If we are creating a new stemma, populate the textarea with a
459 $(evt.target).dialog('option', 'title', 'Add a new stemma')
460 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
462 // If we are editing a stemma, grab its stemmadot and populate the
463 // textarea with that.
464 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
465 $('#dot_field').val( 'Loading, please wait...' );
466 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
467 $.getJSON( doturl, function (data) {
468 // Re-insert the line breaks
469 var dotstring = data.dot.replace(/\|n/gm, "\n");
470 $('#dot_field').val( dotstring );
474 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
475 $(event.target).parent().find('.ui-button').button("enable");
476 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
477 && ajaxSettings.type == 'POST' ) {
478 display_error( jqXHR, $("#edit_stemma_status") );
482 $('#stemweb-ui-dialog').dialog({
488 Run: function (evt) {
489 $("#stemweb_run_status").empty();
490 $(evt.target).button("disable");
491 var requrl = _get_url([ "stemweb", "request" ]);
492 var reqparam = $('#call_stemweb').serialize();
493 // TODO We need to stash the literal SVG string in stemmata
494 // somehow. Implement accept header on server side to decide
495 // whether to send application/json or application/xml?
496 $.getJSON( requrl, reqparam, function (data) {
497 // Job ID is in data.jobid. TODO do something with it.
498 $(evt.target).button("enable");
499 $('#stemma-edit-dialog').dialog('close');
503 $('#stemweb-ui-dialog').dialog('close');
506 create: function(evt) {
507 // Call out to Stemweb to get the algorithm options, with which we
508 // populate the form.
509 var algorithmTypes = {};
510 var algorithmArgs = {};
511 $.each( stemwebAlgorithms, function( i, o ) {
512 if( o.model === 'algorithms.algorithm' ) {
513 // it's an algorithm.
514 algorithmTypes[ o.pk ] = o.fields;
515 } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
516 // it's an option for an algorithm that we should display.
517 algorithmArgs[ o.pk ] = o.fields;
520 $.each( algorithmTypes, function( pk, fields ) {
521 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
522 $('#stemweb_algorithm').append( algopt );
524 // Set up the relevant options for whichever algorithm is chosen.
525 // "key" -> form name, option ID "stemweb_$key_opt"
526 // "name" -> form label
527 $('#stemweb_algorithm').change( function() {
528 var pk = $(this).val();
529 $('#stemweb_runtime_options').empty();
530 $.each( algorithmTypes[pk].args, function( i, apk ) {
531 var argInfo = algorithmArgs[apk];
533 // Make the element ID
534 var optId = 'stemweb_' + argInfo.key + '_opt';
536 var optLabel = $('<label>').attr( 'for', optId )
537 .append( argInfo.name + ": " );
539 var argType = argInfo.value;
540 if( argType === 'positive_integer' ) {
541 // Make it an input field of smallish size.
542 optCtrl = $('<input>').attr( 'size', 4 );
543 } else if ( argType === 'boolean' ) {
544 // Make it a checkbox.
545 optCtrl = $('<checkbox>');
547 // Add the name and element ID
548 optCtrl.attr( 'name', argInfo.key ).attr( 'id', optId );
549 // Append the label and the option itself to the form.
550 $('#stemweb_runtime_options').append( optLabel )
551 .append( optCtrl ).append( $('<br>') );
555 // Prime the initial options
556 $('#stemweb_algorithm').change();
558 open: function(evt) {
559 $('#stemweb_run_status').empty();
560 $('#stemweb_tradition').attr('value', selectedTextID );
562 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
563 $(event.target).parent().find('.ui-button').button("enable");
564 if( ajaxSettings.url.indexOf( 'stemweb/request' ) > -1 ) {
565 display_error( jqXHR, $("#stemweb_run_status") );
569 $('#upload-collation-dialog').dialog({
579 $('#upload_status').empty();
580 $('#upload_button').button("disable");
586 id: 'pick_file_button',
588 $('#new_file').click();
592 $('#upload-collation-dialog').dialog('close');
596 // Set the upload button to its correct state based on
597 // whether a file is loaded
598 file_selected( $('#new_file').get(0) );
599 $('#upload_status').empty();
601 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
602 // Reset button state
603 file_selected( $('#new_file').get(0) );
604 // Display error message if applicable
605 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
606 && ajaxSettings.type == 'POST' ) {
607 display_error( jqXHR, $("#upload_status") );
611 $('#stemma_graph').mousedown( function(evt) {
612 evt.stopPropagation();
613 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
614 $('body').mousemove( function(evt) {
615 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
616 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
617 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
618 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
619 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
620 var g = $('g.graph', svg_root).get(0);
621 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
622 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
623 g.setAttribute( 'transform', new_transform );
624 evt.returnValue = false;
625 evt.preventDefault();
628 $('body').mouseup( function(evt) {
629 $('body').unbind('mousemove');
630 $('body').unbind('mouseup');
634 $('#stemma_graph').mousewheel(function (event, delta) {
635 event.returnValue = false;
636 event.preventDefault();
637 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
638 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
639 if( delta < -9 ) { delta = -9 };
640 var z = 1 + delta/10;
641 z = delta > 0 ? 1 : -1;
642 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
643 var g = $('g.graph', svg_root).get(0);
644 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
645 var scaleLevel = z/10;
646 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
647 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
648 g.setAttribute( 'transform', new_transform );