Developing...

This commit is contained in:
Oleg Korshul
2021-07-04 22:10:17 +03:00
parent 0fb91dc2f8
commit 04b9c9ae1d
21 changed files with 3702 additions and 9 deletions

View File

@ -78,8 +78,10 @@
#include "DjVuMessage.h"
#include <fcntl.h>
#if defined(WIN32) || defined(__CYGWIN32__)
#ifndef WASM_MODE
# include <io.h>
#endif
#endif
#ifdef UNIX
# ifndef HAS_MEMMAP
@ -125,6 +127,7 @@ namespace DJVU {
const char *ByteStream::EndOfFile=ERR_MSG("EOF");
#ifndef WASM_MODE
/** ByteStream interface for stdio files.
The virtual member functions #read#, #write#, #tell# and #seek# are mapped
to the well known stdio functions #fread#, #fwrite#, #ftell# and #fseek#.
@ -181,6 +184,7 @@ ByteStream::Stdio::init(FILE * const f,const char mode[],const bool closeme)
must_close=closeme;
return init(mode);
}
#endif
/** ByteStream interface managing a memory buffer.
@ -580,7 +584,7 @@ ByteStream::read32()
}
#ifndef WASM_MODE
//// CLASS ByteStream::Stdio
ByteStream::Stdio::Stdio(void)
@ -782,7 +786,7 @@ ByteStream::Stdio::seek(long offset, int whence, bool nothrow)
}
return tell();
}
#endif
@ -1001,6 +1005,7 @@ ByteStream::create(void const * const buffer, const size_t size)
return retval;
}
#ifndef WASM_MODE
GP<ByteStream>
ByteStream::create(const GURL &url,char const * const xmode)
{
@ -1161,6 +1166,31 @@ ByteStream::create(FILE * const f,char const * const mode,const bool closeme)
}
return retval;
}
#else
GP<ByteStream>
ByteStream::create(const GURL &url,char const * const xmode)
{
return NULL;
}
GP<ByteStream>
ByteStream::create(char const * const mode)
{
return NULL;
}
GP<ByteStream>
ByteStream::create(const int fd,char const * const mode,const bool closeme)
{
return NULL;
}
GP<ByteStream>
ByteStream::create(FILE * const f,char const * const mode,const bool closeme)
{
return NULL;
}
#endif
GP<ByteStream>
ByteStream::create_static(const void * buffer, size_t sz)

View File

@ -75,9 +75,11 @@ inline void * operator new(size_t, void * ptr) { return ptr; }
# include <new>
#endif
#ifndef WASM_MODE
#ifdef WIN32
#include <new.h>
#endif
#endif
//#ifdef WIN32
//# ifdef DLL_EXPORT

View File

@ -78,11 +78,6 @@
#include <string.h>
#include <stdlib.h>
// #include <stdio.h>
#ifdef WIN32
#include <tchar.h>
#include <windows.h>
#include <winreg.h>
#endif
#ifdef UNIX
#include <unistd.h>
#include <pwd.h>

View File

@ -259,7 +259,7 @@ GExceptionHandler::rethrow(void)
// This is not activated when C++ memory management
// is overidden. The overriding functions handle
// memory exceptions by themselves.
# if defined(_MSC_VER)
# if defined(_MSC_VER) && !defined(WASM_MODE)
// Microsoft is different!
static int throw_memory_error(size_t) { G_THROW(GException::outofmemory); return 0; }
static int (*old_handler)(size_t) = _set_new_handler(throw_memory_error);

View File

@ -1608,6 +1608,7 @@ GStringRep::setat(int n, char ch) const
return retval;
}
#ifndef WASM_MODE
#if defined(AUTOCONF) && defined(HAVE_VSNPRINTF)
# define USE_VSNPRINTF vsnprintf
#elif defined(WIN32) && !defined(__CYGWIN32__)
@ -1615,6 +1616,7 @@ GStringRep::setat(int n, char ch) const
#elif defined(linux)
# define USE_VSNPRINTF vsnprintf
#endif
#endif
GUTF8String &
GUTF8String::format(const char fmt[], ... )

View File

@ -115,7 +115,6 @@
#include <stdlib.h>
#include <stdarg.h>
#ifdef WIN32
# include <windows.h>
# define HAS_WCHAR 1
# define HAS_MBSTATE 1
#endif

175
DjVuFile/wasm/DjVuFile.pro Normal file
View File

@ -0,0 +1,175 @@
QT -= core gui
TARGET = djvu_common
#TEMPLATE = lib
#CONFIG += staticlib
CONFIG += console
CONFIG -= app_bundle
CONFIG -= debug_and_release debug_and_release_target
DEFINES += _LIB
DEFINES += _CRT_SECURE_NO_WARNINGS
DEFINES -= UNICODE
DEFINES -= _UNICODE
DEFINES += NOMINMAX
DEFINES += WASM_MODE
DEFINES += THREADMODEL=0
DEFINES += "UINT=unsigned int"
DEFINES += DEBUGLVL=0
DEFINES += WASM_MODE_DEBUG
CONFIG += core_windows
core_linux {
DEFINES += \
HAVE_UNISTD_H \
HAVE_MBSTATE_T \
GCONTAINER_NO_MEMBER_TEMPLATES="1" \
HAS_WCHAR \
HAVE_WCHAR_H \
UNIX \
HAVE_STDINCLUDES
}
core_mac {
DEFINES += \
HAVE_UNISTD_H \
HAVE_MBSTATE_T \
GCONTAINER_NO_MEMBER_TEMPLATES="1" \
HAS_WCHAR \
HAVE_WCHAR_H \
UNIX \
HAVE_STDINCLUDES
}
core_windows {
LIBS += -lgdi32 \
-ladvapi32 \
-luser32 \
-lshell32
}
DJVULIB_SOURCE = $$PWD/../libdjvu
DJVULIB_SOURCE_WRAPPER = $$PWD/libdjvu
#SOURCES += \
# $$DJVULIB_SOURCE/atomic.cpp
# $$DJVULIB_SOURCE/wasm/DjVuMessage.cpp \
# $$DJVULIB_SOURCE/wasm/GOS.cpp \
# $$DJVULIB_SOURCE/GURL.cpp
SOURCES += \
$$DJVULIB_SOURCE/Arrays.cpp \
$$DJVULIB_SOURCE/BSByteStream.cpp \
$$DJVULIB_SOURCE/BSEncodeByteStream.cpp \
$$DJVULIB_SOURCE/ByteStream.cpp \
$$DJVULIB_SOURCE/DataPool.cpp \
$$DJVULIB_SOURCE/debug.cpp \
$$DJVULIB_SOURCE/DjVmDir.cpp \
$$DJVULIB_SOURCE/DjVmDir0.cpp \
$$DJVULIB_SOURCE/DjVmDoc.cpp \
$$DJVULIB_SOURCE/DjVmNav.cpp \
$$DJVULIB_SOURCE/DjVuAnno.cpp \
$$DJVULIB_SOURCE/DjVuDocEditor.cpp \
$$DJVULIB_SOURCE/DjVuDocument.cpp \
$$DJVULIB_SOURCE/DjVuDumpHelper.cpp \
$$DJVULIB_SOURCE/DjVuErrorList.cpp \
$$DJVULIB_SOURCE/DjVuFile.cpp \
$$DJVULIB_SOURCE/DjVuFileCache.cpp \
$$DJVULIB_SOURCE/DjVuGlobal.cpp \
$$DJVULIB_SOURCE/DjVuGlobalMemory.cpp \
$$DJVULIB_SOURCE/DjVuImage.cpp \
$$DJVULIB_SOURCE/DjVuInfo.cpp \
$$DJVULIB_SOURCE/DjVuMessageLite.cpp \
$$DJVULIB_SOURCE/DjVuNavDir.cpp \
$$DJVULIB_SOURCE/DjVuPalette.cpp \
$$DJVULIB_SOURCE/DjVuPort.cpp \
$$DJVULIB_SOURCE/DjVuText.cpp \
$$DJVULIB_SOURCE/DjVuToPS.cpp \
$$DJVULIB_SOURCE/GBitmap.cpp \
$$DJVULIB_SOURCE/GContainer.cpp \
$$DJVULIB_SOURCE/GException.cpp \
$$DJVULIB_SOURCE/GIFFManager.cpp \
$$DJVULIB_SOURCE/GMapAreas.cpp \
$$DJVULIB_SOURCE/GPixmap.cpp \
$$DJVULIB_SOURCE/GRect.cpp \
$$DJVULIB_SOURCE/GScaler.cpp \
$$DJVULIB_SOURCE/GSmartPointer.cpp \
$$DJVULIB_SOURCE/GString.cpp \
$$DJVULIB_SOURCE/GThreads.cpp \
$$DJVULIB_SOURCE/GUnicode.cpp \
$$DJVULIB_SOURCE/IFFByteStream.cpp \
$$DJVULIB_SOURCE/IW44EncodeCodec.cpp \
$$DJVULIB_SOURCE/IW44Image.cpp \
$$DJVULIB_SOURCE/JB2EncodeCodec.cpp \
$$DJVULIB_SOURCE/JB2Image.cpp \
$$DJVULIB_SOURCE/JPEGDecoder.cpp \
$$DJVULIB_SOURCE/MMRDecoder.cpp \
$$DJVULIB_SOURCE/MMX.cpp \
$$DJVULIB_SOURCE/UnicodeByteStream.cpp \
$$DJVULIB_SOURCE/XMLParser.cpp \
$$DJVULIB_SOURCE/XMLTags.cpp \
$$DJVULIB_SOURCE/ZPCodec.cpp
SOURCES += \
$$DJVULIB_SOURCE_WRAPPER/atomic.cpp \
$$DJVULIB_SOURCE_WRAPPER/DjVuMessage.cpp \
$$DJVULIB_SOURCE_WRAPPER/GOS.cpp \
$$DJVULIB_SOURCE_WRAPPER/GURL.cpp
SOURCES += djvu_common.cpp
HEADERS += \
$$DJVULIB_SOURCE/Arrays.h \
$$DJVULIB_SOURCE/atomic.h \
$$DJVULIB_SOURCE/BSByteStream.h \
$$DJVULIB_SOURCE/ByteStream.h \
$$DJVULIB_SOURCE/DataPool.h \
$$DJVULIB_SOURCE/debug.h \
$$DJVULIB_SOURCE/DjVmDir.h \
$$DJVULIB_SOURCE/DjVmDir0.h \
$$DJVULIB_SOURCE/DjVmDoc.h \
$$DJVULIB_SOURCE/DjVmNav.h \
$$DJVULIB_SOURCE/DjVuAnno.h \
$$DJVULIB_SOURCE/DjVuDocEditor.h \
$$DJVULIB_SOURCE/DjVuDocument.h \
$$DJVULIB_SOURCE/DjVuDumpHelper.h \
$$DJVULIB_SOURCE/DjVuErrorList.h \
$$DJVULIB_SOURCE/DjVuFile.h \
$$DJVULIB_SOURCE/DjVuFileCache.h \
$$DJVULIB_SOURCE/DjVuGlobal.h \
$$DJVULIB_SOURCE/DjVuImage.h \
$$DJVULIB_SOURCE/DjVuInfo.h \
$$DJVULIB_SOURCE/DjVuMessage.h \
$$DJVULIB_SOURCE/DjVuMessageLite.h \
$$DJVULIB_SOURCE/DjVuNavDir.h \
$$DJVULIB_SOURCE/DjVuPalette.h \
$$DJVULIB_SOURCE/DjVuPort.h \
$$DJVULIB_SOURCE/DjVuText.h \
$$DJVULIB_SOURCE/DjVuToPS.h \
$$DJVULIB_SOURCE/GBitmap.h \
$$DJVULIB_SOURCE/GContainer.h \
$$DJVULIB_SOURCE/GException.h \
$$DJVULIB_SOURCE/GIFFManager.h \
$$DJVULIB_SOURCE/GMapAreas.h \
$$DJVULIB_SOURCE/GOS.h \
$$DJVULIB_SOURCE/GPixmap.h \
$$DJVULIB_SOURCE/GRect.h \
$$DJVULIB_SOURCE/GScaler.h \
$$DJVULIB_SOURCE/GSmartPointer.h \
$$DJVULIB_SOURCE/GString.h \
$$DJVULIB_SOURCE/GThreads.h \
$$DJVULIB_SOURCE/GURL.h \
$$DJVULIB_SOURCE/IFFByteStream.h \
$$DJVULIB_SOURCE/IW44Image.h \
$$DJVULIB_SOURCE/JB2Image.h \
$$DJVULIB_SOURCE/JPEGDecoder.h \
$$DJVULIB_SOURCE/MMRDecoder.h \
$$DJVULIB_SOURCE/MMX.h \
$$DJVULIB_SOURCE/UnicodeByteStream.h \
$$DJVULIB_SOURCE/XMLParser.h \
$$DJVULIB_SOURCE/XMLTags.h \
$$DJVULIB_SOURCE/ZPCodec.h

View File

@ -0,0 +1,426 @@
window.onload = function()
{
var userAgent = navigator.userAgent.toLowerCase();
// ie detect
var isIE = (userAgent.indexOf("msie") > -1 || userAgent.indexOf("trident") > -1 || userAgent.indexOf("edge") > -1);
// chrome detect
var isChrome = !isIE && (userAgent.indexOf("chrome") > -1);
// mobile detect
var isMobile = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent || navigator.vendor || window.opera);
var isOperaOld = (!!window.opera);
var holder = document.body;
holder.ondragover = function(e)
{
var isFile = false;
if (e.dataTransfer.types)
{
for (var i = 0, length = e.dataTransfer.types.length; i < length; ++i)
{
var type = e.dataTransfer.types[i].toLowerCase();
if (type == "files" && e.dataTransfer.items && e.dataTransfer.items.length == 1)
{
var item = e.dataTransfer.items[0];
if (item.kind && "file" == item.kind.toLowerCase())
{
isFile = true;
break;
}
}
}
}
e.dataTransfer.dropEffect = isFile ? "copy" : "none";
e.preventDefault();
return false;
};
holder.ondrop = function(e)
{
var file = e.dataTransfer.files ? e.dataTransfer.files[0] : null;
if (!file)
{
e.preventDefault();
return false;
}
var reader = new FileReader();
reader.onload = function(e) {
window.Viewer.open(e.target.result);
};
reader.readAsArrayBuffer(file);
return false;
};
function CCacheManager()
{
this.images = [];
this.lock = function(w, h)
{
for (let i = 0; i < this.images.length; i++)
{
if (this.images[i].locked)
continue;
let canvas = this.images[i].canvas;
let testW = canvas.width;
let testH = canvas.height;
if (w > testW || h > testH || ((4 * w * h) < (testW * testH)))
{
this.images.splice(i, 1);
continue;
}
this.images[i].locked = true;
return canvas;
}
let newImage = { canvas : document.createElement("canvas"), locked : true };
newImage.canvas.width = w + 100;
newImage.canvas.height = h + 100;
this.images.push(newImage);
return newImage.canvas;
};
this.unlock = function(canvas)
{
for (let i = 0, len = this.images.length; i < len; i++)
{
if (this.images[i].canvas === canvas)
{
this.images[i].locked = false;
return;
}
}
};
this.clear = function()
{
this.images = [];
};
};
function CHtmlPage()
{
this.width = 0;
this.height = 0;
this.retinaPixelRatio = 1;
this.zoom = 1;
this.drawingPages = [];
this.isRepaint = false;
this.canvas = document.getElementById("main");
this.scroller = document.getElementById("pos");
this.documentWidth = 0;
this.documentHeight = 0;
this.file = new AscViewer.DjVuFile();
this.file.cacheManager = new CCacheManager();
/*
[TIMER START]
*/
this.UseRequestAnimationFrame = isChrome;
this.RequestAnimationFrame = (function()
{
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame || null;
})();
this.CancelAnimationFrame = (function()
{
return window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame || null;
})();
if (this.UseRequestAnimationFrame)
{
if (null == this.RequestAnimationFrame)
this.UseRequestAnimationFrame = false;
}
this.RequestAnimationOldTime = -1;
this.startTimer = function()
{
if (this.UseRequestAnimationFrame)
this.timerAnimation();
else
this.timer();
};
/*
[TIMER END]
*/
this.log = function(message)
{
//console.log(message);
};
window.onscroll = function(e) { if (window.Viewer) window.Viewer.scroll(e); };
this.timerAnimation = function()
{
var now = Date.now();
if (-1 == window.Viewer.RequestAnimationOldTime || (now >= (window.Viewer.RequestAnimationOldTime + 40)) || (now < window.Viewer.RequestAnimationOldTime))
{
window.Viewer.RequestAnimationOldTime = now;
window.Viewer.timer();
}
window.Viewer.RequestAnimationFrame.call(window, window.Viewer.timerAnimation);
};
this.timer = function()
{
if (window.Viewer.isRepaint)
{
window.Viewer._paint();
window.Viewer.isRepaint = false;
}
if (!window.Viewer.UseRequestAnimationFrame)
{
setTimeout(window.Viewer.timer, 40);
}
};
this.resize = function()
{
this.zoom = 1;
this.retinaPixelRatio = 1;
/*
if (isChrome && !isOperaOld && !isMobile && document && document.firstElementChild && document.body)
{
// делаем простую проверку
// считаем: 0 < window.devicePixelRatio < 2 => _devicePixelRatio = 1; zoom = window.devicePixelRatio / _devicePixelRatio;
// считаем: window.devicePixelRatio >= 2 => _devicePixelRatio = 2; zoom = window.devicePixelRatio / _devicePixelRatio;
if (window.devicePixelRatio > 0.1)
{
if (window.devicePixelRatio < 1.99)
{
var _devicePixelRatio = 1;
this.zoom = window.devicePixelRatio / _devicePixelRatio;
}
else
{
var _devicePixelRatio = 2;
this.zoom = window.devicePixelRatio / _devicePixelRatio;
this.retinaPixelRatio = 2;
}
// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
//document.firstElementChild.style.zoom = "reset";
document.firstElementChild.style.zoom = 1.0 / this.zoom;
}
else
document.firstElementChild.style.zoom = "normal";
}
else
{
var isRetina = (Math.abs(2 - (window.devicePixelRatio / this.zoom)) < 0.01);
if (isRetina)
this.retinaPixelRatio = 2;
if (isMobile)
{
this.retinaPixelRatio = window.devicePixelRatio;
}
}
*/
this.width = this.canvas.clientWidth;
this.height = this.canvas.clientHeight;
this.canvas.width = (this.width * this.retinaPixelRatio) >> 0;
this.canvas.height = (this.height * this.retinaPixelRatio) >> 0;
this.recalculatePlaces();
this.log("retinaScale: " + this.retinaPixelRatio + ", zoom: " + this.zoom);
};
this.open = function(data)
{
if (this.file)
this.file.close();
this.file = window["AscViewer"].createFile(data);
document.scrollingElement.scrollLeft = 0;
document.scrollingElement.scrollTop = 0;
this.scroller.style.width = "0px";
this.scroller.style.height = "0px";
this.resize();
};
this.recalculatePlaces = function()
{
this.drawingPages = [];
for (let i = 0, len = this.file.pages.length; i < len; i++)
{
this.drawingPages.push({
X : 0,
Y : 0,
W : (this.file.pages[i].W * 96 * this.zoom / this.file.pages[i].Dpi) >> 0,
H : (this.file.pages[i].H * 96 * this.zoom / this.file.pages[i].Dpi) >> 0,
});
}
this.documentWidth = 0;
for (let i = 0, len = this.drawingPages.length; i < len; i++)
{
if (this.drawingPages[i].W > this.documentWidth)
this.documentWidth = this.drawingPages[i].W;
}
var curTop = 20;
for (let i = 0, len = this.drawingPages.length; i < len; i++)
{
this.drawingPages[i].X = (this.documentWidth - this.drawingPages[i].W) >> 1;
this.drawingPages[i].Y = curTop;
curTop += this.drawingPages[i].H;
curTop += 20;
}
this.documentHeight = curTop;
var oldX = document.scrollingElement.scrollLeft;
var oldY = document.scrollingElement.scrollTop;
var oldW = parseInt(this.scroller.style.width);
var oldH = parseInt(this.scroller.style.height);
this.scroller.style.width = this.documentWidth + "px";
this.scroller.style.height = this.documentHeight + "px";
var newX = (oldX * oldW / Math.max(1, this.documentWidth)) >> 0;
var newY = (oldY * oldH / Math.max(1, this.documentHeight)) >> 0;
if (newX < 0) newX = 0;
if (newY < 0) newY = 0;
var newXMax = Math.max(0, this.documentWidth - this.width);
var newYMax = Math.max(0, this.documentHeight - this.height);
if (newX > newXMax)
newX = newXMax;
if (newY > newYMax)
newY = newYMax;
document.scrollingElement.scrollLeft = newX;
document.scrollingElement.scrollTop = newY;
this.paint();
};
this.scroll = function(e)
{
this.log("scroll: [" + document.scrollingElement.scrollLeft + ", " + document.scrollingElement.scrollTop + "]");
this.paint();
};
this.paint = function()
{
this.isRepaint = true;
};
this._paint = function()
{
if (!this.isRepaint)
return;
if (!this.file.isValid())
return;
this.canvas.width = this.canvas.width;
let ctx = this.canvas.getContext("2d");
ctx.strokeStyle = "#000000";
let lineW = this.retinaPixelRatio >> 0;
ctx.lineWidth = lineW;
let yPos = (document.scrollingElement.scrollTop * this.zoom) >> 0;
let yMax = yPos + this.height;
let xCenter = this.width >> 1;
if (this.documentWidth > this.width)
{
xCenter = (this.documentWidth >> 1) - (document.scrollingElement.scrollLeft * this.zoom) >> 0;
}
let lStartPage = -1;
let lEndPage = -1;
let lPagesCount = this.drawingPages.length;
for (let i = 0; i < lPagesCount; i++)
{
let page = this.drawingPages[i];
let pageT = page.Y;
let pageB = page.Y + page.H;
if (yPos < pageB && yMax > pageT)
{
// страница на экране
if (-1 == lStartPage)
lStartPage = i;
lEndPage = i;
}
else
{
// страница не видна - выкидываем из кэша
if (page.Image)
{
if (this.file.cacheManager)
this.file.cacheManager.unlock(page.Image);
delete page.Image;
}
}
}
for (let i = lStartPage; i <= lEndPage; i++)
{
// отрисовываем страницу
let page = this.drawingPages[i];
let w = (page.W * this.retinaPixelRatio) >> 0;
let h = (page.H * this.retinaPixelRatio) >> 0;
if (!this.file.cacheManager)
{
if (page.Image && ((page.Image.width != w) || (page.Image.height != h)))
delete page.Image;
}
else
{
if (page.Image && ((page.Image.width < w) || (page.Image.height < h)))
{
if (this.file.cacheManager)
this.file.cacheManager.unlock(page.Image);
delete page.Image;
}
}
if (!page.Image)
page.Image = this.file.getPage(i, w, h);
let x = ((xCenter * this.retinaPixelRatio) >> 0) - (w >> 1);
let y = ((page.Y - yPos) * this.retinaPixelRatio) >> 0;
ctx.drawImage(page.Image, 0, 0, w, h, x, y, w, h);
ctx.strokeRect(x + lineW / 2, y + lineW / 2, w - lineW, h - lineW);
}
};
}
window.Viewer = new CHtmlPage();
window.Viewer.resize();
window.Viewer.startTimer();
};
window.onresize = function(e)
{
if (window.Viewer)
window.Viewer.resize();
};

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@ -0,0 +1,276 @@
(function(window, undefined) {
function CFile()
{
this.nativeFile = 0;
this.pages = [];
this.zoom = 1;
this.isUse3d = false;
this.cacheManager = null;
this.logging = true;
}
// interface
CFile.prototype.loadFromData = function(data) {};
CFile.prototype.load = function(arrayBuffer)
{
return this.loadFromData(new Uint8Array(arrayBuffer));
};
CFile.prototype.getInfo = function() {};
CFile.prototype.getPagePixmap = function(pageIndex, width, height) {};
CFile.prototype.close = function() {};
CFile.prototype.memory = function() {};
CFile.prototype.free = function(pointer) {};
CFile.prototype.getPage = function(pageIndex, width, height)
{
if (pageIndex < 0 || pageIndex >= this.pages.length)
return null;
if (!width) width = this.pages[pageIndex].W;
if (!height) height = this.pages[pageIndex].H;
var t0 = performance.now();
var pixels = this.getPagePixmap(pageIndex, width, height);
if (!pixels)
return null;
if (!this.logging)
{
var image = this._pixelsToCanvas(pixels, width, height);
}
else
{
var t1 = performance.now();
var image = this._pixelsToCanvas(pixels, width, height);
var t2 = performance.now();
//console.log("time: " + (t1 - t0) + ", " + (t2 - t1));
}
this.free(pixels);
return image;
};
CFile.prototype.getPageBase64 = function(pageIndex, width, height)
{
var _canvas = this.getPage(pageIndex, width, height);
if (!_canvas)
return "";
try
{
return _canvas.toDataURL("image/png");
}
catch (err)
{
}
return "";
};
CFile.prototype.isValid = function()
{
return this.pages.length > 0;
};
// private functions
CFile.prototype._pixelsToCanvas2d = function(pixels, width, height)
{
var canvas = null;
if (this.cacheManager)
{
canvas = this.cacheManager.lock(width, height);
}
else
{
canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
}
var mappedBuffer = new Uint8ClampedArray(this.memory().buffer, pixels, 4 * width * height);
var imageData = new ImageData(mappedBuffer, width, height);
var ctx = canvas.getContext("2d");
if (ctx)
ctx.putImageData(imageData, 0, 0);
return canvas;
};
var vs_source = "\
attribute vec2 aVertex;\n\
attribute vec2 aTex;\n\
varying vec2 vTex;\n\
void main() {\n\
gl_Position = vec4(aVertex, 0.0, 1.0);\n\
vTex = aTex;\n\
}";
var fs_source = "\
precision mediump float;\n\
uniform sampler2D uTexture;\n\
varying vec2 vTex;\n\
void main() {\n\
gl_FragColor = texture2D(uTexture, vTex);\n\
}";
CFile.prototype._pixelsToCanvas3d = function(pixels, width, height)
{
var canvas = null;
if (this.cacheManager)
{
canvas = this.cacheManager.lock(width, height);
}
else
{
canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
}
var gl = canvas.getContext('webgl', { preserveDrawingBuffer : true });
if (!gl)
throw new Error('FAIL: could not create webgl canvas context');
var colorCorrect = gl.BROWSER_DEFAULT_WEBGL;
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, colorCorrect);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
if (gl.getError() != gl.NONE)
throw new Error('FAIL: webgl canvas context setup failed');
function createShader(source, type) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
throw new Error('FAIL: shader ' + id + ' compilation failed');
return shader;
}
var program = gl.createProgram();
gl.attachShader(program, createShader(vs_source, gl.VERTEX_SHADER));
gl.attachShader(program, createShader(fs_source, gl.FRAGMENT_SHADER));
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS))
throw new Error('FAIL: webgl shader program linking failed');
gl.useProgram(program);
var texture = gl.createTexture();
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(this.memory().buffer, pixels, 4 * width * height));
if (gl.getError() != gl.NONE)
throw new Error('FAIL: creating webgl image texture failed');
function createBuffer(data) {
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
return buffer;
}
var vertexCoords = new Float32Array([-1, 1, -1, -1, 1, -1, 1, 1]);
var vertexBuffer = createBuffer(vertexCoords);
var location = gl.getAttribLocation(program, 'aVertex');
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0);
if (gl.getError() != gl.NONE)
throw new Error('FAIL: vertex-coord setup failed');
var texCoords = new Float32Array([0, 1, 0, 0, 1, 0, 1, 1]);
var texBuffer = createBuffer(texCoords);
var location = gl.getAttribLocation(program, 'aTex');
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0);
if (gl.getError() != gl.NONE)
throw new Error('FAIL: tex-coord setup setup failed');
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
return canvas;
};
CFile.prototype._pixelsToCanvas = function(pixels, width, height)
{
if (!this.isUse3d)
{
return this._pixelsToCanvas2d(pixels, width, height);
}
try
{
return this._pixelsToCanvas3d(pixels, width, height);
}
catch (err)
{
this.isUse3d = false;
if (this.cacheManager)
this.cacheManager.clear();
return this._pixelsToCanvas(pixels, width, height);
}
};
window["AscViewer"] = window["AscViewer"] || {};
window["AscViewer"].IFile = CFile;
window["AscViewer"].createFile = function(buffer)
{
var data = new Uint8Array(buffer);
var file = null;
if (data.length > 7 &&
0x41 == data[0] && 0x54 == data[1] && 0x26 == data[2] && 0x54 == data[3] &&
0x46 == data[4] && 0x4f == data[5] && 0x52 == data[6] && 0x4d == data[7])
{
file = new window["AscViewer"].DjVuFile();
}
if (!file)
{
var maxCheck = Math.min(100, data.length - 5);
var pdfCheck = [
"%".charCodeAt(0),
"P".charCodeAt(0),
"D".charCodeAt(0),
"F".charCodeAt(0),
"-".charCodeAt(0)
];
var isPdf = false;
for (var i = 0; i < maxCheck; i++)
{
if (data[i + 0] == pdfCheck[0] &&
data[i + 1] == pdfCheck[1] &&
data[i + 2] == pdfCheck[2] &&
data[i + 3] == pdfCheck[3] &&
data[i + 4] == pdfCheck[4])
{
isPdf = true;
break;
}
}
if (isPdf)
{
file = new window["AscViewer"].PdfFile();
file.type = 0;
}
}
if (!file)
{
file = new window["AscViewer"].PdfFile();
file.type = 1;
}
file.loadFromData(data);
return file;
};
})(window, undefined);

