Exemplo n.º 1
0
/*
 * Add a table row
 *
 * Returns TRUE when conversion type is XML
 */
BOOL
bAddTableRow(diagram_type *pDiag, char **aszColTxt,
    int iNbrOfColumns, const short *asColumnWidth, UCHAR ucBorderInfo)
{
    TRACE("antiword::bAddTableRow()");
//        vAddTableRowXML(pDiag, aszColTxt,
//                iNbrOfColumns, asColumnWidth,
//                ucBorderInfo);
	if ( table_col_count!=iNbrOfColumns ) {
		if (inside_table)
			writer->OnTagClose(NULL, L"table");
		writer->OnTagOpenNoAttr(NULL, L"table");
        inside_table = true;
		int totalWidth = 0;
		int i;
		for ( i=0; i<iNbrOfColumns; i++ )
			totalWidth += asColumnWidth[i];
		if ( totalWidth>0 ) {
			for ( i=0; i<iNbrOfColumns; i++ ) {
				int cw = asColumnWidth[i] * 100 / totalWidth;
		        writer->OnTagOpen(NULL, L"col");
				if ( cw>=0 )
                    writer->OnAttribute(NULL, L"width", (lString16::itoa(cw) + "%").c_str());
		        writer->OnTagBody();
		        writer->OnTagClose(NULL, L"col");
			}
		}
		table_col_count = iNbrOfColumns;
	}
    if (!inside_table) {
        writer->OnTagOpenNoAttr(NULL, L"table");
        inside_table = true;
    }
    writer->OnTagOpenNoAttr(NULL, L"tr");
    for ( int i=0; i<iNbrOfColumns; i++ ) {
        writer->OnTagOpenNoAttr(NULL, L"td");
        lString16 text = lString16(aszColTxt[i]);
        writer->OnText(text.c_str(), text.length(), 0);
        writer->OnTagClose(NULL, L"td");
    }
    writer->OnTagClose(NULL, L"tr");
    return TRUE;
    //return FALSE;
} /* end of bAddTableRow */
Exemplo n.º 2
0
    virtual ~LVRtfPictDestination()
    {
        if (!_fmt || _buf.empty())
            return;
        // add Image BLOB
        lString16 name(BLOB_NAME_PREFIX); // L"@blob#"
        name << L"image";
        name << lString16::itoa(m_parser.nextImageIndex());
        name << (_fmt==rtf_img_jpeg ? L".jpg" : L".png");
        m_callback->OnBlob(name, _buf.get(), _buf.length());
#if 0
        {
            LVStreamRef stream = LVOpenFileStream((lString16(L"/tmp/") + name).c_str(), LVOM_WRITE);
            stream->Write(_buf.get(), _buf.length(), NULL);
        }
#endif
        m_callback->OnTagOpen(LXML_NS_NONE, L"img");
        m_callback->OnAttribute(LXML_NS_NONE, L"src", name.c_str());
        m_callback->OnTagClose(LXML_NS_NONE, L"img");
    }
Exemplo n.º 3
0
 bool setManglingKey(lString16 key) {
     if (key.startsWith(lString16(L"urn:uuid:")))
         key = key.substr(9);
     _fontManglingKey.clear();
     _fontManglingKey.reserve(16);
     lUInt8 b = 0;
     int n = 0;
     for (int i=0; i<key.length(); i++) {
         int d = hexDigit(key[i]);
         if (d>=0) {
             b = (b << 4) | d;
             if (++n > 1) {
                 _fontManglingKey.add(b);
                 n = 0;
                 b = 0;
             }
         }
     }
     return _fontManglingKey.length() == 16;
 }
Exemplo n.º 4
0
static void dumpZip( LVContainerRef arc ) {
    lString16 arcName = LVExtractFilenameWithoutExtension( arc->GetName() );
    if ( arcName.empty() )
        arcName = L"unziparc";
    lString16 outDir = lString16("/tmp/") + arcName;
    LVCreateDirectory(outDir);
    for ( int i=0; i<arc->GetObjectCount(); i++ ) {
        const LVContainerItemInfo * info = arc->GetObjectInfo(i);
        if ( !info->IsContainer() ) {
            lString16 outFileName = outDir + L"/" + info->GetName();
            LVCreateDirectory(LVExtractPath(outFileName));
            LVStreamRef in = arc->OpenStream(info->GetName(), LVOM_READ);
            LVStreamRef out = LVOpenFileStream(outFileName.c_str(), LVOM_WRITE);
            if ( !in.isNull() && !out.isNull() ) {
                CRLog::trace("Writing %s", LCSTR(outFileName));
                LVPumpStream(out.get(), in.get());
            }
        }
    }
}
Exemplo n.º 5
0
void V3DocViewWin::showHelpDialog()
{
	LVStreamRef stream = LVOpenFileStream( _helpFile.c_str(), LVOM_READ );
	lString8 help;
    if ( stream.isNull() ) {
        // show warning
        lString8 body;
        body << "<title><p>" << _("No manual currently available for this language, sorry!") << "</p></title>";
        help = CRViewDialog::makeFb2Xml( body );
    } else {
        int len = stream->GetSize();
        if ( len>100 && len <1000000 ) {
            help.append( len, ' ' );
            stream->Read( help.modify(), len, NULL );
        }
    }
	//lString8 help = UnicodeToUtf8( LVReadTextFile( _helpFile ) );
	if ( !help.empty() ) {
		CRViewDialog * dlg = new CRViewDialog( _wm, lString16(_("Help")), help, lvRect(), true, true );
		_wm->activateWindow( dlg );
	}
}
Exemplo n.º 6
0
 */JNIEXPORT jboolean JNICALL Java_com_reader_app_YouYouApplication_initInternal(
		JNIEnv * penv, jclass obj, jobjectArray fontArray) {

	CRJNIEnv env(penv);

	// to catch crashes and remove current cache file on crash (SIGSEGV etc.)
	crSetSignalHandler();

	LOGI("initInternal called");
	// set fatal error handler
	LOGD("Redirecting CDRLog to Android");
	CRLog::setLogger(new JNICDRLogger());
	CRLog::setLogLevel(CRLog::LL_TRACE);
	CRLog::info("CREngine log redirected");

	CRLog::info("initializing hyphenation manager");
	HyphMan::initDictionaries(lString16::empty_str); //don't look for dictionaries
	HyphMan::activateDictionary(lString16(HYPH_DICT_ID_NONE));
	CRLog::info("creating font manager");
	InitFontManager(lString8::empty_str);
	CRLog::debug("converting fonts array: %d items",
			(int) env->GetArrayLength(fontArray));
	lString16Collection fonts;
	env.fromJavaStringArray(fontArray, fonts);
	int len = fonts.length();
	CRLog::debug("registering fonts: %d fonts in list", len);
	for (int i = 0; i < len; i++) {
		lString8 fontName = UnicodeToUtf8(fonts[i]);
//		CRLog::debug("registering font %s", fontName.c_str());
		if (!fontMan->RegisterFont(fontName))
//			CRLog::error("cannot load font %s", fontName.c_str());
			;
	}

	CRLog::info("%d fonts registered", fontMan->GetFontCount());
	return fontMan->GetFontCount() ? JNI_TRUE : JNI_FALSE;

}
Exemplo n.º 7
0
void ReadEpubToc( ldomDocument * doc, ldomNode * mapRoot, LVTocItem * baseToc, ldomDocumentFragmentWriter & appender ) {
    if ( !mapRoot || !baseToc)
        return;
    lUInt16 navPoint_id = mapRoot->getDocument()->getElementNameIndex(L"navPoint");
    lUInt16 navLabel_id = mapRoot->getDocument()->getElementNameIndex(L"navLabel");
    lUInt16 content_id = mapRoot->getDocument()->getElementNameIndex(L"content");
    lUInt16 text_id = mapRoot->getDocument()->getElementNameIndex(L"text");
    for ( int i=0; i<5000; i++ ) {
        ldomNode * navPoint = mapRoot->findChildElement(LXML_NS_ANY, navPoint_id, i);
        if ( !navPoint )
            break;
        ldomNode * navLabel = navPoint->findChildElement(LXML_NS_ANY, navLabel_id, -1);
        if ( !navLabel )
            continue;
        ldomNode * text = navLabel->findChildElement(LXML_NS_ANY, text_id, -1);
        if ( !text )
            continue;
        ldomNode * content = navPoint->findChildElement(LXML_NS_ANY, content_id, -1);
        if ( !content )
            continue;
        lString16 href = content->getAttributeValue(L"src");
        lString16 title = text->getText(' ');
        title.trimDoubleSpaces(false, false, false);
        if ( href.empty() || title.empty() )
            continue;
        //CRLog::trace("TOC href before convert: %s", LCSTR(href));
        href = appender.convertHref(href);
        //CRLog::trace("TOC href after convert: %s", LCSTR(href));
        if ( href.empty() || href[0]!='#' )
            continue;
        ldomNode * target = doc->getNodeById(doc->getAttrValueIndex(href.substr(1).c_str()));
        if ( !target )
            continue;
        ldomXPointer ptr(target, 0);
        LVTocItem * tocItem = baseToc->addChild(title, ptr, lString16());
        ReadEpubToc( doc, navPoint, tocItem, appender );
    }
}
Exemplo n.º 8
0
    bool match( const lChar16 * s, char * mask )
    {
        TexPattern * p = this;
        bool found = false;
        while ( p ) {
            bool res = true;
            for ( int i=2; p->word[i]; i++ )
                if ( p->word[i]!=s[i] ) {
                    res = false;
                    break;
                }
            if ( res ) {
                if ( p->word[0]==s[0] && (p->word[1]==0 || p->word[1]==s[1]) ) {
#if DUMP_PATTERNS==1
                    CRLog::debug("Pattern matched: %s %s on %s %s", LCSTR(lString16(p->word)), p->attr, LCSTR(lString16(s)), mask);
#endif
                    p->apply(mask);
                    found = true;
                }
            }
            p = p->next;
        }
        return found;
    }
