1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-02 15:38:15 +00:00

[file_rewrite] extracted file_content files, cleaned up code & rm unused files of pdf view

This commit is contained in:
llj
2012-12-20 19:50:56 +08:00
parent 6fb2b16c1f
commit 604c024275
32 changed files with 160 additions and 37781 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,359 +0,0 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
// Checking if the typed arrays are supported
(function checkTypedArrayCompatibility() {
if (typeof Uint8Array !== 'undefined') {
// some mobile versions do not support subarray (e.g. safari 5 / iOS)
if (typeof Uint8Array.prototype.subarray === 'undefined') {
Uint8Array.prototype.subarray = function subarray(start, end) {
return new Uint8Array(this.slice(start, end));
};
Float32Array.prototype.subarray = function subarray(start, end) {
return new Float32Array(this.slice(start, end));
};
}
// some mobile version might not support Float64Array
if (typeof Float64Array === 'undefined')
window.Float64Array = Float32Array;
return;
}
function subarray(start, end) {
return new TypedArray(this.slice(start, end));
}
function setArrayOffset(array, offset) {
if (arguments.length < 2)
offset = 0;
for (var i = 0, n = array.length; i < n; ++i, ++offset)
this[offset] = array[i] & 0xFF;
}
function TypedArray(arg1) {
var result;
if (typeof arg1 === 'number') {
result = [];
for (var i = 0; i < arg1; ++i)
result[i] = 0;
} else
result = arg1.slice(0);
result.subarray = subarray;
result.buffer = result;
result.byteLength = result.length;
result.set = setArrayOffset;
if (typeof arg1 === 'object' && arg1.buffer)
result.buffer = arg1.buffer;
return result;
}
window.Uint8Array = TypedArray;
// we don't need support for set, byteLength for 32-bit array
// so we can use the TypedArray as well
window.Uint32Array = TypedArray;
window.Int32Array = TypedArray;
window.Uint16Array = TypedArray;
window.Float32Array = TypedArray;
window.Float64Array = TypedArray;
})();
// Object.create() ?
(function checkObjectCreateCompatibility() {
if (typeof Object.create !== 'undefined')
return;
Object.create = function objectCreate(proto) {
var constructor = function objectCreateConstructor() {};
constructor.prototype = proto;
return new constructor();
};
})();
// Object.defineProperty() ?
(function checkObjectDefinePropertyCompatibility() {
if (typeof Object.defineProperty !== 'undefined') {
// some browsers (e.g. safari) cannot use defineProperty() on DOM objects
// and thus the native version is not sufficient
var definePropertyPossible = true;
try {
Object.defineProperty(new Image(), 'id', { value: 'test' });
} catch (e) {
definePropertyPossible = false;
}
if (definePropertyPossible) return;
}
Object.defineProperty = function objectDefineProperty(obj, name, def) {
delete obj[name];
if ('get' in def)
obj.__defineGetter__(name, def['get']);
if ('set' in def)
obj.__defineSetter__(name, def['set']);
if ('value' in def) {
obj.__defineSetter__(name, function objectDefinePropertySetter(value) {
this.__defineGetter__(name, function objectDefinePropertyGetter() {
return value;
});
return value;
});
obj[name] = def.value;
}
};
})();
// Object.keys() ?
(function checkObjectKeysCompatibility() {
if (typeof Object.keys !== 'undefined')
return;
Object.keys = function objectKeys(obj) {
var result = [];
for (var i in obj) {
if (obj.hasOwnProperty(i))
result.push(i);
}
return result;
};
})();
// No XMLHttpRequest.response ?
(function checkXMLHttpRequestResponseCompatibility() {
var xhrPrototype = XMLHttpRequest.prototype;
if ('response' in xhrPrototype ||
'mozResponseArrayBuffer' in xhrPrototype ||
'mozResponse' in xhrPrototype ||
'responseArrayBuffer' in xhrPrototype)
return;
// IE ?
if (typeof VBArray !== 'undefined') {
Object.defineProperty(xhrPrototype, 'response', {
get: function xmlHttpRequestResponseGet() {
return new Uint8Array(new VBArray(this.responseBody).toArray());
}
});
Object.defineProperty(xhrPrototype, 'overrideMimeType', {
value: function xmlHttpRequestOverrideMimeType(mimeType) {}
});
return;
}
// other browsers
function responseTypeSetter() {
// will be only called to set "arraybuffer"
this.overrideMimeType('text/plain; charset=x-user-defined');
}
if (typeof xhrPrototype.overrideMimeType === 'function') {
Object.defineProperty(xhrPrototype, 'responseType',
{ set: responseTypeSetter });
}
function responseGetter() {
var text = this.responseText;
var i, n = text.length;
var result = new Uint8Array(n);
for (i = 0; i < n; ++i)
result[i] = text.charCodeAt(i) & 0xFF;
return result;
}
Object.defineProperty(xhrPrototype, 'response', { get: responseGetter });
})();
// window.btoa (base64 encode function) ?
(function checkWindowBtoaCompatibility() {
if ('btoa' in window)
return;
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
window.btoa = function windowBtoa(chars) {
var buffer = '';
var i, n;
for (i = 0, n = chars.length; i < n; i += 3) {
var b1 = chars.charCodeAt(i) & 0xFF;
var b2 = chars.charCodeAt(i + 1) & 0xFF;
var b3 = chars.charCodeAt(i + 2) & 0xFF;
var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
buffer += (digits.charAt(d1) + digits.charAt(d2) +
digits.charAt(d3) + digits.charAt(d4));
}
return buffer;
};
})();
// Function.prototype.bind ?
(function checkFunctionPrototypeBindCompatibility() {
if (typeof Function.prototype.bind !== 'undefined')
return;
Function.prototype.bind = function functionPrototypeBind(obj) {
var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
var bound = function functionPrototypeBindBound() {
var args = Array.prototype.concat.apply(headArgs, arguments);
return fn.apply(obj, args);
};
return bound;
};
})();
// IE9 text/html data URI
(function checkDocumentDocumentModeCompatibility() {
if (!('documentMode' in document) || document.documentMode !== 9)
return;
// overriding the src property
var originalSrcDescriptor = Object.getOwnPropertyDescriptor(
HTMLIFrameElement.prototype, 'src');
Object.defineProperty(HTMLIFrameElement.prototype, 'src', {
get: function htmlIFrameElementPrototypeSrcGet() { return this.$src; },
set: function htmlIFrameElementPrototypeSrcSet(src) {
this.$src = src;
if (src.substr(0, 14) != 'data:text/html') {
originalSrcDescriptor.set.call(this, src);
return;
}
// for text/html, using blank document and then
// document's open, write, and close operations
originalSrcDescriptor.set.call(this, 'about:blank');
setTimeout((function htmlIFrameElementPrototypeSrcOpenWriteClose() {
var doc = this.contentDocument;
doc.open('text/html');
doc.write(src.substr(src.indexOf(',') + 1));
doc.close();
}).bind(this), 0);
},
enumerable: true
});
})();
// HTMLElement dataset property
(function checkDatasetProperty() {
var div = document.createElement('div');
if ('dataset' in div)
return; // dataset property exists
Object.defineProperty(HTMLElement.prototype, 'dataset', {
get: function() {
if (this._dataset)
return this._dataset;
var dataset = {};
for (var j = 0, jj = this.attributes.length; j < jj; j++) {
var attribute = this.attributes[j];
if (attribute.name.substring(0, 5) != 'data-')
continue;
var key = attribute.name.substring(5).replace(/\-([a-z])/g,
function(all, ch) { return ch.toUpperCase(); });
dataset[key] = attribute.value;
}
Object.defineProperty(this, '_dataset', {
value: dataset,
writable: false,
enumerable: false
});
return dataset;
},
enumerable: true
});
})();
// HTMLElement classList property
(function checkClassListProperty() {
var div = document.createElement('div');
if ('classList' in div)
return; // classList property exists
function changeList(element, itemName, add, remove) {
var s = element.className || '';
var list = s.split(/\s+/g);
if (list[0] == '') list.shift();
var index = list.indexOf(itemName);
if (index < 0 && add)
list.push(itemName);
if (index >= 0 && remove)
list.splice(index, 1);
element.className = list.join(' ');
}
var classListPrototype = {
add: function(name) {
changeList(this.element, name, true, false);
},
remove: function(name) {
changeList(this.element, name, false, true);
},
toggle: function(name) {
changeList(this.element, name, true, true);
}
};
Object.defineProperty(HTMLElement.prototype, 'classList', {
get: function() {
if (this._classList)
return this._classList;
var classList = Object.create(classListPrototype, {
element: {
value: this,
writable: false,
enumerable: true
}
});
Object.defineProperty(this, '_classList', {
value: classList,
writable: false,
enumerable: false
});
return classList;
},
enumerable: true
});
})();
// Check console compatability
(function checkConsoleCompatibility() {
if (typeof console == 'undefined') {
console = {log: function() {}};
}
})();
// Check onclick compatibility in Opera
(function checkOnClickCompatibility() {
// workaround for reported Opera bug DSK-354448:
// onclick fires on disabled buttons with opaque content
function ignoreIfTargetDisabled(event) {
if (isDisabled(event.target)) {
event.stopPropagation();
}
}
function isDisabled(node) {
return node.disabled || (node.parentNode && isDisabled(node.parentNode));
}
if (navigator.userAgent.indexOf('Opera') != -1) {
// use browser detection since we cannot feature-check this bug
document.addEventListener('click', ignoreIfTargetDisabled, true);
}
})();
// Checks if navigator.language is supported
(function checkNavigatorLanguage() {
if ('language' in navigator)
return;
Object.defineProperty(navigator, 'language', {
get: function navigatorLanguage() {
var language = navigator.userLanguage || 'en-US';
return language.substring(0, 2).toLowerCase() +
language.substring(2).toUpperCase();
},
enumerable: true
});
})();