View File

@ -0,0 +1,16 @@
<!doctype html>
<html style="width:100%;height:100%;margin:0;padding:0;">
<head>
<title>ONLYOFFICE Documents</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=IE8">
<script src="./code.js"></script>
<script src="./file.js"></script>
<script src="./djvu/djvu.js"></script>
<script src="./pdf/pdf.js"></script>
</head>
<body style="width:100%;height:100%;margin:0;padding:0;overflow-x:scroll;overflow-y:scroll;">
<div id="pos" style="position:absolute;margin:0;padding:0;left:0px;top:0px;width:0px;height:0px;"></div>
<canvas width="100%" height="100%" style="position:fixed;left:0px;top:0px;width:100%;height:100%;" id="main"></canvas>
</body>
</html>

File diff suppressed because one or more lines are too long

Binary file not shown.

88
DjVuFile/wasm/compile.bat Normal file
View File

@ -0,0 +1,88 @@
SET SCRIPTPATH=%~dp0
CD /D %~dp0
call ../emsdk/emsdk_env.bat
call em++ -o djvu.js^
-O3^
-fno-rtti^
-s WASM=1^
-s ALLOW_MEMORY_GROWTH=1^
-s FILESYSTEM=0^
-s ENVIRONMENT='web'^
-s ERROR_ON_UNDEFINED_SYMBOLS=0^
-s EXPORTED_FUNCTIONS="['_malloc', '_free', '_DJVU_Load', '_DJVU_Close', '_DJVU_GetInfo', '_DJVU_GetPixmap', '_DJVU_Delete']"^
"libdjvu/Arrays.cpp"^
"libdjvu/BSByteStream.cpp"^
"libdjvu/BSEncodeByteStream.cpp"^
"libdjvu/ByteStream.cpp"^
"libdjvu/DataPool.cpp"^
"libdjvu/debug.cpp"^
"libdjvu/DjVmDir.cpp"^
"libdjvu/DjVmDir0.cpp"^
"libdjvu/DjVmDoc.cpp"^
"libdjvu/DjVmNav.cpp"^
"libdjvu/DjVuAnno.cpp"^
"libdjvu/DjVuDocEditor.cpp"^
"libdjvu/DjVuDocument.cpp"^
"libdjvu/DjVuDumpHelper.cpp"^
"libdjvu/DjVuErrorList.cpp"^
"libdjvu/DjVuFile.cpp"^
"libdjvu/DjVuFileCache.cpp"^
"libdjvu/DjVuGlobal.cpp"^
"libdjvu/DjVuGlobalMemory.cpp"^
"libdjvu/DjVuImage.cpp"^
"libdjvu/DjVuInfo.cpp"^
"libdjvu/DjVuMessageLite.cpp"^
"libdjvu/DjVuNavDir.cpp"^
"libdjvu/DjVuPalette.cpp"^
"libdjvu/DjVuPort.cpp"^
"libdjvu/DjVuText.cpp"^
"libdjvu/DjVuToPS.cpp"^
"libdjvu/GBitmap.cpp"^
"libdjvu/GContainer.cpp"^
"libdjvu/GException.cpp"^
"libdjvu/GIFFManager.cpp"^
"libdjvu/GMapAreas.cpp"^
"libdjvu/GPixmap.cpp"^
"libdjvu/GRect.cpp"^
"libdjvu/GScaler.cpp"^
"libdjvu/GSmartPointer.cpp"^
"libdjvu/GString.cpp"^
"libdjvu/GThreads.cpp"^
"libdjvu/GUnicode.cpp"^
"libdjvu/IFFByteStream.cpp"^
"libdjvu/IW44EncodeCodec.cpp"^
"libdjvu/IW44Image.cpp"^
"libdjvu/JB2EncodeCodec.cpp"^
"libdjvu/JB2Image.cpp"^
"libdjvu/JPEGDecoder.cpp"^
"libdjvu/MMRDecoder.cpp"^
"libdjvu/MMX.cpp"^
"libdjvu/UnicodeByteStream.cpp"^
"libdjvu/XMLParser.cpp"^
"libdjvu/XMLTags.cpp"^
"libdjvu/ZPCodec.cpp"^
"libdjvu/wasm/atomic.cpp"^
"libdjvu/wasm/DjVuMessage.cpp"^
"libdjvu/wasm/GOS.cpp"^
"libdjvu/wasm/GURL.cpp"^
"djvu_common.cpp"^
-DWIN32^
-DNDEBUG^
-D_LIB^
-D_CRT_SECURE_NO_WARNINGS^
-DWASM_MODE^
-Derrno=0^
"-DUINT=unsigned int"^
-DTHREADMODEL=0^
-DDEBUGLVL=0
echo "finalize..."
call powershell -Command "(Get-Content ./djvu.js) -replace 'function getBinaryPromise\(\){', 'function getBinaryPromise2(){' | Set-Content ./djvu.js"
if not exist "./deploy/djvu" mkdir "./../deploy/djvu"
call powershell -Command "(Get-Content ./djvu_base.js) -replace '//module', (Get-Content ./djvu.js) | Set-Content ./../deploy/djvu/djvu.js"
call echo f | xcopy /b/v/y/f "djvu.wasm" "./../deploy/djvu/djvu.wasm"