Exemplo n.º 9
0
void CRCitesMenu::createDefaultItem()
{
    CRBookmarkMenuItem * item = new CRBookmarkMenuItem( this, 0, NULL, 0 );
    item->setLabel(lString16(_("Cite selection dialog")));
    addItem( item );
}
Exemplo n.º 10
0
CRRecentBookMenuItem::CRRecentBookMenuItem( CRMenu * menu, int index, CRFileHistRecord * book )
: CRMenuItem(menu, index, lString16(L""), LVImageSourceRef(), LVFontRef() ), _book( book )
{
}
Exemplo n.º 11
0
bool TexHyph::hyphenate( const lChar16 * str, int len, lUInt16 * widths, lUInt8 * flags, lUInt16 hyphCharWidth, lUInt16 maxWidth )
{
    if ( len<=3 )
        return false;
    if ( len>WORD_LENGTH )
        len = WORD_LENGTH - 2;
    lChar16 word[WORD_LENGTH+3];
    char mask[WORD_LENGTH+3];
    word[0] = ' ';
    lStr_memcpy( word+1, str, len );
    lStr_lowercase(word+1, len);
    word[len+1] = ' ';
    word[len+2] = 0;
    word[len+3] = 0;
    word[len+4] = 0;

#if DUMP_HYPHENATION_WORDS==1
    CRLog::trace("word to hyphenate: '%s'", LCSTR(lString16(word)));
#endif

    memset( mask, '0', len+3 );
    mask[len+3] = 0;
    bool found = false;
    for ( int i=0; i<len; i++ ) {
        found = match( word + i, mask + i ) || found;
    }
    if ( !found )
        return false;

#if DUMP_HYPHENATION_WORDS==1
    lString16 buf;
    lString16 buf2;
    bool boundFound = false;
    for ( int i=0; i<len; i++ ) {
        buf << word[i+1];
        buf2 << word[i+1];
        buf2 << (lChar16)mask[i+2];
        int nw = widths[i]+hyphCharWidth;
        if ( (mask[i+2]&1) ) {
            buf << (lChar16)'-';
            buf2 << (lChar16)'-';
        }
        if ( nw>maxWidth && !boundFound ) {
            buf << (lChar16)'|';
            buf2 << (lChar16)'|';
            boundFound = true;
//            buf << (lChar16)'-';
//            buf2 << (lChar16)'-';
        }
    }
    CRLog::trace("Hyphenate: %s  %s", LCSTR(buf), LCSTR(buf2) );
#endif

    bool res = false;
    int p=0;
    for ( p=len-3; p>=1; p-- ) {
        // hyphenate
        //00010030100
        int nw = widths[p]+hyphCharWidth;
        if ( (mask[p+2]&1) && nw <= maxWidth ) {
            //if ( checkHyphenRules( word+1, len, p ) ) {
            //widths[p] += hyphCharWidth; // don't add hyph width
            flags[p] |= LCHAR_ALLOW_HYPH_WRAP_AFTER;
            res = true;
            //}
        }
    }
    return res;
}
Exemplo n.º 12
0
bool TexHyph::load( LVStreamRef stream )
{
    int w = isCorrectHyphFile(stream.get());
    int patternCount = 0;
    if (w) {
        _hash = stream->crc32();
        int        i;
        lvsize_t   dw;

        lvByteOrderConv cnv;

        int hyph_count = w;
        thyph hyph;

        lvpos_t p = 78 + (hyph_count * 8 + 2);
        stream->SetPos(p);
        if ( stream->SetPos(p)!=p )
            return false;
        lChar16 charMap[256];
        unsigned char buf[0x10000];
        memset( charMap, 0, sizeof( charMap ) );
        // make char map table
        for (i=0; i<hyph_count; i++)
        {
            if ( stream->Read( &hyph, 522, &dw )!=LVERR_OK || dw!=522 ) 
                return false;
            cnv.msf( &hyph.len ); //rword(_main_hyph[i].len);
            lvpos_t newPos;
            if ( stream->Seek( hyph.len, LVSEEK_CUR, &newPos )!=LVERR_OK )
                return false;

            cnv.msf( hyph.wl );
            cnv.msf( hyph.wu );
            charMap[ (unsigned char)hyph.al ] = hyph.wl;
            charMap[ (unsigned char)hyph.au ] = hyph.wu;
//            lChar16 ch = hyph.wl;
//            CRLog::debug("wl=%s mask=%c%c", LCSTR(lString16(&ch, 1)), hyph.mask0[0], hyph.mask0[1]);
            if (hyph.mask0[0]!='0'||hyph.mask0[1]!='0') {
                unsigned char pat[4];
                pat[0] = hyph.al;
                pat[1] = hyph.mask0[0];
                pat[2] = hyph.mask0[1];
                pat[3] = 0;
                TexPattern * pattern = new TexPattern(pat, 1, charMap);
#if DUMP_PATTERNS==1
                CRLog::debug("Pattern: '%s' - %s", LCSTR(lString16(pattern->word)), pattern->attr );
#endif
                addPattern( pattern );
                patternCount++;
            }
        }

        if ( stream->SetPos(p)!=p )
            return false;

        for (i=0; i<hyph_count; i++)
        {
            stream->Read( &hyph, 522, &dw );
            if (dw!=522) 
                return false;
            cnv.msf( &hyph.len );

            stream->Read(buf, hyph.len, &dw); 
            if (dw!=hyph.len)
                return false;

            unsigned char * p = buf;
            unsigned char * end_p = p + hyph.len;
            while ( p < end_p ) {
                lUInt8 sz = *p++;
                if ( p + sz > end_p )
                    break;
                TexPattern * pattern = new TexPattern( p, sz, charMap );
#if DUMP_PATTERNS==1
                CRLog::debug("Pattern: '%s' - %s", LCSTR(lString16(pattern->word)), pattern->attr);
#endif
                addPattern( pattern );
                patternCount++;
                p += sz + sz + 1;
            }
        }

        return patternCount>0;
    } else {
        // tex xml format as for FBReader
        lString16Collection data;
        HyphPatternReader reader( data );
        LVXMLParser parser( stream, &reader );
        if ( !parser.CheckFormat() )
            return false;
        if ( !parser.Parse() )
            return false;
        if ( !data.length() )
            return false;
        for ( int i=0; i<(int)data.length(); i++ ) {
            data[i].lowercase();
            TexPattern * pattern = new TexPattern( data[i] );
#if DUMP_PATTERNS==1
            CRLog::debug("Pattern: (%s) '%s' - %s", LCSTR(data[i]), LCSTR(lString16(pattern->word)), pattern->attr);
#endif
            addPattern( pattern );
            patternCount++;
        }
        return patternCount>0;
    }
}
Exemplo n.º 13
0
/// returns true if command is processed
bool V3DocViewWin::onCommand( int command, int params )
{
    CRLog::info("V3DocViewWin::onCommand(%d [%s], %d)", command, getCommandName(command, params), params );
    switch ( command ) {
    case MCMD_QUIT:
        getWindowManager()->closeAllWindows();
        return true;
    case MCMD_MAIN_MENU:
        showMainMenu();
        return true;
    case MCMD_SETTINGS_FONTSIZE:
        showFontSizeMenu();
        return true;
#if CR_INTERNAL_PAGE_ORIENTATION==1
    case MCMD_SETTINGS_ORIENTATION:
        showOrientationMenu();
        return true;
#endif
    case MCMD_SETTINGS:
        showSettingsMenu();
        return true;
    case MCMD_RECENT_BOOK_LIST:
        showRecentBooksMenu();
        return true;
    case MCMD_OPEN_RECENT_BOOK:
        _docview->swapToCache();
        _docview->getDocument()->updateMap();
        openRecentBook( params );
        return true;
    case MCMD_SWITCH_TO_RECENT_BOOK:
        _docview->swapToCache();
        _docview->getDocument()->updateMap();
        openRecentBook( 1 );
        return true;
    case MCMD_ABOUT:
        showAboutDialog();
        return true;
    case MCMD_CITE:
        activate_cite( _wm, this);
        return true;
    case MCMD_GO_PAGE_APPLY:
        _docview->doCommand( DCMD_GO_PAGE, params-1 );
        return true;
    case MCMD_GO_PERCENT_APPLY:
        _docview->doCommand( DCMD_GO_POS, params * _docview->GetFullHeight() / 100 );
        return true;
    case MCMD_SETTINGS_APPLY:
#if CR_INTERNAL_PAGE_ORIENTATION==1
    case mm_Orientation:
#endif
    case mm_FontSize:
        applySettings();
        saveSettings( lString16() );
        _wm->getSkin()->gc();
        return true;
    case DCMD_SAVE_HISTORY:
        saveHistory( lString16() );
        saveSettings( lString16() );
        return true;
    case DCMD_SAVE_TO_CACHE:
        _docview->swapToCache();
        _docview->getDocument()->updateMap();
        return true;
    case MCMD_BOOKMARK_LIST:
        showBookmarksMenu(false);
        return true;
    case MCMD_BOOKMARK_LIST_GO_MODE:
        showBookmarksMenu(true);
        return true;
    case DCMD_ZOOM_IN:
    case DCMD_ZOOM_OUT:
        showWaitIcon();
		CRViewDialog::onCommand( command, params );
        _props->setInt( PROP_FONT_SIZE, _docview->getFontSize() );
        saveSettings( lString16() );
        return true;
    case MCMD_HELP:
        showHelpDialog();
        return true;
    case DCMD_BOOKMARK_SAVE_N:
        _docview->doCommand( DCMD_BOOKMARK_SAVE_N, params );
        if ( _props->getBoolDef( PROP_AUTOSAVE_BOOKMARKS, true ) )
            saveHistory( lString16() );
        return true;
    default:
        // do nothing
        ;
    }
    return CRViewDialog::onCommand( command, params );
}
Exemplo n.º 14
0
LVStreamRef GetEpubCoverpage(LVContainerRef arc)
{
    // check root media type
    lString16 rootfilePath = EpubGetRootFilePath(arc);
    if ( rootfilePath.empty() )
        return LVStreamRef();

    EncryptedDataContainer * decryptor = new EncryptedDataContainer(arc);
    if (decryptor->open()) {
        CRLog::debug("EPUB: encrypted items detected");
    }

    LVContainerRef m_arc = LVContainerRef(decryptor);

    lString16 codeBase = LVExtractPath(rootfilePath, false);
    CRLog::trace("codeBase=%s", LCSTR(codeBase));

    LVStreamRef content_stream = m_arc->OpenStream(rootfilePath.c_str(), LVOM_READ);
    if ( content_stream.isNull() )
        return LVStreamRef();


    LVStreamRef coverPageImageStream;
    // reading content stream
    {
        lString16 coverId;
        ldomDocument * doc = LVParseXMLStream( content_stream );
        if ( !doc )
            return LVStreamRef();

        for ( int i=1; i<20; i++ ) {
            ldomNode * item = doc->nodeFromXPath( lString16(L"package/metadata/meta[") + lString16::itoa(i) + L"]" );
            if ( !item )
                break;
            lString16 name = item->getAttributeValue(L"name");
            lString16 content = item->getAttributeValue(L"content");
            if (name == L"cover")
                coverId = content;
        }

        // items
        for ( int i=1; i<50000; i++ ) {
            ldomNode * item = doc->nodeFromXPath( lString16(L"package/manifest/item[") + lString16::itoa(i) + L"]" );
            if ( !item )
                break;
            lString16 href = item->getAttributeValue(L"href");
            lString16 id = item->getAttributeValue(L"id");
            if ( !href.empty() && !id.empty() ) {
                if (id == coverId) {
                    // coverpage file
                    lString16 coverFileName = codeBase + href;
                    CRLog::info("EPUB coverpage file: %s", LCSTR(coverFileName));
                    coverPageImageStream = m_arc->OpenStream(coverFileName.c_str(), LVOM_READ);
                }
            }
        }
        delete doc;
    }

    return coverPageImageStream;
}
Exemplo n.º 15
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

    CRLog::setFileLogger( "crengine.log", true );
    CRLog::setLogLevel( CRLog::LL_TRACE );
    //InitCREngineLog("/root/abook/crengine/crlog.ini");

#if 0
	MMapTest();