View File

@@ -1,476 +0,0 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
var FontInspector = (function FontInspectorClosure() {
var fonts;
var panelWidth = 300;
var active = false;
var fontAttribute = 'data-font-name';
function removeSelection() {
var divs = document.querySelectorAll('div[' + fontAttribute + ']');
for (var i = 0, ii = divs.length; i < ii; ++i) {
var div = divs[i];
div.className = '';
}
}
function resetSelection() {
var divs = document.querySelectorAll('div[' + fontAttribute + ']');
for (var i = 0, ii = divs.length; i < ii; ++i) {
var div = divs[i];
div.className = 'debuggerHideText';
}
}
function selectFont(fontName, show) {
var divs = document.querySelectorAll('div[' + fontAttribute + '=' +
fontName + ']');
for (var i = 0, ii = divs.length; i < ii; ++i) {
var div = divs[i];
div.className = show ? 'debuggerShowText' : 'debuggerHideText';
}
}
function textLayerClick(e) {
if (!e.target.dataset.fontName || e.target.tagName != 'DIV')
return;
var fontName = e.target.dataset.fontName;
var selects = document.getElementsByTagName('input');
for (var i = 0; i < selects.length; ++i) {
var select = selects[i];
if (select.dataset.fontName != fontName) continue;
select.checked = !select.checked;
selectFont(fontName, select.checked);
select.scrollIntoView();
}
}
return {
// Poperties/functions needed by PDFBug.
id: 'FontInspector',
name: 'Font Inspector',
panel: null,
manager: null,
init: function init() {
var panel = this.panel;
panel.setAttribute('style', 'padding: 5px;');
var tmp = document.createElement('button');
tmp.addEventListener('click', resetSelection);
tmp.textContent = 'Refresh';
panel.appendChild(tmp);
fonts = document.createElement('div');
panel.appendChild(fonts);
},
enabled: false,
get active() {
return active;
},
set active(value) {
active = value;
if (active) {
document.body.addEventListener('click', textLayerClick, true);
resetSelection();
} else {
document.body.removeEventListener('click', textLayerClick, true);
removeSelection();
}
},
// FontInspector specific functions.
fontAdded: function fontAdded(fontObj, url) {
function properties(obj, list) {
var moreInfo = document.createElement('table');
for (var i = 0; i < list.length; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
td1.textContent = list[i];
tr.appendChild(td1);
var td2 = document.createElement('td');
td2.textContent = obj[list[i]].toString();
tr.appendChild(td2);
moreInfo.appendChild(tr);
}
return moreInfo;
}
var moreInfo = properties(fontObj, ['name', 'type']);
var m = /url\(['"]?([^\)"']+)/.exec(url);
var fontName = fontObj.loadedName;
var font = document.createElement('div');
var name = document.createElement('span');
name.textContent = fontName;
var download = document.createElement('a');
download.href = m[1];
download.textContent = 'Download';
var logIt = document.createElement('a');
logIt.href = '';
logIt.textContent = 'Log';
logIt.addEventListener('click', function(event) {
event.preventDefault();
console.log(fontObj);
});
var select = document.createElement('input');
select.setAttribute('type', 'checkbox');
select.dataset.fontName = fontName;
select.addEventListener('click', (function(select, fontName) {
return (function() {
selectFont(fontName, select.checked);
});
})(select, fontName));
font.appendChild(select);
font.appendChild(name);
font.appendChild(document.createTextNode(' '));
font.appendChild(download);
font.appendChild(document.createTextNode(' '));
font.appendChild(logIt);
font.appendChild(moreInfo);
fonts.appendChild(font);
// Somewhat of a hack, should probably add a hook for when the text layer
// is done rendering.
setTimeout(function() {
if (this.active)
resetSelection();
}.bind(this), 2000);
}
};
})();
// Manages all the page steppers.
var StepperManager = (function StepperManagerClosure() {
var steppers = [];
var stepperDiv = null;
var stepperControls = null;
var stepperChooser = null;
var breakPoints = {};
return {
// Poperties/functions needed by PDFBug.
id: 'Stepper',
name: 'Stepper',
panel: null,
manager: null,
init: function init() {
var self = this;
this.panel.setAttribute('style', 'padding: 5px;');
stepperControls = document.createElement('div');
stepperChooser = document.createElement('select');
stepperChooser.addEventListener('change', function(event) {
self.selectStepper(this.value);
});
stepperControls.appendChild(stepperChooser);
stepperDiv = document.createElement('div');
this.panel.appendChild(stepperControls);
this.panel.appendChild(stepperDiv);
if (sessionStorage.getItem('pdfjsBreakPoints'))
breakPoints = JSON.parse(sessionStorage.getItem('pdfjsBreakPoints'));
},
enabled: false,
active: false,
// Stepper specific functions.
create: function create(pageIndex) {
var debug = document.createElement('div');
debug.id = 'stepper' + pageIndex;
debug.setAttribute('hidden', true);
debug.className = 'stepper';
stepperDiv.appendChild(debug);
var b = document.createElement('option');
b.textContent = 'Page ' + (pageIndex + 1);
b.value = pageIndex;
stepperChooser.appendChild(b);
var initBreakPoints = breakPoints[pageIndex] || [];
var stepper = new Stepper(debug, pageIndex, initBreakPoints);
steppers.push(stepper);
if (steppers.length === 1)
this.selectStepper(pageIndex, false);
return stepper;
},
selectStepper: function selectStepper(pageIndex, selectPanel) {
if (selectPanel)
this.manager.selectPanel(1);
for (var i = 0; i < steppers.length; ++i) {
var stepper = steppers[i];
if (stepper.pageIndex == pageIndex)
stepper.panel.removeAttribute('hidden');
else
stepper.panel.setAttribute('hidden', true);
}
var options = stepperChooser.options;
for (var i = 0; i < options.length; ++i) {
var option = options[i];
option.selected = option.value == pageIndex;
}
},
saveBreakPoints: function saveBreakPoints(pageIndex, bps) {
breakPoints[pageIndex] = bps;
sessionStorage.setItem('pdfjsBreakPoints', JSON.stringify(breakPoints));
}
};
})();
// The stepper for each page's IRQueue.
var Stepper = (function StepperClosure() {
function Stepper(panel, pageIndex, initialBreakPoints) {
this.panel = panel;
this.len;
this.breakPoint = 0;
this.nextBreakPoint = null;
this.pageIndex = pageIndex;
this.breakPoints = initialBreakPoints;
this.currentIdx = -1;
}
Stepper.prototype = {
init: function init(IRQueue) {
// Shorter way to create element and optionally set textContent.
function c(tag, textContent) {
var d = document.createElement(tag);
if (textContent)
d.textContent = textContent;
return d;
}
var panel = this.panel;
this.len = IRQueue.fnArray.length;
var content = c('div', 'c=continue, s=step');
var table = c('table');
content.appendChild(table);
table.cellSpacing = 0;
var headerRow = c('tr');
table.appendChild(headerRow);
headerRow.appendChild(c('th', 'Break'));
headerRow.appendChild(c('th', 'Idx'));
headerRow.appendChild(c('th', 'fn'));
headerRow.appendChild(c('th', 'args'));
for (var i = 0; i < IRQueue.fnArray.length; i++) {
var line = c('tr');
line.className = 'line';
line.dataset.idx = i;
table.appendChild(line);
var checked = this.breakPoints.indexOf(i) != -1;
var args = IRQueue.argsArray[i] ? IRQueue.argsArray[i] : [];
var breakCell = c('td');
var cbox = c('input');
cbox.type = 'checkbox';
cbox.className = 'points';
cbox.checked = checked;
var self = this;
cbox.onclick = (function(x) {
return function() {
if (this.checked)
self.breakPoints.push(x);
else
self.breakPoints.splice(self.breakPoints.indexOf(x), 1);
StepperManager.saveBreakPoints(self.pageIndex, self.breakPoints);
}
})(i);
breakCell.appendChild(cbox);
line.appendChild(breakCell);
line.appendChild(c('td', i.toString()));
line.appendChild(c('td', IRQueue.fnArray[i]));
line.appendChild(c('td', args.join(', ')));
}
panel.appendChild(content);
var self = this;
},
getNextBreakPoint: function getNextBreakPoint() {
this.breakPoints.sort(function(a, b) { return a - b; });
for (var i = 0; i < this.breakPoints.length; i++) {
if (this.breakPoints[i] > this.currentIdx)
return this.breakPoints[i];
}
return null;
},
breakIt: function breakIt(idx, callback) {
StepperManager.selectStepper(this.pageIndex, true);
var self = this;
var dom = document;
self.currentIdx = idx;
var listener = function(e) {
switch (e.keyCode) {
case 83: // step
dom.removeEventListener('keydown', listener, false);
self.nextBreakPoint = self.currentIdx + 1;
self.goTo(-1);
callback();
break;
case 67: // continue
dom.removeEventListener('keydown', listener, false);
var breakPoint = self.getNextBreakPoint();
self.nextBreakPoint = breakPoint;
self.goTo(-1);
callback();
break;
}
}
dom.addEventListener('keydown', listener, false);
self.goTo(idx);
},
goTo: function goTo(idx) {
var allRows = this.panel.getElementsByClassName('line');
for (var x = 0, xx = allRows.length; x < xx; ++x) {
var row = allRows[x];
if (row.dataset.idx == idx) {
row.style.backgroundColor = 'rgb(251,250,207)';
row.scrollIntoView();
} else {
row.style.backgroundColor = null;
}
}
}
};
return Stepper;
})();
var Stats = (function Stats() {
var stats = [];
function clear(node) {
while (node.hasChildNodes())
node.removeChild(node.lastChild);
}
function getStatIndex(pageNumber) {
for (var i = 0, ii = stats.length; i < ii; ++i)
if (stats[i].pageNumber === pageNumber)
return i;
return false;
}
return {
// Poperties/functions needed by PDFBug.
id: 'Stats',
name: 'Stats',
panel: null,
manager: null,
init: function init() {
this.panel.setAttribute('style', 'padding: 5px;');
PDFJS.enableStats = true;
},
enabled: false,
active: false,
// Stats specific functions.
add: function(pageNumber, stat) {
if (!stat)
return;
var statsIndex = getStatIndex(pageNumber);
if (statsIndex !== false) {
var b = stats[statsIndex];
this.panel.removeChild(b.div);
stats.splice(statsIndex, 1);
}
var wrapper = document.createElement('div');
wrapper.className = 'stats';
var title = document.createElement('div');
title.className = 'title';
title.textContent = 'Page: ' + pageNumber;
var statsDiv = document.createElement('div');
statsDiv.textContent = stat.toString();
wrapper.appendChild(title);
wrapper.appendChild(statsDiv);
stats.push({ pageNumber: pageNumber, div: wrapper });
stats.sort(function(a, b) { return a.pageNumber - b.pageNumber});
clear(this.panel);
for (var i = 0, ii = stats.length; i < ii; ++i)
this.panel.appendChild(stats[i].div);
}
};
})();
// Manages all the debugging tools.
var PDFBug = (function PDFBugClosure() {
var panelWidth = 300;
var buttons = [];
var activePanel = null;
return {
tools: [
FontInspector,
StepperManager,
Stats
],
enable: function(ids) {
var all = false, tools = this.tools;
if (ids.length === 1 && ids[0] === 'all')
all = true;
for (var i = 0; i < tools.length; ++i) {
var tool = tools[i];
if (all || ids.indexOf(tool.id) !== -1)
tool.enabled = true;
}
if (!all) {
// Sort the tools by the order they are enabled.
tools.sort(function(a, b) {
var indexA = ids.indexOf(a.id);
indexA = indexA < 0 ? tools.length : indexA;
var indexB = ids.indexOf(b.id);
indexB = indexB < 0 ? tools.length : indexB;
return indexA - indexB;
});
}
},
init: function init() {
/*
* Basic Layout:
* PDFBug
* Controls
* Panels
* Panel
* Panel
* ...
*/
var ui = document.createElement('div');
ui.id = 'PDFBug';
var controls = document.createElement('div');
controls.setAttribute('class', 'controls');
ui.appendChild(controls);
var panels = document.createElement('div');
panels.setAttribute('class', 'panels');
ui.appendChild(panels);
var container = document.getElementById('viewerContainer');
container.appendChild(ui);
container.style.right = panelWidth + 'px';
// Initialize all the debugging tools.
var tools = this.tools;
for (var i = 0; i < tools.length; ++i) {
var tool = tools[i];
var panel = document.createElement('div');
var panelButton = document.createElement('button');
panelButton.textContent = tool.name;
var self = this;
panelButton.addEventListener('click', (function(selected) {
return function(event) {
event.preventDefault();
self.selectPanel(selected);
};
})(i));
controls.appendChild(panelButton);
panels.appendChild(panel);
tool.panel = panel;
tool.manager = this;
if (tool.enabled)
tool.init();
else
panel.textContent = tool.name + ' is disabled. To enable add ' +
' "' + tool.id + '" to the pdfBug parameter ' +
'and refresh (seperate multiple by commas).';
buttons.push(panelButton);
}
this.selectPanel(0);
},
selectPanel: function selectPanel(index) {
if (index === activePanel)
return;
activePanel = index;
var tools = this.tools;
for (var j = 0; j < tools.length; ++j) {
if (j == index) {
buttons[j].setAttribute('class', 'active');
tools[j].active = true;
tools[j].panel.removeAttribute('hidden');
} else {
buttons[j].setAttribute('class', '');
tools[j].active = false;
tools[j].panel.setAttribute('hidden', 'true');
}
}
}
};
})();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 244 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 512 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 237 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 417 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 353 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 344 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 474 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 503 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 300 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 228 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 B