144
DjVuFile/wasm/djvu_base.js Normal file
View File

@ -0,0 +1,144 @@
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
(function(window, undefined) {
var printErr = undefined;
var FS = undefined;
var print = undefined;
var getBinaryPromise = null;
if (window["AscDesktopEditor"] && document.currentScript && 0 == document.currentScript.src.indexOf("file:///"))
{
// fetch not support file:/// scheme
window.fetch = undefined;
getBinaryPromise = function() {
var wasmPath = "ascdesktop://fonts/" + wasmBinaryFile.substr(8);
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', wasmPath, true);
xhr.responseType = 'arraybuffer';
if (xhr.overrideMimeType)
xhr.overrideMimeType('text/plain; charset=x-user-defined');
else
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
xhr.onload = function () {
if (this.status == 200) {
resolve(new Uint8Array(this.response));
}
};
xhr.send(null);
});
}
}
else
{
getBinaryPromise = function() {
return getBinaryPromise2();
}
}
//module
/**
*
* @param config
* @constructor
* @extends {AscViewer.IFile}
*/
function CFile()
{
AscViewer.IFile.call(this);
}
CFile.prototype = Object.create(AscViewer.IFile.prototype);
CFile.prototype.constructor = CFile;
CFile.prototype.load = function(arrayBuffer)
{
var data = new Uint8Array(arrayBuffer);
var _stream = Module["_malloc"](data.length);
Module["HEAP8"].set(data, _stream);
this.nativeFile = Module["_DJVU_Load"](_stream, data.length);
Module["_free"](_stream);
return this.getInfo();
};
CFile.prototype.getInfo = function()
{
if (!this.nativeFile)
return false;
var _info = Module["_DJVU_GetInfo"](this.nativeFile);
if (!_info)
return false;
var _pages = Module["HEAP32"][_info >> 2];
var _buffer = new Int32Array(Module["HEAP8"].buffer, _info, 1 + 3 * _pages);
var _cur = 1;
for (var i = 0; i < _pages; i++)
{
this.pages.push({ W : _buffer[_cur++], H : _buffer[_cur++], Dpi : _buffer[_cur++] });
}
this.free(_info);
return this.pages.length > 0;
};
CFile.prototype.getPagePixmap = function(pageIndex, width, height)
{
return Module["_DJVU_GetPixmap"](this.nativeFile, pageIndex, width, height);
};
CFile.prototype.close = function()
{
Module["_DJVU_Close"](this.nativeFile);
this.nativeFile = 0;
this.pages = [];
};
CFile.prototype.memory = function()
{
return Module["HEAP8"];
};
CFile.prototype.free = function(pointer)
{
Module["_DJVU_Delete"](pointer);
};
window["AscViewer"].DjVuFile = CFile;
})(window, undefined);