#endif

    lString8 exe_dir;
    char exe_fn[MAX_PATH+1];
    GetModuleFileNameA( NULL, exe_fn, MAX_PATH );
    lChar16 exe_fn16[MAX_PATH+1];
    GetModuleFileNameW( NULL, exe_fn16, MAX_PATH );
	lString16 exedir = LVExtractPath(lString16(exe_fn16));	
	lString8 exedir8 = UnicodeToUtf8( exedir );
	CRLog::debug("exedir=%s", exedir8.c_str());

	CRMoFileTranslator * translator = new CRMoFileTranslator();
	translator->openMoFile(exedir + L"/po/ru.mo");
	CRI18NTranslator::setTranslator( translator );


	lChar16 sysdir[MAX_PATH+1];
	GetWindowsDirectoryW(sysdir, MAX_PATH);
	lString16 fontdir( sysdir );
	fontdir << L"\\Fonts\\";
	lString8 fontdir8( UnicodeToUtf8(fontdir) );
	lString8 fd = UnicodeToLocal(exedir);
	lString16Collection fontDirs;
	//fontDirs.add( fontdir );
    fontDirs.add( exedir + L"fonts" );
	InitCREngine( exe_fn, fontDirs );
    const char * fontnames[] = {
#if 1
        "arial.ttf",
        "ariali.ttf",
        "arialb.ttf",
        "arialbi.ttf",
#endif
        "arialn.ttf",
        "arialni.ttf",
        "arialnb.ttf",
        "arialnbi.ttf",
        "cour.ttf",
        "couri.ttf",
        "courbd.ttf",
        "courbi.ttf",
        "times.ttf",
        "timesi.ttf",
        "timesb.ttf",
        "timesbi.ttf",
#if 0
        "comic.ttf",
        "comicbd.ttf",
        "verdana.ttf",
        "verdanai.ttf",
        "verdanab.ttf",
        "verdanaz.ttf",
        "bookos.ttf",
        "bookosi.ttf",
        "bookosb.ttf",
        "bookosbi.ttf",
#endif
#if 0
        "calibri.ttf",
        "calibrii.ttf",
        "calibrib.ttf",
        "calibriz.ttf",
        "cambria.ttf",
        "cambriai.ttf",
        "cambriab.ttf",
        "cambriaz.ttf",
        "georgia.ttf",
        "georgiai.ttf",
        "georgiab.ttf",
        "georgiaz.ttf",
#endif
        NULL
    };
    for ( int fi = 0; fontnames[fi]; fi++ ) {
        fontMan->RegisterFont( fontdir8 + fontnames[fi] );
    }
    //LVCHECKPOINT("WinMain start");

    if (!fontMan->GetFontCount())
    {
        //error
        char str[1000];
#if (USE_FREETYPE==1)
        sprintf(str, "Cannot open font file(s) fonts/*.ttf \nCannot work without font\nPlace some TTF files to font\\ directory" );
#else
        sprintf(str, "Cannot open font file(s) font#.lbf \nCannot work without font\nUse FontConv utility to generate .lbf fonts from TTF" );
#endif
        MessageBoxA( NULL, str, "CR Engine :: Fb2Test -- fatal error!", MB_OK);
        return 1;
    }

    lString8 cmdline(lpCmdLine);
    if ( cmdline.empty() )
        return 2; // need filename

    hInst = hInstance;
    MyRegisterClass(hInstance);

    {

		CRWin32WindowManager winman(500, 700);

		const char * keymap_locations [] = {
			exedir8.c_str(),
			NULL,
		};
		loadKeymaps( winman, keymap_locations );
		

        ldomDocCache::init( exedir + L"cache", 0x100000 * 96 ); /*96Mb*/

        winman.loadSkin( LVExtractPath(LocalToUnicode(lString8(exe_fn))) + L"skin" );
        V3DocViewWin * main_win = new V3DocViewWin( &winman, LVExtractPath(LocalToUnicode(lString8(exe_fn))) );
        main_win->getDocView()->setBackgroundColor(0xFFFFFF);
        main_win->getDocView()->setTextColor(0x000000);
        main_win->getDocView()->setFontSize( 20 );
		main_win->loadCSS( exedir + L"fb2.css" );
		main_win->loadSettings( exedir + L"cr3.ini" );
		main_win->saveSettings(lString16());
		main_win->setHelpFile( exedir + L"cr3-manual-ru.fb2" );
		HyphMan::initDictionaries( exedir + L"hyph\\" );
		main_win->loadDefaultCover( exedir + L"cr3_def_cover.png" );
		main_win->setBookmarkDir(lString16("c:\\cr3\\bookmarks\\"));
		lString8 exedir8 = UnicodeToUtf8( exedir );
		const char * dirs[] = {
			exedir8.c_str(),
			NULL
		};

		loadKeymaps( winman, dirs );

        main_win->loadHistory( exedir + L"cr3hist.bmk" );

        winman.activateWindow( main_win );
        if ( !main_win->loadDocument( LocalToUnicode( cmdline )) ) {
            char str[100];
            sprintf(str, "Cannot open document file %s", cmdline.c_str());
            MessageBoxA( NULL, str, "CR Engine :: Fb2Test -- fatal error!", MB_OK);
            return 1;
        } else {
            winman.runEventLoop();
        }
    }
    //ShutdownFontManager();

    return 0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
    int res = 0;
    {
        Device::instance(); // initialize device
#ifndef i386
        QProcess::execute("eips -c");
        pTouch = new TouchScreen();
#endif
        lString16 exedir = LVExtractPath(LocalToUnicode(lString8(argv[0])));
        LVAppendPathDelimiter(exedir);
        lString16 datadir = exedir + L"data/";
        lString16 exefontpath = exedir + L"fonts";

        lString16Collection fontDirs;
        fontDirs.add(exefontpath);
#ifndef i386
        fontDirs.add(lString16(L"/usr/java/lib/fonts"));
        fontDirs.add(lString16(L"/mnt/us/fonts"));
#endif
        CRPropRef props = LVCreatePropsContainer();
        {
            LVStreamRef cfg = LVOpenFileStream(UnicodeToUtf8(datadir + L"cr3.ini").data(), LVOM_READ);
            if(!cfg.isNull()) props->loadFromStream(cfg.get());
        }

        lString16 lang = props->getStringDef(PROP_WINDOW_LANG, "");
        InitCREngineLog(props);
        CRLog::info("main()");

        if(!InitCREngine(argv[0], fontDirs)) {
            printf("Cannot init CREngine - exiting\n");
            return 2;
        }
#ifndef i386
        PrintString(1, 1, "crengine version: " + QString(CR_ENGINE_VERSION));
        PrintString(1, 2, QString("buid date: %1 %2").arg(__DATE__).arg(__TIME__));
        if (!Device::isTouch()) {
            QString message = "Please wait while application is loading...";
            int xpos = ((Device::getWidth()/12-1)-message.length())/2;
            int ypos = (Device::getHeight()/20-2)/2;
            PrintString(xpos, ypos, message);
        }
#endif

        // set row count depending on device model (used in lists)
        int rc = props->getIntDef(PROP_WINDOW_ROW_COUNT, 0);
        if(!rc) {
#ifndef i386
            switch(Device::getModel()) {
            case Device::KDX:
                rc = 16;
                break;
            case Device::KT:
            case Device::KPW:
                rc = 8;
                break;
            default:
                rc = 10;
            }
            props->setInt(PROP_WINDOW_ROW_COUNT, rc);
#else
            props->setInt(PROP_WINDOW_ROW_COUNT, 10);
#endif
            LVStreamRef cfg = LVOpenFileStream(UnicodeToUtf8(datadir + L"cr3.ini").data(), LVOM_WRITE);
            props->saveToStream(cfg.get());
        }

        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
        MyApplication a(argc, argv);
        pMyApp = &a;
        // set app stylesheet
#ifndef i386
        QString style = Device::isTouch() ? "stylesheet_pw.qss" : "stylesheet_k3.qss";
        QFile qss(QDir::toNativeSeparators(cr2qt(datadir)) + style);
        // set up full update interval for the graphics driver
        Device::setFullScreenUpdateEvery(props->getIntDef(PROP_DISPLAY_FULL_UPDATE_INTERVAL, 1));
#else
        QFile qss(QDir::toNativeSeparators(cr2qt(datadir)) + "stylesheet_k3.qss");
#endif
        qss.open(QFile::ReadOnly);
        if(qss.error() == QFile::NoError) {
            a.setStyleSheet(qss.readAll());
            qss.close();
        }
        QString translations = cr2qt(datadir) + "i18n";
        QTranslator myappTranslator;
        if(!lang.empty() && lang.compare(L"English")) {
            if(myappTranslator.load(cr2qt(lang), translations))
                QApplication::installTranslator(&myappTranslator);
            else
                qDebug("Can`t load translation file %s from dir %s", UnicodeToUtf8(lang).c_str(), UnicodeToUtf8(qt2cr(translations)).c_str());
        }

        (void) signal(SIGUSR1, sigCatcher);

        MainWindow mainWin;
        a.setMainWindow(&mainWin);
        mainWin.showFullScreen();
        mainWin.doStartupActions();
        res = a.exec();
    }
    ShutdownCREngine();
    return res;
}
Exemplo n.º 17
0
void V3DocViewWin::showAboutDialog()
{
	_docview->savePosition();
	CRFileHistRecord * hist = _docview->getCurrentFileHistRecord();
    lString16 title = L"Cool Reader ";
#ifndef PACKAGE_VERSION
#define PACKAGE_VERSION CR_ENGINE_VERSION
#endif
    title << Utf8ToUnicode(lString8(PACKAGE_VERSION));

    lString8 txt;
    //=========================================================
    txt << "<table><col width=\"30%\"/><col width=\"70%\"/>\n";
    CRPropRef props = _docview->getDocProps();

    lString8 statusInfo;
	addPropLine( statusInfo, _("Current page"), lString16::itoa(_docview->getCurPage()+1) );
	addPropLine( statusInfo, _("Total pages"), lString16::itoa(_docview->getPageCount()) );
    addPropLine( statusInfo, _("Battery state"), _docview->getBatteryState()==-1 ? lString16(_("charging...")) : lString16::itoa(_docview->getBatteryState()) + L"%" );
	addPropLine( statusInfo, _("Current Time"), _docview->getTimeString() );
	// TODO:
	if ( hist ) {
		CRBookmark * lastpos = hist->getLastPos();
		if ( lastpos ) {
			addPropLine( statusInfo, _("Current chapter"), lastpos->getTitleText() );
		}
	}
    addInfoSection( txt, statusInfo, _("Status") );

    lString8 fileInfo;
    addPropLine( fileInfo, _("Archive name"), props->getStringDef(DOC_PROP_ARC_NAME) );
    addPropLine( fileInfo, _("Archive path"), props->getStringDef(DOC_PROP_ARC_PATH) );
    addPropLine( fileInfo, _("Archive size"), props->getStringDef(DOC_PROP_ARC_SIZE) );
    addPropLine( fileInfo, _("File name"), props->getStringDef(DOC_PROP_FILE_NAME) );
    addPropLine( fileInfo, _("File path"), props->getStringDef(DOC_PROP_FILE_PATH) );
    addPropLine( fileInfo, _("File size"), props->getStringDef(DOC_PROP_FILE_SIZE) );
    addPropLine( fileInfo, _("File format"), props->getStringDef(DOC_PROP_FILE_FORMAT) );
    addInfoSection( txt, fileInfo, _("File info") );

    lString8 bookInfo;
    addPropLine( bookInfo, _("Title"), props->getStringDef(DOC_PROP_TITLE) );
    addPropLine( bookInfo, _("Author(s)"), props->getStringDef(DOC_PROP_AUTHORS) );
    addPropLine( bookInfo, _("Series name"), props->getStringDef(DOC_PROP_SERIES_NAME) );
    addPropLine( bookInfo, _("Series number"), props->getStringDef(DOC_PROP_SERIES_NUMBER) );
    addPropLine( bookInfo, _("Date"), getDocText( getDocView()->getDocument(), "/FictionBook/description/title-info/date", ", " ) );
    addPropLine( bookInfo, _("Genres"), getDocText( getDocView()->getDocument(), "/FictionBook/description/title-info/genre", ", " ) );
    addPropLine( bookInfo, _("Translator"), getDocText( getDocView()->getDocument(), "/FictionBook/description/title-info/translator", ", " ) );
    addInfoSection( txt, bookInfo, _("Book info") );

    lString8 docInfo;
    addPropLine( docInfo, _("Document author"), getDocAuthors( getDocView()->getDocument(), "/FictionBook/description/document-info/author", " " ) );
    addPropLine( docInfo, _("Document date"), getDocText( getDocView()->getDocument(), "/FictionBook/description/document-info/date", " " ) );
    addPropLine( docInfo, _("Document source URL"), getDocText( getDocView()->getDocument(), "/FictionBook/description/document-info/src-url", " " ) );
    addPropLine( docInfo, _("OCR by"), getDocText( getDocView()->getDocument(), "/FictionBook/description/document-info/src-ocr", " " ) );
    addPropLine( docInfo, _("Document version"), getDocText( getDocView()->getDocument(), "/FictionBook/description/document-info/version", " " ) );
    addPropLine( docInfo, _("Change history"), getDocText( getDocView()->getDocument(), "/FictionBook/description/document-info/history", " " ) );
    addInfoSection( txt, docInfo, _("Document info") );

    lString8 pubInfo;
    addPropLine( pubInfo, _("Publication name"), getDocText( getDocView()->getDocument(), "/FictionBook/description/publish-info/book-name", " " ) );
    addPropLine( pubInfo, _("Publisher"), getDocText( getDocView()->getDocument(), "/FictionBook/description/publish-info/publisher", " " ) );
    addPropLine( pubInfo, _("Publisher city"), getDocText( getDocView()->getDocument(), "/FictionBook/description/publish-info/city", " " ) );
    addPropLine( pubInfo, _("Publication year"), getDocText( getDocView()->getDocument(), "/FictionBook/description/publish-info/year", " " ) );
    addPropLine( pubInfo, _("ISBN"), getDocText( getDocView()->getDocument(), "/FictionBook/description/publish-info/isbn", " " ) );
    addInfoSection( txt, pubInfo, _("Publication info") );

    addPropLine( txt, _("Custom info"), getDocText( getDocView()->getDocument(), "/FictionBook/description/custom-info", " " ) );

    txt << "</table>\n";

    //CRLog::trace(txt.c_str());
    //=========================================================
    txt = CRViewDialog::makeFb2Xml(txt);
    CRViewDialog * dlg = new CRViewDialog( _wm, title, txt, lvRect(), true, true );
    dlg->getDocView()->setVisiblePageCount(1);
    //int fs = _props->getIntDef( PROP_FILE_PROPS_FONT_SIZE, 26 );
    //dlg->getDocView()->setFontSize(fs);
    _wm->activateWindow( dlg );
}
Exemplo n.º 18
0
void V3DocViewWin::showMainMenu()
{
    lvRect fullRc = _wm->getScreen()->getRect();
    CRFullScreenMenu * menu_win = new CRFullScreenMenu(
            _wm, 0, lString16(_("Main Menu")), 8, fullRc );
/*
VIEWER_MENU_GOTOFIRSTPAGE=Go to first page
VIEWER_MENU_GOTOENDPAGE=Go to last page
VIEWER_MENU_GOTOPAGE=Go to page...
VIEWER_MENU_GOTOINDEX=Go to index
VIEWER_MENU_5ABOUT=About...
VIEWER_MENU_4ABOUT=About...
*/
    menu_win->setSkinName(lString16(L"#main"));
	CRGUIAcceleratorTableRef menuItems = _wm->getAccTables().get(lString16("mainMenuItems"));
	if ( !menuItems.isNull() && menuItems->length()>1 ) {
		// get menu from file
		for ( unsigned i=0; i<menuItems->length(); i++ ) {
			const CRGUIAccelerator * acc = menuItems->get( i );
			int cmd = acc->commandId;
			int param = acc->commandParam;
			const char * name = getCommandName( cmd, param );
			int key = 0;
			int keyFlags = 0;
			lString8 label( name );
			if ( _acceleratorTable->findCommandKey( cmd, param, key, keyFlags ) ) {
				const char * keyname = getKeyName( key, keyFlags );
				if ( keyname && keyname[0] )
					label << "\t" << keyname;
			}
			menu_win->addItem( new CRMenuItem( menu_win, cmd,
				label.c_str(),
				LVImageSourceRef(),
				LVFontRef() ) );
		}
	} else {
		// default menu
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_ABOUT,
					_("About"),
					LVImageSourceRef(),
					LVFontRef() ) );
	#if 0
		menu_win->addItem( new CRMenuItem( menu_win, DCMD_BEGIN,
					_wm->translateString("VIEWER_MENU_GOTOFIRSTPAGE", "Go to first page"),
					LVImageSourceRef(),
					LVFontRef() ) );
	#endif
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_GO_PAGE,
					_("Go to page"),
					LVImageSourceRef(),
					LVFontRef() ) );
	#if 0
		menu_win->addItem( new CRMenuItem( menu_win, DCMD_END,
					_wm->translateString("VIEWER_MENU_GOTOENDPAGE", "Go to last page"),
					LVImageSourceRef(),
					LVFontRef() ) );
	#endif

		menu_win->addItem( new CRMenuItem( menu_win, MCMD_RECENT_BOOK_LIST,
					_("Open recent book"),
					LVImageSourceRef(),
					LVFontRef() ) );

	#ifdef WITH_DICT
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_DICT,
					_("Dictionary"),
					LVImageSourceRef(),
					LVFontRef() ) );
	#endif
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_CITE,
					_("Cite"),
					LVImageSourceRef(),
					LVFontRef() ) );
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_BOOKMARK_LIST,
					_("Bookmarks"),
					LVImageSourceRef(),
					LVFontRef() ) );
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_SEARCH,
					_("Search"),
					LVImageSourceRef(),
					LVFontRef() ) );
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_SETTINGS,
					_("Settings"),
					LVImageSourceRef(),
					LVFontRef() ) );
		if ( !_helpFile.empty() )
			menu_win->addItem( new CRMenuItem( menu_win, MCMD_HELP,
					_("Help"),
					LVImageSourceRef(),
					LVFontRef() ) );
		menu_win->addItem( new CRMenuItem( menu_win, MCMD_HELP_KEYS,
					_("Keyboard layout"),
					LVImageSourceRef(),
					LVFontRef() ) );
	}

    menu_win->setAccelerators( getMenuAccelerators() );

    lString16 s(_("$1 - choose command\n$2, $3 - close"));
    s.replaceParam(1, menu_win->getItemNumberKeysName());
    s.replaceParam(2, menu_win->getCommandKeyName(MCMD_OK) );
    s.replaceParam(3, menu_win->getCommandKeyName(MCMD_CANCEL) );
    menu_win->setStatusText( s );
    menu_win->setFullscreen( true );

    menu_win->reconfigure(0);
    _wm->activateWindow( menu_win );
}
Exemplo n.º 19
0
bool InitCREngine( const char * exename, lString16Collection & fontDirs )
{
	CRLog::trace("InitCREngine(%s)", exename);
#ifdef _WIN32
    lString16 appname( exename );
    int lastSlash=-1;
    lChar16 slashChar = '/';
    for ( int p=0; p<(int)appname.length(); p++ ) {
        if ( appname[p]=='\\' ) {
            slashChar = '\\';
            lastSlash = p;
        } else if ( appname[p]=='/' ) {
            slashChar = '/';
            lastSlash=p;
        }
    }

    lString16 appPath;
    if ( lastSlash>=0 )
        appPath = appname.substr( 0, lastSlash+1 );
	InitCREngineLog(UnicodeToUtf8(appPath).c_str());
    lString16 datadir = appPath;
#else
    lString16 datadir = lString16(CR3_DATA_DIR);
#endif
    lString16 fontDir = datadir + L"fonts";
	lString8 fontDir8_ = UnicodeToUtf8(fontDir);

    fontDirs.add( fontDir );

    LVAppendPathDelimiter( fontDir );

    lString8 fontDir8 = UnicodeToLocal(fontDir);
    //const char * fontDir8s = fontDir8.c_str();
    //InitFontManager( fontDir8 );
    InitFontManager( lString8() );

#ifdef _WIN32
    lChar16 sysdir[MAX_PATH+1];
    GetWindowsDirectoryW(sysdir, MAX_PATH);
    lString16 fontdir( sysdir );
    fontdir << L"\\Fonts\\";
    lString8 fontdir8( UnicodeToUtf8(fontdir) );
    const char * fontnames[] = {
        "arial.ttf",
        "ariali.ttf",
        "arialb.ttf",
        "arialbi.ttf",
        "arialn.ttf",
        "arialni.ttf",
        "arialnb.ttf",
        "arialnbi.ttf",
        "cour.ttf",
        "couri.ttf",
        "courbd.ttf",
        "courbi.ttf",
        "times.ttf",
        "timesi.ttf",
        "timesb.ttf",
        "timesbi.ttf",
        "comic.ttf",
        "comicbd.ttf",
        "verdana.ttf",
        "verdanai.ttf",
        "verdanab.ttf",
        "verdanaz.ttf",
        "bookos.ttf",
        "bookosi.ttf",
        "bookosb.ttf",
        "bookosbi.ttf",
       "calibri.ttf",
        "calibrii.ttf",
        "calibrib.ttf",
        "calibriz.ttf",
        "cambria.ttf",
        "cambriai.ttf",
        "cambriab.ttf",
        "cambriaz.ttf",
        "georgia.ttf",
        "georgiai.ttf",
        "georgiab.ttf",
        "georgiaz.ttf",
        NULL
    };
    for ( int fi = 0; fontnames[fi]; fi++ ) {
        fontMan->RegisterFont( fontdir8 + fontnames[fi] );
    }
#endif
    // Load font definitions into font manager
    // fonts are in files font1.lbf, font2.lbf, ... font32.lbf
    // use fontconfig

    lString16Collection fontExt;
    fontExt.add(lString16(L".ttf"));
    fontExt.add(lString16(L".otf"));
    fontExt.add(lString16(L".pfa"));
    fontExt.add(lString16(L".pfb"));
    lString16Collection fonts;

    getDirectoryFonts( fontDirs, fontExt, fonts, true );

    // load fonts from file
    CRLog::debug("%d font files found", fonts.length());
    //if (!fontMan->GetFontCount()) {
	for ( unsigned fi=0; fi<fonts.length(); fi++ ) {
	    lString8 fn = UnicodeToLocal(fonts[fi]);
	    CRLog::trace("loading font: %s", fn.c_str());
	    if ( !fontMan->RegisterFont(fn) ) {
		CRLog::trace("    failed\n");
	    }
	}
    //}

    // init hyphenation manager
    //char hyphfn[1024];
    //sprintf(hyphfn, "Russian_EnUS_hyphen_(Alan).pdb" );
    //if ( !initHyph( (UnicodeToLocal(appPath) + hyphfn).c_str() ) ) {
#ifdef _LINUX
    //    initHyph( "/usr/share/crengine/hyph/Russian_EnUS_hyphen_(Alan).pdb" );
#endif
    //}

    if (!fontMan->GetFontCount())
    {
        //error
#if (USE_FREETYPE==1)
        printf("Fatal Error: Cannot open font file(s) .ttf \nCannot work without font\n" );
#else
        printf("Fatal Error: Cannot open font file(s) font#.lbf \nCannot work without font\nUse FontConv utility to generate .lbf fonts from TTF\n" );
#endif
        return false;
    }

    printf("%d fonts loaded.\n", fontMan->GetFontCount());

    return true;

}
Exemplo n.º 20
0
V3DocViewWin::V3DocViewWin( CRGUIWindowManager * wm, lString16 dataDir )
: CRViewDialog ( wm, lString16(), lString8(), lvRect(), false, false ), _dataDir(dataDir), _loadFileStart(0)
{
    CRLog::trace("V3DocViewWin()");
    LVArray<int> sizes( cr_font_sizes, sizeof(cr_font_sizes)/sizeof(int) );
	_fullscreen = true;
    _docview->setShowCover( true );
    _docview->setFontSizes( sizes, true );
    _docview->setCallback( this );
    _props = LVCreatePropsContainer();
    _newProps = _props;
    // TODO: move skin outside
    //lString16 skinfile = _dataDir;
    //LVAppendPathDelimiter( skinfile );
    //skinfile << L"skin";
    //lString8 s8 = UnicodeToLocal( skinfile );
    //CRLog::debug("Skin file is %s", s8.c_str() );
    //loadSkin( skinfile );

#define BATTERY_HEADER \
        "36 19 5 1", \
        "0 c #000000", \
        "X c #000000", \
        "o c #AAAAAA", \
        ". c #FFFFFF", \
        "  c None",


    LVRefVec<LVImageSource> icons;
    static const char * battery8[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        "....0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0000.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0000.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        "....0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        "   .0.XXXXXX.XXXXXX.XXXXXX.XXXXXX.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery7[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        "....0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0000.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        ".0000.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        "....0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        "   .0.oooooo.XXXXXX.XXXXXX.XXXXXX.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery6[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0........XXXXXX.XXXXXX.XXXXXX.0.",
        "....0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0000........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0..0........XXXXXX.XXXXXX.XXXXXX.0.",
        ".0000........XXXXXX.XXXXXX.XXXXXX.0.",
        "....0........XXXXXX.XXXXXX.XXXXXX.0.",
        "   .0........XXXXXX.XXXXXX.XXXXXX.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery5[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0........oooooo.XXXXXX.XXXXXX.0.",
        "....0........oooooo.XXXXXX.XXXXXX.0.",
        ".0000........oooooo.XXXXXX.XXXXXX.0.",
        ".0..0........oooooo.XXXXXX.XXXXXX.0.",
        ".0..0........oooooo.XXXXXX.XXXXXX.0.",
        ".0..0........oooooo.XXXXXX.XXXXXX.0.",
        ".0..0........oooooo.XXXXXX.XXXXXX.0.",
        ".0..0........oooooo.XXXXXX.XXXXXX.0.",
        ".0..0........oooooo.XXXXXX.XXXXXX.0.",
        ".0..0........oooooo.XXXXXX.XXXXXX.0.",
        ".0000........oooooo.XXXXXX.XXXXXX.0.",
        "....0........oooooo.XXXXXX.XXXXXX.0.",
        "   .0........oooooo.XXXXXX.XXXXXX.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery4[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0...............XXXXXX.XXXXXX.0.",
        "....0...............XXXXXX.XXXXXX.0.",
        ".0000...............XXXXXX.XXXXXX.0.",
        ".0..0...............XXXXXX.XXXXXX.0.",
        ".0..0...............XXXXXX.XXXXXX.0.",
        ".0..0...............XXXXXX.XXXXXX.0.",
        ".0..0...............XXXXXX.XXXXXX.0.",
        ".0..0...............XXXXXX.XXXXXX.0.",
        ".0..0...............XXXXXX.XXXXXX.0.",
        ".0..0...............XXXXXX.XXXXXX.0.",
        ".0000...............XXXXXX.XXXXXX.0.",
        "....0...............XXXXXX.XXXXXX.0.",
        "   .0...............XXXXXX.XXXXXX.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery3[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0...............oooooo.XXXXXX.0.",
        "....0...............oooooo.XXXXXX.0.",
        ".0000...............oooooo.XXXXXX.0.",
        ".0..0...............oooooo.XXXXXX.0.",
        ".0..0...............oooooo.XXXXXX.0.",
        ".0..0...............oooooo.XXXXXX.0.",
        ".0..0...............oooooo.XXXXXX.0.",
        ".0..0...............oooooo.XXXXXX.0.",
        ".0..0...............oooooo.XXXXXX.0.",
        ".0..0...............oooooo.XXXXXX.0.",
        ".0000...............oooooo.XXXXXX.0.",
        "....0...............oooooo.XXXXXX.0.",
        "   .0...............oooooo.XXXXXX.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery2[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0......................XXXXXX.0.",
        "....0......................XXXXXX.0.",
        ".0000......................XXXXXX.0.",
        ".0..0......................XXXXXX.0.",
        ".0..0......................XXXXXX.0.",
        ".0..0......................XXXXXX.0.",
        ".0..0......................XXXXXX.0.",
        ".0..0......................XXXXXX.0.",
        ".0..0......................XXXXXX.0.",
        ".0..0......................XXXXXX.0.",
        ".0000......................XXXXXX.0.",
        "....0......................XXXXXX.0.",
        "   .0......................XXXXXX.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery1[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0......................oooooo.0.",
        "....0......................oooooo.0.",
        ".0000......................oooooo.0.",
        ".0..0......................oooooo.0.",
        ".0..0......................oooooo.0.",
        ".0..0......................oooooo.0.",
        ".0..0......................oooooo.0.",
        ".0..0......................oooooo.0.",
        ".0..0......................oooooo.0.",
        ".0..0......................oooooo.0.",
        ".0000......................oooooo.0.",
        "....0......................oooooo.0.",
        "   .0......................oooooo.0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery0[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0.............................0.",
        "....0.............................0.",
        ".0000.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0000.............................0.",
        "....0.............................0.",
        "   .0.............................0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery_charge[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0.............................0.",
        "....0.............................0.",
        ".0000.............................0.",
        ".0..0................XX...........0.",
        ".0..0...............XXXXX.........0.",
        ".0..0..XXXX........XXXXXXXX.......0.",
        ".0..0....XXXXXX...XXXX...XXXXX....0.",
        ".0..0.......XXXXXXXXX.......XXXX..0.",
        ".0..0.........XXXXXX..............0.",
        ".0..0............XX...............0.",
        ".0000.............................0.",
        "....0.............................0.",
        "   .0.............................0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    static const char * battery_frame[] = {
        BATTERY_HEADER
        "   .................................",
        "   .0000000000000000000000000000000.",
        "   .0.............................0.",
        "   .0.............................0.",
        "....0.............................0.",
        ".0000.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0..0.............................0.",
        ".0000.............................0.",
        "....0.............................0.",
        "   .0.............................0.",
        "   .0.............................0.",
        "   .0000000000000000000000000000000.",
        "   .................................",
    };
    icons.add( LVCreateXPMImageSource( battery_charge ) );
//#ifdef NO_BATTERY_GAUGE
//    icons.add( LVCreateXPMImageSource( battery_frame ) );
//#else
    icons.add( LVCreateXPMImageSource( battery0 ) );
    icons.add( LVCreateXPMImageSource( battery1 ) );
    icons.add( LVCreateXPMImageSource( battery2 ) );
    icons.add( LVCreateXPMImageSource( battery3 ) );
    icons.add( LVCreateXPMImageSource( battery4 ) );
    icons.add( LVCreateXPMImageSource( battery5 ) );
    icons.add( LVCreateXPMImageSource( battery6 ) );
    icons.add( LVCreateXPMImageSource( battery7 ) );
    icons.add( LVCreateXPMImageSource( battery8 ) );
//#endif
    icons.add( LVCreateXPMImageSource( battery_frame ) );
    _docview->setBatteryIcons( icons );
    _wm->setBatteryIcons(icons);
    setAccelerators( _wm->getAccTables().get("main") );
}
Exemplo n.º 21
0
/// document formatting finished
void V3DocViewWin::OnFormatEnd()
{
    time_t t = time((time_t)0);
    if ( t - _loadFileStart >= SECONDS_BEFORE_PROGRESS_BAR )
        _wm->showProgress(lString16("cr3_wait_icon.png"), 100);
}
Exemplo n.º 22
0
CRBookmarkMenuItem::CRBookmarkMenuItem( CRMenu * menu, int shortcut, CRBookmark * bookmark, int page )
: CRMenuItem(menu, shortcut, lString16(_("Empty slot")), LVImageSourceRef(), LVFontRef() ), _bookmark( bookmark ), _page(page)
{

}
Exemplo n.º 23
0
lString16 qt2cr(QString str)
{
    return lString16( str.toUtf8().constData() );
}
Exemplo n.º 24
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

    CRLog::setFileLogger( "crengine.log" );
    CRLog::setLogLevel( CRLog::LL_TRACE );

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	//make_dither_table();

	//TestWol();