View File

@@ -1,322 +0,0 @@
/* Copyright (c) 2011-2012 Fabien Cazenave, Mozilla.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/*
Additional modifications for PDF.js project:
- Loading resources from <script type='application/l10n'>;
- Disabling language initialization on page loading;
- Add fallback argument to the translateString.
*/
'use strict';
(function(window) {
var gL10nData = {};
var gTextData = '';
var gLanguage = '';
// parser
function evalString(text) {
return text.replace(/\\\\/g, '\\')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\b/g, '\b')
.replace(/\\f/g, '\f')
.replace(/\\{/g, '{')
.replace(/\\}/g, '}')
.replace(/\\"/g, '"')
.replace(/\\'/g, "'");
}
function parseProperties(text, lang) {
var reBlank = /^\s*|\s*$/;
var reComment = /^\s*#|^\s*$/;
var reSection = /^\s*\[(.*)\]\s*$/;
var reImport = /^\s*@import\s+url\((.*)\)\s*$/i;
// parse the *.properties file into an associative array
var currentLang = '*';
var supportedLang = [];
var skipLang = false;
var data = [];
var match = '';
var entries = text.replace(reBlank, '').split(/[\r\n]+/);
for (var i = 0; i < entries.length; i++) {
var line = entries[i];
// comment or blank line?
if (reComment.test(line))
continue;
// section start?
if (reSection.test(line)) {
match = reSection.exec(line);
currentLang = match[1];
skipLang = (currentLang != lang) && (currentLang != '*') &&
(currentLang != lang.substring(0, 2));
continue;
} else if (skipLang) {
continue;
}
// @import rule?
if (reImport.test(line)) {
match = reImport.exec(line);
}
// key-value pair
var tmp = line.split('=');
if (tmp.length > 1)
data[tmp[0]] = evalString(tmp[1]);
}
// find the attribute descriptions, if any
for (var key in data) {
var id, prop, index = key.lastIndexOf('.');
if (index > 0) { // attribute
id = key.substring(0, index);
prop = key.substr(index + 1);
} else { // textContent, could be innerHTML as well
id = key;
prop = 'textContent';
}
if (!gL10nData[id])
gL10nData[id] = {};
gL10nData[id][prop] = data[key];
}
}
function parse(text, lang) {
gTextData += text;
// we only support *.properties files at the moment
return parseProperties(text, lang);
}
// load and parse the specified resource file
function loadResource(href, lang, onSuccess, onFailure) {
var xhr = new XMLHttpRequest();
xhr.open('GET', href, true);
xhr.overrideMimeType('text/plain; charset=utf-8');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 0) {
parse(xhr.responseText, lang);
if (onSuccess)
onSuccess();
} else {
if (onFailure)
onFailure();
}
}
};
xhr.send(null);
}
// load and parse all resources for the specified locale
function loadLocale(lang, callback) {
clear();
// check all <link type="application/l10n" href="..." /> nodes
// and load the resource files
var langLinks = document.querySelectorAll('link[type="application/l10n"]');
var langLinksCount = langLinks.length;
var langScripts = document.querySelectorAll('script[type="application/l10n"]');
var langScriptCount = langScripts.length;
var langCount = langLinksCount + langScriptCount;
// start the callback when all resources are loaded
var onResourceLoaded = null;
var gResourceCount = 0;
onResourceLoaded = function() {
gResourceCount++;
if (gResourceCount >= langCount) {
// execute the [optional] callback
if (callback)
callback();
// fire a 'localized' DOM event
var evtObject = document.createEvent('Event');
evtObject.initEvent('localized', false, false);
evtObject.language = lang;
window.dispatchEvent(evtObject);
}
}
// load all resource files
function l10nResourceLink(link) {
var href = link.href;
var type = link.type;
this.load = function(lang, callback) {
var applied = lang;
loadResource(href, lang, callback, function() {
console.warn(href + ' not found.');
applied = '';
});
return applied; // return lang if found, an empty string if not found
};
}
gLanguage = lang;
for (var i = 0; i < langLinksCount; i++) {
var resource = new l10nResourceLink(langLinks[i]);
var rv = resource.load(lang, onResourceLoaded);
if (rv != lang) // lang not found, used default resource instead
gLanguage = '';
}
for (var i = 0; i < langScriptCount; i++) {
var scriptText = langScripts[i].text;
parse(scriptText, lang);
onResourceLoaded();
}
}
// fetch an l10n object, warn if not found
function getL10nData(key) {
var data = gL10nData[key];
if (!data)
console.warn('[l10n] #' + key + ' missing for [' + gLanguage + ']');
return data;
}
// replace {{arguments}} with their values
function substArguments(str, args) {
var reArgs = /\{\{\s*([a-zA-Z\.]+)\s*\}\}/;
var match = reArgs.exec(str);
while (match) {
if (!match || match.length < 2)
return str; // argument key not found
var arg = match[1];
var sub = '';
if (arg in args) {
sub = args[arg];
} else if (arg in gL10nData) {
sub = gL10nData[arg].textContent;
} else {
console.warn('[l10n] could not find argument {{' + arg + '}}');
return str;
}
str = str.substring(0, match.index) + sub +
str.substr(match.index + match[0].length);
match = reArgs.exec(str);
}
return str;
}
// translate a string
function translateString(key, args, fallback) {
var data = getL10nData(key);
if (!data && fallback)
data = {textContent: fallback};
if (!data)
return '{{' + key + '}}';
return substArguments(data.textContent, args);
}
// translate an HTML element
function translateElement(element) {
if (!element || !element.dataset)
return;
// get the related l10n object
var key = element.dataset.l10nId;
var data = getL10nData(key);
if (!data)
return;
// get arguments (if any)
// TODO: more flexible parser?
var args;
if (element.dataset.l10nArgs) try {
args = JSON.parse(element.dataset.l10nArgs);
} catch (e) {
console.warn('[l10n] could not parse arguments for #' + key + '');
}
// translate element
// TODO: security check?
for (var k in data)
element[k] = substArguments(data[k], args);
}
// translate an HTML subtree
function translateFragment(element) {
element = element || document.querySelector('html');
// check all translatable children (= w/ a `data-l10n-id' attribute)
var children = element.querySelectorAll('*[data-l10n-id]');
var elementCount = children.length;
for (var i = 0; i < elementCount; i++)
translateElement(children[i]);
// translate element itself if necessary
if (element.dataset.l10nId)
translateElement(element);
}
// clear all l10n data
function clear() {
gL10nData = {};
gTextData = '';
gLanguage = '';
}
/*
// load the default locale on startup
window.addEventListener('DOMContentLoaded', function() {
var lang = navigator.language;
if (navigator.mozSettings) {
var req = navigator.mozSettings.getLock().get('language.current');
req.onsuccess = function() {
loadLocale(req.result['language.current'] || lang, translateFragment);
};
req.onerror = function() {
loadLocale(lang, translateFragment);
};
} else {
loadLocale(lang, translateFragment);
}
});
*/
// Public API
document.mozL10n = {
// get a localized string
get: translateString,
// get|set the document language and direction
get language() {
return {
// get|set the document language (ISO-639-1)
get code() { return gLanguage; },
set code(lang) { loadLocale(lang, translateFragment); },
// get the direction (ltr|rtl) of the current language
get direction() {
// http://www.w3.org/International/questions/qa-scripts
// Arabic, Hebrew, Farsi, Pashto, Urdu
var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
return (rtlList.indexOf(gLanguage) >= 0) ? 'rtl' : 'ltr';
}
};
}
};
})(this);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -76,18 +76,7 @@
{% endif %}
<button data="{{ SITE_ROOT }}repo/{{ repo.id }}/{{ obj_id }}/?file_name={{ file_name }}&op=download" id="download">{% trans "Download"%}</button>
</div>
<div id="file-view">
{% if filetype == 'Text' or filetype == 'Sf' %}
{% ifnotequal file_content None %}
{% if filetype == 'Text' %}
<textarea id="docu-view" class="vh">{{ file_content|escape }}</textarea>
{% else %}
<div id="sf" class="article">{{ file_content|safe }}</div>
{% endif %}
{% endifnotequal %}
{% endif %}
</div>
{% include 'snippets/file_content_html.html' %}
</div>
<form id="link-send-form" action="" method="post" class="hide">
@@ -402,9 +391,10 @@ $('#file-op .history').click(function () {
location.href = $(this).data('url');
});
{% include "snippets/repo_file_get.html" %}
//places file_content_js here so that op-btns can work before file content is fully loaded.
{% include "snippets/file_content_js.html" %}
//bottom bar: after repo_file_get
//bottom bar
{% include "snippets/bottom_bar.html" %}
{% if request.user.is_authenticated %}
$('#main-panel').css({'margin-bottom':0});