View File

@ -0,0 +1,238 @@
// djvu wrapper
#include "../libdjvu/DjVuDocument.h"
#include "../libdjvu/DjVuImage.h"
#include "../libdjvu/GBitmap.h"
#include "../libdjvu/GScaler.h"
#include "../libdjvu/IFFByteStream.h"
#include "../libdjvu/BSByteStream.h"
#include "../libdjvu/DataPool.h"
#include "../libdjvu/DjVuText.h"
#include "../libdjvu/DjVmNav.h"
#include "../libdjvu/IW44Image.h"
class CDjvuFile
{
public:
GP<DjVuDocument> m_doc;
};
extern "C"
{
CDjvuFile* DJVU_Load(unsigned char* pData, unsigned int len);
void DJVU_Close(CDjvuFile* file);
int* DJVU_GetInfo(CDjvuFile* file);
unsigned char* DJVU_GetPixmap(CDjvuFile* file, int page_index, int w, int h);
void DJVU_Delete(unsigned char* pData);
}
CDjvuFile* DJVU_Load(unsigned char* pData, unsigned int len)
{
GP<ByteStream> stream = ByteStream::create(pData, (size_t)len);
CDjvuFile* file = new CDjvuFile();
file->m_doc = DjVuDocument::create(stream);
file->m_doc->wait_get_pages_num();
int pages_count = file->m_doc->get_pages_num();
if (0 == pages_count)
{
delete file;
return NULL;
}
return file;
}
void DJVU_Close(CDjvuFile* file)
{
delete file;
}
int* DJVU_GetInfo(CDjvuFile* file)
{
int pages_count = file->m_doc->get_pages_num();
int* buffer = new int[pages_count * 3 + 1];
int buffer_index = 0;
buffer[buffer_index++] = pages_count;
for (int page = 0; page < pages_count; ++page)
{
int nW = 0;
int nH = 0;
int nDpi = 0;
file->m_doc->ReadPageInfo(page, nW, nH, nDpi);
buffer[buffer_index++] = nW;
buffer[buffer_index++] = nH;
buffer[buffer_index++] = nDpi;
}
return buffer;
}
unsigned char* DJVU_GetPixmap(CDjvuFile* file, int page_index, int w, int h)
{
GP<DjVuImage> page = file->m_doc->get_page(page_index);
int w_real = page->get_real_width();
int h_real = page->get_real_height();
unsigned char* pixmap = new unsigned char[4 * w * h];
if (!pixmap)
return NULL;
if (page->is_legal_photo() || page->is_legal_compound())
{
GRect oRectAll(0, 0, w, h);
GP<GPixmap> pImage = page->get_pixmap(oRectAll, oRectAll);
unsigned char* pixmap_cur = pixmap;
for (int j = h - 1; j >= 0; --j)
{
GPixel* pLine = pImage->operator [](j);
for (int i = 0; i < w; ++i, pixmap_cur += 4, ++pLine)
{
pixmap_cur[0] = pLine->b;
pixmap_cur[1] = pLine->g;
pixmap_cur[2] = pLine->r;
pixmap_cur[3] = 255;
}
}
}
else if (page->is_legal_bilevel())
{
GRect oRectAll(0, 0, w, h);
GP<GBitmap> pBitmap = page->get_bitmap(oRectAll, oRectAll, 4);
int nPaletteEntries = pBitmap->get_grays();
unsigned int* palette = new unsigned int[nPaletteEntries];
// Create palette for the bitmap
int color = 0xff0000;
int decrement = color / (nPaletteEntries - 1);
for (int i = 0; i < nPaletteEntries; ++i)
{
unsigned char level = (unsigned char)(color >> 16);
palette[i] = (0xFF000000 | level << 16 | level << 8 | level);
color -= decrement;
}
unsigned int* pixmap_cur = (unsigned int*)pixmap;
for (int j = h - 1; j >= 0; --j)
{
unsigned char* pLine = pBitmap->operator [](j);
for (int i = 0; i < w; ++i, ++pixmap_cur, ++pLine)
{
if (*pLine < nPaletteEntries)
{
*pixmap_cur = palette[*pLine];
}
else
{
*pixmap_cur = palette[0];
}
}
}
delete [] palette;
}
else
{
GRect oRectAll(0, 0, w, h);
GP<GPixmap> pImage = page->get_pixmap(oRectAll, oRectAll);
if (NULL != pImage)
{
unsigned char* pixmap_cur = pixmap;
for (int j = h - 1; j >= 0; --j)
{
GPixel* pLine = pImage->operator [](j);
for (int i = 0; i < w; ++i, pixmap_cur += 4, ++pLine)
{
pixmap_cur[0] = pLine->b;
pixmap_cur[1] = pLine->g;
pixmap_cur[2] = pLine->r;
pixmap_cur[3] = 255;
}
}
}
else
{
GP<GBitmap> pBitmap = page->get_bitmap(oRectAll, oRectAll, 4);
if (NULL != pBitmap)
{
int nPaletteEntries = pBitmap->get_grays();
unsigned int* palette = new unsigned int[nPaletteEntries];
// Create palette for the bitmap
int color = 0xff0000;
int decrement = color / (nPaletteEntries - 1);
for (int i = 0; i < nPaletteEntries; ++i)
{
unsigned char level = (unsigned char)(color >> 16);
palette[i] = (0xFF000000 | level << 16 | level << 8 | level);
color -= decrement;
}
unsigned int* pixmap_cur = (unsigned int*)pixmap;
for (int j = h - 1; j >= 0; --j)
{
unsigned char* pLine = pBitmap->operator [](j);
for (int i = 0; i < w; ++i, ++pixmap_cur, ++pLine)
{
if (*pLine < nPaletteEntries)
{
*pixmap_cur = palette[*pLine];
}
else
{
*pixmap_cur = palette[0];
}
}
}
delete [] palette;
}
}
}
return pixmap;
}
void DJVU_Delete(unsigned char* pData)
{
delete [] pData;
}
#ifdef WASM_MODE_DEBUG
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE* f = fopen("D:\\1.djvu", "rb");
fseek(f, 0, SEEK_END);
int file_size = (int)ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char* file_data = new unsigned char[file_size];
fread((void*)file_data, 1, file_size, f);
fclose(f);
CDjvuFile* file = DJVU_Load(file_data, file_size);
delete [] file_data;
if (file)
{
int* info = DJVU_GetInfo(file);
int pages_count = *info;
if (pages_count > 0)
{
unsigned char* pixmap = DJVU_GetPixmap(file, 0, 300, 300);
delete [] pixmap;
}
delete [] info;
}
return 0;
}
#endif