/*
    LVStreamRef zipfile = LVOpenFileStream( L"zip_test.zip", LVOM_READ );
    if (!zipfile.isNull())
    {
        LVContainerRef zip = LVOpenArchieve( zipfile );
        if (!zip.isNull())
        {
            LVStreamRef log = LVOpenFileStream("ziptest.log", LVOM_WRITE);
            for (int i=0; i<zip->GetObjectCount(); i++)
            {
                const LVContainerItemInfo * item = zip->GetObjectInfo(i);
                if (item)
                {
                    //
                    *log << UnicodeToLocal( item->GetName() );
                    *log << lString8::itoa( (int)item->GetSize() );

                    LVStreamRef unpstream = zip->OpenStream( item->GetName(), LVOM_READ );
                    if (!unpstream.isNull())
                    {
                        *log << "\n arc stream opened ok \n";
                        LVStreamRef outstream = LVOpenFileStream( item->GetName(), LVOM_WRITE );
                        if ( !outstream.isNull() )
                        {
                            int copiedBytes = (int)LVPumpStream( outstream, unpstream );
                            *log << " copied " << lString8::itoa(copiedBytes) << " bytes\n";
                        }
                        else
                        {
                            *log << " error opening out stream\n";
                        }
                    }
                }
            }
        }
    }
*/
	lString8 exe_dir;
	char exe_fn[MAX_PATH+1];
	GetModuleFileNameA( NULL, exe_fn, MAX_PATH );
	int last_slash = -1;
	int i;
	for (i=0; exe_fn[i]; i++)
		if (exe_fn[i]=='\\' || exe_fn[i]=='/')
			last_slash = i;
	if (last_slash>0)
		exe_dir = lString8( exe_fn, last_slash );

	// init hyphenation manager
	initHyph( (exe_dir + "\\russian_EnUS_hyphen_(Alan).pdb").c_str() );

    lString8 fontDir = exe_dir;
    fontDir << "\\fonts";

    // init bitmap font manager
    InitFontManager( fontDir );


    // Load font definitions into font manager
    // fonts are in files font1.lbf, font2.lbf, ... font32.lbf