View File

@@ -65,17 +65,7 @@
{% endif %}
<button data="{{ SITE_ROOT }}repo/{{ repo.id }}/{{ obj_id }}/?file_name={{ file_name }}&op=download" id="download">{% trans "Download"%}</button>
</div>
<div id="file-view">
{% if filetype == 'Text' or filetype == 'Sf' %}
{% ifnotequal file_content None %}
{% if filetype == 'Text' %}
<textarea id="docu-view" class="vh">{{ file_content|escape }}</textarea>
{% else %}
<div id="sf" class="article">{{ file_content|safe }}</div>
{% endif %}
{% endifnotequal %}
{% endif %}
</div>
{% include 'snippets/file_content_html.html' %}
</div>
{% endblock %}
@@ -86,7 +76,7 @@ $('#view-original, #download').click(function() {
window.open($(this).attr('data'));
});
{% include "snippets/repo_file_get.html" %}
{% include "snippets/file_content_js.html" %}
{% if page_from == 'file_history' or page_from == 'recycle' %}
$('#back').click(function() {

View File

@@ -21,17 +21,7 @@
<button data="{{ SITE_ROOT }}repo/{{ repo.id }}/{{ obj_id }}/?file_name={{ file_name }}&op=download&t={{ shared_token }}" id="download">{% trans "Download" %}</button>
</div>
<div id="file-view">
{% if filetype == 'Text' or filetype == 'Sf' %}
{% ifnotequal file_content None %}
{% if filetype == 'Text' %}
<textarea id="docu-view" class="vh">{{ file_content|escape }}</textarea>
{% else %}
<div id="sf" class="article">{{ file_content|safe }}</div>
{% endif %}
{% endifnotequal %}
{% endif %}
</div>
{% include 'snippets/file_content_html.html' %}
</div>
{% endblock %}
@@ -41,6 +31,6 @@
$('#view-original, #download').click(function() {
window.open($(this).attr('data'));
});
{% include "snippets/repo_file_get.html" %}
{% include "snippets/file_content_js.html" %}
</script>
{% endblock %}

View File

@@ -0,0 +1,25 @@
{%comment%}
content of files that can be viewed online shows here.
For details please refer to 'snippets/file_content_js.html'.
{%endcomment%}
<div id="file-view">
{% if not err %}
{% if filetype == 'Text' or filetype == 'Sf' %}
{% ifnotequal file_content None %}
{% if filetype == 'Text' %}
<textarea id="docu-view" class="vh">{{ file_content|escape }}</textarea>
{% else %}
<div id="sf" class="article">{{ file_content|safe }}</div>
{% endif %}
{% endifnotequal %}
{% endif %}
{% if filetype == 'Image' %}
<img src="{{ raw_path }}" alt="{{ u_filename}}" id="image-view" />
{% endif %}
{% else %}
<div id="file-view-tip">
<p class="error">{{ err }}</p>
</div>
{% endif %}
</div>

View File

@@ -0,0 +1,111 @@
{% load i18n %}
{% if not err %}
{% if filetype == 'Text' %}
{% ifnotequal file_content None %}
var editor = CodeMirror.fromTextArea($('#docu-view')[0], {
{% include 'snippets/editor_set_mode.html' %}
theme: 'default',
indentUnit: 4,
{% if fileext != 'txt' and fileext != 'text' %}
lineNumbers: true,
{% endif %}
lineWrapping: true,
readOnly: true
});
{% endifnotequal %}
{% endif %}
{% if filetype == 'Image' %}
window.onload = function() {
if ($('#image-view').width() > $('#file-view').width()) {
$('#image-view').css('width', $('#file-view').width() - 4);
}
}
{% endif %}
{% if filetype == 'SVG' %}
if (!$.browser.mozilla && !$.browser.safari && !($.browser.msie && parseInt($.browser.version) > 8)) {
$('#file-view').html('<div id="file-view-tip"><p>{% trans "To view it online, you can use firefox, chrome or IE 9." %}</p></div>');
} else {
$('#file-view').html('<iframe src="{{ raw_path }}" frameborder="0" id="svg-view"></iframe>');
}
{% endif %}
{% if filetype == 'Markdown' %}
{% ifnotequal file_content None %}
var converter = new Showdown.converter();
$('#file-view').html('<div id="md-view" class="article">' + converter.makeHtml('{{ file_content|escapejs }}') + '</div>');
$('#md-view').children(':first').css('margin-top', '0');
{% endifnotequal %}
{% endif %}
{% if filetype == 'Document' or filetype == 'PDF' %}
$('#file-view').html('<div id="flash"></div>');
function load_flexpaper() {
var swf_url = '{{ DOCUMENT_CONVERTOR_ROOT }}swf/{{ obj_id }}';
var fp = new FlexPaperViewer(
'{{MEDIA_URL}}flexpaper/FlexPaperViewer',
'flash', { config : {
SwfFile : escape(swf_url),
Scale : 1.0,
ZoomTransition : 'easeOut',
ZoomTime : 0.5,
ZoomInterval : 0.2,
FitPageOnLoad : false,
FitWidthOnLoad : true,
FullScreenAsMaxWindow : false,
ProgressiveLoading : false,
MinZoomSize : 0.2,
MaxZoomSize : 5,
SearchMatchAll : false,
InitViewMode : 'Portrait',
PrintPaperAsBitmap : false,
ViewModeToolsVisible : true,
ZoomToolsVisible : true,
NavToolsVisible : true,
CursorToolsVisible : true,
SearchToolsVisible : true,
localeChain: 'en_US'
}});
}
{% if swf_exists %}
load_flexpaper();
{% else %}
function check_status () {
$.ajax({
url: '{{ DOCUMENT_CONVERTOR_ROOT }}status?file_id={{ obj_id }}',
cache: false,
dataType: 'jsonp',
jsonpCallback: 'xx',
crossDomain: true,
success: function(data) {
if (data['error']) {
$('#file-view').html('<div id="file-view-tip"><p class="error">' + data['error'] + '</p></div>');
} else {
var status = data['status'];
if (status == 'QUEUED' || status == 'PROCESSING') {
setTimeout(check_status, 2000);
} else {
load_flexpaper();
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
var jsonVal = jQuery.parseJSON(xhr.responseText);
$('#file-view').html('<div id="file-view-tip"><p class="error">' + jsonVal['error'] + '</p></div>');
}
});
}
check_status();
{% endif %}
{% endif %}
{% if filetype == 'Unknown' %}
$('#file-view').html('<div id="file-view-tip"><p>{% trans "This type of file cannot be viewed online." %}</p></div>');
{% endif %}
{% endif %}

View File

@@ -1,14 +1,7 @@
{% if filetype == 'Text' %}
<script type="text/javascript" src="{{MEDIA_URL}}codemirror/codemirror-2.36.js"></script>
{% endif %}
{% if filetype == 'PDF' %}
{% if pdf_use_flash %}
<script type="text/javascript" src="{{MEDIA_URL}}flexpaper/js/flexpaper_flash.js"></script>
{% else %}
<script type="text/javascript" src="{{MEDIA_URL}}js/pdf.js"></script>
{% endif %}
{% endif %}
{% if filetype == 'Document' %}
{% if filetype == 'Document' or filetype == 'PDF' %}
<script type="text/javascript" src="{{MEDIA_URL}}flexpaper/js/flexpaper_flash.js"></script>
{% endif %}
{% if filetype == 'Markdown' %}

View File

@@ -8,11 +8,14 @@
<style type="text/css">
.CodeMirror-scroll { min-height:400px; }
.CodeMirror { margin-bottom:40px; }
{% if fileext == 'txt' or fileext == 'text' %}
.CodeMirror {
width:624px;
padding:40px 96px;
}
{% endif %}
{% if fileext == 'txt' or fileext == 'text' %}
.CodeMirror { width:624px; padding:40px 96px; }
{% endif %}
</style>
{% endif %}
{% if filetype == 'Image' %}
<style type="text/css">
#file-view { text-align:center; padding:30px 0; }
</style>
{% endif %}

View File

@@ -1,177 +0,0 @@
{% load i18n %}
{% if filetype == 'Text' %}
{% ifnotequal file_content None %}
var editor = CodeMirror.fromTextArea($('#docu-view')[0], {
{% include 'snippets/editor_set_mode.html' %}
theme: 'default',
indentUnit: 4,
{% if fileext != 'txt' and fileext != 'text' %}
lineNumbers: true,
{% endif %}
lineWrapping: true,
readOnly: true
});
{% endifnotequal %}
{% if err %}
$('#file-view').html('<div id="file-view-tip"><p class="error">{{ err }}</p></div>');
{% endif %}
{% endif %}
{% if filetype == 'Image' %}
$('#file-view').html('<img src="{{ raw_path }}" alt="{{ u_filename}}" id="image-view" />').css({'text-align':'center', 'padding':'30px 0'});
window.onload = function() {
if ($('#image-view').width() > $('#file-view').width()) {
$('#image-view').css('width', $('#file-view').width() - 4);
}
}
{% endif %}
{% if filetype == 'SVG' %}
if (!$.browser.mozilla && !$.browser.safari && !($.browser.msie && parseInt($.browser.version) > 8)) {
$('#file-view').html('<p>{% trans "To view it online, you can use firefox, chrome or IE 9." %}</p>').addClass('file-view-tip');
} else {
$('#file-view').html('<div><iframe src="{{ raw_path }}" frameborder="0" id="svg-view"></iframe></div>');
}
{% endif %}
{% if filetype == 'PDF' and not pdf_use_flash %}
PDFJS.workerSrc = '{{MEDIA_URL}}js/pdf.js';
$('#file-view').html('<div id="pdf"><div id="pdf-op-bar" class="vh"><span id="pdf-page-left"><button id="prev">{% trans "Previous" %}</button></span>{% blocktrans %}<span id="pdf-page"><label for="page-number">Page</label> <input type="number" id="page-number" value="1" min="1"></input> / <span id="page-nums"></span></span>{% endblocktrans %}<span id="pdf-page-right"><button id="next" style="margin-right:15px;">{% trans "Next" %}</button><button id="full-screen">{% trans "Full Screen" %}</button></span></div><img src="{{ MEDIA_URL }}pdf_full_view/images/loading-icon.gif" alt="{% trans "loading..." %}" id="pdf-loading" style="margin:20px 0;" /><canvas data="{{ raw_path }}" id="pdf-view" class="hide"></canvas></div>').css({'text-align':'center'});
$('#pdf-page-left, #pdf-page-right').css('display', 'inline-block');
$('#pdf-page-left').css({'text-align':'right', 'width': $('#pdf-page-right').width()});
$('#pdf-op-bar').removeClass('vh');
var seahub_getPage = function (pdf, page_number) {
pdf.getPage(page_number).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = $('#pdf-view')[0];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
};
PDFJS.getDocument($('#pdf-view').attr('data')).then(function(pdf) {
$('#page-nums').html(pdf.numPages);
$('#page-number').attr('max', pdf.numPages).css('width', String(pdf.numPages).length * 6 + 10);
seahub_getPage(pdf, 1);
$('#pdf-loading').addClass('hide');
$('#pdf-view').removeClass('hide');
$('#page-number').change(function() {
seahub_getPage(pdf, $(this).val());
});
$('#prev').click(function() {
var current = $('#page-number').val();
if (current > 1) {
seahub_getPage(pdf, --current);
$('#page-number').val(current);
}
});
$('#next').click(function() {
var current = $('#page-number').val();
if (current < pdf.numPages) {
seahub_getPage(pdf, ++current);
$('#page-number').val(current);
}
});
$('#full-screen').click(function() {
window.open('{{ SITE_ROOT }}pdf_full_view/?repo_id={{ repo.id }}&obj_id={{obj_id}}&file_name=' + e('{{ file_name }}'));
});
});
{% endif %}
{% if filetype == 'Markdown' %}
{% ifnotequal file_content None %}
var converter = new Showdown.converter();
$('#file-view').html('<div id="md-view" class="article">' + converter.makeHtml('{{ file_content|escapejs }}') + '</div>');
$('#md-view').children(':first').css('margin-top', '0');
{% endifnotequal %}
{% if err %}
$('#file-view').html('<div id="file-view-tip"><p class="error">{{ err }}</p></div>');
{% endif %}
{% endif %}
{% if filetype == 'Unknown' %}
$('#file-view').html('<div id="file-view-tip"><p>{% trans "This type of file cannot be viewed online." %}</p></div>');
{% endif %}
{% if filetype == 'Document' or filetype == 'PDF' and pdf_use_flash %}
{% if err %}
$('#file-view').html('<div id="file-view-tip"><p class="error">{{ err }}</p></div>');
{% else %}
$('#file-view').html('<div id="flash"></div>');
function load_flexpaper() {
var swf_url = '{{ DOCUMENT_CONVERTOR_ROOT }}swf/{{ obj_id }}';
var fp = new FlexPaperViewer(
'{{MEDIA_URL}}flexpaper/FlexPaperViewer',
'flash', { config : {
SwfFile : escape(swf_url),
Scale : 1.0,
ZoomTransition : 'easeOut',
ZoomTime : 0.5,
ZoomInterval : 0.2,
FitPageOnLoad : false,
FitWidthOnLoad : true,
FullScreenAsMaxWindow : false,
ProgressiveLoading : false,
MinZoomSize : 0.2,
MaxZoomSize : 5,
SearchMatchAll : false,
InitViewMode : 'Portrait',
PrintPaperAsBitmap : false,
ViewModeToolsVisible : true,
ZoomToolsVisible : true,
NavToolsVisible : true,
CursorToolsVisible : true,
SearchToolsVisible : true,
localeChain: 'en_US'
}});
}
{% if swf_exists %}
load_flexpaper();
{% else %}
function check_status () {
url = '{{ DOCUMENT_CONVERTOR_ROOT }}status';
url += '?file_id={{ obj_id }}';
$.ajax({
url: url,
cache: false,
dataType: 'jsonp',
jsonpCallback: 'xx',
crossDomain: true,
success: function(data) {
if (data['error']) {
$('#file-view').html('<div id="file-view-tip"><p class="error">' + data['error'] + '</p></div>');
} else {
var status = data['status'];
if (status == 'QUEUED' || status == 'PROCESSING') {
setTimeout(check_status, 2000);
} else {
load_flexpaper();
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
var jsonVal = jQuery.parseJSON(xhr.responseText);
$('#file-view').html('<div id="file-view-tip"><p class="error">' + jsonVal['error'] + '</p></div>');
}
});
}
check_status();
{% endif %}
{% endif %}
{% endif %}

View File

@@ -62,7 +62,6 @@ urlpatterns = patterns('',
(r'^publicrepo/create/$', public_repo_create),
(r'^events/$', events),
(r'^file_comment/$', file_comment),
(r'^pdf_full_view/$', pdf_full_view),
(r'^pubinfo/$', pubinfo),
url(r'^i18n/$', i18n, name='i18n'),
(r'^download/repo/$', repo_download),

View File

@@ -1232,15 +1232,10 @@ def repo_view_file(request, repo_id):
err = ''
file_content = ''
swf_exists = False
pdf_use_flash = False
if filetype == 'Text' or filetype == 'Markdown' or filetype == 'Sf':
err, file_content, encoding, newline_mode = repo_file_get(raw_path)
elif filetype == 'Document':
elif filetype == 'Document' or filetype == 'PDF':
err, swf_exists = flash_prepare(raw_path, obj_id, fileext)
elif filetype == 'PDF':
pdf_use_flash = use_flash_for_pdf(request)
if pdf_use_flash:
err, swf_exists = flash_prepare(raw_path, obj_id, 'pdf')
if view_history:
return render_to_response('history_file_view.html', {
@@ -1259,7 +1254,6 @@ def repo_view_file(request, repo_id):
'err': err,
'file_content': file_content,
'swf_exists': swf_exists,
'pdf_use_flash': pdf_use_flash,
'DOCUMENT_CONVERTOR_ROOT': DOCUMENT_CONVERTOR_ROOT,
'page_from': page_from,
'basedir': basedir,
@@ -1344,7 +1338,6 @@ def repo_view_file(request, repo_id):
'comments': comments,
'comment_open':comment_open,
'swf_exists': swf_exists,
'pdf_use_flash': pdf_use_flash,
'DOCUMENT_CONVERTOR_ROOT': DOCUMENT_CONVERTOR_ROOT,
'contributors': contributors,
'latest_contributor': latest_contributor,
@@ -1449,19 +1442,6 @@ def repo_file_get(raw_path):
newline_mode = 'windows'
return err, file_content, encoding, newline_mode
def pdf_full_view(request):
repo_id = request.GET.get('repo_id', '')
obj_id = request.GET.get('obj_id', '')
file_name = request.GET.get('file_name', '')
token = seafserv_rpc.web_get_access_token(repo_id, obj_id,
'view', request.user.username)
file_src = gen_file_get_url(token, file_name)
return render_to_response('pdf_full_view.html', {
'file_src': file_src,
}, context_instance=RequestContext(request))
def update_file_after_edit(request, repo_id):
content_type = 'application/json; charset=utf-8'
def error_json(error_msg=_(u'Internal Error')):
@@ -2422,22 +2402,17 @@ def view_shared_file(request, token):
err = ''
file_content = ''
swf_exists = False
pdf_use_flash = False
if filetype == 'Text' or filetype == 'Markdown' or filetype == 'Sf':
err, file_content, encoding, newline_mode = repo_file_get(raw_path)
elif filetype == 'Document':
elif filetype == 'Document' or filetype == 'PDF':
err, swf_exists = flash_prepare(raw_path, obj_id, fileext)
elif filetype == 'PDF':
pdf_use_flash = use_flash_for_pdf(request)
if pdf_use_flash:
err, swf_exists = flash_prepare(raw_path, obj_id, 'pdf')
# Increase file shared link view_cnt, this operation should be atomic
fileshare = FileShare.objects.get(token=token)
fileshare.view_cnt = F('view_cnt') + 1
fileshare.save()
return render_to_response('view_shared_file.html', {
return render_to_response('shared_file_view.html', {
'repo': repo,
'obj_id': obj_id,
'path': path,
@@ -2451,7 +2426,6 @@ def view_shared_file(request, token):
'err': err,
'file_content': file_content,
'swf_exists': swf_exists,
'pdf_use_flash': pdf_use_flash,
'DOCUMENT_CONVERTOR_ROOT': DOCUMENT_CONVERTOR_ROOT,
}, context_instance=RequestContext(request))
@@ -2473,17 +2447,6 @@ def flash_prepare(raw_path, obj_id, doctype):
else:
return None, ret_dict['exists']
def use_flash_for_pdf(request):
"""Only use pdfjs to display PDF in Firefox. For IE/Chrome/Others, use flash.
"""
ua = request.META.get('HTTP_USER_AGENT', '')
if 'firefox' in ua.lower():
# Browser is firefox
return False
else:
return True
def demo(request):
"""
Login as demo account.