View File

@ -0,0 +1,356 @@
//C- -*- C++ -*-
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002 Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001 AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, either Version 2 of the license,
//C- or (at your option) any later version. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C-
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from
//C- Lizardtech Software. Lizardtech Software has authorized us to
//C- replace the original DjVu(r) Reference Library notice by the following
//C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu):
//C-
//C- ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, either Version 2 of the license,
//C- | or (at your option) any later version. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE." Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
//C- | non-exclusive license to make, use, sell, or otherwise dispose of
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
//C- | General Public License. This grant only confers the right to
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
//C- | the extent such infringement is reasonably necessary to enable
//C- | recipient to make, have made, practice, sell, or otherwise dispose
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
//C- | any greater extent that may be necessary to utilize further
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
//
// $Id: DjVuMessage.cpp,v 1.24 2008/01/27 17:32:56 leonb Exp $
// $Name: $
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma implementation
#endif
// From: Leon Bottou, 1/31/2002
// All these XML messages are Lizardtech innovations.
#include "./../libdjvu/DjVuMessage.h"
#include "./../libdjvu/GOS.h"
#include "./../libdjvu/XMLTags.h"
#include "./../libdjvu/ByteStream.h"
#include "./../libdjvu/GURL.h"
#include "./../libdjvu/debug.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
#ifndef LC_MESSAGES
# define LC_MESSAGES LC_ALL
#endif
#ifdef HAVE_NAMESPACES
namespace DJVU {
# ifdef NOT_DEFINED // Just to fool emacs c++ mode
}
#endif
#endif
GUTF8String &
DjVuMessage::programname(void)
{
static GUTF8String xprogramname;
use_language();
return xprogramname;
}
static const char namestring[]="name";
static const char srcstring[]="src";
static const char *failed_to_parse_XML=ERR_MSG("DjVuMessage.failed_to_parse_XML");
static const char bodystring[]="BODY";
static const char languagestring[]="LANGUAGE";
static const char headstring[]="HEAD";
static const char includestring[]="INCLUDE";
static const char messagestring[]="MESSAGE";
static const char localestring[]="locale";
// directory names for searching messages
#ifdef AUTOCONF
static const char DjVuDataDir[] = DIR_DATADIR "/djvu/osi";
#endif /* AUTOCONF */
static const char ModuleDjVuDir[] ="share/djvu/osi";
static const char ProfilesDjVuDir[] ="profiles";
static const char LocalDjVuDir[] =".DjVu"; // relative to ${HOME}
#ifdef LT_DEFAULT_PREFIX
static const char DjVuPrefixDir[] = LT_DEFAULT_PREFIX "/profiles";
#endif
#ifndef NDEBUG
static const char DebugModuleDjVuDir[] ="../TOPDIR/SRCDIR/profiles";
#endif
static const char DjVuEnv[] = "DJVU_CONFIG_DIR";
// The name of the message file
static const char MessageFile[]="messages.xml";
static const char LanguageFile[]="languages.xml";
static void
appendPath(const GURL &url,
GMap<GUTF8String,void *> &map,
GList<GURL> &list)
{
if( !url.is_empty() && !map.contains(url.get_string()) )
{
map[url.get_string()]=0;
list.append(url);
}
}
GList<GURL>
DjVuMessage::GetProfilePaths(void)
{
static GList<GURL> realpaths;
return realpaths;
}
static GUTF8String
getbodies(
GList<GURL> &paths,
const GUTF8String &MessageFileName,
GPList<lt_XMLTags> &body,
GMap<GUTF8String, void *> & map )
{
GUTF8String errors;
bool isdone=false;
GPosition firstpathpos=paths;
for(GPosition pathpos=firstpathpos;!isdone && pathpos;++pathpos)
{
const GURL::UTF8 url(MessageFileName,paths[pathpos]);
if(url.is_file())
{
map[MessageFileName]=0;
GP<lt_XMLTags> gtags;
{
GP<ByteStream> bs=ByteStream::create(url,"rb");
G_TRY
{
gtags=lt_XMLTags::create(bs);
}
G_CATCH(ex)
{
GUTF8String mesg(failed_to_parse_XML+("\t"+url.get_string()));
if(errors.length())
{
errors+="\n"+mesg;
}else
{
errors=mesg;
}
errors+="\n"+GUTF8String(ex.get_cause());
}
G_ENDCATCH;
}
if(gtags)
{
lt_XMLTags &tags=*gtags;
GPList<lt_XMLTags> Bodies=tags.get_Tags(bodystring);
if(! Bodies.isempty())
{
isdone=true;
for(GPosition pos=Bodies;pos;++pos)
{
body.append(Bodies[pos]);
}
}
GPList<lt_XMLTags> Head=tags.get_Tags(headstring);
if(! Head.isempty())
{
isdone=true;
GMap<GUTF8String, GP<lt_XMLTags> > includes;
lt_XMLTags::get_Maps(includestring,namestring,Head,includes);
for(GPosition pos=includes;pos;++pos)
{
const GUTF8String file=includes.key(pos);
if(! map.contains(file))
{
GList<GURL> xpaths;
xpaths.append(url.base());
const GUTF8String err2(getbodies(xpaths,file,body,map));
if(err2.length())
{
if(errors.length())
{
errors+="\n"+err2;
}else
{
errors=err2;
}
}
}
}
}
}
}
}
return errors;
}
static GUTF8String
parse(GMap<GUTF8String,GP<lt_XMLTags> > &retval)
{
GUTF8String errors;
GPList<lt_XMLTags> body;
{
GList<GURL> paths=DjVuMessage::GetProfilePaths();
GMap<GUTF8String, void *> map;
GUTF8String m(MessageFile);
errors=getbodies(paths,m,body,map);
}
if(! body.isempty())
{
lt_XMLTags::get_Maps(messagestring,namestring,body,retval);
}
return errors;
}
const DjVuMessageLite &
DjVuMessage::create_full(void)
{
GP<DjVuMessageLite> &static_message=getDjVuMessageLite();
if(!static_message)
{
DjVuMessage *mesg=new DjVuMessage;
static_message=mesg;
mesg->init();
}
return DjVuMessageLite::create_lite();
}
void
DjVuMessage::set_programname(const GUTF8String &xprogramname)
{
programname()=xprogramname;
DjVuMessageLite::create=create_full;
}
void
DjVuMessage::use_language(void)
{
DjVuMessageLite::create=create_full;
}
// Constructor
DjVuMessage::DjVuMessage( void ) {}
void
DjVuMessage::init(void)
{
errors=parse(Map);
}
// Destructor
DjVuMessage::~DjVuMessage( )
{
}
// A C function to perform a message lookup. Arguments are a buffer to receiv
// translated message, a buffer size (bytes), and a message_list. The transla
// result is returned in msg_buffer encoded in Native MBS encoding. In case
// of error, msg_b empty (i.e., msg_buffer[0] == '\0').
void
DjVuMessageLookUpNative(
char *msg_buffer, const unsigned int buffer_size, const char *message)
{
const GNativeString converted(DjVuMessage::LookUpNative( message ));
if( converted.length() >= buffer_size )
msg_buffer[0] = '\0';
else
strcpy( msg_buffer, converted );
}
// A C function to perform a message lookup. Arguments are a buffer to receiv
// translated message, a buffer size (bytes), and a message_list. The transla
// result is returned in msg_buffer encoded in UTF8 encoding. In case
// of error, msg_b empty (i.e., msg_buffer[0] == '\0').
void
DjVuMessageLookUpUTF8(
char *msg_buffer, const unsigned int buffer_size, const char *message)
{
const GUTF8String converted(DjVuMessage::LookUpUTF8( message ));
if( converted.length() >= buffer_size )
msg_buffer[0] = '\0';
else
strcpy( msg_buffer, converted );
}
#ifdef HAVE_NAMESPACES
}
# ifndef NOT_USING_DJVU_NAMESPACE
using namespace DJVU;
# endif
#endif
void
DjVuFormatErrorUTF8( const char *fmt, ... )
{
va_list args;
va_start(args, fmt);
const GUTF8String message(fmt,args);
DjVuWriteError( message );
}
void
DjVuFormatErrorNative( const char *fmt, ... )
{
va_list args;
va_start(args, fmt);
const GNativeString message(fmt,args);
DjVuWriteError( message );
}
const char *
djvu_programname(const char *xprogramname)
{
if(xprogramname)
DjVuMessage::programname()=GNativeString(xprogramname);
return DjVuMessage::programname();
}