#if (USE_FREETYPE==1)
        LVContainerRef dir = LVOpenDirectory( LocalToUnicode(fontDir).c_str() );
        if ( !dir.isNull() )
        for ( i=0; i<dir->GetObjectCount(); i++ ) {
            const LVContainerItemInfo * item = dir->GetObjectInfo(i);
            lString16 fileName = item->GetName();
            if ( !item->IsContainer() && fileName.length()>4 && lString16(fileName, fileName.length()-4, 4)==L".ttf" ) {
                lString8 fn = UnicodeToLocal(fileName);
                printf("loading font: %s\n", fn.c_str());
                if ( !fontMan->RegisterFont(fn) ) {
                    printf("    failed\n");
                }
            }
        }
        //fontMan->RegisterFont(lString8("arial.ttf"));
#else
#if (USE_WIN32_FONTS==0)

    #define MAX_FONT_FILE 32
    for (i=0; i<MAX_FONT_FILE; i++)
    {
        char fn[32];
        sprintf( fn, "font%d.lbf", i );
        fontMan->RegisterFont( lString8(fn) );
    }
#endif
#endif
    //LVCHECKPOINT("WinMain start");
    text_view = new LVDocView;

    // stylesheet can be placed to file fb2.css
    // if not found, default stylesheet will be used
    lString8 css = readFileToString( (exe_dir + "\\fb2.css").c_str() );
    if (css.length() > 0)
        text_view->setStyleSheet( css );

    //LVCHECKPOINT("WinMain before loads");

    if (!fontMan->GetFontCount())
    {
        //error
        char str[1000];
#if (USE_FREETYPE==1)
        sprintf(str, "Cannot open font file(s) fonts/*.ttf \nCannot work without font\nPlace some TTF files to font\\ directory" );
#else
        sprintf(str, "Cannot open font file(s) font#.lbf \nCannot work without font\nUse FontConv utility to generate .lbf fonts from TTF" );
#endif
        MessageBoxA( NULL, str, "CR Engine :: Fb2Test -- fatal error!", MB_OK);
        return 1;
    }

    lString8 cmdline(lpCmdLine);
    cmdline.trim();
    if ( cmdline == "test_format" ) {
        testFormatting();
        return 1;
    }
    if (cmdline.empty())
    {
        cmdline = OpenFileDialog( NULL );
        //cmdline = "example2.fb2";
    }

    if ( cmdline.empty() )
        return 2;
    if ( !text_view->LoadDocument( cmdline.c_str() ))
    {
        //error
        char str[100];
        sprintf(str, "Cannot open document file %s", cmdline.c_str());
        MessageBoxA( NULL, str, "CR Engine :: Fb2Test -- fatal error!", MB_OK);
        return 1;
    }

    //LVCHECKPOINT("WinMain after loads");

	// Initialize global strings
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}


	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_FONTTEST);

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

    delete text_view;

    ShutdownFontManager();

	return msg.wParam;
}
Exemplo n.º 25
0
bool ImportEpubDocument( LVStreamRef stream, ldomDocument * m_doc, LVDocViewCallback * progressCallback, CacheLoadingCallback * formatCallback )
{
    LVContainerRef arc = LVOpenArchieve( stream );
    if ( arc.isNull() )
        return false; // not a ZIP archive

    // check root media type
    lString16 rootfilePath = EpubGetRootFilePath(arc);
    if ( rootfilePath.empty() )
    	return false;

    EncryptedDataContainer * decryptor = new EncryptedDataContainer(arc);
    if (decryptor->open()) {
        CRLog::debug("EPUB: encrypted items detected");
    }

    LVContainerRef m_arc = LVContainerRef(decryptor);

    if (decryptor->hasUnsupportedEncryption()) {
        // DRM!!!
        createEncryptedEpubWarningDocument(m_doc);
        return true;
    }

    m_doc->setContainer(m_arc);

    // read content.opf
    EpubItems epubItems;
    //EpubItem * epubToc = NULL; //TODO
    LVArray<EpubItem*> spineItems;
    lString16 codeBase;
    //lString16 css;

    //
    {
        codeBase=LVExtractPath(rootfilePath, false);
        CRLog::trace("codeBase=%s", LCSTR(codeBase));
    }

    LVStreamRef content_stream = m_arc->OpenStream(rootfilePath.c_str(), LVOM_READ);
    if ( content_stream.isNull() )
        return false;


    lString16 ncxHref;
    lString16 coverId;

    LVEmbeddedFontList fontList;
    EmbeddedFontStyleParser styleParser(fontList);

    // reading content stream
    {
        ldomDocument * doc = LVParseXMLStream( content_stream );
        if ( !doc )
            return false;

        CRPropRef m_doc_props = m_doc->getProps();
        lString16 author = doc->textFromXPath( lString16(L"package/metadata/creator"));
        lString16 title = doc->textFromXPath( lString16(L"package/metadata/title"));
        m_doc_props->setString(DOC_PROP_TITLE, title);
        m_doc_props->setString(DOC_PROP_AUTHORS, author );

        for ( int i=1; i<50; i++ ) {
            ldomNode * item = doc->nodeFromXPath( lString16(L"package/metadata/identifier[") + lString16::itoa(i) + L"]" );
            if (!item)
                break;
            lString16 key = item->getText();
            if (decryptor->setManglingKey(key)) {
                CRLog::debug("Using font mangling key %s", LCSTR(key));
                break;
            }
        }

        CRLog::info("Author: %s Title: %s", LCSTR(author), LCSTR(title));
        for ( int i=1; i<20; i++ ) {
            ldomNode * item = doc->nodeFromXPath( lString16(L"package/metadata/meta[") + lString16::itoa(i) + L"]" );
            if ( !item )
                break;
            lString16 name = item->getAttributeValue(L"name");
            lString16 content = item->getAttributeValue(L"content");
            if ( name == L"cover" )
                coverId = content;
            else if ( name==L"calibre:series" )
                m_doc_props->setString(DOC_PROP_SERIES_NAME, content );
            else if ( name==L"calibre:series_index" )
                m_doc_props->setInt(DOC_PROP_SERIES_NUMBER, content.atoi() );
        }

        // items
        for ( int i=1; i<50000; i++ ) {
            ldomNode * item = doc->nodeFromXPath( lString16(L"package/manifest/item[") + lString16::itoa(i) + L"]" );
            if ( !item )
                break;
            lString16 href = item->getAttributeValue(L"href");
            lString16 mediaType = item->getAttributeValue(L"media-type");
            lString16 id = item->getAttributeValue(L"id");
            if ( !href.empty() && !id.empty() ) {
                if ( id==coverId ) {
                    // coverpage file
                    lString16 coverFileName = codeBase + href;
                    CRLog::info("EPUB coverpage file: %s", LCSTR(coverFileName));
                    LVStreamRef stream = m_arc->OpenStream(coverFileName.c_str(), LVOM_READ);
                    if ( !stream.isNull() ) {
                        LVImageSourceRef img = LVCreateStreamImageSource(stream);
                        if ( !img.isNull() ) {
                            CRLog::info("EPUB coverpage image is correct: %d x %d", img->GetWidth(), img->GetHeight() );
                            m_doc_props->setString(DOC_PROP_COVER_FILE, coverFileName);
                        }
                    }
                }
                EpubItem * epubItem = new EpubItem;
                epubItem->href = href;
                epubItem->id = id;
                epubItem->mediaType = mediaType;
                epubItems.add( epubItem );

//                // register embedded document fonts
//                if (mediaType == L"application/vnd.ms-opentype"
//                        || mediaType == L"application/x-font-otf"
//                        || mediaType == L"application/x-font-ttf") { // TODO: more media types?
//                    // TODO:
//                    fontList.add(codeBase + href);
//                }
            }
            if ( mediaType==L"text/css" ) {
                lString16 name = LVCombinePaths(codeBase, href);
                LVStreamRef cssStream = m_arc->OpenStream(name.c_str(), LVOM_READ);
                if (!cssStream.isNull()) {
                    lString8 cssFile = UnicodeToUtf8(LVReadTextFile(cssStream));
                    lString16 base = name;
                    LVExtractLastPathElement(base);
                    CRLog::trace("style: %s", cssFile.c_str());
                    styleParser.parse(base, cssFile);
                }
            }
        }

        // spine == itemrefs
        if ( epubItems.length()>0 ) {
            ldomNode * spine = doc->nodeFromXPath( lString16(L"package/spine") );
            if ( spine ) {

                EpubItem * ncx = epubItems.findById( spine->getAttributeValue(L"toc") ); //TODO
                //EpubItem * ncx = epubItems.findById(lString16("ncx"));
                if ( ncx!=NULL )
                    ncxHref = codeBase + ncx->href;

                for ( int i=1; i<50000; i++ ) {
                    ldomNode * item = doc->nodeFromXPath( lString16(L"package/spine/itemref[") + lString16::itoa(i) + L"]" );
                    if ( !item )
                        break;
                    EpubItem * epubItem = epubItems.findById( item->getAttributeValue(L"idref") );
                    if ( epubItem ) {
                        // TODO: add to document
                        spineItems.add( epubItem );
                    }
                }
            }
        }
        delete doc;
    }

    if ( spineItems.length()==0 )
        return false;


#if BUILD_LITE!=1
    if ( m_doc->openFromCache(formatCallback) ) {
        if ( progressCallback ) {
            progressCallback->OnLoadFileEnd( );
        }
        return true;
    }
#endif

    lUInt32 saveFlags = m_doc->getDocFlags();
    m_doc->setDocFlags( saveFlags );
    m_doc->setContainer( m_arc );

    ldomDocumentWriter writer(m_doc);
#if 0
    m_doc->setNodeTypes( fb2_elem_table );
    m_doc->setAttributeTypes( fb2_attr_table );
    m_doc->setNameSpaceTypes( fb2_ns_table );
#endif
    //m_doc->setCodeBase( codeBase );

    ldomDocumentFragmentWriter appender(&writer, lString16(L"body"), lString16(L"DocFragment"), lString16::empty_str );
    writer.OnStart(NULL);
    writer.OnTagOpenNoAttr(L"", L"body");
    int fragmentCount = 0;
    for ( int i=0; i<spineItems.length(); i++ ) {
        if ( spineItems[i]->mediaType==L"application/xhtml+xml" ) {
            lString16 name = codeBase + spineItems[i]->href;
            appender.addPathSubstitution( name, lString16(L"_doc_fragment_") + lString16::itoa(i) );
        }
    }
    for ( int i=0; i<spineItems.length(); i++ ) {
        if ( spineItems[i]->mediaType==L"application/xhtml+xml" ) {
            lString16 name = codeBase + spineItems[i]->href;
            {
                CRLog::debug("Checking fragment: %s", LCSTR(name));
                LVStreamRef stream = m_arc->OpenStream(name.c_str(), LVOM_READ);
                if ( !stream.isNull() ) {
                    appender.setCodeBase( name );
                    lString16 base = name;
                    LVExtractLastPathElement(base);
                    //CRLog::trace("base: %s", LCSTR(base));
                    //LVXMLParser
                    LVHTMLParser parser(stream, &appender);
                    if ( parser.CheckFormat() && parser.Parse() ) {
                        // valid
                        fragmentCount++;
                        lString8 headCss = appender.getHeadStyleText();
                        //CRLog::trace("style: %s", headCss.c_str());
                        styleParser.parse(base, headCss);
                    } else {
                        CRLog::error("Document type is not XML/XHTML for fragment %s", LCSTR(name));
                    }
                }
            }
        }
    }

    ldomDocument * ncxdoc = NULL;
    if ( !ncxHref.empty() ) {
        LVStreamRef stream = m_arc->OpenStream(ncxHref.c_str(), LVOM_READ);
        lString16 codeBase = LVExtractPath( ncxHref );
        if ( codeBase.length()>0 && codeBase.lastChar()!='/' )
            codeBase.append(1, L'/');
        appender.setCodeBase(codeBase);
        if ( !stream.isNull() ) {
            ldomDocument * ncxdoc = LVParseXMLStream( stream );
            if ( ncxdoc!=NULL ) {
                ldomNode * navMap = ncxdoc->nodeFromXPath( lString16(L"ncx/navMap"));
                if ( navMap!=NULL )
                    ReadEpubToc( m_doc, navMap, m_doc->getToc(), appender );
                delete ncxdoc;
            }
        }
    }

    writer.OnTagClose(L"", L"body");
    writer.OnStop();
    CRLog::debug("EPUB: %d documents merged", fragmentCount);

    if (!fontList.empty()) {
        // set document font list, and register fonts
        m_doc->getEmbeddedFontList().set(fontList);
        m_doc->registerEmbeddedFonts();
        m_doc->forceReinitStyles();
    }

    if ( fragmentCount==0 )
        return false;

#if 0
    // set stylesheet
    //m_doc->getStyleSheet()->clear();
    m_doc->setStyleSheet( NULL, true );
    //m_doc->getStyleSheet()->parse(m_stylesheet.c_str());
    if ( !css.empty() && m_doc->getDocFlag(DOC_FLAG_ENABLE_INTERNAL_STYLES) ) {

        m_doc->setStyleSheet( "p.p { text-align: justify }\n"
            "svg { text-align: center }\n"
            "i { display: inline; font-style: italic }\n"
            "b { display: inline; font-weight: bold }\n"
            "abbr { display: inline }\n"
            "acronym { display: inline }\n"
            "address { display: inline }\n"
            "p.title-p { hyphenate: none }\n"
//abbr, acronym, address, blockquote, br, cite, code, dfn, div, em, h1, h2, h3, h4, h5, h6, kbd, p, pre, q, samp, span, strong, var
        , false);
        m_doc->setStyleSheet( UnicodeToUtf8(css).c_str(), false );
        //m_doc->getStyleSheet()->parse(UnicodeToUtf8(css).c_str());
    } else {
        //m_doc->getStyleSheet()->parse(m_stylesheet.c_str());
        //m_doc->setStyleSheet( m_stylesheet.c_str(), false );
    }
#endif
#if 0
    LVStreamRef out = LVOpenFileStream( L"c:\\doc.xml" , LVOM_WRITE );
    if ( !out.isNull() )
        m_doc->saveToStream( out, "utf-8" );
#endif

    // DONE!
    if ( progressCallback ) {
        progressCallback->OnLoadFileEnd( );
        m_doc->compact();
        m_doc->dumpStatistics();
    }
    return true;

}
Exemplo n.º 26
0
 /// called on text
 virtual void OnText( const lChar16 * text, int len, lUInt32 flags )
 {
     if ( insidePatternTag )
         data.add( lString16(text, len) );
 }
Exemplo n.º 27
0
int InitDoc(char *fileName)
{


    static const lChar16 * css_file_name = L"fb2.css"; // fb2

    CRLog::trace("InitDoc()");
#ifdef __i386__
    //CRLog::setFileLogger("/root/abook/crengine.log");
    CRLog::setStdoutLogger();
    CRLog::setLogLevel(CRLog::LL_TRACE);
#else
    //InitCREngineLog(NULL);
#if 0
    CRLog::setFileLogger("/root/abook/.cr3/cr3.log", true);
    CRLog::setLogLevel(CRLog::LL_TRACE);
#else
    InitCREngineLog("/root/abook/crengine/crlog.ini");
#endif
#endif

    CRLog::trace("creating window manager...");
    CRJinkeWindowManager * wm = new CRJinkeWindowManager(600,800);
    CRLog::trace("loading skin...");
    if ( !wm->loadSkin(  lString16( L"/root/abook/crengine/skin" ) ) )
        if ( !wm->loadSkin(  lString16( L"/home/crengine/skin" ) ) )
            wm->loadSkin( lString16( L"/root/crengine/skin" ) );
    CRLog::trace("drawing progressbar 0%%...");
    //wm->getScreen()->getCanvas()->Clear(0xFFFFFF);
    //wm->getScreen()->invalidateRect( lvRect(0, 0, 600, 800) );
    //wm->showProgress(lString16("cr3_wait_icon.png"), 10);
        {
            const lChar16 * imgname =
                ( wm->getScreenOrientation()&1 ) ? L"cr3_logo_screen_landscape.png" : L"cr3_logo_screen.png";
            LVImageSourceRef img = wm->getSkin()->getImage(imgname);
            if ( !img.isNull() ) {
                wm->getScreen()->getCanvas()->Draw(img, 0, 0, wm->getScreen()->getWidth(), wm->getScreen()->getHeight(),  false );
            }
        }

    lString16 bookmarkDir("/root/abook/bookmarks/");
    {
        lString8 fn(fileName);
        if ( fn.startsWith(lString8("/home")) ) {
            strcpy( history_file_name, "/home/.cr3hist" );
            bookmarkDir = lString16("/home/bookmarks/");
        }
        CRLog::info( "History file name: %s", history_file_name );
    }

    char manual_file[512] = "";
    {
        const char * lang = getLang();
        if ( lang && lang[0] ) {
            // set translator
            CRLog::info("Current language is %s, looking for translation file", lang);
            lString16 mofilename = L"/root/crengine/i18n/" + lString16(lang) + L".mo";
            lString16 mofilename2 = L"/root/abook/crengine/i18n/" + lString16(lang) + L".mo";
            CRMoFileTranslator * t = new CRMoFileTranslator();
            if ( t->openMoFile( mofilename2 ) || t->openMoFile( mofilename ) ) {
                CRLog::info("translation file %s.mo found", lang);
                CRI18NTranslator::setTranslator( t );
            } else {
                CRLog::info("translation file %s.mo not found", lang);
                delete t;
            }
            sprintf( manual_file, "/root/abook/crengine/manual/cr3-manual-%s.fb2", lang );
            if ( !LVFileExists( lString16(manual_file).c_str() ) )
                sprintf( manual_file, "/root/crengine/manual/cr3-manual-%s.fb2", lang );
        }
    }

    const lChar16 * ini_fname = L"cr3.ini";
#ifdef SEPARATE_INI_FILES
    if ( strstr(fileName, ".txt")!=NULL || strstr(fileName, ".tcr")!=NULL) {
        ini_fname = L"cr3-txt.ini";
        css_file_name = L"txt.css";
    } else if ( strstr(fileName, ".rtf")!=NULL ) {
        ini_fname = L"cr3-rtf.ini";
        css_file_name = L"rtf.css";
    } else if ( strstr(fileName, ".htm")!=NULL ) {
        ini_fname = L"cr3-htm.ini";
        css_file_name = L"htm.css";
    } else if ( strstr(fileName, ".epub")!=NULL ) {
        ini_fname = L"cr3-epub.ini";
        css_file_name = L"epub.css";
    } else {
        ini_fname = L"cr3-fb2.ini";
        css_file_name = L"fb2.css";
    }
#endif

    lString16Collection fontDirs;
    fontDirs.add( lString16(L"/root/abook/fonts/") );
    fontDirs.add( lString16(L"/home/fonts/") );
    //fontDirs.add( lString16(L"/root/crengine/fonts") ); // will be added
    CRLog::info("INIT...");
    if ( !InitCREngine( "/root/crengine/", fontDirs ) )
        return 0;



#ifdef ALLOW_RUN_EXE
    {
        __pid_t pid;
        if( strstr(fileName, ".exe.txt") || strstr(fileName, ".exe.fb2")) {
            pid = fork();
            if(!pid) {
                execve(fileName, NULL, NULL);
                exit(0);
            } else {
                waitpid(pid, NULL, 0);
                exit(0);
                //return 0;
            }
        }
    }
#endif
    {
        //main_win = new V3DocViewWin( wm, lString16(CRSKIN) );

        const char * keymap_locations [] = {
            "/root/crengine/",
            "/home/crengine/",
            "/root/abook/crengine/",
            NULL,
        };
        loadKeymaps( *wm, keymap_locations );
        if ( LVDirectoryExists( L"/root/abook/crengine/hyph" ) )
            HyphMan::initDictionaries( lString16("/root/abook/crengine/hyph/") );
        else
            HyphMan::initDictionaries( lString16("/root/crengine/hyph/") );

        if ( !ldomDocCache::init( lString16(L"/root/abook/crengine/.cache"), 0x100000 * 64 ) ) {
            if ( !ldomDocCache::init( lString16(L"/home/crengine/.cache"), 0x100000 * 64 ) ) {
                CRLog::error("Cannot initialize swap directory");
            }
        }

        CRLog::trace("creating main window...");
        main_win = new CRJinkeDocView( wm, lString16(L"/root/crengine") );
        CRLog::trace("setting colors...");
        main_win->getDocView()->setBackgroundColor(0xFFFFFF);
        main_win->getDocView()->setTextColor(0x000000);
        main_win->getDocView()->setFontSize( 20 );
        if ( manual_file[0] )
            main_win->setHelpFile( lString16( manual_file ) );
        if ( !main_win->loadDefaultCover( lString16( L"/root/abook/crengine/cr3_def_cover.png" ) ) )
            if ( !main_win->loadDefaultCover( lString16( L"/home/crengine/cr3_def_cover.png" ) ) )
                main_win->loadDefaultCover( lString16( L"/root/crengine/cr3_def_cover.png" ) );
        if ( !main_win->loadCSS(  lString16( L"/root/abook/crengine/" ) + lString16(css_file_name) ) )
            if ( !main_win->loadCSS(  lString16( L"/home/crengine/" ) + lString16(css_file_name) ) )
                main_win->loadCSS( lString16( L"/root/crengine/" ) + lString16(css_file_name) );
        main_win->setBookmarkDir( bookmarkDir );
        CRLog::trace("choosing init file...");
        static const lChar16 * dirs[] = {
            L"/root/abook/crengine/",
            L"/home/crengine/",
            L"/root/appdata/",
            NULL
        };
        int i;
        CRLog::debug("Loading settings...");
        lString16 ini;
        for ( i=0; dirs[i]; i++ ) {
            ini = lString16(dirs[i]) + ini_fname;
            if ( main_win->loadSettings( ini ) ) {
                break;
            }
        }
        CRLog::debug("settings at %s", UnicodeToUtf8(ini).c_str() );
#if USE_JINKE_USER_DATA!=1
    if ( !main_win->loadHistory( lString16(history_file_name) ) ) {
        CRLog::error("Cannot read history file %s", history_file_name);
    }
#endif

        LVDocView * _docview = main_win->getDocView();
        _docview->setBatteryState( checkPowerState() );
        //_docview->setBatteryState( ::getBatteryState() );
        wm->activateWindow( main_win );
        if ( !main_win->loadDocument( lString16(fileName) ) ) {
            printf("Cannot open book file %s\n", fileName);
            delete wm;
            return 0;
        } else {
#ifdef ENABLE_LEDS
            postLeds( true );
#endif
        }
    }

    //_docview->setVisiblePageCount( 1 );



    //tocDebugDump( _docview->getToc() );

    return 1;
}
Exemplo n.º 28
0
int main(int argc, char *argv[])
{
    int res = 0;
    {
#ifdef DEBUG
        lString8 loglevel("TRACE");
        lString8 logfile("stdout");
#else
        lString8 loglevel("ERROR");
        lString8 logfile("stderr");
#endif
        for ( int i=1; i<argc; i++ ) {
            if ( !strcmp("-h", argv[i]) || !strcmp("-?", argv[i]) || !strcmp("/?", argv[i]) || !strcmp("--help", argv[i]) ) {
                printHelp();
                return 0;
            }
            if ( !strcmp("-v", argv[i]) || !strcmp("/v", argv[i]) || !strcmp("--version", argv[i]) ) {
                printVersion();
                return 0;
            }
            if ( !strcmp("--stats", argv[i]) && i<argc-4 ) {
                if ( i!=argc-5 ) {
                    printf("To calculate character encoding statistics, use cr3 <infile.txt> <outfile.cpp> <codepagename> <langname>\n");
                    return 1;
                }
                lString8 list;
                FILE * out = fopen(argv[i+2], "wb");
                if ( !out ) {
                    printf("Cannot create file %s", argv[i+2]);
                    return 1;
                }
                MakeStatsForFile( argv[i+1], argv[i+3], argv[i+4], 0, out, list );
                fclose(out);
                return 0;
            }
            lString8 s(argv[i]);
            if ( s.startsWith(lString8("--loglevel=")) ) {
                loglevel = s.substr(11, s.length()-11);
            } else if ( s.startsWith(lString8("--logfile=")) ) {
                logfile = s.substr(10, s.length()-10);
            }
        }

        // set logger
        if ( logfile=="stdout" )
            CRLog::setStdoutLogger();
        else if ( logfile=="stderr" )
                CRLog::setStderrLogger();
        else if ( !logfile.empty() )
                CRLog::setFileLogger(logfile.c_str());
        if ( loglevel=="TRACE" )
            CRLog::setLogLevel(CRLog::LL_TRACE);
        else if ( loglevel=="DEBUG" )
            CRLog::setLogLevel(CRLog::LL_DEBUG);
        else if ( loglevel=="INFO" )
            CRLog::setLogLevel(CRLog::LL_INFO);
        else if ( loglevel=="WARN" )
            CRLog::setLogLevel(CRLog::LL_WARN);
        else if ( loglevel=="ERROR" )
            CRLog::setLogLevel(CRLog::LL_ERROR);
        else
            CRLog::setLogLevel(CRLog::LL_FATAL);

        lString16 exename = LocalToUnicode( lString8(argv[0]) );
        lString16 exedir = LVExtractPath(exename);
        lString16 datadir = lString16(CR3_DATA_DIR);
        LVAppendPathDelimiter(exedir);
        LVAppendPathDelimiter(datadir);
        lString16 exefontpath = exedir + L"fonts";
        CRLog::info("main()");
        lString16Collection fontDirs;
        //fontDirs.add( lString16(L"/usr/local/share/crengine/fonts") );
        //fontDirs.add( lString16(L"/usr/local/share/fonts/truetype/freefont") );
        //fontDirs.add( lString16(L"/mnt/fonts") );
#if 0
        fontDirs.add( exefontpath );
        fontDirs.add( lString16(L"/usr/share/fonts/truetype") );
        fontDirs.add( lString16(L"/usr/share/fonts/truetype/liberation") );
        fontDirs.add( lString16(L"/usr/share/fonts/truetype/freefont") );
#endif
        // TODO: use fontconfig instead
        //fontDirs.add( lString16(L"/root/fonts/truetype") );
        if ( !InitCREngine( argv[0], fontDirs ) ) {
            printf("Cannot init CREngine - exiting\n");
            return 2;
        }

		if ( argc>=2 && !strcmp(argv[1], "unittest") ) {
#ifdef _DEBUG
			runTinyDomUnitTests();
#endif
			CRLog::info("UnitTests finished: exiting");
			return 0;
		}
        //if ( argc!=2 ) {
        //    printf("Usage: cr3 <filename_to_open>\n");
        //    return 3;
        //}
        {
            QApplication a(argc, argv);
#ifdef _WIN32
            QString exeDir = QDir::toNativeSeparators(qApp->applicationDirPath() + "/"); //QDir::separator();
            QString translations = exeDir + "i18n";
#else
            QString exeDir = cr2qt(datadir);
            QString translations = exeDir + "i18n/";
#endif
             QTranslator qtTranslator;
             if (qtTranslator.load("qt_" + QLocale::system().name(),
                     QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
                QApplication::installTranslator(&qtTranslator);

             QTranslator myappTranslator;
             QString trname = "cr3_" + QLocale::system().name();
             CRLog::info("Using translation file %s from dir %s", UnicodeToUtf8(qt2cr(trname)).c_str(), UnicodeToUtf8(qt2cr(translations)).c_str() );
             if ( myappTranslator.load(trname, translations) )
                 QApplication::installTranslator(&myappTranslator);
             else
                CRLog::error("Canot load translation file %s from dir %s", UnicodeToUtf8(qt2cr(trname)).c_str(), UnicodeToUtf8(qt2cr(translations)).c_str() );
            MainWindow w;
            w.show();
            res = a.exec();
        }
    }
    ShutdownCREngine();
    return res;
}
Exemplo n.º 29
0
static bool GetBookProperties(const char *name,  BookProperties * pBookProps)
{
    CRLog::trace("GetBookProperties( %s )", name);

    // check archieve
    lString16 arcPathName;
    lString16 arcItemPathName;
    bool isArchiveFile = LVSplitArcName( lString16(name), arcPathName, arcItemPathName );

    // open stream
    LVStreamRef stream = LVOpenFileStream( (isArchiveFile ? arcPathName : Utf8ToUnicode(lString8(name))).c_str() , LVOM_READ);
    if (!stream) {
        CRLog::error("cannot open file %s", name);
        return false;
    }


    if ( DetectEpubFormat( stream ) ) {
        CRLog::trace("GetBookProperties() : epub format detected");
    	return GetEPUBBookProperties( name, stream, pBookProps );
    }

    time_t t = (time_t)time(0);

    if ( isArchiveFile ) {
        int arcsize = (int)stream->GetSize();
        LVContainerRef container = LVOpenArchieve(stream);
        if ( container.isNull() ) {
            CRLog::error( "Cannot read archive contents from %s", LCSTR(arcPathName) );
            return false;
        }
        stream = container->OpenStream(arcItemPathName.c_str(), LVOM_READ);
        if ( stream.isNull() ) {
            CRLog::error( "Cannot open archive file item stream %s", LCSTR(lString16(name)) );
            return false;
        }
    }
    struct stat fs;
    if ( !stat( name, &fs ) ) {
        t = fs.st_mtime;
    }

    // read document
#if COMPACT_DOM==1
    ldomDocument doc(stream, 0);
#else
    ldomDocument doc;
#endif
    ldomDocumentWriter writer(&doc, true);
    doc.setNodeTypes( fb2_elem_table );
    doc.setAttributeTypes( fb2_attr_table );
    doc.setNameSpaceTypes( fb2_ns_table );
    LVXMLParser parser( stream, &writer );
    CRLog::trace( "checking format..." );
    if ( !parser.CheckFormat() ) {
        return false;
    }
    CRLog::trace( "parsing..." );
    if ( !parser.Parse() ) {
        return false;
    }
    CRLog::trace( "parsed" );
    #if 0
        char ofname[512];
        sprintf(ofname, "%s.xml", name);
        CRLog::trace("    writing to file %s", ofname);
        LVStreamRef out = LVOpenFileStream(ofname, LVOM_WRITE);
        doc.saveToStream(out, "utf16");
    #endif
    lString16 authors = extractDocAuthors( &doc, lString16("|"), false );
    lString16 title = extractDocTitle( &doc );
    lString16 language = extractDocLanguage( &doc ).lowercase();
    lString16 series = extractDocSeries( &doc, &pBookProps->seriesNumber );
#if SERIES_IN_AUTHORS==1
    if ( !series.empty() )
        authors << "    " << series;
#endif
    pBookProps->title = title;
    pBookProps->author = authors;
    pBookProps->series = series;
    pBookProps->filesize = (long)stream->GetSize();
    pBookProps->filename = lString16(name);
    pBookProps->filedate = getDateTimeString( t );
    pBookProps->language = language;
    return true;
}
Exemplo n.º 30
0
bool LVCssSelectorRule::check( const ldomNode * & node )
{
    if (!node || node->isNull() || node->isRoot())
        return false;
    switch (_type)
    {
    case cssrt_parent:        // E > F
        //
        {
            node = node->getParentNode();
            if (!node || node->isNull())
                return false;
            return node->getNodeId() == _id;
        }
        break;
    case cssrt_ancessor:      // E F
        //
        {
            for (;;)
            {
                node = node->getParentNode();
                if (!node || node->isNull())
                    return false;
                if (node->getNodeId() == _id)
                    return true;
            }
        }
        break;
    case cssrt_predecessor:   // E + F
        //
        {
            int index = node->getNodeIndex();
            // while
            if (index>0) {
                ldomNode * elem = node->getParentNode()->getChildElementNode(index-1, _id);
                if ( elem ) {
                    node = elem;
                    //CRLog::trace("+ selector: found pred element");
                    return true;
                }
                //index--;
            }
            return false;
        }
        break;
    case cssrt_attrset:       // E[foo]
        {
            if ( !node->hasAttributes() )
                return false;
            return node->hasAttribute(_attrid);
        }
        break;
    case cssrt_attreq:        // E[foo="value"]
        {
            lString16 val = node->getAttributeValue(_attrid);
            bool res = (val == _value);
            //if ( res )
            //    return true;
            //CRLog::trace("attreq: %s %s", LCSTR(val), LCSTR(_value) );
            return res;
        }
        break;
    case cssrt_attrhas:       // E[foo~="value"]
        // one of space separated values
        {
            lString16 val = node->getAttributeValue(_attrid);
            int p = val.pos( lString16(_value.c_str()) );            
            if (p<0)
                return false;
            if ( (p>0 && val[p-1]!=' ') 
                    || (p+_value.length()<val.length() && val[p+_value.length()]!=' ') )
                return false;
            return true;
        }
        break;
    case cssrt_attrstarts:    // E[foo|="value"]
        // todo
        {
            lString16 val = node->getAttributeValue(_attrid);
            if (_value.length()>val.length())
                return false;
            val = val.substr(0, _value.length());
            return val == _value;
        }
        break;
    case cssrt_id:            // E#id
        // todo
        {
            lString16 val = node->getAttributeValue(attr_id);
            if (_value.length()>val.length())
                return false;
            return val == _value;
        }
        break;
    case cssrt_class:         // E.class
        // todo
        {
            lString16 val = node->getAttributeValue(attr_class);
            val.lowercase();
//            if ( val.length() != _value.length() )
//                return false;
            //CRLog::trace("attr_class: %s %s", LCSTR(val), LCSTR(_value) );
            return val == _value;
        }
        break;
    case cssrt_universal:     // *
        return true;
    }
    return true;
}