View File

@ -0,0 +1,117 @@
//C- -*- C++ -*-
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002 Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001 AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, either Version 2 of the license,
//C- or (at your option) any later version. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C-
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from
//C- Lizardtech Software. Lizardtech Software has authorized us to
//C- replace the original DjVu(r) Reference Library notice by the following
//C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu):
//C-
//C- ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, either Version 2 of the license,
//C- | or (at your option) any later version. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE." Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
//C- | non-exclusive license to make, use, sell, or otherwise dispose of
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
//C- | General Public License. This grant only confers the right to
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
//C- | the extent such infringement is reasonably necessary to enable
//C- | recipient to make, have made, practice, sell, or otherwise dispose
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
//C- | any greater extent that may be necessary to utilize further
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
//
// $Id: GOS.cpp,v 1.17 2008/03/10 13:58:54 leonb Exp $
// $Name: $
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma implementation
#endif
#include "./../libdjvu/GOS.h"
// basename(filename[, suffix])
// -- returns the last component of filename and removes suffix
// when present. works like /bin/basename.
GUTF8String
GOS::basename(const GUTF8String &gfname, const char *suffix)
{
GUTF8String retval;
return retval;
}
// -----------------------------------------
// Functions for measuring time
// -----------------------------------------
// ticks() --
// -- returns the number of milliseconds elapsed since
// a system dependent date.
unsigned long
GOS::ticks()
{
return 0;
}
// sleep(int milliseconds) --
// -- sleeps during the specified time (in milliseconds)
void
GOS::sleep(int milliseconds)
{
}
// -----------------------------------------
// Testing
// -----------------------------------------
// cwd([dirname])
// -- changes directory to dirname (when specified).
// returns the full path name of the current directory.
GUTF8String
GOS::cwd(const GUTF8String &dirname)
{
GUTF8String retval;
return retval;
}
GUTF8String
GOS::getenv(const GUTF8String &name)
{
GUTF8String retval;
return retval;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,80 @@
/* -*- C -*-
// -------------------------------------------------------------------
// MiniLock - a quick mostly user space lock
// Copyright (c) 2008 Leon Bottou. All rights reserved
//
// 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.
//
// ------------------------------------------------------------------- */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "../libdjvu/atomic.h"
int
atomicAcquire(int volatile *lock)
{
int tmp;
if ((tmp = !*lock))
*lock = 1;
return tmp;
}
void
atomicAcquireOrSpin(int volatile *lock)
{
while (*lock)
;
*lock = 1;
}
void
atomicRelease(int volatile *lock)
{
*lock = 0;
}
int
atomicIncrement(int volatile *var)
{
int res;
res = ++(*var);
return res;
}
int
atomicDecrement(int volatile *var)
{
int res;
res = --(*var);
return res;
}
int
atomicCompareAndSwap(int volatile *var, int oldval, int newval)
{
int ret;
ret = *var;
if (ret == oldval)
*var = newval;
return (ret == oldval);
}