94 files changed, 4630 insertions, 1068 deletions
diff --git a/noncore/apps/opie-reader/Aportis.cpp b/noncore/apps/opie-reader/Aportis.cpp index 353996c..37dcc99 100644 --- a/noncore/apps/opie-reader/Aportis.cpp +++ b/noncore/apps/opie-reader/Aportis.cpp @@ -1,454 +1,460 @@ #include <stdio.h> #include <string.h> #include "Aportis.h" #include "my_list.h" #include "Bkmks.h" Aportis::Aportis() : peanutfile(false) { /*printf("constructing:%x\n",fin);*/ } void Aportis::dePeanut(int& ch) { if (peanutfile && ch != EOF) { unsigned char c = ch; if (peanutfile) c ^= 0xa5; ch = c; } } CList<Bkmk>* Aportis::getbkmklist() { /* if (peanutfile) { if (nRecs2 > nRecs) { CList<Bkmk>* t = new CList<Bkmk>; for (int i = nRecs; i < nRecs2; i++) { char name[17]; name[16] = '\0'; // qDebug("Record:%d, Length:%u",i,recordlength(i)); gotorecordnumber(i); fread(name,1,16,fin); unsigned long lcn; fread(&lcn,sizeof(lcn),1,fin); lcn ^= 0xa5a5a5a5; lcn = SwapLong(lcn); // qDebug("Bookmark:%s:%u", name,lcn); tchar tname[17]; memset(tname, 0, sizeof(tname)); for (int i = 0; name[i] != 0; i++) { tname[i] = name[i] ^ 0xa5; } t->push_back(Bkmk(tname, NULL, lcn)); } return t; } else { return NULL; } } */ if (bCompressed != 4) return NULL; CList<Bkmk>* t = new CList<Bkmk>; + unsuspend(); size_t cur = ftell(fin); for (int i = 0; i < nRecs2; i++) { DWORD dwPos; fseek(fin, 0x56 + 8*i, SEEK_SET); fread(&dwPos, 4, 1, fin); dwPos = SwapLong(dwPos); fseek(fin,dwPos,SEEK_SET); unsigned char ch; fread(&ch,1,1,fin); if (ch != 241) { char name[17]; name[16] = '\0'; fseek(fin,dwPos,SEEK_SET); fread(name,1,16,fin); unsigned long lcn; fread(&lcn,sizeof(lcn),1,fin); lcn = SwapLong(lcn); #ifdef _UNICODE tchar tname[17]; memset(tname, 0, sizeof(tname)); for (int i = 0; name[i] != 0; i++) { tname[i] = name[i]; } t->push_back(Bkmk(tname, NULL, lcn)); #else t->push_back(Bkmk(name,lcn)); #endif } } fseek(fin, cur, SEEK_SET); return t; } int Aportis::OpenFile(const char *src) { // printf("In openfile\n"); int ret = 0; html = false; mobiimagerec = 0; if (!Cpdb::openpdbfile(src)) return -1; if (head.creator == 0x64414552 // 'dAER' || head.type == 0x74584554) // 'tXET') { } else if (memcmp(&head.creator, "PPrs", 4) == 0 && memcmp(&head.type, "PNRd", 4) == 0) { peanutfile = true; } else if (memcmp(&head.creator, "MOBI", 4) == 0 && memcmp(&head.type, "BOOK", 4) == 0) { html = true; unsigned char vsn; fseek(fin, recordpos(0)+39, SEEK_SET); fread(&vsn, 1, sizeof(vsn), fin); qDebug("Mobi version:%x", vsn); if (vsn > 2) { fseek(fin, recordpos(0)+110, SEEK_SET); fread(&mobiimagerec, 1, sizeof(mobiimagerec), fin); mobiimagerec = ntohs(mobiimagerec)-1; } } else { return -2; } nRecs2 = nRecs = SwapWord(head.recordList.numRecords) - 1; struct stat _stat; stat(src,&_stat); dwLen = _stat.st_size; //fseek(fin,0,SEEK_END); //dwLen = ftell(fin); if (peanutfile) { PeanutHeader hdr0; gotorecordnumber(0); fread(&hdr0, sizeof(hdr0), 1, fin); // qDebug("Version:%x", ntohs(hdr0.Version)); if (hdr0.Version && 0x0200) { bCompressed = 2; } else { bCompressed = 1; } BlockSize = 4096; nRecs = SwapWord(hdr0.Records)-1; dwTLen = nRecs*BlockSize; } else { gotorecordnumber(0); tDocRecord0 hdr0; fread(&hdr0, sizeof(hdr0), 1, fin); bCompressed = SwapWord(hdr0.wVersion); if (bCompressed!=1 && bCompressed!=2 && bCompressed != 4) { qDebug("ERROR:Unrecognised compression type in Aportis:%u", bCompressed); ret = bCompressed; bCompressed = 2; } switch (bCompressed) { case 4: { dwTLen = 0; int i; for (i = 0; i < nRecs; i++) { unsigned int bs = GetBS(i); if (bs == 0) break; else dwTLen += bs; } nRecs = i; BlockSize = 0; } break; case 1: case 2: default: nRecs = SwapWord(hdr0.wNumRecs); if (mobiimagerec == 0 || mobiimagerec > nRecs2) mobiimagerec = nRecs; dwTLen = SwapLong(hdr0.dwStoryLen); BlockSize = SwapWord(hdr0.wRecSize); if (BlockSize == 0) { BlockSize = 4096; printf("WARNING: Blocksize not set in source file\n"); } } } qDebug("Mobi image rec:%u", mobiimagerec); // this is the main record buffer // it knows how to stretch to accomodate the decompress currentrec = 0; cbptr = 0; outptr = 0; refreshbuffer(); if (!html) { int c; char htmltag[] = "<HTML>"; char *p = htmltag; while (1) { c = getch(); char ch = *p++; if (ch == 0) { html = true; break; } if (c != ch) { html = false; break; } } currentrec = 0; cbptr = 0; outptr = 0; refreshbuffer(); } /* for (int i = 0; i < nRecs2; i++) { qDebug("Record:%u - %u bytes at position %x", i, recordlength(i), recordpos(i)); } */ qDebug("Number of records:[%u,%u]", nRecs, nRecs2); return ret; } int Aportis::getch() { if (bCompressed == 1) { if ((dwRecLen == 0) && !refreshbuffer()) return EOF; else { +unsuspend(); int c = getc(fin); dePeanut(c); dwRecLen--; currentpos++; return c; } } if (outptr != cbptr) { currentpos++; return (circbuf[outptr = (outptr + 1) % 2048]); } if ((dwRecLen == 0) && !refreshbuffer()) return EOF; currentpos++; int c; // take a char from the input buffer +unsuspend(); c = getc(fin); dePeanut(c); dwRecLen--; // separate the char into zones: 0, 1...8, 9...0x7F, 0x80...0xBF, 0xC0...0xFF // codes 1...8 mean copy that many chars; for accented chars & binary if (c == 0) { circbuf[outptr = cbptr = (cbptr+1)%2048] = c; return c; } else if (c >= 0x09 && c <= 0x7F) { circbuf[outptr = cbptr = (cbptr+1)%2048] = c; return c; } else if (c >= 0x01 && c <= 0x08) { dwRecLen -= c; while(c--) { int c = getc(fin); dePeanut(c); circbuf[cbptr = (cbptr+1)%2048] = c; } return circbuf[outptr = (outptr+1)%2048]; } else if (c >= 0x80 && c <= 0xBF) { int m,n; c <<= 8; int c1 = getc(fin); dePeanut(c1); c += c1; dwRecLen--; m = (c & 0x3FFF) >> COUNT_BITS; n = c & ((1<<COUNT_BITS) - 1); n += 3; while (n--) { cbptr = (cbptr+1)%2048; circbuf[cbptr] = circbuf[(cbptr+2048-m)%2048]; } return circbuf[outptr = (outptr+1)%2048]; } else if (c >= 0xC0 && c <= 0xFF) { circbuf[cbptr = (cbptr+1)%2048] = ' '; circbuf[cbptr = (cbptr+1)%2048] = c^0x80; return circbuf[outptr = (outptr+1)%2048]; } } unsigned int Aportis::GetBS(unsigned int bn) { DWORD dwPos; WORD fs; - +unsuspend(); fseek(fin, 0x56 + 8*bn, SEEK_SET); fread(&dwPos, 4, 1, fin); dwPos = SwapLong(dwPos); fseek(fin,dwPos,SEEK_SET); // gotorecordnumber(bn+1); unsigned char ch; fread(&ch,1,1,fin); if (ch == 241) { fread(&fs,sizeof(fs),1,fin); fs = SwapWord(fs); } else fs = 0; return fs; } unsigned int Aportis::locate() { if (bCompressed == 4) { +unsuspend(); size_t cur = ftell(fin); unsigned int clen = 0; for (unsigned int i = 0; i < currentrec-1; i++) { unsigned int bs = GetBS(i); if (bs == 0) break; clen += bs; } fseek(fin,cur,SEEK_SET); return clen+currentpos; } else return (currentrec-1)*BlockSize+currentpos; } void Aportis::locate(unsigned int n) { unsigned int offset; // currentrec = (n >> OFFBITS); switch (bCompressed) { case 4: { DWORD clen = 0; offset = n; unsigned int i; for (i = 0; i < nRecs; i++) { unsigned int bs = GetBS(i); if (bs == 0) break; clen += bs; if (clen > n) break; offset = n - clen; } currentrec = i; } break; case 1: case 2: default: currentrec = n / BlockSize; offset = n % BlockSize; } outptr = cbptr; refreshbuffer(); while (currentpos < offset && getch() != EOF); } bool Aportis::refreshbuffer() { if (currentrec < nRecs) { dwRecLen = recordlength(currentrec+1); gotorecordnumber(currentrec+1); if (bCompressed == 4) { unsigned char t[3]; + unsuspend(); fread(t,1,3,fin); if (t[0] != 241) { printf("You shouldn't be here!\n"); return false; } dwRecLen -= 3; } /* int n = fread(t.buf, 1, dwRecLen, fin); t.len = n; // if(bCompressed) t.Decompress(); t.buf[t.Len()] = '\0'; */ currentpos = 0; currentrec++; return true; } else { return false; } } #include <qimage.h> QImage* Aportis::getPicture(unsigned long tgt) { +unsuspend(); unsigned short tgtrec = tgt+mobiimagerec; if (tgtrec > nRecs2) return NULL; size_t cur = ftell(fin); unsigned short reclen = recordlength(tgtrec); gotorecordnumber(tgtrec); UInt8* imgbuffer = new UInt8[reclen]; fread(imgbuffer, 1, reclen, fin); QByteArray arr; arr.assign((const char*)imgbuffer, reclen); QImage* qimage = new QImage(arr); fseek(fin, cur, SEEK_SET); return qimage; } #ifndef __STATIC extern "C" { CExpander* newcodec() { return new Aportis; } } #endif diff --git a/noncore/apps/opie-reader/ArriereCodec/.cvsignore b/noncore/apps/opie-reader/ArriereCodec/.cvsignore new file mode 100644 index 0000000..1810ee0 --- a/dev/null +++ b/noncore/apps/opie-reader/ArriereCodec/.cvsignore @@ -0,0 +1,5 @@ +Makefile +config.in +moc_* +.moc +.obj diff --git a/noncore/apps/opie-reader/ArriereCodec/ArriereCodec.pro b/noncore/apps/opie-reader/ArriereCodec/ArriereCodec.pro new file mode 100644 index 0000000..8d820d6 --- a/dev/null +++ b/noncore/apps/opie-reader/ArriereCodec/ArriereCodec.pro @@ -0,0 +1,16 @@ +DEFINES += OPIE USEQPE +VPATH = .. +TEMPLATE = lib +CONFIG = qt warn_on release dll +HEADERS = arrierego.h + +SOURCES = arrierego.cpp + +INTERFACES = +DESTDIR = $(OPIEDIR)/plugins/reader/codecs +TARGET = ArriereGo +LIBS += -L$(OPIEDIR)/lib -lreader_pdb -lreader_pluckerbase -lreader_codec + +INCLUDEPATH += $(OPIEDIR)/include +DEPENDPATH += $(OPIEDIR)/include +DEFINES += USENEF diff --git a/noncore/apps/opie-reader/BuffDoc.cpp b/noncore/apps/opie-reader/BuffDoc.cpp index 1f0a524..355d14d 100644 --- a/noncore/apps/opie-reader/BuffDoc.cpp +++ b/noncore/apps/opie-reader/BuffDoc.cpp @@ -1,708 +1,759 @@ #include "names.h" #define NEWLINEBREAK #define INCREMENTALWIDTH -#include "usenef.h" #include "BuffDoc.h" #include "config.h" #include "CDrawBuffer.h" #include "ZText.h" #include "ebookcodec.h" #ifdef __STATIC #include "Aportis.h" #include "CHM.h" #include "ppm_expander.h" #include "ztxt.h" #include "plucker.h" #ifdef USENEF #include "nef.h" #include "arrierego.h" #endif #include "iSilo.h" +#include "Reb.h" #endif linkType BuffDoc::hyperlink(unsigned int n, unsigned int noff, QString& wrd, QString& nm) { linkType bRet = eNone; if (exp != NULL) { bRet = filt->hyperlink(n, noff, wrd, nm); if ((bRet & eLink) != 0) { lastword.empty(); lastsizes[0] = laststartline = n; #ifdef NEWLINEBREAK lastispara = false; #else lastispara = false; #endif lastsizes[0] = laststartline = exp->locate(); } } return bRet; } void BuffDoc::locate(unsigned int n) { // //qDebug("BuffDoc:locating:%u",n); lastword.empty(); lastsizes[0] = laststartline = n; #ifdef NEWLINEBREAK lastispara = false; #else lastispara = false; #endif // tchar linebuf[1024]; if (exp != NULL) filt->locate(n); // //qDebug("BuffDoc:Located"); } +void BuffDoc::resetPos() +{ + // //qDebug("BuffDoc:locating:%u",n); + lastword.empty(); + lastsizes[0] = laststartline = exp->locate(); +#ifdef NEWLINEBREAK + lastispara = false; +#else + lastispara = false; +#endif +} + static bool isletter(unsigned short c) { if ('a' <= c && c <= 'z') return true; if ('A' <= c && c <= 'Z') return true; // Cyrillic letters if (0x400 <= c && c <= 0x52F) return true; return false; } static bool isvowel(unsigned short c) // Only want lower case vowels { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': // Cyrillic vowels case 0x430: case 0x435: case 0x438: case 0x43E: case 0x443: case 0x44B: case 0x44D: case 0x44E: case 0x44F: case 0x451: case 0x450: case 0x454: case 0x456: case 0x457: case 0x45D: case 0x463: case 0x4AF: case 0x4B1: case 0x4D1: case 0x4D3: case 0x4D5: case 0x4D7: case 0x4E3: case 0x4E5: case 0x4E7: case 0x4E9: case 0x4EB: case 0x4ED: case 0x4EF: case 0x4F1: case 0x4F3: case 0x4F9: return true; default: return ((0xe0 <= c) && (c <= 0xfc) && (c != 0xf1) && (c != 0xf7) && (c != 0xe7)); } } inline bool isconsonant(unsigned short c) { switch( c ) { // Some cyrillic letters are neither vowels, nor consonants, or otherwise // the letters no word can start from. case 0x439: case 0x44A: case 0x44C: case 0x45E: return false; default: return (isletter(c) && !isvowel(c)); } return (isletter(c) && !isvowel(c)); } #ifdef NEWLINEBREAK bool BuffDoc::getline(CDrawBuffer* buff, int wth, unsigned short _lborder, unsigned short _rborder, bool hyphenate, int availht) { bool moreleft = true; bool margindone = false; int isCentred = -1; int w = wth-(_lborder+_rborder); tchar ch = 32; CStyle cs; buff->empty(); if (exp == NULL) { buff->empty(); buff->setEof(); return false; } int len = 0; if (lastword.length() > 0) { if (isCentred < 0) { isCentred = (lastword.firststyle().getJustify() == m_AlignCentre) ? 1 : 0; } *buff = lastword; cs = lastword.laststyle(); w -= buff->leftMargin() + buff->rightMargin(); margindone = true; len = lastword.length(); } else buff->empty(); lastword.empty(); unsigned int slen = buff->width(availht, len); if (lastispara) buff->setstartpara(); int nospaces = 0; while (1) { getch(ch, cs, lastsizes[len]); if (isCentred < 0) { isCentred = (cs.getJustify() == m_AlignCentre) ? 1 : 0; } if (ch == 10 && len == 0 && !lastispara) { getch(ch, cs, lastsizes[len]); buff->setstartpara(); } if (ch == UEOF) { buff->setendpara(cs); if (len == 0) { buff->setEof(); moreleft = false; } laststartline = exp->locate(); break; } if (ch == 10) { buff->setendpara(cs); lastispara = true; laststartline = exp->locate(); break; } if (ch == 6) { buff->setendpara(cs); buff->setBop(); lastispara = true; laststartline = exp->locate(); break; } lastispara = false; buff->addch(ch, cs); if (ch == ' ') { nospaces++; } len++; if (!margindone) { w -= buff->leftMargin() + buff->rightMargin(); margindone = true; } #ifdef INCREMENTALWIDTH if ((slen += buff->charwidth(len-1, cs)) > w) #else if ((slen = buff->width(availht, len)) > w) #endif { if (ch == ' ' || len == 1) { if (ch == ' ') buff->truncate(len-1); laststartline = exp->locate(); break; } else // should do a backward search for spaces, first. { int lastk = len-4; for (int i = len-2; i > 0; i--) { if ( (((*buff)[i] == 0x2014) && isletter((*buff)[i+1])) || ((*buff)[i] == '-') // ((*buff)[i] == '-' && !(((*buff)[i-1] == '-') || ((*buff)[i+1] == '-'))) ) { (*buff)[len] = 0; lastword.setright(*buff, i+1); buff->truncate(i+1); (*buff)[i+1] = '\0'; laststartline = lastsizes[i+1]; // buff->resize(); for (int j = 0; j < lastword.length(); j++) { lastsizes[j] = lastsizes[j+i+1]; } return true; } //if (hyphenate && (m_hyphenthreshold+1)*i < m_hyphenthreshold*len) // We end up with i+1 characters instead of len-1 // Thus we are removing len - 1 - (i + 1) = len-i-2 // The space characters will be stretched to cover // nospaces to nospaces + len - i - 2 // The stretch factor is hence // (nospaces+len-i-2)/nospaces if (hyphenate && !isCentred && ( 100*(nospaces+len-i-2) > (100+m_hyphenthreshold)*nospaces )) { /* if (m_customhyphen) { for (int k = lastk; k >= i && k >= 2; k--) { if ( isletter((*buff)[k+3]) && isletter((*buff)[k+2]) && isvowel((*buff)[k+1]) && isconsonant((*buff)[k]) && isletter((*buff)[k-1]) && isletter((*buff)[k-2]) ) { (*buff)[len] = 0; lastword.setright(*buff, k+1); buff->truncate(k+2); (*buff)[k+1] = '-'; (*buff)[k+2] = '\0'; laststartline = lastsizes[k+1]; buff->resize(); for (int j = 0; j < lastword.length(); j++) { lastsizes[j] = lastsizes[j+k+1]; } return true; } } } else */ { for (int k = lastk; k >= i && k >= 1; k--) { if ( /* ( k < len-3 && k >= 1 && isletter((*buff)[k+3]) && isletter((*buff)[k+2]) && isconsonant((*buff)[k+1]) && ((*buff)[k+1] != 'y') && ((*buff)[k+1] != 'h') && isconsonant((*buff)[k]) && ((*buff)[k] != 'h') && isletter((*buff)[k-1]) ) || */ ( isletter((*buff)[k+3]) && isletter((*buff)[k+2]) && isconsonant((*buff)[k+1]) && ((*buff)[k+1] != 'y') && isletter((*buff)[k]) && ((*buff)[k] != 'h') && isletter((*buff)[k-1]) && // Do not hyphenate when the first part ends with a vowel, // and the second starts with the two consonants. // Examples: "co-nsona-nts" -> "con-sonants", // "hy-phenation" -> "hyp-henation" etc. !( isvowel( (*buff)[k] ) && isconsonant( (*buff)[k+2] ) ) ) ) { (*buff)[len] = 0; lastword.setright(*buff, k+1); buff->truncate(k+2); (*buff)[k+1] = '-'; (*buff)[k+2] = '\0'; laststartline = lastsizes[k+1]; // buff->resize(); for (int j = 0; j < lastword.length(); j++) { lastsizes[j] = lastsizes[j+k+1]; } return true; } } } lastk = i; } if ((*buff)[i] == ' ') { (*buff)[len] = 0; lastword.setright(*buff, i+1); buff->truncate(i); (*buff)[i] = '\0'; laststartline = lastsizes[i+1]; // buff->resize(); for (int j = 0; j < lastword.length(); j++) { lastsizes[j] = lastsizes[j+i+1]; } return true; } } laststartline = lastsizes[len-1]; (*buff)[len] = 0; lastword.setright(*buff, len - 1); buff->truncate(len-1); buff->addch('-', cs); for (int j = 0; j < lastword.length(); j++) { lastsizes[j] = lastsizes[j+len]; } break; } } } (*buff)[len] = '\0'; // buff->resize(); return moreleft; } #else bool BuffDoc::getline(CDrawBuffer* buff, int wth, unsigned short _lborder, unsigned short _rborder) { bool margindone = false; int w = wth-(_lborder+_rborder); tchar ch = 32; CStyle cs; buff->empty(); if (exp == NULL) { // (*buff)[0] = '\0'; buff->empty(); return false; } int len = 0, lastcheck = 0; if (lastword.length() > 0) { *buff = lastword; cs = lastword.laststyle(); w -= buff->leftMargin() + buff->rightMargin(); margindone = true; } else buff->empty(); // //qDebug("Buff:%s Lastword:%s", (const char*)toQString(buff->data()), (const char*)toQString(lastword.data())); lastcheck = len = buff->length(); unsigned int slen = buff->width(availht, len); if (slen > w) { for ( ; len > 1; len--) { if (buff->width(availht, len) < w) break; } // lastword = buff->data() + len - 1; laststartline = lastsizes[len-1]; for (int i = 0; i < buff->length(); i++) lastsizes[i] = lastsizes[i+len-1]; // (*buff)[len-1] = '-'; if (len > 2) { lastword.setright(*buff, len - 1); buff->truncate(len-1); buff->addch('-', cs); (*buff)[len] = '\0'; } else { lastword.empty(); (*buff)[len] = '\0'; } // buff->resize(); return true; } if (lastispara) { lastispara = false; // lastword[0] = '\0'; lastword.empty(); len = buff->length(); while (buff->width(availht, len) > w) len--; // (*buff)[len] = '\0'; buff->truncate(len); laststartline = exp->locate(); // buff->resize(); return true; } lastispara = false; for (int i = 0; i < len; i++) allsizes[i] = lastsizes[i]; while (slen < w) { lastcheck = len; getch(ch, cs, allsizes[len]); while (ch != ' ' && ch != '\012' && ch != UEOF && len < 128) { len++; buff->addch(ch,cs); getch(ch, cs, allsizes[len]); } (*buff)[len] = 0; slen = buff->width(availht, len); len++; buff->addch(' ', cs); if (!margindone) { w -= buff->leftMargin() + buff->rightMargin(); margindone = true; } allsizes[len] = exp->locate(); if (slen < w && ch != ' ') { lastcheck = len; break; } lastispara = (ch == '\012'); } (*buff)[len] = '\0'; // lastword = buff->data()+lastcheck; #ifdef _WINDOWS lastword.setright(*buff, (lastcheck > 0) ? lastcheck : 1); { int i; for (i = 0; i < lastword.length(); i++) lastsizes[i] = allsizes[i+lastcheck]; } #else lastword.setright(*buff, (lastcheck > 0) ? lastcheck : 1); for (int i = 0; i < lastword.length(); i++) lastsizes[i] = allsizes[i+lastcheck]; #endif if (lastcheck > 0) { laststartline = allsizes[lastcheck]; // (*buff)[lastcheck-1] = '\0'; buff->truncate(lastcheck-1); } else { laststartline = (lastcheck == len) ? exp->locate() : allsizes[lastcheck+1]; // (*buff)[lastcheck] = '\0'; buff->truncate(lastcheck); } // buff->frig(); // buff->resize(); if (ch == UEOF && buff->length() == 0) { buff->setEof(); return false; } return true; } #endif bool BuffDoc::getline(CDrawBuffer* buff, int wth, int cw, unsigned short _lborder, unsigned short _rborder, int availht) { int w = wth-(_lborder+_rborder); buff->empty(); if (exp == NULL) { return false; } tchar ch; CStyle cs; int i = 1; int offset = buff->offset(w,0,0,availht); while (i*cw < w-offset) { unsigned long dummy; getch(ch, cs, dummy); if (ch == '\12' || ch == UEOF) break; buff->addch(ch,cs); i++; } buff->truncate(i); laststartline = exp->locate(); // buff->resize(); return (ch != UEOF); } int BuffDoc::openfile(QWidget* _parent, const char *src) { if (exp != NULL) delete exp; exp = NULL; #ifdef __STATIC exp = new Aportis; int ret = exp->openfile(src); if (ret == -1) { delete exp; exp = NULL; return ret; } if (ret == -2) { delete exp; exp = new ztxt; ret = exp->openfile(src); } /* } if (ret != 0) { delete exp; exp = new ebookcodec("Aportis"); ret = exp->openfile(src); if (ret == 0) qDebug("Aportis format"); } */ #ifdef USENEF if (ret != 0) { delete exp; exp = new CArriere; ret = exp->openfile(src); if (ret == 0) qDebug("Arriere format"); } if (ret != 0) { delete exp; exp = new CNEF; ret = exp->openfile(src); if (ret == 0) qDebug("NEF format"); } #endif if (ret != 0) { delete exp; exp = new CPlucker; ret = exp->openfile(src); } if (ret != 0) { delete exp; exp = new CHM; ret = exp->openfile(src); } if (ret != 0) { delete exp; exp = new iSilo; ret = exp->openfile(src); } if (ret != 0) { delete exp; //qDebug("Trying ppms"); + exp = new CReb; + ret = exp->openfile(src); + } + if (ret != 0) + { + delete exp; + //qDebug("Trying ppms"); exp = new ppm_expander; ret = exp->openfile(src); } if (ret != 0) { delete exp; exp = new Text; // //qDebug("Trying text"); ret = exp->openfile(src); if (ret == 0) qDebug("Text format"); } if (ret != 0) { delete exp; QMessageBox::information(_parent, PROGNAME, "Unknown file compression type","Try another file"); return ret; } // //qDebug("Doing final open:%x:%x",exp,filt); #else - QString codecpath(QTReaderUtil::getPluginPath()); +#ifdef USEQPE +#ifdef OPIE + QString codecpath(getenv("OPIEDIR")); +#else + QString codecpath(getenv("QTDIR")); +#endif + codecpath += "/plugins/reader/codecs"; +#else + QString codecpath(getenv("READERDIR")); + codecpath += "/codecs"; +#endif QDir d(codecpath, "*.so"); if (d.exists()) { const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); // create list iterator QFileInfo *fi; // pointer for traversing int ret = -1; while ( ret != 0 && (fi=it.current()) ) { // for each file... if (exp != NULL) delete exp; qDebug("Trying %s", (const char*)fi->fileName()); exp = new ebookcodec(fi->fileName()); ret = exp->openfile(src); ++it; } qDebug("Buffdoc:Finished opening"); if (ret != 0) { if (exp != NULL) delete exp; exp = new Text; ret = exp->openfile(src); } } else { if (exp != NULL) delete exp; exp = new Text; exp->openfile(src); } #endif lastword.empty(); lastsizes[0] = laststartline = 0; #ifdef NEWLINEBREAK lastispara = false; #else lastispara = false; #endif exp->locate(exp->getHome()); filt->setsource(exp); qDebug("BuffDoc:file opened"); return 0; } QString BuffDoc::about() { return QString("Buffered Decompressor (c) Tim Wentford\nHyphenation algorithm (c) Tim Wentford\n (Cyrillic support by Konstantin Isakov\n")+filt->about(); } + +int BuffDoc::getsentence(CBuffer& buff) +{ + tchar ch; + int i = 0; + bool intext = false; + while ((ch = getch()) != 10 && ch != UEOF) + { + buff[i++] = ch; + if (ch == '"' || ch == '\'' || ch == 0x2018 || ch == 0x2019 || + ch == 0x201a || ch == 0x201b || ch == 0x201c || ch == 0x201d) + { + intext = !intext; + } + if (!intext && (ch == '.' || ch == '!' || ch == '?')) break; + } + + buff[i] = '\0'; + if (i == 0 && ch == UEOF) i = -1; + laststartline = exp->locate(); + return i; +} diff --git a/noncore/apps/opie-reader/BuffDoc.h b/noncore/apps/opie-reader/BuffDoc.h index 2b4fb57..d6bfd99 100644 --- a/noncore/apps/opie-reader/BuffDoc.h +++ b/noncore/apps/opie-reader/BuffDoc.h @@ -1,143 +1,158 @@ #ifndef __BuffDoc_h #define __BuffDoc_h #include "CDrawBuffer.h" #include "CFilter.h" #include "CExpander.h" #include <qfontmetrics.h> #include <qmessagebox.h> class BuffDoc { CDrawBuffer lastword; CSizeBuffer lastsizes, allsizes; size_t laststartline; bool lastispara; CExpander_Interface* exp; CFilterChain* filt; int m_hyphenthreshold; // bool m_customhyphen; public: QString about(); bool findanchor(const QString& nm) { return filt->findanchor(nm); } // void setCustomHyphen(bool _v) { m_customhyphen = _v; } // bool getCustomHyphen() { return m_customhyphen; } void setHyphenThreshold(int _v) { m_hyphenthreshold = _v; } void setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen) { if (exp == NULL) { data = NULL; len = 0; } else { exp->setSaveData(data, len, src, srclen); } } void putSaveData(unsigned char*& src, unsigned short& srclen) { if (exp != NULL) { exp->putSaveData(src, srclen); } } #ifdef USEQPE void suspend() { if (exp != NULL) exp->suspend(); } - void unsuspend() { if (exp != NULL) exp->unsuspend(); } #else void suspend() {} - void unsuspend() {} #endif ~BuffDoc() { delete filt; delete exp; } BuffDoc() { exp = NULL; filt = NULL; lastword.empty(); // // qDebug("Buffdoc created"); } bool empty() { return (exp == NULL); } void setfilter(CFilterChain* _f) { if (filt != NULL) delete filt; filt = _f; filt->setsource(exp); } CList<Bkmk>* getbkmklist() { return exp->getbkmklist(); } bool hasrandomaccess() { return (exp == NULL) ? false : exp->hasrandomaccess(); } bool iseol() { return (lastword[0] == '\0'); } int openfile(QWidget* _parent, const char *src); tchar getch() { tchar ch = UEOF; CStyle sty; if (exp != NULL) { unsigned long dummy; filt->getch(ch, sty, dummy); } return ch; } void getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (exp != NULL) { filt->getch(ch, sty, pos); } else ch = UEOF; } + /* + void rawgetch(tchar& ch, CStyle& sty, unsigned long& pos) + { + if (exp != NULL) + { + filt->rawgetch(ch, sty, pos); + } + else + ch = UEOF; + } + */ void setwidth(int w) { if (exp != NULL) exp->setwidth(w); } QImage* getPicture(unsigned long tgt) { return (exp == NULL) ? NULL : exp->getPicture(tgt); } unsigned int startSection() { return (exp == NULL) ? 0 : exp->startSection(); } unsigned int endSection() { return (exp == NULL) ? 0 : exp->endSection(); } + void resetPos(); unsigned int locate() { return (exp == NULL) ? 0 : laststartline; } unsigned int explocate() { return (exp == NULL) ? 0 : exp->locate(); } void setContinuous(bool _b) { if (exp != NULL) exp->setContinuous(_b); } MarkupType PreferredMarkup() { return (exp == NULL) ? cTEXT : exp->PreferredMarkup(); } linkType hyperlink(unsigned int n, unsigned int noff, QString& wrd, QString& nm); size_t getHome() { return ((exp != NULL) ? exp->getHome() : 0); } void locate(unsigned int n); bool getline(CDrawBuffer* buff, int w, unsigned short _lborder, unsigned short _rborder, bool hyphenate, int availht); bool getline(CDrawBuffer* buff, int w, int cw, unsigned short _lborder, unsigned short _rborder, int availht); void sizes(unsigned long& fs, unsigned long& ts) { if (exp != NULL) { exp->sizes(fs,ts); } else { fs = ts = 0; } } int getpara(CBuffer& buff) { tchar ch; int i = 0; while ((ch = getch()) != 10 && ch != UEOF) buff[i++] = ch; buff[i] = '\0'; if (i == 0 && ch == UEOF) i = -1; laststartline = exp->locate(); return i; } + int getsentence(CBuffer& buff); void saveposn(const QString& f, size_t posn) { filt->saveposn(f, posn); } void writeposn(const QString& f, size_t posn) { filt->writeposn(f, posn); } linkType forward(QString& f, size_t& loc) { return filt->forward(f, loc); } linkType back(QString& f, size_t& loc) { return filt->back(f, loc); } - bool hasnavigation() { return filt->hasnavigation(); } - bool getFile(QString href) + bool hasnavigation() { return (exp == NULL) ? false : filt->hasnavigation(); } + bool getFile(const QString& href, QString& nm) + { + return (exp == NULL) ? false : exp->getFile(href, nm); + } + QString getTableAsHtml(unsigned long loc) { - return (exp == NULL) ? false : exp->getFile(href); + return (exp != NULL) ? filt->getTableAsHtml(loc) : QString(""); } }; #endif diff --git a/noncore/apps/opie-reader/ButtonPrefs.cpp b/noncore/apps/opie-reader/ButtonPrefs.cpp index 50365a8..762de55 100644 --- a/noncore/apps/opie-reader/ButtonPrefs.cpp +++ b/noncore/apps/opie-reader/ButtonPrefs.cpp @@ -1,181 +1,185 @@ /**************************************************************************** ** Form implementation generated from reading ui file 'Prefs.ui' ** ** Created: Tue Feb 11 23:53:35 2003 ** by: The User Interface Compiler (uic) ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ #include "ButtonPrefs.h" #include <qcheckbox.h> #include <qlabel.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qlayout.h> #include <qvariant.h> #include <qtooltip.h> #include <qwhatsthis.h> #include <qbuttongroup.h> #include <qmultilineedit.h> #ifdef USECOMBO #include <qcombobox.h> #else #include <qpe/menubutton.h> #endif #include <qfontdatabase.h> #include <qlistview.h> class MyQListViewItem : public QListViewItem { orKey o; public: MyQListViewItem(const orKey& _o, QListView* p, const QString& c1, const QString& c2, const QString& c3) : QListViewItem(p, c1, c2, c3), o(_o) { } orKey getKey() { return o; } }; void CButtonPrefs::mapkey(Qt::ButtonState st, int _key) { mapkey(st, _key, action->currentItem()); } void CButtonPrefs::mapkey(Qt::ButtonState st, int _key, int act) { orKey key(st, _key, ((act == cesScrollMore) || (act == cesScrollLess))); QMap<orKey,QListViewItem*>::Iterator iter = listmap.find(key); if (iter != listmap.end()) { lb->takeItem(iter.data()); } (*kmap)[key] = act; listmap[key] = new MyQListViewItem(key, lb, key.text(), action->text(act), (key.isScroll()) ? "*":""); } void CButtonPrefs::keyPressEvent(QKeyEvent* e) { switch (e->key()) { case Key_Shift: case Key_Control: case Key_Meta: case Key_Alt: case Key_CapsLock: case Key_NumLock: case Key_ScrollLock: e->ignore(); break; default: mapkey(e->state(), e->key()); e->accept(); break; } } #ifdef USECOMBO void CButtonPrefs::populate(QComboBox *mb) #else void CButtonPrefs::populate(MenuButton *mb) #endif { mb->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); mb->insertItem( tr("Open file") ); mb->insertItem( tr("Autoscroll") ); mb->insertItem( tr("Bookmark") ); mb->insertItem( tr("Annotate") ); mb->insertItem( tr("Fullscreen") ); mb->insertItem( tr("Zoom in") ); mb->insertItem( tr("Zoom out") ); mb->insertItem( tr("Back") ); mb->insertItem( tr("Forward") ); mb->insertItem( tr("Home") ); mb->insertItem( tr("Page up") ); mb->insertItem( tr("Page down") ); mb->insertItem( tr("Line up") ); mb->insertItem( tr("Line down") ); mb->insertItem( tr("Beginning") ); mb->insertItem( tr("End") ); mb->insertItem( tr("Rotate") ); mb->insertItem( tr("Scroll faster") ); mb->insertItem( tr("Scroll slower") ); mb->insertItem( tr("Invert colours") ); mb->insertItem( tr("Toggle tools") ); mb->insertItem( tr("Toggle scrollbar") ); mb->insertItem( tr("Toggle statusbar") ); mb->insertItem( tr("Next link") ); mb->insertItem( tr("Goto link") ); } CButtonPrefs::CButtonPrefs( QMap<orKey, int>* _kmap, QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ), kmap(_kmap) { QVBoxLayout* vo = new QVBoxLayout(this); QHBoxLayout* lo = new QHBoxLayout(); setFocusPolicy(QWidget::StrongFocus); #ifdef USECOMBO action = new QComboBox( this ); #else action = new MenuButton( this ); #endif populate(action); action->setFocusProxy(this); QMultiLineEdit* TextLabel1 = new QMultiLineEdit( this ); TextLabel1->setText( tr( "Press the key(s) you want assigned to the highlighted function.\n\nPress the delete button to unmap the key.\n\nUse the \"Close\" button (not the [x]) to finish." ) ); TextLabel1->setReadOnly(true); TextLabel1->setWordWrap(QMultiLineEdit::WidgetWidth); // lo->addWidget(TextLabel, 0, Qt::AlignTop); // lo->addWidget(action, 0, Qt::AlignTop); lo->addWidget(TextLabel1); lo->addWidget(action); vo->addLayout(lo); lb = new QListView(this); lb->addColumn( tr( "Key" ) ); lb->addColumn( tr( "Function" ) ); lb->addColumn( tr( "Scroll" ) ); lb->setFocusProxy(this); vo->addWidget(lb,1); for (QMap<orKey,int>::Iterator i = kmap->begin(); i != kmap->end(); i++) { listmap[i.key()] = new MyQListViewItem(i.key(), lb, i.key().text(), action->text(i.data()), (i.key().isScroll()) ? "*":""); } lo = new QHBoxLayout(); QLabel* TextLabel = new QLabel( this, "TextLabel1" ); TextLabel->setText( tr( "Debounce" ) ); lo->addWidget(TextLabel); debounce = new QSpinBox( this, "Debounce" ); debounce->setRange(0,1000); lo->addWidget(debounce); + /* + QPushButton* assignClose = new QPushButton("Assign\nCancel", this); + lo->addWidget(assignClose); + */ lo->addStretch(1); QPushButton* delButton = new QPushButton("Delete", this); connect(delButton, SIGNAL( clicked() ), this, SLOT( erasemapping() )); lo->addWidget(delButton); QPushButton* exitButton = new QPushButton("Close", this); connect(exitButton, SIGNAL( clicked() ), this, SLOT( slotClosed() ) ); lo->addWidget(exitButton); vo->addLayout(lo); } void CButtonPrefs::erasemapping() { MyQListViewItem* li = (MyQListViewItem*)lb->selectedItem(); if (li != NULL) { orKey key(li->getKey()); qDebug("Tapped %s", (const char*)key.text()); kmap->remove(key); lb->takeItem(listmap[key]); listmap.remove(key); } } CButtonPrefs::~CButtonPrefs() { // no need to delete child widgets, Qt does it all for us } diff --git a/noncore/apps/opie-reader/CDrawBuffer.cpp b/noncore/apps/opie-reader/CDrawBuffer.cpp index bfb3027..227f0f6 100644 --- a/noncore/apps/opie-reader/CDrawBuffer.cpp +++ b/noncore/apps/opie-reader/CDrawBuffer.cpp @@ -1,862 +1,879 @@ #include "CDrawBuffer.h" #include "FontControl.h" #include <qfontmetrics.h> #include <qpainter.h> #include <qpixmap.h> #include <qimage.h> CDrawBuffer::~CDrawBuffer() { while (!segs.isEmpty()) segs.erase(0); } void CDrawBuffer::setright(CDrawBuffer& rhs, int f) { int i; len = rhs.len; fc = rhs.fc; m_ascent = m_descent = m_lineSpacing = m_lineExtraSpacing = 0; while (!segs.isEmpty()) { segs.erase(0); } for (CList<textsegment>::iterator iter = rhs.segs.begin(); iter != rhs.segs.end(); ) { CList<textsegment>::iterator next = iter; iter++; if (iter == rhs.segs.end() || iter->start > f) { int st = next->start-f; if (st < 0) st = 0; CStyle _style = next->style; segs.push_back(textsegment(st,next->style)); } } for (i = f; rhs[i] != '\0'; i++) (*this)[i-f] = rhs[i]; (*this)[i-f] = '\0'; len = i; } CDrawBuffer& CDrawBuffer::operator=(CDrawBuffer& rhs) { int i; // //qDebug("Trying 2"); len = rhs.len; m_ascent = rhs.m_ascent; m_descent = rhs.m_descent; m_lineSpacing = rhs.m_lineSpacing; m_lineExtraSpacing = rhs.m_lineExtraSpacing; m_showPartial = rhs.m_showPartial; while (!segs.isEmpty()) { segs.erase(0); } for (CList<textsegment>::iterator iter = rhs.segs.begin(); iter != rhs.segs.end(); iter++) { segs.push_back(*iter); } for (i = 0; rhs[i] != '\0'; i++) (*this)[i] = rhs[i]; (*this)[i] = '\0'; len = i; // //qDebug("Tried 2"); return *this; } CDrawBuffer& CDrawBuffer::operator=(const tchar*sztmp) { int i; while (!segs.isEmpty()) { segs.erase(0); } segs.push_back(textsegment(0, CStyle())); for (i = 0; sztmp[i] != '\0'; i++) (*this)[i] = sztmp[i]; (*this)[i] = '\0'; len = i; return *this; } void CDrawBuffer::empty() { m_bSop = false; m_bEop = false; m_bBop = false; len = 0; (*this)[0] = 0; while (!segs.isEmpty()) { segs.erase(0); } segs.push_back(textsegment(0,CStyle())); m_ascent = m_descent = m_lineSpacing = m_lineExtraSpacing = 0; m_bEof = false; } void CDrawBuffer::setendpara(const CStyle& _style/* = ucFontBase*/) { m_bEop = true; if (len == 0) { segs.first().start = 0; segs.first().style = _style; } } void CDrawBuffer::addch(tchar ch, CStyle _style/* = ucFontBase*/) { if (len == 0) { segs.first().start = 0; segs.first().style = _style; } else if (_style != segs.last().style) { segs.push_back(textsegment(len, _style)); } (*this)[len++] = ch; } void CDrawBuffer::truncate(int n) { len = n; (*this)[n] = 0; } int CDrawBuffer::width(int availht, int numchars, bool onscreen, int scwidth, unsigned short _lborder, unsigned short _rborder) { int gzoom = fc->gzoom(); int currentx = 0, end = 0; QString text = (numchars < 0) ? toQString(data()) : toQString(data(), numchars); CList<textsegment>::iterator textstart = segs.begin(); int extraspace = 0; bool just = (onscreen && !m_bEop && textstart->style.getJustify() == m_AlignJustify); int spaces = 0; int spacesofar = 0; int spacenumber = 0; int nonspace = 0; if (just) { for (int i = 0; i < len; i++) { if ((*this)[i] != ' ') { nonspace = i; break; } } #ifdef _WINDOWS for (i = nonspace; i < len; i++) #else for (int i = nonspace; i < len; i++) #endif { if ((*this)[i] == ' ') { spaces++; } } if (spaces == 0) { just = false; } else { extraspace = (scwidth - (_lborder+_rborder) - rightMargin() - leftMargin() - width(availht)); if (extraspace == 0) just = false; } } CList<textsegment>::iterator textend = textstart; do { textend++; end = (textend != segs.end()) ? textend->start : len; if (numchars >= 0 && end > numchars) { end = numchars; } CStyle currentstyle = textstart->style; if (currentstyle.isPicture()) { if (currentstyle.canScale()) { int ht = (gzoom*currentstyle.getPicture()->height())/100; int wt = (gzoom*currentstyle.getPicture()->width())/100; if (ht > availht) { wt = (wt*availht)/ht; } currentx += wt; } else { currentx += currentstyle.getPicture()->width(); } } else { if (currentstyle.isMono() && !fc->hasCourier()) { int cw = (7*fc->getsize(currentstyle))/10; currentx += cw*(end-textstart->start); } else { QFont f(currentstyle.isMono() ? QString(fc->fixedfontname()) : fc->name(), fc->getsize(currentstyle), (currentstyle.isBold()) ? QFont::Bold : QFont::Normal, (currentstyle.isItalic()) ); // f.setUnderline(currentstyle.isUnderline()); QString str = text.mid(textstart->start, end-textstart->start); QFontMetrics fm(f); if (just) { int lastspace = -1; int nsp = 0; int cx = currentx; while ((nsp = str.find(" ", lastspace+1)) >= 0) { if (nsp > nonspace) { spacenumber++; int nexttoadd = (extraspace*spacenumber+spaces/2)/spaces - spacesofar; QString nstr = str.mid(lastspace+1, nsp-lastspace); int lw = fm.width(nstr); cx += lw+nexttoadd; spacesofar += nexttoadd; lastspace = nsp; } else { QString nstr = str.mid(lastspace+1, nsp-lastspace); // qDebug("str:%s: last:%d new:%d nstr:%s:", (const char*)str, lastspace, nsp, (const char*)nstr); int lw = fm.width(nstr); cx += lw; lastspace = nsp; } } QString nstr = str.right(str.length()-1-lastspace); cx += fm.width(nstr); currentx = cx; } else { currentx += fm.width(str); } } } textstart = textend; } while (textend != segs.end() && end != numchars && textstart->start < len); return currentx; } int CDrawBuffer::charwidth(int numchars, CStyle& currentstyle) { if (currentstyle.isPicture()) { int gzoom = fc->gzoom(); if (currentstyle.canScale()) { return (gzoom*currentstyle.getPicture()->width())/100; } else { return currentstyle.getPicture()->width(); } } else { if (currentstyle.isMono() && !fc->hasCourier()) { return (7*fc->getsize(currentstyle))/10; } else { QString text = QChar((data())[numchars]); QFont f(currentstyle.isMono() ? QString(fc->fixedfontname()) : fc->name(), fc->getsize(currentstyle), (currentstyle.isBold()) ? QFont::Bold : QFont::Normal, (currentstyle.isItalic()) ); // f.setUnderline(currentstyle.isUnderline()); QFontMetrics fm(f); return fm.width(text); } } return 0; } int CDrawBuffer::charwidth(int numchars) { int gzoom = fc->gzoom(); int end = 0; QString text = QChar((data())[numchars]); CList<textsegment>::iterator textstart = segs.begin(); CList<textsegment>::iterator textend = textstart; do { textend++; end = (textend != segs.end()) ? textend->start : len; if (end <= numchars) { textstart = textend; continue; } if (numchars >= 0 && end > numchars) { end = numchars; } CStyle currentstyle = textstart->style; if (currentstyle.isPicture()) { if (currentstyle.canScale()) { return (gzoom*currentstyle.getPicture()->width())/100; } else { return currentstyle.getPicture()->width(); } } else { if (currentstyle.isMono() && !fc->hasCourier()) { return (7*fc->getsize(currentstyle))/10; } else { QFont f(currentstyle.isMono() ? QString(fc->fixedfontname()) : fc->name(), fc->getsize(currentstyle), (currentstyle.isBold()) ? QFont::Bold : QFont::Normal, (currentstyle.isItalic()) ); // f.setUnderline(currentstyle.isUnderline()); QFontMetrics fm(f); return fm.width(text); } } textstart = textend; } while (textend != segs.end() /* && end != numchars*/ && textstart->start < len); return 0; } int CDrawBuffer::leftMargin() { return (segs.begin()->style.getLeftMargin()*fc->getsize(segs.begin()->style)+3)/6; } int CDrawBuffer::rightMargin() { return (segs.begin()->style.getRightMargin()*fc->getsize(segs.begin()->style)+3)/6; } int CDrawBuffer::offset(int scwidth, unsigned short _lborder, unsigned short _rborder, int availht) { int currentx = _lborder; switch(segs.begin()->style.getJustify()) { case m_AlignRight: { currentx = scwidth - _rborder - rightMargin() - width(availht); } break; case m_AlignCentre: { currentx = ( scwidth - _lborder -_rborder + leftMargin() - rightMargin() - width(availht))/2 + _lborder; } break; case m_AlignJustify: case m_AlignLeft: + case m_AlignNone: currentx = _lborder + leftMargin(); break; } return currentx; } void CDrawBuffer::render(QPainter* _p, int _y, bool _bMono, int _charWidth, int scwidth, unsigned short _lborder, unsigned short _rborder, const QColor& _bg, int availht) { CList<textsegment>::iterator textstart = segs.begin(); QColor paperColour = QColor(qRgb(textstart->style.pRed(), textstart->style.pGreen(), textstart->style.pBlue())); Highlight(_p, !(paperColour == _bg), _lborder, _y, scwidth-(_lborder+_rborder), paperColour); // Highlight(_p, true, _lborder, _y, scwidth-(_lborder+_rborder), paperColour); int gzoom = fc->gzoom(); int currentx = offset(scwidth, _lborder, _rborder, availht); if (!m_hastext) { for (CList<textsegment>::iterator iter = segs.begin(); iter != segs.end(); iter++) { CStyle currentstyle = iter->style; if (currentstyle.isPicture()) { CStyle currentstyle = segs.begin()->style; int ht = (gzoom*currentstyle.getPicture()->height())/100; int wt = (gzoom*currentstyle.getPicture()->width())/100; bool willscale = false; if (ht > availht) { wt = (wt*availht)/ht; ht = availht; willscale = true; } QPixmap pc; if ((willscale || gzoom != 100) && currentstyle.canScale()) { QImage im = currentstyle.getPicture()->smoothScale(wt,ht); pc.convertFromImage(im); } else { pc.convertFromImage(*currentstyle.getPicture()); } int yoffset = pc.height()/2; _p->drawPixmap( currentx, _y-yoffset, pc ); currentx += pc.width(); } } return; } QString text = toQString(data()); int extraspace = 0; bool just = (!m_bEop && textstart->style.getJustify() == m_AlignJustify); int spaces = 0; int spacesofar = 0; int spacenumber = 0; int nonspace = 0; if (just) { for (int i = 0; i < len; i++) { if ((*this)[i] != ' ') { nonspace = i; break; } } #ifdef _WINDOWS for (i = nonspace; i < len; i++) #else for (int i = nonspace; i < len; i++) #endif { if ((*this)[i] == ' ') { spaces++; } } if (spaces == 0) { just = false; } else { extraspace = (scwidth - (_lborder+_rborder) - rightMargin() - leftMargin() - width(availht)); if (extraspace == 0) just = false; } } CList<textsegment>::iterator textend = textstart; bool drawBackground = false; do { textend++; int end = (textend != segs.end()) ? textend->start : len; CStyle currentstyle = textstart->style; /* bool drawBackground = ( currentstyle.bRed() != 255 || currentstyle.bGreen() != 255 || currentstyle.bBlue() != 255 ); */ QColor bgColour = QColor(qRgb(currentstyle.bRed(), currentstyle.bGreen(), currentstyle.bBlue())); drawBackground = !(bgColour == _bg); // if (drawBackground) qDebug("Drawing background"); QFont f((currentstyle.isMono() && fc->hasCourier()) ? fc->fixedfontname() : fc->name(), fc->getsize(currentstyle), (currentstyle.isBold()) ? QFont::Bold : QFont::Normal, (currentstyle.isItalic()) ); // f.setUnderline(currentstyle.isUnderline()); // if (currentstyle.isUnderline()) qDebug("UNDERLINE"); _p->setFont(f); QString str = text.mid(textstart->start, end-textstart->start); #if defined(OPIE) || !defined(USEQPE) - _p->setPen(QPen(QColor(currentstyle.Red(), currentstyle.Green(), currentstyle.Blue()), fc->getsize(currentstyle)/100)); + _p->setPen(QPen(QColor(currentstyle.Red(), currentstyle.Green(), currentstyle.Blue()), fc->getsize(currentstyle)/10/*0*/)); #else _p->setPen(QPen(QColor(currentstyle.Red(), currentstyle.Green(), currentstyle.Blue()), fc->getsize(currentstyle)/10)); #endif int voffset = currentstyle.getVOffset()*fc->getsize(currentstyle)/2; if (_bMono) { Highlight(_p, drawBackground, currentx, _y, str.length()*_charWidth, bgColour); if (currentstyle.isUnderline()) { _p->drawLine( currentx, _y+voffset, currentx + str.length()*_charWidth, _y+voffset); } if (currentstyle.isStrikethru()) { int ascent = fc->ascent(currentstyle)/3; _p->drawLine( currentx, _y-ascent+voffset, currentx + str.length()*_charWidth, _y-ascent+voffset); } for (int i = 0; i < str.length(); i++) { _p->drawText( currentx + i*_charWidth, _y+voffset, QString(str[i])); } currentx += str.length()*_charWidth; } else { if (currentstyle.isPicture()) { int ht = (gzoom*currentstyle.getPicture()->height())/100; int wt = (gzoom*currentstyle.getPicture()->width())/100; bool willscale = false; if (ht > availht) { wt = (wt*availht)/ht; ht = availht; willscale = true; } int ascent = fc->ascent(currentstyle)/2; int yoffset = ht/2 + ascent; QPixmap pc; if ((willscale || gzoom != 100) && currentstyle.canScale()) { QImage im = currentstyle.getPicture()->smoothScale(wt,ht); pc.convertFromImage(im); } else { pc.convertFromImage(*currentstyle.getPicture()); } _p->drawPixmap( currentx, _y-yoffset, pc ); currentx += wt; } else { if (currentstyle.isMono() && !fc->hasCourier()) { int cw = (7*fc->getsize(currentstyle))/10; int w = cw*(end-textstart->start); Highlight(_p, drawBackground, currentx, _y, w, bgColour); if (currentstyle.isUnderline()) { _p->drawLine( currentx, _y+voffset, currentx + w, _y+voffset); } if (currentstyle.isStrikethru()) { int ascent = fc->ascent(currentstyle)/3; _p->drawLine( currentx, _y-ascent+voffset, currentx + w, _y-ascent+voffset); } QString str = text.mid(textstart->start, end-textstart->start); for (unsigned int i = 0; i < str.length(); i++) { #ifdef _WINDOWS _p->drawText( currentx, _y+voffset, QString(str.at(i))); #else _p->drawText( currentx, _y+voffset, QString(str[i])); #endif currentx += cw; } } else { QFontMetrics fm(f); int w; if (just) { int lastspace = -1; int nsp = 0; int cx = currentx; while ((nsp = str.find(" ", lastspace+1)) >= 0) { if (nsp+textstart->start >= nonspace) { spacenumber++; int nexttoadd = (extraspace*spacenumber+spaces/2)/spaces - spacesofar; QString nstr = str.mid(lastspace+1, nsp-lastspace); // qDebug("str:%s: last:%d new:%d nstr:%s:", (const char*)str, lastspace, nsp, (const char*)nstr); int lw = fm.width(nstr); Highlight(_p, drawBackground, cx, _y, lw, bgColour); _p->drawText( cx, _y+voffset, nstr); Highlight(_p, drawBackground, cx+lw, _y, nexttoadd, bgColour); cx += lw+nexttoadd; spacesofar += nexttoadd; lastspace = nsp; } else { QString nstr = str.mid(lastspace+1, nsp-lastspace); // qDebug("str:%s: last:%d new:%d nstr:%s:", (const char*)str, lastspace, nsp, (const char*)nstr); int lw = fm.width(nstr); Highlight(_p, drawBackground, cx, _y, lw, bgColour); _p->drawText( cx, _y+voffset, nstr); cx += lw; lastspace = nsp; } } QString nstr = str.right(str.length()-1-lastspace); int lw = fm.width(nstr); Highlight(_p, drawBackground, cx, _y, lw, bgColour); _p->drawText( cx, _y+voffset, nstr); cx += lw; w = cx - currentx; } else { int lw = fm.width(str); Highlight(_p, drawBackground, currentx, _y, lw, bgColour); _p->drawText( currentx, _y+voffset, str); w = lw; } if (currentstyle.isUnderline()) { _p->drawLine( currentx, _y+voffset, currentx + w, _y+voffset); } if (currentstyle.isStrikethru()) { int ascent = fc->ascent(currentstyle)/3; _p->drawLine( currentx, _y-ascent+voffset, currentx + w, _y-ascent+voffset); } currentx += w; } } } textstart = textend; } while (textend != segs.end() && textstart->start < len); /* if (firstColour == bgColour) { Highlight(_p, drawBackground, currentx, _y, scwidth - (currentx + _lborder + _rborder), bgColour); } */ } void CDrawBuffer::Highlight(QPainter* _p, bool drawBackground, int _x, int _y, int w, QColor bgColour) { if (drawBackground) { _p->fillRect(_x, _y-m_ascent, w, m_lineSpacing, bgColour); } } CStyle CDrawBuffer::laststyle() { return segs.last().style; } CStyle CDrawBuffer::firststyle() { return segs.first().style; } -linkType CDrawBuffer::getLinkType(int numchars, size_t& tgt, size_t& offset, size_t& pictgt, QImage*& img) +linkType CDrawBuffer::getLinkType(int numchars, size_t& tgt, size_t& offset, size_t& pictgt, QImage*& img, size_t& tabletgt) { linkType ret = eNone; int end = 0; CStyle currentstyle; CList<textsegment>::iterator textstart = segs.begin(); CList<textsegment>::iterator textend = textstart; do { textend++; end = (textend != segs.end()) ? textend->start : len; currentstyle = textstart->style; /* if (currentstyle.isPicture()) qDebug("Passed thru picture"); if (currentstyle.getLink()) qDebug("Passed thru link"); //qDebug("islink:%d - %d", numchars, end); */ textstart = textend; } while (textend != segs.end() && end <= numchars); img = currentstyle.getPicture(); if (currentstyle.getPictureLink()) { pictgt = currentstyle.getPictureLinkData(); ret |= ePicture; } if (currentstyle.getLink()) { tgt = currentstyle.getData(); offset = currentstyle.getOffset(); ret |= eLink; } + if (currentstyle.isTable()) + { + tabletgt = currentstyle.getTable(); + ret |= eTable; + } return ret; } void CDrawBuffer::resize(int availht) { int gzoom = fc->gzoom(); m_ascent = m_descent = m_lineSpacing = m_lineExtraSpacing = 0; /* int t_ascent = 0; int t_descent = 0; int t_lineExtraSpacing = 0; */ int t_lineSpacing = 0; m_hastext = false; for (CList<textsegment>::iterator iter = segs.begin(); iter != segs.end() && iter->start <= len; ) { CStyle _style = iter->style; if (!_style.isPicture()) { m_hastext = true; break; } iter++; } if (m_hastext) { - + int p_linespacing = 0; for (CList<textsegment>::iterator iter = segs.begin(); iter != segs.end() && iter->start <= len; ) { CList<textsegment>::iterator next = iter; iter++; int st = next->start; if (st < 0) st = 0; CStyle _style = next->style; int linespacing, ascent, descent, extra; ascent = fc->ascent(_style); descent = fc->descent(_style); linespacing = fc->lineSpacing(_style); extra = linespacing - ascent - descent; /* if (ascent > t_ascent) t_ascent = ascent; if (descent > t_descent) t_descent = descent; if (extra > t_lineExtraSpacing) t_lineExtraSpacing = extra; t_lineSpacing = t_ascent+t_descent+t_lineExtraSpacing; */ if (linespacing > t_lineSpacing) t_lineSpacing = linespacing; if (_style.isPicture()) { int ht = (gzoom*_style.getPicture()->height())/100; int wt = (gzoom*_style.getPicture()->width())/100; bool willscale = false; if (ht > availht) { wt = (wt*availht)/ht; ht = availht; willscale = true; } if (willscale || _style.canScale()) { descent = ((gzoom*_style.getPicture()->height())/100-ascent)/2; ascent = ((gzoom*_style.getPicture()->height())/100+ascent)/2; } + else + { + descent = (_style.getPicture()->height()-ascent)/2; + ascent = (_style.getPicture()->height()+ascent)/2; + } + int lineSpacing = ascent+descent; + if (lineSpacing > p_linespacing) + { + p_linespacing = lineSpacing; + } + extra = 0; } /* else if (fc != NULL) { ascent = fc->ascent(_style); descent = fc->descent(_style); linespacing = fc->lineSpacing(_style); extra = linespacing - ascent - descent; } */ if (ascent > m_ascent) m_ascent = ascent; if (descent > m_descent) m_descent = descent; if (extra > m_lineExtraSpacing) m_lineExtraSpacing = extra; m_lineSpacing = m_ascent+m_descent+m_lineExtraSpacing; } - m_showPartial = (m_lineSpacing > t_lineSpacing); + m_showPartial = (p_linespacing > t_lineSpacing); int lead = fc->getlead(); if (lead != 0) { int xt = (lead*t_lineSpacing+5)/10; m_lineExtraSpacing += xt; m_lineSpacing += xt; } if (m_bSop) { int xt = ((segs.begin()->style.getExtraSpace()+fc->getextraspace())*fc->getsize(segs.begin()->style)+5)/10; // qDebug("ExtraSpace:%d", xt); m_ascent += xt; m_lineSpacing += xt; } } else { m_showPartial = true; int maxheight = 0; for (CList<textsegment>::iterator iter = segs.begin(); iter != segs.end(); iter++) { CStyle _style = iter->style; if (_style.isPicture()) { int ht = 0; if (_style.canScale()) { ht = ((gzoom*_style.getPicture()->height())/100); } else { ht = _style.getPicture()->height(); } if (ht > availht) { ht = availht; } if (ht > maxheight) maxheight = ht; } } m_ascent = maxheight/2; m_descent = maxheight-m_ascent; m_lineExtraSpacing = 0; m_lineSpacing = m_ascent+m_descent; } } CStyle* CDrawBuffer::getNextLink(int& offset) { CStyle* ret = NULL; for (CList<textsegment>::iterator iter = segs.begin(); iter != segs.end(); ++iter) { if (offset < iter->start && iter->style.getLink()) { ret = &(iter->style); offset = iter->start; qDebug("Found a link at offset %d!", offset); break; } } return ret; } int CDrawBuffer::invertLink(int offset) { for (CList<textsegment>::iterator iter = segs.begin(); iter != segs.end(); ++iter) { if (offset <= iter->start && iter->style.getLink()) { iter->style.invert(); unsigned long currentvalue = iter->style.getData(); qDebug("Link data %u", currentvalue); CList<textsegment>::iterator next = iter; ++next; while (next != segs.end() && (currentvalue == next->style.getData()) && next->style.getLink()) { next->style.invert(); offset = next->start; iter++; next++; } return offset; } } qDebug("Failed to invert"); return offset; } diff --git a/noncore/apps/opie-reader/CDrawBuffer.h b/noncore/apps/opie-reader/CDrawBuffer.h index 2625a72..1782cf8 100644 --- a/noncore/apps/opie-reader/CDrawBuffer.h +++ b/noncore/apps/opie-reader/CDrawBuffer.h @@ -1,87 +1,87 @@ #ifndef __CDRAWBUFFER_H #define __CDRAWBUFFER_H #include <qcolor.h> #include "StyleConsts.h" #include "CBuffer.h" #include "my_list.h" #include "linktype.h" class QPainter; class QImage; struct textsegment { int start; CStyle style; textsegment(int _start, const CStyle& _style) : start(_start), style(_style) {} }; class FontControl; class CDrawBuffer : public CBuffer { bool m_hastext; CList<textsegment> segs; int len; FontControl* fc; int m_ascent, m_descent, m_lineSpacing, m_lineExtraSpacing; bool m_bEof, m_bBop; bool m_bSop, m_bEop; bool m_showPartial; CDrawBuffer(const CDrawBuffer&); CDrawBuffer& operator=(const tchar*sztmp); void Highlight(QPainter*_p, bool drawBackground, int _x, int _y, int w, QColor bgColour); public: void setstartpara() { m_bSop = true; } void setBop() { m_bBop = true; } bool isBop() { return m_bBop; } void setendpara() { m_bEop = true; } void setendpara(const CStyle& cs); int leftMargin(); int rightMargin(); void setEof() { m_bEof = true; } bool eof() { return m_bEof; } CDrawBuffer& operator=(CDrawBuffer&); CDrawBuffer(FontControl* _fs = NULL) : fc(_fs) { empty(); } ~CDrawBuffer(); /* CDrawBuffer() : size(0) { empty(); } */ int charwidth(int numchars, CStyle& currentstyle); int charwidth(int numchars); int width(int availht, int numchars = -1, bool onscreen = false, int scwidth = 0, unsigned short _lborder = 0, unsigned short _rborder = 0); int offset(int, unsigned short, unsigned short, int); void render(QPainter* _p, int _y, bool _bMono, int _charWidth, int scw, unsigned short, unsigned short, const QColor&, int availht); void empty(); void addch(tchar ch, CStyle _style); void truncate(int); void setright(CDrawBuffer&, int); CStyle firststyle(); CStyle laststyle(); int ascent() { return m_ascent; } int descent() { return m_descent; } int lineSpacing() { return m_lineSpacing; } int lineExtraSpacing() { return m_lineExtraSpacing; } // void frig(); - linkType getLinkType(int numchars, size_t& tgt, size_t& offset, size_t& pictgt, QImage*&); + linkType getLinkType(int numchars, size_t& tgt, size_t& offset, size_t& pictgt, QImage*&, size_t&); void resize(int); bool showPartial() { return m_showPartial; } CStyle* getNextLink(int&); int invertLink(int); }; #endif diff --git a/noncore/apps/opie-reader/CEncoding.h b/noncore/apps/opie-reader/CEncoding.h index 1dfd74d..76cbfae 100644 --- a/noncore/apps/opie-reader/CEncoding.h +++ b/noncore/apps/opie-reader/CEncoding.h @@ -1,94 +1,101 @@ #ifndef __CENCODING_H #define __CENCODING_H #include "CExpander.h" #define MAX_ENCODING 6 class CEncoding : public CCharacterSource { friend class CFilterChain; protected: CExpander_Interface* parent; linkType hyperlink(unsigned int n, unsigned int noff, QString& t, QString& nm) { return parent->hyperlink(n, noff, t, nm); } public: + virtual QString getTableAsHtml(unsigned long loc) + { + qDebug("CEncoding::getTableAsHtml()"); + return parent->getTableAsHtml(loc); + } CEncoding() : parent(NULL) {} void setparent(CExpander_Interface* p) { parent = p; } virtual ~CEncoding() {}; void locate(unsigned int n) { parent->locate(n); } - bool findanchor(const QString& nm) { return false; } + bool findanchor(const QString& nm) + { + return parent->findanchor(nm); + } void saveposn(const QString& f, size_t posn) { parent->saveposn(posn); } void writeposn(const QString& f, size_t posn) { parent->writeposn(posn); } linkType forward(QString& f, size_t& loc) { return parent->forward(loc); } linkType back(QString& f, size_t& loc) { return parent->back(loc); } bool hasnavigation() { return parent->hasnavigation(); } virtual int getwidth() { return parent->getwidth(); } QImage* getPicture(unsigned long tgt) { return parent->getPicture(tgt); } QImage* getPicture(const QString& href) { return parent->getPicture(href); } - bool getFile(const QString& href) { qDebug("Encoding Get File"); return parent->getFile(href);} - - + bool getFile(const QString& href, const QString& nm) { qDebug("Encoding Get File"); return parent->getFile(href, nm);} + unsigned long startSection() { return parent->startSection(); } }; class CUtf8 : public CEncoding { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("UTF8 decoder (c) Tim Wentford\n")+parent->about(); } }; class CUcs16be : public CEncoding { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("UCS16 decoder (c) Tim Wentford\n")+parent->about(); } }; class CUcs16le : public CEncoding { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("UCS16 decoder (c) Tim Wentford\n")+parent->about(); } }; class Ccp1252 : public CEncoding { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Codepage 1252 decoder (c) Tim Wentford\n")+parent->about(); } }; class CPalm : public Ccp1252 { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Palm decoder (c) Tim Wentford\n")+parent->about(); } }; class CAscii : public CEncoding { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Vanilla Ascii decoder (c) Tim Wentford\n")+parent->about(); } }; #include "CEncoding_tables.h" class CGeneral8Bit : public CEncoding { int m_index; public: CGeneral8Bit(int _i) : m_index(_i) { // qDebug("8Bit:%d", _i); // qDebug("%s", unicodetable::iterator(_i)->mime); } void getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); ch = unicodetable::unicodevalue(m_index, ch); } QString about() { return QString("8-bit decoder (c) Tim Wentford - based on QT code\n")+parent->about(); } }; #endif diff --git a/noncore/apps/opie-reader/CExpander.cpp b/noncore/apps/opie-reader/CExpander.cpp index e398d86..1158a7a 100644 --- a/noncore/apps/opie-reader/CExpander.cpp +++ b/noncore/apps/opie-reader/CExpander.cpp @@ -1,103 +1,111 @@ #include "CExpander.h" +#ifdef USEQPE +#include <qpe/global.h> +#endif size_t CExpander::getHome() { return m_homepos; } CExpander::CExpander() : m_homepos(0), fname(NULL), m_scrWidth(240), m_currentstart(1), m_currentend(0) {}; CExpander::~CExpander() { if (fname != NULL) delete [] fname; }; int CExpander::openfile(const char *src) { bSuspended = false; fname = strdup(src); return OpenFile(src); } void CExpander::getch(tchar& ch, CStyle& sty, unsigned long& pos) { pos = locate(); int ich = getch(); ch = (ich == EOF) ? UEOF : ich; // sty.unset(); } linkType CExpander::hyperlink(unsigned int n, unsigned int, QString& wrd, QString& nm) { locate(n); return eLink; } unsigned long CExpander::startSection() { unsigned long current = locate(); if (m_currentstart > current || current > m_currentend) { start2endSection(); } return m_currentstart; } unsigned long CExpander::endSection() { unsigned long current = locate(); if (m_currentstart > current || current > m_currentend) { start2endSection(); } return m_currentend; } void CExpander::start2endSection() { m_currentstart = 0; unsigned long file; sizes(file, m_currentend); } #ifdef USEQPE void CExpander::suspend(FILE*& fin) { bSuspended = true; suspos = ftell(fin); fclose(fin); fin = NULL; sustime = time(NULL); } void CExpander::unsuspend(FILE*& fin) { if (bSuspended) { bSuspended = false; int delay = time(NULL) - sustime; - if (delay < 10) sleep(10-delay); + if (delay < 10) + { + Global::statusMessage("Stalling"); + sleep(10-delay); + } fin = fopen(fname, "rb"); for (int i = 0; fin == NULL && i < 5; i++) { + Global::statusMessage("Stalling"); sleep(5); fin = fopen(fname, "rb"); } if (fin == NULL) { QMessageBox::warning(NULL, PROGNAME, "Couldn't reopen file"); exit(0); } suspos = fseek(fin, suspos, SEEK_SET); } } #endif void CExpander::setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen) { len = srclen; data = new unsigned char[len]; memcpy(data, src, len); } void CExpander::putSaveData(unsigned char*& src, unsigned short& srclen) { if (srclen != 0) { qDebug("Don't know what to do with non-zero save data"); } } diff --git a/noncore/apps/opie-reader/CExpander.h b/noncore/apps/opie-reader/CExpander.h index 7fa84f9..24c317d 100644 --- a/noncore/apps/opie-reader/CExpander.h +++ b/noncore/apps/opie-reader/CExpander.h @@ -1,148 +1,156 @@ #ifndef __CExpander_h #define __CExpander_h #ifndef _WINDOWS #include <unistd.h> #endif #include <stdio.h> #include <time.h> #include <sys/stat.h> #include <qmessagebox.h> #include "config.h" #include "StyleConsts.h" #include "Markups.h" #include "names.h" #include "linktype.h" class QImage; class Bkmk; class QString; template<class T> class CList; class CCharacterSource { public: + virtual QString getTableAsHtml(unsigned long loc) = 0; virtual void getch(tchar&, CStyle&, unsigned long&) = 0; virtual linkType hyperlink(unsigned int n, unsigned int noff, QString&, QString& nm) = 0; virtual void locate(unsigned int n) = 0; virtual bool findanchor(const QString& nm) = 0; virtual void saveposn(const QString& f, size_t posn) = 0; virtual void writeposn(const QString& f, size_t posn) = 0; virtual linkType forward(QString& f, size_t& loc) = 0; virtual linkType back(QString& f, size_t& loc) = 0; virtual bool hasnavigation() = 0; virtual int getwidth() = 0; virtual QImage* getPicture(unsigned long) = 0; virtual QImage* getPicture(const QString& href) = 0; - virtual bool getFile(const QString& href) = 0; + virtual bool getFile(const QString& href, const QString& nm) = 0; virtual QString about() = 0; + virtual unsigned long startSection() = 0; }; class CExpander_Interface { public: #ifdef USEQPE virtual void suspend() = 0; virtual void unsuspend() = 0; #endif virtual QString about() = 0; virtual size_t getHome() = 0; //CExpander_Interface(); //virtual ~CExpander_Interface(); virtual int openfile(const char *src) = 0; //virtual int OpenFile(const char *src) = 0; virtual unsigned int locate() = 0; virtual void locate(unsigned int n) = 0; virtual bool hasrandomaccess() = 0; virtual void sizes(unsigned long& file, unsigned long& text) = 0; virtual CList<Bkmk>* getbkmklist() { return NULL; } virtual void getch(tchar& ch, CStyle& sty, unsigned long& pos) = 0; virtual int getch() = 0; virtual linkType hyperlink(unsigned int n, unsigned int noff, QString& wrd, QString& nm) = 0; virtual MarkupType PreferredMarkup() = 0; virtual void saveposn(size_t posn) {} virtual void writeposn(size_t posn) {} virtual linkType forward(size_t& loc) { return eNone; } virtual linkType back(size_t& loc) { return eNone; } virtual bool hasnavigation() { return false; } virtual unsigned long startSection() = 0; virtual unsigned long endSection() = 0; virtual void start2endSection() = 0; virtual QImage* getPicture(unsigned long tgt) { return NULL; } virtual void setContinuous(bool _b) = 0; #ifdef USEQPE virtual void suspend(FILE*& fin) = 0; virtual void unsuspend(FILE*& fin) = 0; #endif virtual void setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen) = 0; virtual void putSaveData(unsigned char*& src, unsigned short& srclen) = 0; virtual void setwidth(int w) = 0; // bool findstring(const QString& info); // int getpara(CBuffer& buff); virtual int getwidth() = 0; virtual QImage* getPicture(const QString& href) = 0; - virtual bool getFile(const QString& href) = 0; + virtual bool getFile(const QString& href, const QString& nm) = 0; + virtual bool findanchor(const QString& nm) = 0; + virtual QString getTableAsHtml(unsigned long loc) { return QString(""); } }; class CExpander : public CExpander_Interface { protected: size_t m_homepos; bool m_continuous; char* fname; bool bSuspended; size_t suspos; time_t sustime; int m_scrWidth; unsigned long m_currentstart, m_currentend; public: #ifdef USEQPE virtual void suspend() = 0; virtual void unsuspend() = 0; #endif size_t getHome(); CExpander(); virtual ~CExpander(); int openfile(const char *src); virtual int OpenFile(const char *src) = 0; virtual unsigned int locate() = 0; virtual void locate(unsigned int n) = 0; virtual bool hasrandomaccess() = 0; virtual void sizes(unsigned long& file, unsigned long& text) = 0; virtual CList<Bkmk>* getbkmklist() { return NULL; } virtual void getch(tchar& ch, CStyle& sty, unsigned long& pos); virtual int getch() = 0; virtual linkType hyperlink(unsigned int n, unsigned int noff, QString& wrd, QString& nm); virtual MarkupType PreferredMarkup() = 0; virtual void saveposn(size_t posn) {} virtual void writeposn(size_t posn) {} virtual linkType forward(size_t& loc) { return eNone; } virtual linkType back(size_t& loc) { return eNone; } virtual bool hasnavigation() { return false; } unsigned long startSection(); unsigned long endSection(); virtual void start2endSection(); virtual QImage* getPicture(unsigned long tgt) { return NULL; } void setContinuous(bool _b) { m_continuous = _b; } #ifdef USEQPE virtual void suspend(FILE*& fin); virtual void unsuspend(FILE*& fin); #endif virtual void setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen); virtual void putSaveData(unsigned char*& src, unsigned short& srclen); void setwidth(int w) { m_scrWidth = w; } int getwidth() { return m_scrWidth; } // bool findstring(const QString& info); // int getpara(CBuffer& buff); virtual QImage* getPicture(const QString& href) { return NULL; } - virtual bool getFile(const QString& href) { return false; } + virtual bool getFile(const QString& href, const QString& nm) { return false; } + virtual bool findanchor(const QString& nm) + { + return false; + } }; #endif diff --git a/noncore/apps/opie-reader/CFilter.cpp b/noncore/apps/opie-reader/CFilter.cpp index ab98829..25cdfae 100644 --- a/noncore/apps/opie-reader/CFilter.cpp +++ b/noncore/apps/opie-reader/CFilter.cpp @@ -1,815 +1,861 @@ #include <qmap.h> #include <qfileinfo.h> #include <qtextstream.h> #include <qdir.h> + #ifdef USEQPE #include <qpe/global.h> #endif #include "CDrawBuffer.h" #include "CFilter.h" #include "hrule.h" -#include "util.h" #include <qregexp.h> #include <qimage.h> #include <qpixmap.h> //#include <qprogressdialog.h> //#include <qapplication.h> void textfmt::mygetch(tchar& ch, CStyle& sty, unsigned long& pos) { if (uselast) { ch = lastchar; uselast = false; } else { parent->getch(ch, sty, pos); } } void textfmt::getch(tchar& ch, CStyle& sty, unsigned long& pos) { mygetch(ch, sty, pos); do { sty = currentstyle; switch (ch) { case 10: currentstyle.unset(); sty = currentstyle; break; // Use this if you want to replace -- by em-dash case '-': // parent->getch(ch, sty); mygetch(ch, sty, pos); if (ch == '-') { ch = 0x2014; } else { lastchar = ch; uselast = true; ch = '-'; } break; case '*': if (currentstyle.isBold()) { // Already bold - time to turn it off? // The next two lines ensure that * follows a character but it works better without // QChar c(lastchar); // if ((lastchar != '*') && (c.isPunct() || c.isLetterOrNumber())) if (lastchar != '*') { currentstyle.unsetBold(); CStyle dummy; // parent->getch(ch, dummy); mygetch(ch, dummy, pos); } } else { // not bold - time to turn it on? CStyle dummy; // parent->getch(ch, dummy); mygetch(ch, dummy, pos); QChar c(ch); if ((ch != '*') && (c.isPunct() || c.isLetterOrNumber())) { currentstyle.setBold(); } else { lastchar = ch; uselast = true; ch = '*'; } } break; case '_': if (currentstyle.isItalic()) { // Already bold - time to turn it off? // The next two lines ensure that * follows a character but it works better without // QChar c(lastchar); // if ((lastchar != '_') && (c.isPunct() || c.isLetterOrNumber())) if (lastchar != '_') { currentstyle.unsetItalic(); CStyle dummy; // parent->getch(ch, dummy); mygetch(ch, dummy, pos); } } else { // not bold - time to turn it on? CStyle dummy; // parent->getch(ch, dummy); mygetch(ch, dummy, pos); QChar c(ch); if ((ch != '_') && (c.isPunct() || c.isLetterOrNumber())) { currentstyle.setItalic(); } else { lastchar = ch; uselast = true; ch = '_'; } } break; } } while (sty != currentstyle); if (!uselast) lastchar = ch; return; } void remap::getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (q[offset] != 0) { q[offset++]; sty = currentstyle; return; } parent->getch(ch, sty, pos); switch (ch) { case 0x201a: ch = '\''; break; case 0x0192: ch = 'f'; break; case 0x201e: ch = '"'; break; case 0x2026: offset = 0; q[0] = '.'; q[1] = '.'; q[2] = 0; ch = '.'; // should be ... break; case 0x0160: ch = 'S'; break; case 0x2039: ch = '<'; break; case 0x0152: offset = 0; q[0] = 'E'; q[1] = 0; ch = 'O'; break; case 0x017d: ch = 'Z'; break; case 0x2018: ch = '\''; break; case 0x2019: ch = '\''; break; case 0x201c: ch = '"'; break; case 0x201d: ch = '"'; break; case 0x2022: ch = '>'; break; case 0x2013: ch = '-'; break; case 0x2014: offset = 0; q[0] = '-'; q[1] = 0; ch = '-'; // should be -- break; case 0x02dc: ch = '~'; break; case 0x0161: ch = 's'; break; case 0x203a: ch = '>'; break; case 0x0153: offset = 0; q[0] = 'e'; q[1] = 0; ch = 'o';// should be oe break; /* case 0x0009: // tab offset = 0; q[0] = ' '; q[1] = 0; ch = ' '; break; */ case 0x017e: ch = 'z'; break; case 0x0178: ch = 'Y'; break; } currentstyle = sty; } void PeanutFormatter::getch(tchar& ch, CStyle& sty, unsigned long& pos) { CStyle dummy; currentstyle.setColour(0,0,0); parent->getch(ch, dummy, pos); while (ch == '\\') { parent->getch(ch, dummy, pos); if (ch == '\\') break; switch(ch) { case 'a': { int code = 0; for (int i = 0; i < 3; i++) { parent->getch(ch, dummy, pos); code = 10*code + ch - '0'; } ch = code; } break; case 'v': { while (1) { parent->getch(ch, dummy, pos); if (ch == '\\') { parent->getch(ch, dummy, pos); if (ch == 'v') { parent->getch(ch, dummy, pos); break; } } } } break; case 's': case 'n': currentstyle.setFontSize(0); parent->getch(ch,dummy, pos); break; case 'p': currentstyle.unset(); // parent->getch(ch,dummy); ch = 10; break; case 'l': if (currentstyle.getFontSize() == 1) { currentstyle.setFontSize(0); } else { currentstyle.setFontSize(1); } parent->getch(ch, dummy, pos); break; case 'x': if (currentstyle.getFontSize() == 0) { // currentstyle.unset(); // currentstyle.setBold(); currentstyle.setFontSize(1); } else { currentstyle.unset(); } // parent->getch(ch, dummy); ch = 10; break; case 'i': if (currentstyle.isItalic()) { currentstyle.unsetItalic(); } else { currentstyle.setItalic(); } parent->getch(ch, dummy, pos); break; case 'b': case 'B': if (currentstyle.isBold()) { currentstyle.unsetBold(); } else { currentstyle.setBold(); } parent->getch(ch, dummy, pos); break; case 'c': if (currentstyle.getJustify() == m_AlignCentre) { currentstyle.setLeftJustify(); } else { currentstyle.setCentreJustify(); } parent->getch(ch, dummy, pos); break; case 'r': if (currentstyle.getJustify() == m_AlignRight) { currentstyle.setLeftJustify(); } else { currentstyle.setRightJustify(); } parent->getch(ch, dummy, pos); break; default: currentstyle.setColour(255,0,0); } } sty = currentstyle; } void OnePara::getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); if (m_lastchar == 10) { while (ch == 10) parent->getch(ch, sty, pos); } m_lastchar = ch; } void repalm::getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); switch (ch) { case 0x80: ch = 0x20ac; break; case 0x82: ch = 0x201a; break; case 0x83: ch = 0x0192; break; case 0x84: ch = 0x201e; break; case 0x85: ch = 0x2026; break; case 0x86: ch = 0x2020; break; case 0x87: ch = 0x2021; break; case 0x88: ch = 0x02c6; break; case 0x89: ch = 0x2030; break; case 0x8a: ch = 0x0160; break; case 0x8b: ch = 0x2039; break; case 0x8c: ch = 0x0152; break; /* case 0x8e: ch = 0x017d; break; */ case 0x91: ch = 0x2018; break; case 0x92: ch = 0x2019; break; case 0x93: ch = 0x201c; break; case 0x94: ch = 0x201d; break; case 0x95: ch = 0x2022; break; case 0x96: ch = 0x2013; break; case 0x97: ch = 0x2014; break; case 0x98: ch = 0x02dc; break; case 0x99: ch = 0x2122; break; case 0x9a: ch = 0x0161; break; case 0x9b: ch = 0x203a; break; case 0x9c: ch = 0x0153; break; case 0x9e: ch = 0x017e; break; case 0x9f: ch = 0x0178; break; case 0x18: ch = 0x2026; break; case 0x19: ch = 0x2007; break; case 0x8d: ch = 0x2662; break; case 0x8e: ch = 0x2663; break; case 0x8f: ch = 0x2661; break; case 0x90: ch = 0x2660; break; default: break; } } //static tchar nextpart[] = { 'C','l','i','c','k',' ','h','e','r','e',' ','f','o','r',' ','t','h','e',' ','n','e','x','t',' ','p','a','r','t',0 }; //static tchar prevpart[] = { 'C','l','i','c','k',' ','h','e','r','e',' ','f','o','r',' ','t','h','e',' ','p','r','e','v','i','o','u','s',' ','p','a','r','t',0 }; void DePluck::getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (m_buffed > 0) { sty = m_laststyle; ch = nextpart[m_current++]; if (m_current == m_buffed) { m_current = m_buffed = 0; } } else { if (m_buffer != 0) { ch = m_buffer; m_buffer = 0; return; } unsigned long lnk, lnkoff; do { if (nextpart[m_buffed] == 0) break; parent->getch(ch, sty, pos); m_laststyle = sty; if (sty.getLink()) { lnk = sty.getData(); lnkoff = sty.getOffset(); } } while (ch == nextpart[m_buffed] && sty.getLink() && ++m_buffed); m_current = 0; if (nextpart[m_buffed] == 0) { m_buffed = 0; QString dmy, dmy2; parent->hyperlink(lnk, lnkoff, dmy, dmy2); do { parent->getch(ch, sty, pos); } while (ch != 10); parent->getch(ch, sty, pos); } else if (m_buffed > 0) { m_buffer = ch; ch = nextpart[0]; if (m_buffed == 1) { m_buffed = 0; } else m_current = 1; } } return; } HighlightFilter::HighlightFilter(QTReader* _p) : pReader(_p), lastpos(0), nextpos(0), red(255), green(255), blue(255) { } #include "Bkmks.h" #include "QTReader.h" void HighlightFilter::refresh(unsigned long pos) { bkmks = pReader->Bkmklist(); red = green = blue = 255; if (bkmks == NULL) { lastpos = 0; nextpos = 0xffffffff; } else { lastpos = 0; nextpos = 0xffffffff; for (CList<Bkmk>::iterator i = bkmks->begin(); i != bkmks->end(); i++) { if ((*i).value() <= pos && pos < (*i).value2()) { red = i->red(); green = i->green(); blue = i->blue(); lastpos = (*i).value(); nextpos = (*i).value2(); break; } if ((*i).value() > pos) { nextpos = (*i).value(); break; } lastpos = (*i).value(); } } } void HighlightFilter::getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); if (bkmks != pReader->Bkmklist() || pos <= lastpos || pos >= nextpos) { // qDebug("Recalc <%lu, %lu, %lu>", lastpos, pos, nextpos); refresh(pos); // qDebug("Recalc(2) <%lu, %lu, %lu>", lastpos, pos, nextpos); } int r = sty.bRed(), g = sty.bGreen(), b = sty.bBlue(); if (r == 255 && g == 255 && b == 255) { sty.setBackground(red, green, blue); } } void kern::getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (uselast) { ch = lastchar; sty = laststy; uselast = false; return; } else { parent->getch(ch, sty, pos); } switch (ch) { case 'f': { tchar savedchar = 'f'; parent->getch(ch, sty, pos); switch (ch) { case 'i': ch = (251 << 8) + 1; break; case 'l': ch = (251 << 8) + 2; break; default: lastchar = ch; uselast = true; laststy = sty; ch = savedchar; } } break; default: break; } } class ErrorFilter : public CFilter { QString error; int currentpos; public: ErrorFilter(const QString& _s) : error(_s), currentpos(0) {} ~ErrorFilter() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (currentpos == error.length()) { ch = UEOF; currentpos = 0; } else { ch = error[currentpos++].unicode(); } } QString about() { return parent->about(); } }; #ifndef __STATIC ExternFilter::ExternFilter(const QString& nm, const QString& optional) : filt(NULL), handle(NULL) { - QString filterpath(QTReaderUtil::getPluginPath("filters")); - filterpath += "/lib"; +#ifdef USEQPE +#ifdef OPIE + QString filterpath(getenv("OPIEDIR")); +#else + QString filterpath(getenv("QTDIR")); +#endif + filterpath += "/plugins/reader/filters/lib"; +#else + QString filterpath(getenv("READERDIR")); + filterpath += "/filters/lib"; +#endif filterpath += nm; filterpath += ".so"; if (QFile::exists(filterpath)) { qDebug("Filter:%s", (const char*)filterpath); handle = dlopen(filterpath, RTLD_LAZY); if (handle == 0) { qDebug("Can't find filter:%s", dlerror()); // status = -10; filt = new ErrorFilter(QString("Can't find plugin:")+nm); return; } CFilter* (*newfilter)(const QString&); newfilter = (CFilter* (*)(const QString&))dlsym(handle, "newfilter"); if (newfilter == NULL) { qDebug("Can't find newfilter"); filt = new ErrorFilter(QString("Can't find entry point in plugin:")+nm); return; } filt = (*newfilter)(optional); } else { - qDebug("No filter path"); + qDebug("No filter path:%s", (const char*)filterpath); filt = new ErrorFilter(QString("No filter plugins installed:")+nm); } if (filt == NULL) { qDebug("Can't do newfilter"); filt = new ErrorFilter(QString("Filter creation failed:")+nm); return; } } #endif void makeInverse::getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); int r,g,b; r = 255 - sty.Red(), g = 255 - sty.Green(), b = 255 - sty.Blue(); sty.setColour(r,g,b); r = 255 - sty.bRed(), g = 255 - sty.bGreen(), b = 255 - sty.bBlue(); sty.setBackground(r,g,b); r = 255 - sty.pRed(), g = 255 - sty.pGreen(), b = 255 - sty.pBlue(); sty.setPaper(r,g,b); } /* void makeNegative::getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); QColor fg(sty.Red(), sty.Green(), sty.Blue()); int h,s,v; fg.hsv(&h,&s,&v); fg.setHsv(h,s,255-v); int r,g,b; fg.rgb(&r,&g,&b); sty.setColour(r,g,b); fg = QColor(sty.bRed(), sty.bGreen(), sty.bBlue()); fg.hsv(&h,&s,&v); fg.setHsv(h,s,255-v); fg.rgb(&r,&g,&b); sty.setBackground(r,g,b); } */ void setbg::getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); int r = sty.pRed(), g = sty.pGreen(), b = sty.pBlue(); if (r == 255 && g == 255 && b == 255) { sty.setPaper(m_r,m_g,m_b); } else { qDebug("We have background [%x%x%x]", r, g, b); } r = sty.bRed(), g = sty.bGreen(), b = sty.bBlue(); if (r == 255 && g == 255 && b == 255) { sty.setBackground(m_r,m_g,m_b); } else { qDebug("We have background [%x%x%x]", r, g, b); } } void setfg::getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); int r = sty.Red(), g = sty.Green(), b = sty.Blue(); if (r == 0 && g == 0 && b == 0) { sty.setColour(m_r,m_g,m_b); } } #include "CRegExp.h" repara::repara(const QString& pat) : tch(0) { // QString pat("{\\n[A-Z\"]}"); flt = new CRegExpFilt(pat, false); qDebug("Construction done"); } repara::~repara() { delete flt; } void repara::getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (flt->empty()) { while (flt->empty()) { parent->getch(ch, sty, pos); flt->addch(ch); } } ch = flt->pop(); /* parent->getch(ch, sty, pos); if (ch == 10 || ch == ' ') { if (tch == 10) { tch = ch; ch = 10; return; } else { tch = ch; ch = ' '; return; } } tch = ch; */ return; } + +void tableLink::getch(tchar& ch, CStyle& sty, unsigned long& pos) +{ + if (offset >= (int)text.length()) + { + offset = -1; + sty.setColour(m_r, m_g, m_b); + do + { + parent->getch(ch, sty, pos); + } + while (sty.isTable()); + return; + } + if (offset >= 0) + { + ch = text[offset++].unicode(); + return; + } + parent->getch(ch, sty, pos); + if (sty.isTable()) + { + offset = 1; + ch = text[0].unicode(); + m_r = sty.Red(), m_g = sty.Green(), m_b = sty.Blue(); + sty.setColour(255, 0, 0); + } + return; +} + +void underlineLink::getch(tchar& ch, CStyle& sty, unsigned long& pos) +{ + parent->getch(ch, sty, pos); + if (sty.getLink()) sty.setUnderline(); + //if (isLink && !sty.getLink()) sty.unsetUnderline(); + //isLink = sty.getLink(); +} diff --git a/noncore/apps/opie-reader/CFilter.h b/noncore/apps/opie-reader/CFilter.h index 174e6b4..594b606 100644 --- a/noncore/apps/opie-reader/CFilter.h +++ b/noncore/apps/opie-reader/CFilter.h @@ -1,474 +1,523 @@ #ifndef __CFILTER_H #define __CFILTER_H #include "CExpander.h" #include "CEncoding.h" class CFilter_IFace : public CCharacterSource { public: virtual linkType hyperlink(unsigned int n, unsigned int noff, QString& w, QString& nm) = 0; virtual void setparent(CCharacterSource* p) = 0; virtual ~CFilter_IFace() {}; virtual void locate(unsigned int n) = 0; virtual bool findanchor(const QString& nm) = 0; virtual void saveposn(const QString& f, size_t posn) = 0; virtual void writeposn(const QString& f, size_t posn) = 0; virtual linkType forward(QString& f, size_t& loc) = 0; virtual linkType back(QString& f, size_t& loc) = 0; virtual bool hasnavigation() = 0; virtual int getwidth() = 0; virtual CCharacterSource* getparent() = 0; + virtual unsigned long startSection() = 0; }; class CFilter : public CFilter_IFace { protected: CCharacterSource* parent; public: + virtual QString getTableAsHtml(unsigned long loc) + { + qDebug("CFilter::getTableAsHtml()"); + return parent->getTableAsHtml(loc); + } virtual linkType hyperlink(unsigned int n, unsigned int noff, QString& w, QString& nm) { return parent->hyperlink(n,noff,w,nm); } CFilter() : parent(NULL) {} void setparent(CCharacterSource* p) { parent = p; } CCharacterSource* getparent() { return parent; } virtual ~CFilter() {}; virtual void locate(unsigned int n) { parent->locate(n); } virtual bool findanchor(const QString& nm) { return parent->findanchor(nm); } virtual void saveposn(const QString& f, size_t posn) { parent->saveposn(f, posn); } virtual void writeposn(const QString& f, size_t posn) { parent->writeposn(f, posn); } virtual linkType forward(QString& f, size_t& loc) { return parent->forward(f, loc); } virtual linkType back(QString& f, size_t& loc) { return parent->back(f, loc); } virtual bool hasnavigation() { return parent->hasnavigation(); } virtual int getwidth() { return parent->getwidth(); } QImage* getPicture(unsigned long tgt) { return parent->getPicture(tgt); } QImage* getPicture(const QString& href) { return parent->getPicture(href); } - bool getFile(const QString& href) { return parent->getFile(href); } + bool getFile(const QString& href, const QString& nm) { return parent->getFile(href, nm); } + virtual unsigned long startSection() { return parent->startSection(); } }; class CFilterChain { CExpander_Interface* expander; CEncoding* encoder; CFilter_IFace* first; CCharacterSource* front; public: CFilterChain(CEncoding* _e) : encoder(_e), first(NULL), front(_e) {}; ~CFilterChain() { CCharacterSource* p = front; while (p != encoder) { CFilter_IFace* pnext = (CFilter_IFace*)p; p = ((CFilter_IFace*)p)->getparent(); delete pnext; } delete encoder; } linkType hyperlink(unsigned int n, unsigned int noff, QString& wrd, QString& nm) { return front->hyperlink(n, noff, wrd, nm); } + QString getTableAsHtml(unsigned long loc) + { + return front->getTableAsHtml(loc); + } void locate(unsigned int n) { front->locate(n); } void getch(tchar& ch, CStyle& sty, unsigned long& pos) { front->getch(ch, sty, pos); } + /* + void rawgetch(tchar& ch, CStyle& sty, unsigned long& pos) + { + encoder->getch(ch, sty, pos); + } + */ void addfilter(CFilter_IFace* p) { if (first == NULL) { front = first = p; p->setparent(encoder); } else { p->setparent(front); front = p; } } void setsource(CExpander_Interface* p) { expander = p; encoder->setparent(p); } void setencoder(CEncoding* p) { delete encoder; encoder = p; first->setparent(p); encoder->setparent(expander); } bool findanchor(const QString& nm) { return front->findanchor(nm); } void saveposn(const QString& f, size_t posn) { front->saveposn(f, posn); } void writeposn(const QString& f, size_t posn) { front->writeposn(f, posn); } linkType forward(QString& f, size_t& loc) { return front->forward(f, loc); } linkType back(QString& f, size_t& loc) { return front->back(f, loc); } bool hasnavigation() { return front->hasnavigation(); } QString about() { return QString("Filter chain (c) Tim Wentford\n")+front->about(); } }; class stripcr : public CFilter { public: stripcr() {} ~stripcr() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { do { parent->getch(ch, sty, pos); } while (ch == 13); } QString about() { return QString("StripCR filter (c) Tim Wentford\n")+parent->about(); } }; class dehyphen : public CFilter { bool m_bCharWaiting; tchar m_nextChar; CStyle m_nextSty; public: dehyphen() : m_bCharWaiting(false) {} ~dehyphen() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (m_bCharWaiting) { m_bCharWaiting = false; ch = m_nextChar; sty = m_nextSty; return; } parent->getch(ch, sty, pos); if (ch != '-') return; parent->getch(m_nextChar, m_nextSty, pos); if (m_nextChar != 10) { m_bCharWaiting = true; ch = '-'; return; } parent->getch(ch, sty, pos); } QString about() { return QString("Hyphenation filter (c) Tim Wentford\n")+parent->about(); } }; template<class A, class B>class QMap; const int m_cmaxdepth = 8; class htmlmark { QString file; size_t pos; public: htmlmark() : file(), pos(0) {} htmlmark(const QString& _f, size_t _p) : file(_f), pos(_p) {} QString filename() { return file; } size_t posn() { return pos; } }; class unindent : public CFilter { tchar lc; public: unindent() : lc(0) {} ~unindent() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (lc == 10) { do { parent->getch(ch, sty, pos); } while (ch == ' '); } else parent->getch(ch, sty, pos); lc = ch; return; } QString about() { return QString("Unindent filter (c) Tim Wentford\n")+parent->about(); } }; class CRegExpFilt; class repara : public CFilter { tchar tch; CRegExpFilt* flt; public: repara(const QString&); ~repara(); void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Reparagraph filter (c) Tim Wentford\n")+parent->about(); } }; class indenter : public CFilter { int amnt; int indent; CStyle lsty; public: indenter(int _a=5) : amnt(_a), indent(0) {} ~indenter() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (indent > 0) { indent--; ch = ' '; sty = lsty; return; } parent->getch(ch, sty, pos); if (ch == 10) { indent = amnt; lsty = sty; } return; } QString about() { return QString("Indentation filter (c) Tim Wentford\n")+parent->about(); } }; class dblspce : public CFilter { bool lastlf; CStyle lsty; public: dblspce() : lastlf(false) {} ~dblspce() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { if (lastlf) { lastlf = false; ch = 10; sty = lsty; return; } parent->getch(ch, sty, pos); if (lastlf = (ch == 10)) { lsty = sty; } return; } QString about() { return QString("Double space (c) Tim Wentford\n")+parent->about(); } }; class textfmt : public CFilter { CStyle currentstyle; tchar lastchar; bool uselast; void mygetch(tchar&, CStyle&, unsigned long& pos); public: textfmt() : lastchar(0), uselast(false) {} ~textfmt() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Text formatting filter (c) Tim Wentford\n")+parent->about(); } }; class embolden : public CFilter { public: embolden() {} ~embolden() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); sty.setBold(); } QString about() { return QString("Emboldening filter (c) Tim Wentford\n")+parent->about(); } }; class remap : public CFilter { tchar q[3]; int offset; CStyle currentstyle; public: remap() : offset(0) { q[0] = 0; } ~remap() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Character remapping filter (c) Tim Wentford\n")+parent->about(); } }; class PeanutFormatter : public CFilter { CStyle currentstyle; public: ~PeanutFormatter() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("PML filter (c) Tim Wentford\n")+parent->about(); } }; class OnePara : public CFilter { tchar m_lastchar; public: OnePara() : m_lastchar(0) {} ~OnePara() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Single space filter (c) Tim Wentford\n")+parent->about(); } }; class DePluck : public CFilter { tchar* nextpart; tchar m_buffer; int m_buffed; int m_current; bool m_debuff; CStyle m_laststyle; public: DePluck(tchar* t) : nextpart(t), m_buffer(0), m_buffed(0), m_current(0), m_debuff(false) {} ~DePluck() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Depluck filter (c) Tim Wentford\n")+parent->about(); } }; class repalm : public CFilter { public: ~repalm() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Repalm filter (c) Tim Wentford\n")+parent->about(); } }; class FullJust : public CFilter { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); if (sty.getJustify() == m_AlignLeft) sty.setFullJustify(); } QString about() { return QString("Full justification filter (c) Tim Wentford\n")+parent->about(); } }; /* class AddSpace : public CFilter { unsigned char m_espc; public: AddSpace(unsigned char s) : m_espc(s) {} void getch(tchar& ch, CStyle& sty, unsigned long& pos) { parent->getch(ch, sty, pos); sty.setExtraSpace(m_espc); } }; */ class QTReader; class HighlightFilter : public CFilter { QTReader* pReader; unsigned long lastpos, nextpos; unsigned char red, green, blue; CList<Bkmk>* bkmks; public: HighlightFilter(QTReader*); void getch(tchar& ch, CStyle& sty, unsigned long& pos); void refresh(unsigned long); QString about() { return QString("High-lighting filter (c) Tim Wentford\n")+parent->about(); } }; #ifndef __STATIC #include <dlfcn.h> class ExternFilter : public CFilter_IFace { CFilter* filt; void *handle; public: linkType hyperlink(unsigned int n, unsigned int noff, QString& w, QString& nm) { return filt->hyperlink(n, noff, w, nm); } + QString getTableAsHtml(unsigned long loc) + { + qDebug("ExternFilter::getTableAsHtml()"); + return filt->getTableAsHtml(loc); + } void setparent(CCharacterSource* p) { filt->setparent(p); } ExternFilter(const QString& nm, const QString& optional); ~ExternFilter() { if (filt != NULL) delete filt; if (handle != NULL) dlclose(handle); } void locate(unsigned int n) { filt->locate(n); } - bool findanchor(const QString& nm) { return filt->findanchor(nm); } + bool findanchor(const QString& nm) + { + return filt->findanchor(nm); + } void saveposn(const QString& f, size_t posn) { filt->saveposn(f, posn); } void writeposn(const QString& f, size_t posn) { filt->writeposn(f, posn); } linkType forward(QString& f, size_t& loc) { return filt->forward(f, loc); } linkType back(QString& f, size_t& loc) { return filt->back(f, loc); } bool hasnavigation() { return filt->hasnavigation(); } int getwidth() { return filt->getwidth(); } CCharacterSource* getparent() { return filt->getparent(); } void getch(tchar& c, CStyle& s, unsigned long& l) { filt->getch(c, s, l); } QImage* getPicture(unsigned long tgt) { return filt->getPicture(tgt); } CFilter* filter() { return filt; } QImage* getPicture(const QString& href) { return filt->getPicture(href); } - bool getFile(const QString& href) { return filt->getFile(href); } + bool getFile(const QString& href, const QString& nm) { return filt->getFile(href, nm); } QString about() { return QString("Filter plug-in (c) Tim Wentford\n")+filt->about(); } + unsigned long startSection() { return filt->startSection(); } }; #endif class kern : public CFilter { tchar lastchar; bool uselast; CStyle laststy; public: kern() : lastchar(0), uselast(false) {} ~kern() {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Kerning filter (c) Tim Wentford\n")+parent->about(); } }; class makeInverse : public CFilter { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Colourmap inversion filter (c) Tim Wentford\n")+parent->about(); } }; /* class makeNegative : public CFilter { public: void getch(tchar& ch, CStyle& sty, unsigned long& pos); }; */ class setbg : public CFilter { int m_r, m_g, m_b; public: setbg(int _r, int _g, int _b) : m_r(_r), m_g(_g), m_b(_b) {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Background colour filter (c) Tim Wentford\n")+parent->about(); } }; class setfg : public CFilter { int m_r, m_g, m_b; public: setfg(int _r, int _g, int _b) : m_r(_r), m_g(_g), m_b(_b) {} void getch(tchar& ch, CStyle& sty, unsigned long& pos); QString about() { return QString("Foreground colour filter (c) Tim Wentford\n")+parent->about(); } }; +class tableLink : public CFilter +{ + QString text; + int offset; + int m_r, m_g, m_b; + public: + tableLink() : text( "See Table" ), offset(-1) + { + } + void getch(tchar& ch, CStyle& sty, unsigned long& pos); + QString about() { return QString("Table link filter (c) Tim Wentford\n")+parent->about(); } +}; + +class underlineLink : public CFilter +{ + bool isLink; + public: + underlineLink() : isLink(false) {} + ~underlineLink() {} + void getch(tchar& ch, CStyle& sty, unsigned long& pos); + QString about() { return QString("Link underlining filter (c) Tim Wentford\n")+parent->about(); } +}; + #endif diff --git a/noncore/apps/opie-reader/CHM.cpp b/noncore/apps/opie-reader/CHM.cpp index 88d53bf..ace5abc 100644 --- a/noncore/apps/opie-reader/CHM.cpp +++ b/noncore/apps/opie-reader/CHM.cpp @@ -1,379 +1,390 @@ #include "CHM.h" #include "chm_lib.h" #include <qstring.h> #include <qstringlist.h> #include <stdio.h> #include <qimage.h> #include <qpixmap.h> +#ifdef USEQPE +#include <qpe/global.h> +#endif #ifndef __STATIC extern "C" { CExpander* newcodec() { return new CHM; } } #endif static int _print_ui_index(struct chmFile *h, struct chmUnitInfo *ui, void *context) { CHM *chm = (CHM *)context; QString temp = "<tr>"; char buff[1024]; sprintf( buff,"<td align=right>%8d\n</td><td><a href=\"%s\">%s</a></td></tr>",(int)ui->length, ui->path, ui->path); temp += buff; chm->addContent(temp); return CHM_ENUMERATOR_CONTINUE; } static int _get_hhc (struct chmFile *h, struct chmUnitInfo *ui, void *context) { CHM *chm = (CHM *)context; QString PathName = ui->path; if (PathName.find(".hhc") > -1) { chm->setPath(PathName); } return CHM_ENUMERATOR_CONTINUE; } CHM::CHM() { chmFile = NULL; chmPath = ""; chmHHCPath = ""; chmBuffer = ""; bufpos = 0; } CHM::~CHM() { if (chmFile != NULL) chm_close(chmFile); } void CHM::suspend() {
#ifdef USEQPE bSuspended = true; //suspos = gztell(file); chm_close(chmFile); chmFile = NULL; sustime = time(NULL);
#endif } void CHM::unsuspend() {
#ifdef USEQPE if (bSuspended) { bSuspended = false; int delay = time(NULL) - sustime; if (delay < 10)
+ { + Global::statusMessage("Stalling"); sleep(10-delay);
+ } chmFile = chm_open(fname); for (int i = 0; chmFile == NULL && i < 5; i++) { + Global::statusMessage("Stalling"); sleep(5); chmFile = chm_open(fname); } if (chmFile == NULL) { QMessageBox::warning(NULL, PROGNAME, "Couldn't reopen file"); exit(0); } //suspos = gzseek(file, suspos, SEEK_SET); }
#endif } void CHM::addContent(QString content) { chmBuffer += content; } void CHM::FillHomeContent() { +unsuspend(); if (chmHHCPath != "") { const char *ext; char buffer[65536]; unsigned int swath, offset; QString tmp=""; QString HTML=""; /* try to find the file */ const char *filename = (const char *)chmHHCPath; if (chm_resolve_object(chmFile, filename, &m_ui) != CHM_RESOLVE_SUCCESS) { chmBuffer = "HELP"; fsize = chmBuffer.length(); return; } m_homestart = m_ui.start; m_homeend = m_homestart + m_ui.length; swath = 65536; offset = 0; fsize = m_ui.length; while (offset < m_ui.length) { if ((m_ui.length - offset) < 65536) swath = m_ui.length - offset; else swath = 65536; swath = (int)chm_retrieve_object(chmFile, &m_ui, (unsigned char *) buffer, offset, swath); tmp += buffer; offset += swath; } HTML +="<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN>\r\n"; HTML +="<HTML>\r\n"; HTML +="<BODY>\r\n"; HTML +="<h2>Home Page</h2>\r\n"; HTML +="<h3>\r\n"; QStringList qsl = QStringList::split("\r\n",tmp); QString NameFind ="<param name=\"Name\" value=\""; QString LocalFind = "<param name=\"Local\" value=\""; QString ULOpenFind = "<UL>"; QString LIOpenFind = "<LI>"; QString ULCloseFind = "</UL>"; QString Name = ""; QString Local = ""; for ( QStringList::Iterator it = qsl.begin(); it != qsl.end(); ++it ) { QString Line = (*it); int NamePos = Line.find( NameFind); int LocalPos = Line.find( LocalFind); if (NamePos > -1) { Name = Line.mid(NamePos+NameFind.length(),Line.length()); Name = Name.left(Name.length() - 2); } if (LocalPos > -1) { Local = Line.mid(LocalPos+LocalFind.length(),Line.length()); Local = Local.left(Local.length() - 2); if (Name != "") { HTML += "<br>\r\n<a href="; HTML += Local; HTML += ">"; HTML += Name; HTML += "</a>\r\n"; Name = ""; } } } HTML +="</h3>"; HTML +="</BODY>\r\n"; HTML +="</HTML>\r\n"; chmHomeBuffer = HTML; chmBuffer = HTML; fsize = chmBuffer.length(); m_currentstart = m_ui.start; m_currentend = m_currentstart+chmBuffer.length(); } } bool CHM::FillBuffer() { +unsuspend(); bool bRetVal = false; char buffer[65536]; int swath, offset; chmBuffer = ""; swath = 65536; offset = 0; fsize = m_ui.length; while (offset < m_ui.length) { if ((m_ui.length - offset) < 65536) swath = m_ui.length - offset; else swath = 65536; swath = (int)chm_retrieve_object(chmFile, &m_ui, (unsigned char *) buffer, offset, swath); chmBuffer += buffer; offset += swath; } //There seems to be a ton of gobbledygook at the end that is reminiscent of the hhc file - remove it QString temp = chmBuffer.lower(); int lpos = temp.find("</html"); if (lpos > -1) { chmBuffer.truncate(lpos); chmBuffer = chmBuffer+"</HTML>"; } fsize = chmBuffer.length(); bufpos = 0; bRetVal = true; m_currentstart = m_ui.start; m_currentend = m_currentstart+chmBuffer.length(); return bRetVal; } bool CHM::FillContent() { +unsuspend(); bool bRetVal = false; if (chmPath != "") { /* try to find the file */ const char *filename = (const char *)chmPath; if (chm_resolve_object(chmFile, filename, &m_ui) != CHM_RESOLVE_SUCCESS) { fsize = chmBuffer.length(); return bRetVal; } char buffer[65536]; int swath, offset; chmBuffer = ""; swath = 65536; offset = 0; fsize = m_ui.length; while (offset < m_ui.length) { if ((m_ui.length - offset) < 65536) swath = m_ui.length - offset; else swath = 65536; swath = (int)chm_retrieve_object(chmFile, &m_ui, (unsigned char *) buffer, offset, swath); chmBuffer += buffer; offset += swath; } //There seems to be a ton of gobbledygook at the end that is reminiscent of the hhc file - remove it QString temp = chmBuffer.lower(); int lpos = temp.find("</html"); if (lpos > -1) { chmBuffer.truncate(lpos); chmBuffer = chmBuffer+"</HTML>"; } fsize = chmBuffer.length(); bufpos = 0; m_currentstart = m_ui.start; m_currentend = m_currentstart+chmBuffer.length(); bRetVal = true; } return bRetVal; } -bool CHM::getFile(const QString& href) { +bool CHM::getFile(const QString& _href, const QString& ) { + QString href = "/" + _href; qDebug("Got:%s", (const char*)href); bool bRetVal = false; QString temp = chmPath; chmPath = href; if (FillContent()) { qDebug("Got it"); bRetVal = true; } else { qDebug("Missed"); chmPath = temp; FillContent(); } return bRetVal; } QImage *CHM::getPicture(const QString& href) { QImage *img = NULL; QString PicRef = "/"+href; struct chmUnitInfo ui; const char *ext; /* try to find the file */ const char *filename = (const char *)PicRef; if (chm_resolve_object(chmFile, filename, &ui) != CHM_RESOLVE_SUCCESS) { qDebug ("Could not resolve image"); return img; } if (ui.length > 0) { char *temp = new char[ui.length]; char buffer[65536]; int swath, offset; swath = 65536; offset = 0; while (offset < ui.length) { if ((ui.length - offset) < 65536) swath = ui.length - offset; else swath = 65536; swath = (int)chm_retrieve_object(chmFile, &ui, (unsigned char *) buffer, offset, swath); memcpy( (void *) (temp + offset), (void *)&buffer, swath ); offset += swath; } QByteArray qba; qba.setRawData( (const char *)temp, ui.length); QPixmap qpm(qba); img = new QImage(qpm.convertToImage()); qba.resetRawData((const char *)temp, ui.length); delete[] temp; } return img; } int CHM::OpenFile(const char *src) { if (chmFile != NULL) chm_close(chmFile); struct stat _stat; stat(src,&_stat); fsize = _stat.st_size; chmFile = chm_open(src); if (chmFile != NULL) { chm_enumerate(chmFile, CHM_ENUMERATE_ALL, _get_hhc, (void *)this); if ( chmPath != "") { setHomePath(chmPath); FillHomeContent(); } } m_homepos = locate(); qDebug("Home:%u", m_homepos); return (chmFile==NULL); } int CHM::getch() { if ( (bufpos+1) >= chmBuffer.length() ) return EOF; #ifdef _WINDOWS
QChar letter = chmBuffer.at(bufpos++);
#else
QChar letter = chmBuffer[bufpos++];
#endif
return (int)(char)letter; } void CHM::getch(tchar& ch, CStyle& sty) { int ich = getch(); ch = (ich == EOF) ? UEOF : ich; } void CHM::start2endSection() { m_currentstart = m_ui.start; m_currentend = m_currentstart+chmBuffer.length(); } unsigned int CHM::locate() { return m_currentstart+bufpos; } void CHM::locate(unsigned int n) { if (n == 0) n = m_homepos; if (n >= m_homestart && n < m_homeend) { FillHomeContent(); bufpos = n - m_homestart; start2endSection(); qDebug("Home:%u:<%u, %u, %u>", m_ui.start, m_currentstart, n, m_currentend); } else if (n >= m_currentstart && n < m_currentend) { bufpos = n - m_currentstart; } else if (CHM_RESOLVE_FAILURE == chm_resolve_location(chmFile, n/4, &m_ui)) { qDebug("Resolve failure"); FillHomeContent(); bufpos = 0; start2endSection(); qDebug("Home:%u:<%u, %u, %u>", m_ui.start, m_currentstart, n, m_currentend); } else { qDebug("Resolve success"); FillBuffer(); start2endSection(); bufpos=n-m_currentstart; qDebug("Not Home:%u:<%u, %u, %u>", m_ui.start, m_currentstart, n, m_currentend); } } void CHM::sizes(unsigned long& _file, unsigned long& _text) { _text = _file = fsize; } diff --git a/noncore/apps/opie-reader/CHM.h b/noncore/apps/opie-reader/CHM.h index 001f7fc..291818d 100644 --- a/noncore/apps/opie-reader/CHM.h +++ b/noncore/apps/opie-reader/CHM.h @@ -1,67 +1,67 @@ #ifndef __CHM_h #define __CHM_h #include <stdio.h> #include <sys/stat.h> #include "CExpander.h" #include "chm_lib.h" #include "my_list.h" #include "CExpander.h" struct Ref { QString RefName; QString RefLoc; int beginpos; int endpos; }; struct Pic { QString RefName; QString RefLoc; int beginpos; int endpos; }; class CHM : public CExpander { void start2endSection(); struct chmUnitInfo m_ui; struct chmFile *chmFile; chmUnitInfo chmui; //alloc a meg to buffer QString chmHomeBuffer; QString chmBuffer; QString chmPath; QString chmHHCPath; unsigned int bufpos; unsigned long fsize; unsigned long m_homestart, m_homeend; public: void suspend(); void unsuspend(); bool hasnavigation() { return true; } CHM(); virtual ~CHM(); int OpenFile(const char *src); int getch(); unsigned int locate(); void locate(unsigned int n); bool hasrandomaccess() { return true; } void sizes(unsigned long& _file, unsigned long& _text); void addContent(QString content); void getch(tchar& ch, CStyle& sty); void setPath(QString PathName) {chmPath = PathName;}; void setHomePath(QString PathName) {chmHHCPath = PathName;}; MarkupType PreferredMarkup() { return cCHM; } - bool getFile(const QString& href); + bool getFile(const QString& href, const QString& nm); QImage *getPicture(const QString& href); QString about() { return QString("CHM codec (c) Bob Griffin\nchm_lib (c) Jed Wing\nLZX code (c) Stuart Cale"); } private : bool FillBuffer(); bool FillContent(); void FillHomeContent(); }; #endif diff --git a/noncore/apps/opie-reader/CRegExp.cpp b/noncore/apps/opie-reader/CRegExp.cpp index 77dc2dc..6318d28 100644 --- a/noncore/apps/opie-reader/CRegExp.cpp +++ b/noncore/apps/opie-reader/CRegExp.cpp diff --git a/noncore/apps/opie-reader/CSource.h b/noncore/apps/opie-reader/CSource.h new file mode 100644 index 0000000..2885f72 --- a/dev/null +++ b/noncore/apps/opie-reader/CSource.h @@ -0,0 +1,62 @@ +#ifndef __CSOURCE_H +#define __CSOURCE_H + +class CInfo +{ + public: + virtual unsigned long size() = 0; +}; + +class CSource : public CInfo +{ + public: + virtual int get() = 0; +}; + +class CSink : public CInfo +{ + public: + virtual void put(unsigned char c) = 0; +}; + +class CMemSource : public CSource +{ + unsigned long m_total_size; + unsigned long m_current; + unsigned char* m_buffer; + public: + CMemSource(unsigned char* _buffer, unsigned long _size) + : + m_total_size(_size), + m_current(0), + m_buffer(_buffer) + {} + unsigned long size() { return m_current; } + int get() + { + return ((m_current < m_total_size) ? m_buffer[m_current++] : -1); + } +}; + +class CMemSink : public CSink +{ + unsigned long m_total_size; + unsigned long m_current; + unsigned char* m_buffer; + public: + CMemSink(unsigned char* _buffer, unsigned long _size) + : + m_total_size(_size), + m_current(0), + m_buffer(_buffer) + {} + unsigned long size() { return m_current; } + void put(unsigned char c) + { + if (m_current < m_total_size) + { + m_buffer[m_current++] = c; + } + } +}; +#endif diff --git a/noncore/apps/opie-reader/Coder.h b/noncore/apps/opie-reader/Coder.h new file mode 100644 index 0000000..64587cf --- a/dev/null +++ b/noncore/apps/opie-reader/Coder.h @@ -0,0 +1,113 @@ +#include "CSource.h" +/**************************************************************************** + * This file is part of PPMd project * + * Contents: 'Carryless rangecoder' by Dmitry Subbotin * + * Comments: this implementation is claimed to be a public domain * + ****************************************************************************/ +/********************** Original text ************************************* +//////// Carryless rangecoder (c) 1999 by Dmitry Subbotin //////// + +typedef unsigned int uint; +typedef unsigned char uc; + +#define DO(n) for (int _=0; _<n; _++) +#define TOP (1<<24) +#define BOT (1<<16) + + +class RangeCoder +{ + uint low, code, range, passed; + FILE *f; + + void OutByte (uc c) { passed++; fputc(c,f); } + uc InByte () { passed++; return fgetc(f); } + +public: + + uint GetPassed () { return passed; } + void StartEncode (FILE *F) { f=F; passed=low=0; range= (uint) -1; } + void FinishEncode () { DO(4) OutByte(low>>24), low<<=8; } + void StartDecode (FILE *F) { passed=low=code=0; range= (uint) -1; + f=F; DO(4) code= code<<8 | InByte(); + } + + void Encode (uint cumFreq, uint freq, uint totFreq) { + assert(cumFreq+freq<totFreq && freq && totFreq<=BOT); + low += cumFreq * (range/= totFreq); + range*= freq; + while ((low ^ low+range)<TOP || range<BOT && ((range= -low & BOT-1),1)) + OutByte(low>>24), range<<=8, low<<=8; + } + + uint GetFreq (uint totFreq) { + uint tmp= (code-low) / (range/= totFreq); + if (tmp >= totFreq) throw ("Input data corrupt"); // or force it to return + return tmp; // a valid value :) + } + + void Decode (uint cumFreq, uint freq, uint totFreq) { + assert(cumFreq+freq<totFreq && freq && totFreq<=BOT); + low += cumFreq*range; + range*= freq; + while ((low ^ low+range)<TOP || range<BOT && ((range= -low & BOT-1),1)) + code= code<<8 | InByte(), range<<=8, low<<=8; + } +}; +*****************************************************************************/ + +static struct SUBRANGE { + DWORD LowCount, HighCount, scale; +} SubRange; +enum { TOP=1 << 24, BOT=1 << 15 }; +static DWORD low, code, range; + +inline void ariInitEncoder() +{ + low=0; range=DWORD(-1); +} +#define ARI_ENC_NORMALIZE(stream) { \ + while ((low ^ (low+range)) < TOP || range < BOT && \ + ((range= -low & (BOT-1)),1)) { \ + _PPMD_E_PUTC(low >> 24,stream); \ + range <<= 8; low <<= 8; \ + } \ +} +inline void ariEncodeSymbol() +{ + low += SubRange.LowCount*(range /= SubRange.scale); + range *= SubRange.HighCount-SubRange.LowCount; +} +inline void ariShiftEncodeSymbol(UINT SHIFT) +{ + low += SubRange.LowCount*(range >>= SHIFT); + range *= SubRange.HighCount-SubRange.LowCount; +} +#define ARI_FLUSH_ENCODER(stream) { \ + for (UINT i=0;i < 4;i++) { \ + _PPMD_E_PUTC(low >> 24,stream); low <<= 8; \ + } \ +} +#define ARI_INIT_DECODER(stream) { \ + low=code=0; range=DWORD(-1); \ + for (UINT i=0;i < 4;i++) \ + code=(code << 8) | _PPMD_D_GETC(stream); \ +} +#define ARI_DEC_NORMALIZE(stream) { \ + while ((low ^ (low+range)) < TOP || range < BOT && \ + ((range= -low & (BOT-1)),1)) { \ + code=(code << 8) | _PPMD_D_GETC(stream); \ + range <<= 8; low <<= 8; \ + } \ +} +inline UINT ariGetCurrentCount() { + return (code-low)/(range /= SubRange.scale); +} +inline UINT ariGetCurrentShiftCount(UINT SHIFT) { + return (code-low)/(range >>= SHIFT); +} +inline void ariRemoveSubrange() +{ + low += range*SubRange.LowCount; + range *= SubRange.HighCount-SubRange.LowCount; +} diff --git a/noncore/apps/opie-reader/FliteCmd/.cvsignore b/noncore/apps/opie-reader/FliteCmd/.cvsignore new file mode 100644 index 0000000..1810ee0 --- a/dev/null +++ b/noncore/apps/opie-reader/FliteCmd/.cvsignore @@ -0,0 +1,5 @@ +Makefile +config.in +moc_* +.moc +.obj diff --git a/noncore/apps/opie-reader/FliteCmd/FliteCmd.pro b/noncore/apps/opie-reader/FliteCmd/FliteCmd.pro new file mode 100644 index 0000000..0e1a782 --- a/dev/null +++ b/noncore/apps/opie-reader/FliteCmd/FliteCmd.pro @@ -0,0 +1,18 @@ +DEFINES += OPIE USEQPE +VPATH = .. +TEMPLATE = lib +CONFIG = qt warn_on release dll +HEADERS = flitecmd.h + +SOURCES = flitecmd.cpp + + +INTERFACES = +DESTDIR = $(OPIEDIR)/plugins/reader/outcodecs +TARGET = flitecmd + + +INCLUDEPATH += $(OPIEDIR)/include +DEPENDPATH += $(OPIEDIR)/include + +include( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/opie-reader/FliteDyn/.cvsignore b/noncore/apps/opie-reader/FliteDyn/.cvsignore new file mode 100644 index 0000000..1810ee0 --- a/dev/null +++ b/noncore/apps/opie-reader/FliteDyn/.cvsignore @@ -0,0 +1,5 @@ +Makefile +config.in +moc_* +.moc +.obj diff --git a/noncore/apps/opie-reader/FliteDyn/FliteDyn.pro b/noncore/apps/opie-reader/FliteDyn/FliteDyn.pro new file mode 100644 index 0000000..a949209 --- a/dev/null +++ b/noncore/apps/opie-reader/FliteDyn/FliteDyn.pro @@ -0,0 +1,18 @@ +DEFINES += OPIE USEQPE +VPATH = .. +TEMPLATE = lib +CONFIG = qt warn_on release dll +HEADERS = flitedyn.h + +SOURCES = flitedyn.cpp + + +INTERFACES = +DESTDIR = $(OPIEDIR)/plugins/reader/outcodecs +TARGET = flitedyn +LIBS += -L/home/tim/flite/flite-1.2-release/lib -lflite_cmu_us_kal -lflite_usenglish -lflite_cmulex -lflite + +INCLUDEPATH += /home/tim/flite/flite-1.2-release/include $(OPIEDIR)/include +DEPENDPATH += /home/tim/flite/flite-1.2-release/include $(OPIEDIR)/include + +include( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/opie-reader/FliteDyn16/.cvsignore b/noncore/apps/opie-reader/FliteDyn16/.cvsignore new file mode 100644 index 0000000..1810ee0 --- a/dev/null +++ b/noncore/apps/opie-reader/FliteDyn16/.cvsignore @@ -0,0 +1,5 @@ +Makefile +config.in +moc_* +.moc +.obj diff --git a/noncore/apps/opie-reader/FliteDyn16/FliteDyn16.pro b/noncore/apps/opie-reader/FliteDyn16/FliteDyn16.pro new file mode 100644 index 0000000..49c2c42 --- a/dev/null +++ b/noncore/apps/opie-reader/FliteDyn16/FliteDyn16.pro @@ -0,0 +1,18 @@ +DEFINES += OPIE USEQPE +VPATH = .. +TEMPLATE = lib +CONFIG = qt warn_on release dll +HEADERS = flitedyn.h + +SOURCES = flitedyn.cpp + + +INTERFACES = +DESTDIR = $(OPIEDIR)/plugins/reader/outcodecs +TARGET = flitedyn +LIBS += -L/home/tim/flite/flite-1.2-release/lib -lflite_cmu_us_kal16 -lflite_usenglish -lflite_cmulex -lflite + +INCLUDEPATH += /home/tim/flite/flite-1.2-release/include $(OPIEDIR)/include +DEPENDPATH += /home/tim/flite/flite-1.2-release/include $(OPIEDIR)/include + +include( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/opie-reader/FontControl.cpp b/noncore/apps/opie-reader/FontControl.cpp index 9bb3bc0..08b8c52 100644 --- a/noncore/apps/opie-reader/FontControl.cpp +++ b/noncore/apps/opie-reader/FontControl.cpp @@ -1,66 +1,67 @@ #include <qfontdatabase.h> + #include "FontControl.h" int FontControl::gzoom() { if (m_fixgraphics) { return 100; } else { int ret; if (m_size == g_size) { ret = m_fontsizes[m_size]*m_basesize; } else if (g_size < 0) { int f = -g_size; ret = (m_fontsizes[0]*m_basesize) >> (f/2); if (f%2) ret = (2*ret/3); } else { int f = g_size - m_maxsize + 1; ret = (m_fontsizes[m_maxsize-1]*m_basesize) << (f/2); if (f%2) ret = (3*ret/2); } return ret; } } bool FontControl::ChangeFont(QString& n, int tgt) { QValueList<int>::Iterator it; QFontDatabase fdb; QValueList<int> sizes = fdb.pointSizes(n); if (sizes.count() == 0) { return false; } else { m_fontname = n; m_maxsize = sizes.count(); if (m_fontsizes != NULL) delete [] m_fontsizes; m_fontsizes = new int[m_maxsize]; uint i = 0; uint best = 0; for (it = sizes.begin(); it != sizes.end(); it++) { #if defined(OPIE) || !defined(USEQPE) m_fontsizes[i] = (*it); #else m_fontsizes[i] = (*it)/10; #endif if (abs(tgt-m_fontsizes[i]) < abs(tgt-m_fontsizes[best])) { best = i; } i++; } g_size = m_size = best; } return true; } diff --git a/noncore/apps/opie-reader/FontControl.h b/noncore/apps/opie-reader/FontControl.h index 90d39b2..563e1a8 100644 --- a/noncore/apps/opie-reader/FontControl.h +++ b/noncore/apps/opie-reader/FontControl.h @@ -1,172 +1,172 @@ #ifndef __FONTCONTROL_H #define __FONTCONTROL_H #include <qfontmetrics.h> #include "StyleConsts.h" class FontControl { int * m_fontsizes; int m_size, g_size; QString m_fontname; QString m_fixedfontname; int m_maxsize; bool m_hasCourier; int m_leading, m_extraspace; unsigned char m_basesize; bool m_fixgraphics; public: void FixGraphics(bool _b) { m_fixgraphics = _b; } bool FixGraphics() { return m_fixgraphics; } void setBaseSize(unsigned char _s) { m_basesize = _s; } unsigned char getBaseSize() { return m_basesize; } int gzoom(); FontControl(QString n = "helvetica", int size = 10) : m_fontsizes(NULL), m_hasCourier(false), m_leading(0), m_extraspace(0), m_fixgraphics(true) { ChangeFont(n, size); } ~FontControl() { if (m_fontsizes != NULL) delete [] m_fontsizes; } void hasCourier(bool _b, const QString& _nm) { m_hasCourier = _b; m_fixedfontname = _nm; } QString& fixedfontname() { return m_fixedfontname; } bool hasCourier() { return m_hasCourier; } QString name() { return m_fontname; } int currentsize() { return (m_fontsizes == NULL) ? 0 : m_fontsizes[m_size]; } int getsize(const CStyle& size) { return getsize(size.getFontSize()); } int getsize(int _offset) { int tgt = m_size+_offset; if (tgt < 0) { tgt = 0; } if (tgt >= m_maxsize) { tgt = m_maxsize - 1; } - return m_fontsizes[tgt]; + return tgt >= 0 ? m_fontsizes[tgt] : 12; } int ascent() { QFont f(name(), currentsize()); QFontMetrics fm(f); return fm.ascent(); } int ascent(const CStyle& ch) { QFont f(name(), getsize(ch)); QFontMetrics fm(f); return fm.ascent(); } int descent() { QFont f(name(), currentsize()); QFontMetrics fm(f); return fm.descent(); } int descent(const CStyle& ch) { QFont f(name(), getsize(ch)); QFontMetrics fm(f); return fm.descent(); } int lineSpacing() { QFont f(name(), currentsize()); QFontMetrics fm(f); return fm.lineSpacing(); } int lineSpacing(const CStyle& ch) { QFont f(name(), getsize(ch)); QFontMetrics fm(f); return fm.lineSpacing(); } bool decreasesize() { if (m_fixgraphics) { if (--m_size < 0) { m_size = 0; return false; } g_size = m_size; } else { if (g_size-- == m_size) { if (--m_size < 0) { m_size = 0; } } } // qDebug("Font:%d Graphics:%d", m_size, g_size); return true; } bool increasesize() { if (m_fixgraphics) { if (++m_size >= m_maxsize) { m_size = m_maxsize - 1; return false; } g_size = m_size; } else { if (g_size++ == m_size) { if (++m_size >= m_maxsize) { m_size = m_maxsize - 1; } } } return true; } bool ChangeFont(QString& n) { return ChangeFont(n, currentsize()); } bool ChangeFont(QString& n, int tgt); void setlead(int _lead) { m_leading = _lead; } int getlead() { return m_leading; } void setextraspace(int _lead) { m_extraspace = _lead; } int getextraspace() { return m_extraspace; } }; #endif diff --git a/noncore/apps/opie-reader/Model.cpp b/noncore/apps/opie-reader/Model.cpp new file mode 100644 index 0000000..6b61fa0 --- a/dev/null +++ b/noncore/apps/opie-reader/Model.cpp @@ -0,0 +1,721 @@ +/**************************************************************************** + * This file is part of PPMd project * + * Written and distributed to public domain by Dmitry Shkarin 1997, * + * 1999-2001 * + * Contents: PPMII model description and encoding/decoding routines * + ****************************************************************************/ +#include <string.h> +#include "PPMd.h" +#pragma hdrstop +#include "Coder.h" +#include "SubAlloc.h" + +enum { UP_FREQ=5, INT_BITS=7, PERIOD_BITS=7, TOT_BITS=INT_BITS+PERIOD_BITS, + INTERVAL=1 << INT_BITS, BIN_SCALE=1 << TOT_BITS, MAX_FREQ=124, O_BOUND=9 }; + +#pragma pack(1) +static struct SEE2_CONTEXT { // SEE-contexts for PPM-contexts with masked symbols + WORD Summ; + BYTE Shift, Count; + void init(UINT InitVal) { Summ=InitVal << (Shift=PERIOD_BITS-4); Count=7; } + UINT getMean() { + UINT RetVal=(Summ >> Shift); Summ -= RetVal; + return RetVal+(RetVal == 0); + } + void update() { + if (Shift < PERIOD_BITS && --Count == 0) { + Summ += Summ; Count=3 << Shift++; + } + } +} _PACK_ATTR SEE2Cont[24][32], DummySEE2Cont; +static struct PPM_CONTEXT { // Notes: + BYTE NumStats, Flags; // 1. NumStats & NumMasked contain + WORD SummFreq; // number of symbols minus 1 + struct STATE { // 2. sizeof(WORD) > sizeof(BYTE) + BYTE Symbol, Freq; // 3. contexts example: + PPM_CONTEXT* Successor; // MaxOrder: + } _PACK_ATTR * Stats; // ABCD context + PPM_CONTEXT* Suffix; // BCD suffix + inline void encodeBinSymbol(int symbol);// BCDE successor + inline void encodeSymbol1(int symbol);// other orders: + inline void encodeSymbol2(int symbol);// BCD context + inline void decodeBinSymbol();// CD suffix + inline void decodeSymbol1();// BCDE successor + inline void decodeSymbol2(); + inline void update1(STATE* p); + inline void update2(STATE* p); + inline SEE2_CONTEXT* makeEscFreq2(); + void rescale(); + void refresh(int OldNU,BOOL Scale); + PPM_CONTEXT* cutOff(int Order); + PPM_CONTEXT* removeBinConts(int Order); + STATE& oneState() const { return (STATE&) SummFreq; } +} _PACK_ATTR* MaxContext; +#pragma pack() + +static BYTE NS2BSIndx[256], QTable[260]; // constants +static PPM_CONTEXT::STATE* FoundState; // found next state transition +static int InitEsc, OrderFall, RunLength, InitRL, MaxOrder; +static BYTE CharMask[256], NumMasked, PrevSuccess, EscCount, PrintCount; +static WORD BinSumm[25][64]; // binary SEE-contexts +static MR_METHOD MRMethod; + +inline void SWAP(PPM_CONTEXT::STATE& s1,PPM_CONTEXT::STATE& s2) +{ + /* + WORD t1=(WORD&) s1; PPM_CONTEXT* t2=s1.Successor; + (WORD&) s1 = (WORD&) s2; s1.Successor=s2.Successor; + (WORD&) s2 = t1; s2.Successor=t2; + */ + PPM_CONTEXT::STATE t = s1; + s1 = s2; + s2 = t; +} +inline void StateCpy(PPM_CONTEXT::STATE& s1,const PPM_CONTEXT::STATE& s2) +{ + // (WORD&) s1=(WORD&) s2; s1.Successor=s2.Successor; + s1 = s2; +} +struct PPMD_STARTUP { inline PPMD_STARTUP(); } PPMd_StartUp; +inline PPMD_STARTUP::PPMD_STARTUP() // constants initialization +{ + UINT i, k, m, Step; + for (i=0,k=1;i < N1 ;i++,k += 1) Indx2Units[i]=k; + for (k++;i < N1+N2 ;i++,k += 2) Indx2Units[i]=k; + for (k++;i < N1+N2+N3 ;i++,k += 3) Indx2Units[i]=k; + for (k++;i < N1+N2+N3+N4;i++,k += 4) Indx2Units[i]=k; + for (k=i=0;k < 128;k++) { + i += (Indx2Units[i] < k+1); Units2Indx[k]=i; + } + NS2BSIndx[0]=2*0; NS2BSIndx[1]=2*1; + memset(NS2BSIndx+2,2*2,9); memset(NS2BSIndx+11,2*3,256-11); + for (i=0;i < UP_FREQ;i++) QTable[i]=i; + for (m=i=UP_FREQ, k=Step=1;i < 260;i++) { + QTable[i]=m; + if ( !--k ) { k = ++Step; m++; } + } + (DWORD&) DummySEE2Cont=PPMdSignature; +} +static void _STDCALL StartModelRare(int MaxOrder,MR_METHOD MRMethod) +{ + UINT i, k, m; + memset(CharMask,0,sizeof(CharMask)); EscCount=PrintCount=1; + if (MaxOrder < 2) { // we are in solid mode + OrderFall=::MaxOrder; + for (PPM_CONTEXT* pc=MaxContext;pc->Suffix != NULL;pc=pc->Suffix) + OrderFall--; + return; + } + OrderFall=::MaxOrder=MaxOrder; ::MRMethod=MRMethod; + InitSubAllocator(); + RunLength=InitRL=-((MaxOrder < 12)?MaxOrder:12)-1; + MaxContext = (PPM_CONTEXT*) AllocContext(); + MaxContext->Suffix=NULL; + MaxContext->SummFreq=(MaxContext->NumStats=255)+2; + MaxContext->Stats = (PPM_CONTEXT::STATE*) AllocUnits(256/2); + for (PrevSuccess=i=0;i < 256;i++) { + MaxContext->Stats[i].Symbol=i; MaxContext->Stats[i].Freq=1; + MaxContext->Stats[i].Successor=NULL; + } +static const WORD InitBinEsc[]={0x3CDD,0x1F3F,0x59BF,0x48F3,0x64A1,0x5ABC,0x6632,0x6051}; + for (i=m=0;m < 25;m++) { + while (QTable[i] == m) i++; + for (k=0;k < 8;k++) + BinSumm[m][k]=BIN_SCALE-InitBinEsc[k]/(i+1); + for (k=8;k < 64;k += 8) + memcpy(BinSumm[m]+k,BinSumm[m],8*sizeof(WORD)); + } + for (i=m=0;m < 24;m++) { + while (QTable[i+3] == m+3) i++; + SEE2Cont[m][0].init(2*i+5); + for (k=1;k < 32;k++) SEE2Cont[m][k]=SEE2Cont[m][0]; + } +} +void PPM_CONTEXT::refresh(int OldNU,BOOL Scale) +{ + int i=NumStats, EscFreq; + STATE* p = Stats = (STATE*) ShrinkUnits(Stats,OldNU,(i+2) >> 1); + Flags=(Flags & (0x10+0x04*Scale))+0x08*(p->Symbol >= 0x40); + EscFreq=SummFreq-p->Freq; + SummFreq = (p->Freq=(p->Freq+Scale) >> Scale); + do { + EscFreq -= (++p)->Freq; + SummFreq += (p->Freq=(p->Freq+Scale) >> Scale); + Flags |= 0x08*(p->Symbol >= 0x40); + } while ( --i ); + SummFreq += (EscFreq=(EscFreq+Scale) >> Scale); +} +#define P_CALL(F) ( PrefetchData(p->Successor), \ + p->Successor=p->Successor->F(Order+1)) +PPM_CONTEXT* PPM_CONTEXT::cutOff(int Order) +{ + int i, tmp; + STATE* p; + if ( !NumStats ) { + if ((BYTE*) (p=&oneState())->Successor >= UnitsStart) { + if (Order < MaxOrder) P_CALL(cutOff); + else p->Successor=NULL; + if (!p->Successor && Order > O_BOUND) + goto REMOVE; + return this; + } else { +REMOVE: SpecialFreeUnit(this); return NULL; + } + } + PrefetchData(Stats); + Stats = (STATE*) MoveUnitsUp(Stats,tmp=(NumStats+2) >> 1); + for (p=Stats+(i=NumStats);p >= Stats;p--) + if ((BYTE*) p->Successor < UnitsStart) { + p->Successor=NULL; SWAP(*p,Stats[i--]); + } else if (Order < MaxOrder) P_CALL(cutOff); + else p->Successor=NULL; + if (i != NumStats && Order) { + NumStats=i; p=Stats; + if (i < 0) { FreeUnits(p,tmp); goto REMOVE; } + else if (i == 0) { + Flags=(Flags & 0x10)+0x08*(p->Symbol >= 0x40); + StateCpy(oneState(),*p); FreeUnits(p,tmp); + oneState().Freq=(oneState().Freq+11) >> 3; + } else refresh(tmp,SummFreq > 16*i); + } + return this; +} +PPM_CONTEXT* PPM_CONTEXT::removeBinConts(int Order) +{ + STATE* p; + if ( !NumStats ) { + p=&oneState(); + if ((BYTE*) p->Successor >= UnitsStart && Order < MaxOrder) + P_CALL(removeBinConts); + else p->Successor=NULL; + if (!p->Successor && (!Suffix->NumStats || Suffix->Flags == 0xFF)) { + FreeUnits(this,1); return NULL; + } else return this; + } + PrefetchData(Stats); + for (p=Stats+NumStats;p >= Stats;p--) + if ((BYTE*) p->Successor >= UnitsStart && Order < MaxOrder) + P_CALL(removeBinConts); + else p->Successor=NULL; + return this; +} +static void RestoreModelRare(PPM_CONTEXT* pc1,PPM_CONTEXT* MinContext, + PPM_CONTEXT* FSuccessor) +{ + PPM_CONTEXT* pc; + PPM_CONTEXT::STATE* p; + for (pc=MaxContext, pText=HeapStart;pc != pc1;pc=pc->Suffix) + if (--(pc->NumStats) == 0) { + pc->Flags=(pc->Flags & 0x10)+0x08*(pc->Stats->Symbol >= 0x40); + p=pc->Stats; StateCpy(pc->oneState(),*p); + SpecialFreeUnit(p); + pc->oneState().Freq=(pc->oneState().Freq+11) >> 3; + } else + pc->refresh((pc->NumStats+3) >> 1,FALSE); + for ( ;pc != MinContext;pc=pc->Suffix) + if ( !pc->NumStats ) + pc->oneState().Freq -= pc->oneState().Freq >> 1; + else if ((pc->SummFreq += 4) > 128+4*pc->NumStats) + pc->refresh((pc->NumStats+2) >> 1,TRUE); + if (MRMethod > MRM_FREEZE) { + MaxContext=FSuccessor; GlueCount += !(BList[1].Stamp & 1); + } else if (MRMethod == MRM_FREEZE) { + while ( MaxContext->Suffix ) MaxContext=MaxContext->Suffix; + MaxContext->removeBinConts(0); MRMethod=MR_METHOD(MRMethod+1); + GlueCount=0; OrderFall=MaxOrder; + } else if (MRMethod == MRM_RESTART || GetUsedMemory() < (SubAllocatorSize >> 1)) { + StartModelRare(MaxOrder,MRMethod); + EscCount=0; PrintCount=0xFF; + } else { + while ( MaxContext->Suffix ) MaxContext=MaxContext->Suffix; + do { + MaxContext->cutOff(0); ExpandTextArea(); + } while (GetUsedMemory() > 3*(SubAllocatorSize >> 2)); + GlueCount=0; OrderFall=MaxOrder; + } +} +static PPM_CONTEXT* _FASTCALL CreateSuccessors(BOOL Skip,PPM_CONTEXT::STATE* p, + PPM_CONTEXT* pc); +static PPM_CONTEXT* _FASTCALL ReduceOrder(PPM_CONTEXT::STATE* p,PPM_CONTEXT* pc) +{ + PPM_CONTEXT::STATE* p1, * ps[MAX_O], ** pps=ps; + PPM_CONTEXT* pc1=pc, * UpBranch = (PPM_CONTEXT*) pText; + BYTE tmp, sym=FoundState->Symbol; + *pps++ = FoundState; FoundState->Successor=UpBranch; + OrderFall++; + if ( p ) { pc=pc->Suffix; goto LOOP_ENTRY; } + for ( ; ; ) { + if ( !pc->Suffix ) { + if (MRMethod > MRM_FREEZE) { +FROZEN: do { (*--pps)->Successor = pc; } while (pps != ps); + pText=HeapStart+1; OrderFall=1; + } + return pc; + } + pc=pc->Suffix; + if ( pc->NumStats ) { + if ((p=pc->Stats)->Symbol != sym) + do { tmp=p[1].Symbol; p++; } while (tmp != sym); + tmp=2*(p->Freq < MAX_FREQ-9); + p->Freq += tmp; pc->SummFreq += tmp; + } else { p=&(pc->oneState()); p->Freq += (p->Freq < 32); } +LOOP_ENTRY: + if ( p->Successor ) break; + *pps++ = p; p->Successor=UpBranch; + OrderFall++; + } + if (MRMethod > MRM_FREEZE) { + pc = p->Successor; goto FROZEN; + } else if (p->Successor <= UpBranch) { + p1=FoundState; FoundState=p; + p->Successor=CreateSuccessors(FALSE,NULL,pc); + FoundState=p1; + } + if (OrderFall == 1 && pc1 == MaxContext) { + FoundState->Successor=p->Successor; pText--; + } + return p->Successor; +} +void PPM_CONTEXT::rescale() +{ + UINT OldNU, Adder, EscFreq, i=NumStats; + STATE tmp, * p1, * p; + for (p=FoundState;p != Stats;p--) SWAP(p[0],p[-1]); + p->Freq += 4; SummFreq += 4; + EscFreq=SummFreq-p->Freq; + Adder=(OrderFall != 0 || MRMethod > MRM_FREEZE); + SummFreq = (p->Freq=(p->Freq+Adder) >> 1); + do { + EscFreq -= (++p)->Freq; + SummFreq += (p->Freq=(p->Freq+Adder) >> 1); + if (p[0].Freq > p[-1].Freq) { + StateCpy(tmp,*(p1=p)); + do StateCpy(p1[0],p1[-1]); while (tmp.Freq > (--p1)[-1].Freq); + StateCpy(*p1,tmp); + } + } while ( --i ); + if (p->Freq == 0) { + do { i++; } while ((--p)->Freq == 0); + EscFreq += i; OldNU=(NumStats+2) >> 1; + if ((NumStats -= i) == 0) { + StateCpy(tmp,*Stats); + tmp.Freq=(2*tmp.Freq+EscFreq-1)/EscFreq; + if (tmp.Freq > MAX_FREQ/3) tmp.Freq=MAX_FREQ/3; + FreeUnits(Stats,OldNU); StateCpy(oneState(),tmp); + Flags=(Flags & 0x10)+0x08*(tmp.Symbol >= 0x40); + FoundState=&oneState(); return; + } + Stats = (STATE*) ShrinkUnits(Stats,OldNU,(NumStats+2) >> 1); + Flags &= ~0x08; i=NumStats; + Flags |= 0x08*((p=Stats)->Symbol >= 0x40); + do { Flags |= 0x08*((++p)->Symbol >= 0x40); } while ( --i ); + } + SummFreq += (EscFreq -= (EscFreq >> 1)); + Flags |= 0x04; FoundState=Stats; +} +static PPM_CONTEXT* _FASTCALL CreateSuccessors(BOOL Skip,PPM_CONTEXT::STATE* p, + PPM_CONTEXT* pc) +{ + PPM_CONTEXT ct, * UpBranch=FoundState->Successor; + PPM_CONTEXT::STATE* ps[MAX_O], ** pps=ps; + UINT cf, s0; + BYTE tmp, sym=FoundState->Symbol; + if ( !Skip ) { + *pps++ = FoundState; + if ( !pc->Suffix ) goto NO_LOOP; + } + if ( p ) { pc=pc->Suffix; goto LOOP_ENTRY; } + do { + pc=pc->Suffix; + if ( pc->NumStats ) { + if ((p=pc->Stats)->Symbol != sym) + do { tmp=p[1].Symbol; p++; } while (tmp != sym); + tmp=(p->Freq < MAX_FREQ-9); + p->Freq += tmp; pc->SummFreq += tmp; + } else { + p=&(pc->oneState()); + p->Freq += (!pc->Suffix->NumStats & (p->Freq < 24)); + } +LOOP_ENTRY: + if (p->Successor != UpBranch) { + pc=p->Successor; break; + } + *pps++ = p; + } while ( pc->Suffix ); +NO_LOOP: + if (pps == ps) return pc; + ct.NumStats=0; ct.Flags=0x10*(sym >= 0x40); + ct.oneState().Symbol=sym=*(BYTE*) UpBranch; + ct.oneState().Successor=(PPM_CONTEXT*) (((BYTE*) UpBranch)+1); + ct.Flags |= 0x08*(sym >= 0x40); + if ( pc->NumStats ) { + if ((p=pc->Stats)->Symbol != sym) + do { tmp=p[1].Symbol; p++; } while (tmp != sym); + s0=pc->SummFreq-pc->NumStats-(cf=p->Freq-1); + ct.oneState().Freq=1+((2*cf <= s0)?(5*cf > s0):((cf+2*s0-3)/s0)); + } else + ct.oneState().Freq=pc->oneState().Freq; + do { + PPM_CONTEXT* pc1 = (PPM_CONTEXT*) AllocContext(); + if ( !pc1 ) return NULL; + ((DWORD*) pc1)[0] = ((DWORD*) &ct)[0]; + ((DWORD*) pc1)[1] = ((DWORD*) &ct)[1]; + pc1->Suffix=pc; (*--pps)->Successor=pc=pc1; + } while (pps != ps); + return pc; +} +static inline void UpdateModel(PPM_CONTEXT* MinContext) +{ + PPM_CONTEXT::STATE* p=NULL; + PPM_CONTEXT* Successor, * FSuccessor, * pc, * pc1=MaxContext; + UINT ns1, ns, cf, sf, s0, FFreq=FoundState->Freq; + BYTE Flag, sym, FSymbol=FoundState->Symbol; + FSuccessor=FoundState->Successor; pc=MinContext->Suffix; + if (FFreq < MAX_FREQ/4 && pc) { + if ( pc->NumStats ) { + if ((p=pc->Stats)->Symbol != FSymbol) { + do { sym=p[1].Symbol; p++; } while (sym != FSymbol); + if (p[0].Freq >= p[-1].Freq) { + SWAP(p[0],p[-1]); p--; + } + } + cf=2*(p->Freq < MAX_FREQ-9); + p->Freq += cf; pc->SummFreq += cf; + } else { p=&(pc->oneState()); p->Freq += (p->Freq < 32); } + } + if (!OrderFall && FSuccessor) { + FoundState->Successor=CreateSuccessors(TRUE,p,MinContext); + if ( !FoundState->Successor ) goto RESTART_MODEL; + MaxContext=FoundState->Successor; return; + } + *pText++ = FSymbol; Successor = (PPM_CONTEXT*) pText; + if (pText >= UnitsStart) goto RESTART_MODEL; + if ( FSuccessor ) { + if ((BYTE*) FSuccessor < UnitsStart) + FSuccessor=CreateSuccessors(FALSE,p,MinContext); + } else + FSuccessor=ReduceOrder(p,MinContext); + if ( !FSuccessor ) goto RESTART_MODEL; + if ( !--OrderFall ) { + Successor=FSuccessor; pText -= (MaxContext != MinContext); + } else if (MRMethod > MRM_FREEZE) { + Successor=FSuccessor; pText=HeapStart; + OrderFall=0; + } + s0=MinContext->SummFreq-(ns=MinContext->NumStats)-FFreq; + for (Flag=0x08*(FSymbol >= 0x40);pc1 != MinContext;pc1=pc1->Suffix) { + if ((ns1=pc1->NumStats) != 0) { + if ((ns1 & 1) != 0) { + p=(PPM_CONTEXT::STATE*) ExpandUnits(pc1->Stats,(ns1+1) >> 1); + if ( !p ) goto RESTART_MODEL; + pc1->Stats=p; + } + pc1->SummFreq += (3*ns1+1 < ns); + } else { + p=(PPM_CONTEXT::STATE*) AllocUnits(1); + if ( !p ) goto RESTART_MODEL; + StateCpy(*p,pc1->oneState()); pc1->Stats=p; + if (p->Freq < MAX_FREQ/4-1) p->Freq += p->Freq; + else p->Freq = MAX_FREQ-4; + pc1->SummFreq=p->Freq+InitEsc+(ns > 2); + } + cf=2*FFreq*(pc1->SummFreq+6); sf=s0+pc1->SummFreq; + if (cf < 6*sf) { + cf=1+(cf > sf)+(cf >= 4*sf); + pc1->SummFreq += 4; + } else { + cf=4+(cf > 9*sf)+(cf > 12*sf)+(cf > 15*sf); + pc1->SummFreq += cf; + } + p=pc1->Stats+(++pc1->NumStats); p->Successor=Successor; + p->Symbol = FSymbol; p->Freq = cf; + pc1->Flags |= Flag; + } + MaxContext=FSuccessor; return; +RESTART_MODEL: + RestoreModelRare(pc1,MinContext,FSuccessor); +} +// Tabulated escapes for exponential symbol distribution +static const BYTE ExpEscape[16]={ 25,14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; +#define GET_MEAN(SUMM,SHIFT,ROUND) ((SUMM+(1 << (SHIFT-ROUND))) >> (SHIFT)) +inline void PPM_CONTEXT::encodeBinSymbol(int symbol) +{ + BYTE indx=NS2BSIndx[Suffix->NumStats]+PrevSuccess+Flags; + STATE& rs=oneState(); + WORD& bs=BinSumm[QTable[rs.Freq-1]][indx+((RunLength >> 26) & 0x20)]; + if (rs.Symbol == symbol) { + FoundState=&rs; rs.Freq += (rs.Freq < 196); + SubRange.LowCount=0; SubRange.HighCount=bs; + bs += INTERVAL-GET_MEAN(bs,PERIOD_BITS,2); + PrevSuccess=1; RunLength++; + } else { + SubRange.LowCount=bs; bs -= GET_MEAN(bs,PERIOD_BITS,2); + SubRange.HighCount=BIN_SCALE; InitEsc=ExpEscape[bs >> 10]; + CharMask[rs.Symbol]=EscCount; + NumMasked=PrevSuccess=0; FoundState=NULL; + } +} +inline void PPM_CONTEXT::decodeBinSymbol() +{ + BYTE indx=NS2BSIndx[Suffix->NumStats]+PrevSuccess+Flags; + STATE& rs=oneState(); + WORD& bs=BinSumm[QTable[rs.Freq-1]][indx+((RunLength >> 26) & 0x20)]; + if (ariGetCurrentShiftCount(TOT_BITS) < bs) { + FoundState=&rs; rs.Freq += (rs.Freq < 196); + SubRange.LowCount=0; SubRange.HighCount=bs; + bs += INTERVAL-GET_MEAN(bs,PERIOD_BITS,2); + PrevSuccess=1; RunLength++; + } else { + SubRange.LowCount=bs; bs -= GET_MEAN(bs,PERIOD_BITS,2); + SubRange.HighCount=BIN_SCALE; InitEsc=ExpEscape[bs >> 10]; + CharMask[rs.Symbol]=EscCount; + NumMasked=PrevSuccess=0; FoundState=NULL; + } +} +inline void PPM_CONTEXT::update1(STATE* p) +{ + (FoundState=p)->Freq += 4; SummFreq += 4; + if (p[0].Freq > p[-1].Freq) { + SWAP(p[0],p[-1]); FoundState=--p; + if (p->Freq > MAX_FREQ) rescale(); + } +} +inline void PPM_CONTEXT::encodeSymbol1(int symbol) +{ + UINT LoCnt, i=Stats->Symbol; + STATE* p=Stats; SubRange.scale=SummFreq; + if (i == symbol) { + PrevSuccess=(2*(SubRange.HighCount=p->Freq) >= SubRange.scale); + (FoundState=p)->Freq += 4; SummFreq += 4; + RunLength += PrevSuccess; + if (p->Freq > MAX_FREQ) rescale(); + SubRange.LowCount=0; return; + } + LoCnt=p->Freq; + i=NumStats; PrevSuccess=0; + while ((++p)->Symbol != symbol) { + LoCnt += p->Freq; + if (--i == 0) { + if ( Suffix ) PrefetchData(Suffix); + SubRange.LowCount=LoCnt; CharMask[p->Symbol]=EscCount; + i=NumMasked=NumStats; FoundState=NULL; + do { CharMask[(--p)->Symbol]=EscCount; } while ( --i ); + SubRange.HighCount=SubRange.scale; + return; + } + } + SubRange.HighCount=(SubRange.LowCount=LoCnt)+p->Freq; + update1(p); +} +inline void PPM_CONTEXT::decodeSymbol1() +{ + UINT i, count, HiCnt=Stats->Freq; + STATE* p=Stats; SubRange.scale=SummFreq; + if ((count=ariGetCurrentCount()) < HiCnt) { + PrevSuccess=(2*(SubRange.HighCount=HiCnt) >= SubRange.scale); + (FoundState=p)->Freq=(HiCnt += 4); SummFreq += 4; + RunLength += PrevSuccess; + if (HiCnt > MAX_FREQ) rescale(); + SubRange.LowCount=0; return; + } + i=NumStats; PrevSuccess=0; + while ((HiCnt += (++p)->Freq) <= count) + if (--i == 0) { + if ( Suffix ) PrefetchData(Suffix); + SubRange.LowCount=HiCnt; CharMask[p->Symbol]=EscCount; + i=NumMasked=NumStats; FoundState=NULL; + do { CharMask[(--p)->Symbol]=EscCount; } while ( --i ); + SubRange.HighCount=SubRange.scale; + return; + } + SubRange.LowCount=(SubRange.HighCount=HiCnt)-p->Freq; + update1(p); +} +inline void PPM_CONTEXT::update2(STATE* p) +{ + (FoundState=p)->Freq += 4; SummFreq += 4; + if (p->Freq > MAX_FREQ) rescale(); + EscCount++; RunLength=InitRL; +} +inline SEE2_CONTEXT* PPM_CONTEXT::makeEscFreq2() +{ + BYTE* pb=(BYTE*) Stats; UINT t=2*NumStats; + PrefetchData(pb); PrefetchData(pb+t); + PrefetchData(pb += 2*t); PrefetchData(pb+t); + SEE2_CONTEXT* psee2c; + if (NumStats != 0xFF) { + t=Suffix->NumStats; + psee2c=SEE2Cont[QTable[NumStats+2]-3]+(SummFreq > 11*(NumStats+1)); + psee2c += 2*(2*NumStats < t+NumMasked)+Flags; + SubRange.scale=psee2c->getMean(); + } else { + psee2c=&DummySEE2Cont; SubRange.scale=1; + } + return psee2c; +} +inline void PPM_CONTEXT::encodeSymbol2(int symbol) +{ + SEE2_CONTEXT* psee2c=makeEscFreq2(); + UINT Sym, LoCnt=0, i=NumStats-NumMasked; + STATE* p1, * p=Stats-1; + do { + do { Sym=p[1].Symbol; p++; } while (CharMask[Sym] == EscCount); + CharMask[Sym]=EscCount; + if (Sym == symbol) goto SYMBOL_FOUND; + LoCnt += p->Freq; + } while ( --i ); + SubRange.HighCount=(SubRange.scale += (SubRange.LowCount=LoCnt)); + psee2c->Summ += SubRange.scale; NumMasked = NumStats; + return; +SYMBOL_FOUND: + SubRange.LowCount=LoCnt; SubRange.HighCount=(LoCnt+=p->Freq); + for (p1=p; --i ; ) { + do { Sym=p1[1].Symbol; p1++; } while (CharMask[Sym] == EscCount); + LoCnt += p1->Freq; + } + SubRange.scale += LoCnt; + psee2c->update(); update2(p); +} +inline void PPM_CONTEXT::decodeSymbol2() +{ + SEE2_CONTEXT* psee2c=makeEscFreq2(); + UINT Sym, count, HiCnt=0, i=NumStats-NumMasked; + STATE* ps[256], ** pps=ps, * p=Stats-1; + do { + do { Sym=p[1].Symbol; p++; } while (CharMask[Sym] == EscCount); + HiCnt += p->Freq; *pps++ = p; + } while ( --i ); + SubRange.scale += HiCnt; count=ariGetCurrentCount(); + p=*(pps=ps); + if (count < HiCnt) { + HiCnt=0; + while ((HiCnt += p->Freq) <= count) p=*++pps; + SubRange.LowCount = (SubRange.HighCount=HiCnt)-p->Freq; + psee2c->update(); update2(p); + } else { + SubRange.LowCount=HiCnt; SubRange.HighCount=SubRange.scale; + i=NumStats-NumMasked; NumMasked = NumStats; + do { CharMask[(*pps)->Symbol]=EscCount; pps++; } while ( --i ); + psee2c->Summ += SubRange.scale; + } +} +inline void ClearMask(CInfo* EncodedFile, CInfo* DecodedFile) +{ + EscCount=1; memset(CharMask,0,sizeof(CharMask)); + // if (++PrintCount == 0) PrintInfo(DecodedFile,EncodedFile); +} +void _STDCALL EncodeFile(CSink* EncodedFile, CSource* DecodedFile, + int MaxOrder,MR_METHOD MRMethod) +{ + ariInitEncoder(); StartModelRare(MaxOrder,MRMethod); + for (PPM_CONTEXT* MinContext; ; ) { + BYTE ns=(MinContext=MaxContext)->NumStats; + int c = _PPMD_E_GETC(DecodedFile); + if ( ns ) { + MinContext->encodeSymbol1(c); ariEncodeSymbol(); + } else { + MinContext->encodeBinSymbol(c); ariShiftEncodeSymbol(TOT_BITS); + } + while ( !FoundState ) { + ARI_ENC_NORMALIZE(EncodedFile); + do { + OrderFall++; MinContext=MinContext->Suffix; + if ( !MinContext ) goto STOP_ENCODING; + } while (MinContext->NumStats == NumMasked); + MinContext->encodeSymbol2(c); ariEncodeSymbol(); + } + if (!OrderFall && (BYTE*) FoundState->Successor >= UnitsStart) + PrefetchData(MaxContext=FoundState->Successor); + else { + UpdateModel(MinContext); PrefetchData(MaxContext); + if (EscCount == 0) ClearMask(EncodedFile,DecodedFile); + } + ARI_ENC_NORMALIZE(EncodedFile); + } +STOP_ENCODING: + ARI_FLUSH_ENCODER(EncodedFile); //PrintInfo(DecodedFile,EncodedFile); +} +void _STDCALL DecodeFile(CSink* DecodedFile, CSource* EncodedFile, + int MaxOrder,MR_METHOD MRMethod) +{ + ARI_INIT_DECODER(EncodedFile); StartModelRare(MaxOrder,MRMethod); + PPM_CONTEXT* MinContext=MaxContext; + for (BYTE ns=MinContext->NumStats; ; ) { + ( ns )?(MinContext->decodeSymbol1()):(MinContext->decodeBinSymbol()); + ariRemoveSubrange(); + while ( !FoundState ) { + ARI_DEC_NORMALIZE(EncodedFile); + do { + OrderFall++; MinContext=MinContext->Suffix; + if ( !MinContext ) goto STOP_DECODING; + } while (MinContext->NumStats == NumMasked); + MinContext->decodeSymbol2(); ariRemoveSubrange(); + } + _PPMD_D_PUTC(FoundState->Symbol,DecodedFile); + if (!OrderFall && (BYTE*) FoundState->Successor >= UnitsStart) + PrefetchData(MaxContext=FoundState->Successor); + else { + UpdateModel(MinContext); PrefetchData(MaxContext); + if (EscCount == 0) ClearMask(EncodedFile,DecodedFile); + } + ns=(MinContext=MaxContext)->NumStats; + ARI_DEC_NORMALIZE(EncodedFile); + } +STOP_DECODING: + // PrintInfo(DecodedFile,EncodedFile); + return; +} + + + +#include "PPMd.h" +#include "CSource.h" + +size_t UnPPM(bool extra, unsigned char* readbuffer, size_t reclen, unsigned char* buffer, size_t buffersize) +{ + unsigned short order, mem, offset = 1; + int type = 0; + if (extra) + { + order = readbuffer[1]; + mem = readbuffer[0]; + type = order >> 6; + order = (order & 63) + 2; + offset = 2; + } + else + { + order = readbuffer[0]; + mem = order >> 4; + order = (order & 15) + 2; + } + mem++; + // qDebug("Mem:%u Order:%u Type:%u\n", mem, order, type); + StartSubAllocator(mem); + CMemSink sink(buffer, buffersize); + CMemSource source(readbuffer+offset, reclen-offset); + DecodeFile(&sink,&source,order,(MR_METHOD)type); + StopSubAllocator(); + return sink.size(); +} + + +extern "C" +{ + +size_t PluckerDecompress3(unsigned char* a, size_t b, unsigned char* c, size_t d) +{ + return UnPPM(false, a, b, c, d); +} + +size_t PluckerDecompress4(unsigned char* a, size_t b, unsigned char* c, size_t d) +{ + return UnPPM(true, a, b, c, d); +} + +size_t RebDecompress(unsigned char* a, size_t b, unsigned char* c, size_t d) +{ + return UnPPM(true, a, b, c, d); +} + +} diff --git a/noncore/apps/opie-reader/Model.h b/noncore/apps/opie-reader/Model.h new file mode 100644 index 0000000..f3f5274 --- a/dev/null +++ b/noncore/apps/opie-reader/Model.h @@ -0,0 +1,11 @@ +#ifndef __MODEL_H
+#define __MODEL_H
+
+extern "C"
+{
+ size_t PluckerDecompress3(unsigned char* a, size_t b, unsigned char* c, size_t d);
+ size_t PluckerDecompress4(unsigned char* a, size_t b, unsigned char* c, size_t d);
+ size_t RebDecompress(unsigned char* a, size_t b, unsigned char* c, size_t d);
+}
+
+#endif
diff --git a/noncore/apps/opie-reader/Palm2QImage.cpp b/noncore/apps/opie-reader/Palm2QImage.cpp index c6907eb..361755f 100644 --- a/noncore/apps/opie-reader/Palm2QImage.cpp +++ b/noncore/apps/opie-reader/Palm2QImage.cpp @@ -1,298 +1,299 @@ /* -*- mode: c; indent-tabs-mode: nil; -*- */ + #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef _WINDOWS #include <unistd.h> /* for link */ #endif #include <sys/types.h> #include <sys/stat.h> #include <stdarg.h> #include <qimage.h> /***********************************************************************/ /***********************************************************************/ /***** *****/ /***** Code to decode the Palm image format to JPEG *****/ /***** *****/ /***********************************************************************/ /***********************************************************************/ #define READ_BIGENDIAN_SHORT(p) (((p)[0] << 8)|((p)[1])) #define READ_BIGENDIAN_LONG(p) (((p)[0] << 24)|((p)[1] << 16)|((p)[2] << 8)|((p)[3])) #define PALM_IS_COMPRESSED_FLAG 0x8000 #define PALM_HAS_COLORMAP_FLAG 0x4000 #define PALM_HAS_TRANSPARENCY_FLAG 0x2000 #define PALM_DIRECT_COLOR_FLAG 0x0400 #define PALM_4_BYTE_FIELD_FLAG 0x0200 #define PALM_COMPRESSION_SCANLINE 0x00 #define PALM_COMPRESSION_RLE 0x01 #define PALM_COMPRESSION_PACKBITS 0x02 #define PALM_COMPRESSION_NONE 0xFF #define PALM_COLORMAP_SIZE 232 typedef struct { unsigned char red; unsigned char green; unsigned char blue; } ColorMapEntry; static ColorMapEntry Palm8BitColormap[] = { { 255, 255, 255 }, { 255, 204, 255 }, { 255, 153, 255 }, { 255, 102, 255 }, { 255, 51, 255 }, { 255, 0, 255 }, { 255, 255, 204 }, { 255, 204, 204 }, { 255, 153, 204 }, { 255, 102, 204 }, { 255, 51, 204 }, { 255, 0, 204 }, { 255, 255, 153 }, { 255, 204, 153 }, { 255, 153, 153 }, { 255, 102, 153 }, { 255, 51, 153 }, { 255, 0, 153 }, { 204, 255, 255 }, { 204, 204, 255 }, { 204, 153, 255 }, { 204, 102, 255 }, { 204, 51, 255 }, { 204, 0, 255 }, { 204, 255, 204 }, { 204, 204, 204 }, { 204, 153, 204 }, { 204, 102, 204 }, { 204, 51, 204 }, { 204, 0, 204 }, { 204, 255, 153 }, { 204, 204, 153 }, { 204, 153, 153 }, { 204, 102, 153 }, { 204, 51, 153 }, { 204, 0, 153 }, { 153, 255, 255 }, { 153, 204, 255 }, { 153, 153, 255 }, { 153, 102, 255 }, { 153, 51, 255 }, { 153, 0, 255 }, { 153, 255, 204 }, { 153, 204, 204 }, { 153, 153, 204 }, { 153, 102, 204 }, { 153, 51, 204 }, { 153, 0, 204 }, { 153, 255, 153 }, { 153, 204, 153 }, { 153, 153, 153 }, { 153, 102, 153 }, { 153, 51, 153 }, { 153, 0, 153 }, { 102, 255, 255 }, { 102, 204, 255 }, { 102, 153, 255 }, { 102, 102, 255 }, { 102, 51, 255 }, { 102, 0, 255 }, { 102, 255, 204 }, { 102, 204, 204 }, { 102, 153, 204 }, { 102, 102, 204 }, { 102, 51, 204 }, { 102, 0, 204 }, { 102, 255, 153 }, { 102, 204, 153 }, { 102, 153, 153 }, { 102, 102, 153 }, { 102, 51, 153 }, { 102, 0, 153 }, { 51, 255, 255 }, { 51, 204, 255 }, { 51, 153, 255 }, { 51, 102, 255 }, { 51, 51, 255 }, { 51, 0, 255 }, { 51, 255, 204 }, { 51, 204, 204 }, { 51, 153, 204 }, { 51, 102, 204 }, { 51, 51, 204 }, { 51, 0, 204 }, { 51, 255, 153 }, { 51, 204, 153 }, { 51, 153, 153 }, { 51, 102, 153 }, { 51, 51, 153 }, { 51, 0, 153 }, { 0, 255, 255 }, { 0, 204, 255 }, { 0, 153, 255 }, { 0, 102, 255 }, { 0, 51, 255 }, { 0, 0, 255 }, { 0, 255, 204 }, { 0, 204, 204 }, { 0, 153, 204 }, { 0, 102, 204 }, { 0, 51, 204 }, { 0, 0, 204 }, { 0, 255, 153 }, { 0, 204, 153 }, { 0, 153, 153 }, { 0, 102, 153 }, { 0, 51, 153 }, { 0, 0, 153 }, { 255, 255, 102 }, { 255, 204, 102 }, { 255, 153, 102 }, { 255, 102, 102 }, { 255, 51, 102 }, { 255, 0, 102 }, { 255, 255, 51 }, { 255, 204, 51 }, { 255, 153, 51 }, { 255, 102, 51 }, { 255, 51, 51 }, { 255, 0, 51 }, { 255, 255, 0 }, { 255, 204, 0 }, { 255, 153, 0 }, { 255, 102, 0 }, { 255, 51, 0 }, { 255, 0, 0 }, { 204, 255, 102 }, { 204, 204, 102 }, { 204, 153, 102 }, { 204, 102, 102 }, { 204, 51, 102 }, { 204, 0, 102 }, { 204, 255, 51 }, { 204, 204, 51 }, { 204, 153, 51 }, { 204, 102, 51 }, { 204, 51, 51 }, { 204, 0, 51 }, { 204, 255, 0 }, { 204, 204, 0 }, { 204, 153, 0 }, { 204, 102, 0 }, { 204, 51, 0 }, { 204, 0, 0 }, { 153, 255, 102 }, { 153, 204, 102 }, { 153, 153, 102 }, { 153, 102, 102 }, { 153, 51, 102 }, { 153, 0, 102 }, { 153, 255, 51 }, { 153, 204, 51 }, { 153, 153, 51 }, { 153, 102, 51 }, { 153, 51, 51 }, { 153, 0, 51 }, { 153, 255, 0 }, { 153, 204, 0 }, { 153, 153, 0 }, { 153, 102, 0 }, { 153, 51, 0 }, { 153, 0, 0 }, { 102, 255, 102 }, { 102, 204, 102 }, { 102, 153, 102 }, { 102, 102, 102 }, { 102, 51, 102 }, { 102, 0, 102 }, { 102, 255, 51 }, { 102, 204, 51 }, { 102, 153, 51 }, { 102, 102, 51 }, { 102, 51, 51 }, { 102, 0, 51 }, { 102, 255, 0 }, { 102, 204, 0 }, { 102, 153, 0 }, { 102, 102, 0 }, { 102, 51, 0 }, { 102, 0, 0 }, { 51, 255, 102 }, { 51, 204, 102 }, { 51, 153, 102 }, { 51, 102, 102 }, { 51, 51, 102 }, { 51, 0, 102 }, { 51, 255, 51 }, { 51, 204, 51 }, { 51, 153, 51 }, { 51, 102, 51 }, { 51, 51, 51 }, { 51, 0, 51 }, { 51, 255, 0 }, { 51, 204, 0 }, { 51, 153, 0 }, { 51, 102, 0 }, { 51, 51, 0 }, { 51, 0, 0 }, { 0, 255, 102 }, { 0, 204, 102 }, { 0, 153, 102 }, { 0, 102, 102 }, { 0, 51, 102 }, { 0, 0, 102 }, { 0, 255, 51 }, { 0, 204, 51 }, { 0, 153, 51 }, { 0, 102, 51 }, { 0, 51, 51 }, { 0, 0, 51 }, { 0, 255, 0 }, { 0, 204, 0 }, { 0, 153, 0 }, { 0, 102, 0 }, { 0, 51, 0 }, { 17, 17, 17 }, { 34, 34, 34 }, { 68, 68, 68 }, { 85, 85, 85 }, { 119, 119, 119 }, { 136, 136, 136 }, { 170, 170, 170 }, { 187, 187, 187 }, { 221, 221, 221 }, { 238, 238, 238 }, { 192, 192, 192 }, { 128, 0, 0 }, { 128, 0, 128 }, { 0, 128, 0 }, { 0, 128, 128 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 }}; static ColorMapEntry Palm1BitColormap[] = {{ 255, 255, 255 }, { 0, 0, 0 }}; static ColorMapEntry Palm2BitColormap[] = { { 255, 255, 255 }, { 192, 192, 192 }, { 128, 128, 128 }, { 0, 0, 0 }}; static ColorMapEntry Palm4BitColormap[] = { { 255, 255, 255 }, { 238, 238, 238 }, { 221, 221, 221 }, { 204, 204, 204 }, { 187, 187, 187 }, { 170, 170, 170 }, { 153, 153, 153 }, { 136, 136, 136 }, { 119, 119, 119 }, { 102, 102, 102 }, { 85, 85, 85 }, { 68, 68, 68 }, { 51, 51, 51 }, { 34, 34, 34 }, { 17, 17, 17 }, { 0, 0, 0 }}; QImage* Palm2QImage (unsigned char *image_bytes_in, int byte_count_in) { unsigned int width, height, bytes_per_row, flags, next_depth_offset; unsigned int bits_per_pixel, version, transparent_index, compression_type, i, j, inval, inbit, mask, incount; unsigned int palm_red_bits, palm_green_bits, palm_blue_bits; unsigned char *palm_ptr, *x_ptr, *imagedata, *inbyte, *rowbuf, *lastrow, *imagedatastart, *palmimage; ColorMapEntry *colormap; palmimage = image_bytes_in; width = READ_BIGENDIAN_SHORT(palmimage + 0); height = READ_BIGENDIAN_SHORT(palmimage + 2); bytes_per_row = READ_BIGENDIAN_SHORT(palmimage + 4); flags = READ_BIGENDIAN_SHORT(palmimage + 6); bits_per_pixel = palmimage[8]; version = palmimage[9]; next_depth_offset = READ_BIGENDIAN_SHORT(palmimage + 10); transparent_index = palmimage[12]; compression_type = palmimage[13]; /* bytes 14 and 15 are reserved by Palm and always 0 */ #if 0 // qDebug ("Palm image is %dx%d, %d bpp, version %d, flags 0x%x, compression %d", width, height, bits_per_pixel, version, flags, compression_type); #endif if (compression_type == PALM_COMPRESSION_PACKBITS) { // qDebug ("Image uses packbits compression; not yet supported"); return NULL; } else if ((compression_type != PALM_COMPRESSION_NONE) && (compression_type != PALM_COMPRESSION_RLE) && (compression_type != PALM_COMPRESSION_SCANLINE)) { // qDebug ("Image uses unknown compression, code 0x%x", compression_type); return NULL; } /* as of PalmOS 4.0, there are 6 different kinds of Palm pixmaps: 1, 2, or 4 bit grayscale 8-bit StaticColor using the Palm standard colormap 8-bit PseudoColor using a user-specified colormap 16-bit DirectColor using 5 bits for red, 6 for green, and 5 for blue Each of these can be compressed with one of four compression schemes, "RLE", "Scanline", "PackBits", or none. We begin by constructing the colormap. */ if (flags & PALM_HAS_COLORMAP_FLAG) { // qDebug("Palm images with custom colormaps are not currently supported.\n"); return NULL; } else if (bits_per_pixel == 1) { colormap = Palm1BitColormap; imagedatastart = palmimage + 16; } else if (bits_per_pixel == 2) { colormap = Palm2BitColormap; imagedatastart = palmimage + 16; } else if (bits_per_pixel == 4) { colormap = Palm4BitColormap; imagedatastart = palmimage + 16; } else if (bits_per_pixel == 8) { colormap = Palm8BitColormap; imagedatastart = palmimage + 16; } else if (bits_per_pixel == 16 && (flags & PALM_DIRECT_COLOR_FLAG)) { colormap = NULL; palm_red_bits = palmimage[16]; palm_green_bits = palmimage[17]; palm_blue_bits = palmimage[18]; // qDebug("Bits:%d, %d, %d", palm_red_bits, palm_green_bits, palm_blue_bits); if (palm_blue_bits > 8 || palm_green_bits > 8 || palm_red_bits > 8) { // qDebug("Can't handle this format DirectColor image -- too wide in some color (%d:%d:%d)\n", palm_red_bits, palm_green_bits, palm_blue_bits); return NULL; } if (bits_per_pixel > (8 * sizeof(unsigned long))) { // qDebug ("Can't handle this format DirectColor image -- too many bits per pixel (%d)\n", bits_per_pixel); return NULL; } imagedatastart = palmimage + 24; } else { // qDebug("Unknown bits-per-pixel of %d encountered.\n", bits_per_pixel); return NULL; } #ifndef USEQPE QImage* qimage = new QImage(width, height, 32); #else QImage* qimage = new QImage(width, height, 16); #endif /* row by row, uncompress the Palm image and copy it to the JPEG buffer */ rowbuf = new unsigned char[bytes_per_row * width]; lastrow = new unsigned char[bytes_per_row * width]; for (i=0, palm_ptr = imagedatastart , x_ptr = imagedata; i < height; ++i) { // qDebug("inval:%x palm_ptr:%x x_ptr:%x bpr:%x", inval, palm_ptr, x_ptr, bytes_per_row); /* first, uncompress the Palm image */ if ((flags & PALM_IS_COMPRESSED_FLAG) && (compression_type == PALM_COMPRESSION_RLE)) { for (j = 0; j < bytes_per_row; ) { incount = *palm_ptr++; inval = *palm_ptr++; memset(rowbuf + j, inval, incount); j += incount; } } else if ((flags & PALM_IS_COMPRESSED_FLAG) && (compression_type == PALM_COMPRESSION_SCANLINE)) { for (j = 0; j < bytes_per_row; j += 8) { incount = *palm_ptr++; inval = ((bytes_per_row - j) < 8) ? (bytes_per_row - j) : 8; for (inbit = 0; inbit < inval; inbit += 1) { if (incount & (1 << (7 - inbit))) rowbuf[j + inbit] = *palm_ptr++; else rowbuf[j + inbit] = lastrow[j + inbit]; } } memcpy (lastrow, rowbuf, bytes_per_row); } else if (((flags & PALM_IS_COMPRESSED_FLAG) && (compression_type == PALM_COMPRESSION_NONE)) || ((flags & PALM_IS_COMPRESSED_FLAG) == 0)) { memcpy (rowbuf, palm_ptr, bytes_per_row); palm_ptr += bytes_per_row; } else { qDebug("Case 4"); qDebug("Is compressed:%s", ((flags & PALM_IS_COMPRESSED_FLAG) == 0) ? "false" : "true"); qDebug("Has colourmap:%s", ((flags & PALM_HAS_COLORMAP_FLAG) == 0) ? "false" : "true"); qDebug("Has transparency:%s", ((flags & PALM_HAS_TRANSPARENCY_FLAG) == 0) ? "false" : "true"); qDebug("Direct colour:%s", ((flags & PALM_DIRECT_COLOR_FLAG) == 0) ? "false" : "true"); qDebug("four byte field:%s", ((flags & PALM_4_BYTE_FIELD_FLAG) == 0) ? "false" : "true"); memcpy (rowbuf, palm_ptr, bytes_per_row); palm_ptr += bytes_per_row; } /* next, write it to the GDK bitmap */ if (colormap) { mask = (1 << bits_per_pixel) - 1; for (inbit = 8 - bits_per_pixel, inbyte = rowbuf, j = 0; j < width; ++j) { inval = ((*inbyte) & (mask << inbit)) >> inbit; /* correct for oddity of the 8-bit color Palm pixmap... */ if ((bits_per_pixel == 8) && (inval == 0xFF)) inval = 231; /* now lookup the correct color and set the pixel in the GTK bitmap */ QRgb colour = qRgb(colormap[inval].red, colormap[inval].green, colormap[inval].blue); qimage->setPixel(j, i, colour); if (!inbit) { ++inbyte; inbit = 8 - bits_per_pixel; } else { inbit -= bits_per_pixel; } } } else if (!colormap && bits_per_pixel == 16) { for (inbyte = rowbuf, j = 0; j < width; ++j) { inval = ((unsigned short)inbyte[0] << (unsigned short)8) | inbyte[1]; /* qDebug ("pixel is %d,%d (%d:%d:%d)", j, i, ((inval >> (bits_per_pixel - palm_red_bits)) & ((1 << palm_red_bits) - 1)) << (8-palm_red_bits), ((inval >> palm_blue_bits) & ((1 << palm_green_bits) - 1)) << (8-palm_green_bits), ((inval >> 0) & ((1 << palm_blue_bits) - 1)) << (8-palm_blue_bits)); */ QRgb colour = qRgb( ((inval >> (bits_per_pixel - palm_red_bits)) & ((1 << palm_red_bits) - 1)) << (8-palm_red_bits), ((inval >> palm_blue_bits) & ((1 << palm_green_bits) - 1)) << (8-palm_green_bits), ((inval >> 0) & ((1 << palm_blue_bits) - 1)) << (8-palm_blue_bits)); qimage->setPixel(j, i, colour); inbyte += 2; } } } delete [] rowbuf; delete [] lastrow; return qimage; } diff --git a/noncore/apps/opie-reader/Prefs.cpp b/noncore/apps/opie-reader/Prefs.cpp index 2733faa..6c4d45b 100644 --- a/noncore/apps/opie-reader/Prefs.cpp +++ b/noncore/apps/opie-reader/Prefs.cpp @@ -1,777 +1,840 @@ /**************************************************************************** ** Form implementation generated from reading ui file 'Prefs.ui' ** ** Created: Tue Feb 11 23:53:35 2003 ** by: The User Interface Compiler (uic) ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ #include "Prefs.h" +#include <stdlib.h> + #include <qcheckbox.h> #include <qlabel.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qlayout.h> #include <qvariant.h> #include <qtooltip.h> #include <qwhatsthis.h> #include <qbuttongroup.h> #include <qlineedit.h> +#include <qdir.h> #ifdef USECOMBO #include <qcombobox.h> #else #include <qpe/menubutton.h> #endif #include <qfontdatabase.h> #ifdef USECOMBO void populate_colours(QComboBox *mb) #else void populate_colours(MenuButton *mb) #endif { mb->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); mb->insertItem("White"); mb->insertItem("Black"); mb->insertItem("Dark Gray"); mb->insertItem("Gray"); mb->insertItem("Light Gray"); mb->insertItem("Red"); mb->insertItem("Green"); mb->insertItem("Blue"); mb->insertItem("Cyan"); mb->insertItem("Magenta"); mb->insertItem("Yellow"); mb->insertItem("Dark Red"); mb->insertItem("Dark Green"); mb->insertItem("Dark Blue"); mb->insertItem("Dark Cyan"); mb->insertItem("Dark Magenta"); mb->insertItem("Dark Yellow"); } CLayoutPrefs::CLayoutPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QHBoxLayout* hb = new QHBoxLayout(this); QButtonGroup* bg = new QButtonGroup(2, Qt::Horizontal, "Text", this); hb->addWidget(bg); StripCR = new QCheckBox( bg ); StripCR->setText( tr( "Strip CR" ) ); Dehyphen = new QCheckBox( bg ); Dehyphen->setText( tr( "Dehyphen" ) ); SingleSpace = new QCheckBox( bg ); SingleSpace->setText( tr( "Single Space" ) ); Unindent = new QCheckBox( bg ); Unindent->setText( tr( "Unindent" ) ); Reparagraph = new QCheckBox( bg ); Reparagraph->setText( tr( "Reparagraph" ) ); DoubleSpace = new QCheckBox( bg ); DoubleSpace->setText( tr( "Double Space" ) ); Remap = new QCheckBox( bg ); Remap->setText( tr( "Remap" ) ); Embolden = new QCheckBox( bg ); Embolden->setText( tr( "Embolden" ) ); FullJustify = new QCheckBox( bg ); FullJustify->setText( tr( "Full Justify" ) ); FixGraphics = new QCheckBox( bg ); FixGraphics->setText( tr( "Fix Graphic Size" ) ); hyphenate = new QCheckBox( bg ); hyphenate->setText( tr( "Hyphenate" ) ); /* customhyphen = new QCheckBox( bg ); customhyphen->setText( tr( "Custom Hyphen'n" ) ); */ prepalm = new QCheckBox( bg ); prepalm->setText( tr( "Repalm(Baen)" ) ); pkern = new QCheckBox( bg ); pkern->setText( tr( "Kern" ) ); + InlineTables = new QCheckBox( bg ); + InlineTables->setText( tr( "Inline Tables" ) ); + + Underlinelinks = new QCheckBox( bg ); + Underlinelinks->setText( tr( "Underline Links" ) ); /* Negative = new QCheckBox( bg ); Negative->setText( tr( "Negative" ) ); */ // Inverse = new QCheckBox( bg ); // Inverse->setText( tr( "Inverse" ) ); } /* * Destroys the object and frees any allocated resources */ CLayoutPrefs::~CLayoutPrefs() { // no need to delete child widgets, Qt does it all for us } CLayoutPrefs2::CLayoutPrefs2( int w, QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QVBoxLayout* vb = new QVBoxLayout(this); QGridLayout* gl = new QGridLayout(vb, 4, 5); QLabel *TextLabel; TextLabel = new QLabel( this ); TextLabel->setText( tr( "Page\nOverlap" ) ); gl->addWidget(TextLabel, 0, 0); pageoverlap = new QSpinBox( this ); pageoverlap->setRange(0,20); gl->addWidget(pageoverlap, 0, 1); TextLabel = new QLabel( this, "TextLabel1" ); TextLabel->setText( tr( "Indent" ) ); gl->addWidget(TextLabel, 1, 0); Indent = new QSpinBox( this, "Indent" ); Indent->setRange(0,20); gl->addWidget(Indent, 1, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Graphics\nZoom" ) ); gl->addWidget(TextLabel, 1, 2); gfxzoom = new QSpinBox( this ); gfxzoom->setRange(0,2000); gfxzoom->setLineStep(10); gfxzoom->setSuffix("%"); gl->addWidget(gfxzoom, 1, 3); TextLabel = new QLabel( this, "TextLabel4" ); TextLabel->setText( tr( "Top\nMargin" ) ); gl->addWidget(TextLabel, 2, 0); TopMargin = new QSpinBox( this, "TMargin" ); TopMargin->setRange(0, 1000); gl->addWidget(TopMargin, 2, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Bottom\nMargin" ) ); gl->addWidget(TextLabel, 2, 2); BottomMargin = new QSpinBox( this, "BMargin" ); BottomMargin->setRange(0, 1000); gl->addWidget(BottomMargin, 2, 3); TextLabel = new QLabel( this, "TextLabel4" ); TextLabel->setText( tr( "Left\nMargin" ) ); gl->addWidget(TextLabel, 3, 0); LeftMargin = new QSpinBox( this, "LMargin" ); LeftMargin->setRange(0, 1000); gl->addWidget(LeftMargin, 3, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Right\nMargin" ) ); gl->addWidget(TextLabel, 3, 2); RightMargin = new QSpinBox( this, "RMargin" ); RightMargin->setRange(0, 1000); gl->addWidget(RightMargin, 3, 3); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Paragraph\nLeading" ) ); gl->addWidget(TextLabel, 4, 0); ParaLead = new QSpinBox( this ); ParaLead->setRange(-5, 50); gl->addWidget(ParaLead, 4, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Line\nLeading" ) ); gl->addWidget(TextLabel, 4, 2); LineLead = new QSpinBox( this ); LineLead->setRange(-5, 50); gl->addWidget(LineLead, 4, 3); gl = new QGridLayout(vb, 2, 2); TextLabel = new QLabel( this); TextLabel->setText( tr( "Markup" ) ); gl->addWidget(TextLabel, 0, 0, Qt::AlignBottom); TextLabel = new QLabel( this); TextLabel->setText( tr( "Font" ) ); gl->addWidget(TextLabel, 0, 1, Qt::AlignBottom); #ifdef USECOMBO Markup = new QComboBox( this); #else Markup = new MenuButton( this); #endif Markup->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); Markup->insertItem("Auto"); Markup->insertItem("None"); Markup->insertItem("Text"); Markup->insertItem("HTML"); Markup->insertItem("PML"); gl->addWidget(Markup, 1, 0, Qt::AlignTop); #ifdef USECOMBO fontselector = new QComboBox( this); #else fontselector = new MenuButton( this); #endif fontselector->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); { QFontDatabase f; QStringList flist = f.families(); for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) { fontselector->insertItem(*nm); } } // delete the FontDatabase!!! gl->addWidget(fontselector, 1, 1, Qt::AlignTop); #ifdef USECOMBO bgsel = new QComboBox( this ); #else bgsel = new MenuButton( this ); #endif populate_colours(bgsel); #ifdef USECOMBO fgsel = new QComboBox( this ); #else fgsel = new MenuButton( this ); #endif populate_colours(fgsel); gl = new QGridLayout(vb, 2, 2); TextLabel = new QLabel( this); TextLabel->setText( tr( "Background" ) ); gl->addWidget(TextLabel, 0, 0, Qt::AlignBottom); TextLabel = new QLabel( this); TextLabel->setText( tr( "Foreground" ) ); gl->addWidget(TextLabel, 0, 1, Qt::AlignBottom); gl->addWidget(bgsel, 1, 0, Qt::AlignTop); gl->addWidget(fgsel, 1, 1, Qt::AlignTop); } /* CLayoutPrefs2::CLayoutPrefs2( int w, QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QVBoxLayout* vb = new QVBoxLayout(this); QGridLayout* gl = new QGridLayout(vb, 4, 3); QLabel *TextLabel; TextLabel = new QLabel( this, "TextLabel1" ); TextLabel->setText( tr( "Indent" ) ); gl->addWidget(TextLabel, 0, 0); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Page\nOverlap" ) ); gl->addWidget(TextLabel, 0, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Graphics\nZoom" ) ); gl->addWidget(TextLabel, 0, 2); Indent = new QSpinBox( this, "Indent" ); Indent->setRange(0,20); gl->addWidget(Indent, 1, 0); pageoverlap = new QSpinBox( this ); pageoverlap->setRange(0,20); gl->addWidget(pageoverlap, 1, 1); gfxzoom = new QSpinBox( this ); gfxzoom->setRange(0,100); gl->addWidget(gfxzoom, 1, 2); TextLabel = new QLabel( this, "TextLabel4" ); TextLabel->setText( tr( "Margin" ) ); gl->addWidget(TextLabel, 2, 0); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Paragraph\nLeading" ) ); gl->addWidget(TextLabel, 2, 1); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Line\nLeading" ) ); gl->addWidget(TextLabel, 2, 2); Margin = new QSpinBox( this, "Margin" ); Margin->setRange(0, w/2); gl->addWidget(Margin, 3, 0); ParaLead = new QSpinBox( this ); ParaLead->setRange(-5, 50); gl->addWidget(ParaLead, 3, 1); LineLead = new QSpinBox( this ); LineLead->setRange(-5, 50); gl->addWidget(LineLead, 3, 2); gl = new QGridLayout(vb, 2, 2); TextLabel = new QLabel( this); TextLabel->setText( tr( "Markup" ) ); gl->addWidget(TextLabel, 0, 0, Qt::AlignBottom); TextLabel = new QLabel( this); TextLabel->setText( tr( "Font" ) ); gl->addWidget(TextLabel, 0, 1, Qt::AlignBottom); #ifdef USECOMBO Markup = new QComboBox( this); #else Markup = new MenuButton( this); #endif Markup->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); Markup->insertItem("Auto"); Markup->insertItem("None"); Markup->insertItem("Text"); Markup->insertItem("HTML"); Markup->insertItem("PML"); gl->addWidget(Markup, 1, 0, Qt::AlignTop); #ifdef USECOMBO fontselector = new QComboBox( this); #else fontselector = new MenuButton( this); #endif fontselector->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); { QFontDatabase f; QStringList flist = f.families(); for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) { fontselector->insertItem(*nm); } } // delete the FontDatabase!!! gl->addWidget(fontselector, 1, 1, Qt::AlignTop); #ifdef USECOMBO bgsel = new QComboBox( this ); #else bgsel = new MenuButton( this ); #endif populate_colours(bgsel); #ifdef USECOMBO fgsel = new QComboBox( this ); #else fgsel = new MenuButton( this ); #endif populate_colours(fgsel); gl = new QGridLayout(vb, 2, 2); TextLabel = new QLabel( this); TextLabel->setText( tr( "Background" ) ); gl->addWidget(TextLabel, 0, 0, Qt::AlignBottom); TextLabel = new QLabel( this); TextLabel->setText( tr( "Foreground" ) ); gl->addWidget(TextLabel, 0, 1, Qt::AlignBottom); gl->addWidget(bgsel, 1, 0, Qt::AlignTop); gl->addWidget(fgsel, 1, 1, Qt::AlignTop); } */ /* CLayoutPrefs2::CLayoutPrefs2( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QHBoxLayout* hb = new QHBoxLayout(this); QVBoxLayout* vb = new QVBoxLayout; hb->addLayout(vb); QLabel *TextLabel; TextLabel = new QLabel( this, "TextLabel1" ); TextLabel->setText( tr( "Indent" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); Indent = new QSpinBox( this, "Indent" ); Indent->setRange(0,20); vb->addWidget( Indent, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Page\nOverlap" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); pageoverlap = new QSpinBox( this ); pageoverlap->setRange(0,20); vb->addWidget( pageoverlap, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Graphics\nZoom" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); gfxzoom = new QSpinBox( this ); gfxzoom->setRange(0,100); vb->addWidget( gfxzoom, 0, Qt::AlignLeft ); vb->addStretch(); vb = new QVBoxLayout; hb->addLayout(vb); TextLabel = new QLabel( this, "TextLabel4" ); TextLabel->setText( tr( "Margin" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); Margin = new QSpinBox( this, "Margin" ); Margin->setRange(0, 100); vb->addWidget( Margin, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Paragraph\nLeading" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); ParaLead = new QSpinBox( this ); ParaLead->setRange(-5, 50); vb->addWidget( ParaLead, 0, Qt::AlignLeft ); TextLabel = new QLabel( this ); TextLabel->setText( tr( "Line\nLeading" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); LineLead = new QSpinBox( this ); LineLead->setRange(-5, 50); vb->addWidget( LineLead, 0, Qt::AlignLeft ); vb->addStretch(); vb = new QVBoxLayout; hb->addLayout(vb); TextLabel = new QLabel( this); TextLabel->setText( tr( "Markup" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); Markup = new MenuButton( this); Markup->insertItem("Auto"); Markup->insertItem("None"); Markup->insertItem("Text"); Markup->insertItem("HTML"); Markup->insertItem("PML"); vb->addWidget( Markup, 0, Qt::AlignLeft ); TextLabel = new QLabel( this); TextLabel->setText( tr( "Font" ) ); vb->addWidget( TextLabel, 0, Qt::AlignBottom ); fontselector = new MenuButton( this); fontselector->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); { FontDatabase f; QStringList flist = f.families(); for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) { fontselector->insertItem(*nm); } } // delete the FontDatabase!!! vb->addWidget( fontselector, 0, Qt::AlignLeft ); vb->addStretch(); } */ /* * Destroys the object and frees any allocated resources */ CLayoutPrefs2::~CLayoutPrefs2() { // no need to delete child widgets, Qt does it all for us } /* CPluckerPrefs::CPluckerPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { Layout11 = new QVBoxLayout(this); Layout11->setMargin( 0 ); Depluck = new QCheckBox( this, "Depluck" ); Depluck->setText( tr( "Depluck" ) ); Layout11->addWidget( Depluck ); Dejpluck = new QCheckBox( this, "Dejpluck" ); Dejpluck->setText( tr( "Dejpluck" ) ); Layout11->addWidget( Dejpluck ); Continuous = new QCheckBox( this, "Continuous" ); Continuous->setText( tr( "Continuous" ) ); Layout11->addWidget( Continuous ); } CPluckerPrefs::~CPluckerPrefs() { // no need to delete child widgets, Qt does it all for us } */ /* CMiscPrefs::CMiscPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QVBoxLayout* Layout11 = new QVBoxLayout(this); Layout11->setMargin( 0 ); QHBoxLayout* hl = new QHBoxLayout; QLabel* TextLabel = new QLabel( this ); TextLabel->setText( tr( "Action for\nSelect Button" ) ); hl->addWidget(TextLabel); action = new QComboBox( this ); action->insertItem("Open file"); action->insertItem("Autoscroll"); action->insertItem("Mark"); action->insertItem("Annotate"); action->insertItem("Fullscreen"); hl->addWidget( action ); Layout11->addLayout(hl); hl = new QHBoxLayout; TextLabel = new QLabel( this ); TextLabel->setText( tr( "Dictionary\nApplication" ) ); hl->addWidget(TextLabel); target = new QLineEdit(this); hl->addWidget( target ); Layout11->addLayout(hl); QButtonGroup* bg = new QButtonGroup(1, Qt::Horizontal, "Selection Target", this); Layout11->addWidget( bg ); annotation = new QCheckBox( bg ); annotation->setText( tr( "Annotation" ) ); dictionary = new QCheckBox( bg ); dictionary->setText( tr( "Dictionary" ) ); clipboard = new QCheckBox( bg ); clipboard->setText( tr( "Clipboard" ) ); + QCheckBox* outcodec = new QCheckBox( bg ); + outcodec->setText( tr( "Output" ) ); + } CMiscPrefs::~CMiscPrefs() { // no need to delete child widgets, Qt does it all for us } */ CMiscPrefs::CMiscPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QVBoxLayout* vl = new QVBoxLayout(this); QHBoxLayout* hl = new QHBoxLayout; vl->addLayout(hl); vl->setMargin( 0 ); hl->setMargin( 0 ); QGroupBox* gb = new QGroupBox(1, Qt::Horizontal, "Select Action", this); hl->addWidget( gb ); annotation = new QCheckBox( gb ); annotation->setText( tr( "Annotation" ) ); dictionary = new QCheckBox( gb ); dictionary->setText( tr( "Dictionary" ) ); clipboard = new QCheckBox( gb ); clipboard->setText( tr( "Clipboard" ) ); + boutput = new QCheckBox( gb ); + boutput->setText( tr( "Output" ) ); + QButtonGroup* bg = new QButtonGroup(1, Qt::Horizontal, "Plucker", this); hl->addWidget( bg ); Depluck = new QCheckBox( bg ); Depluck->setText( tr( "Depluck" ) ); Dejpluck = new QCheckBox( bg ); Dejpluck->setText( tr( "Dejpluck" ) ); Continuous = new QCheckBox( bg ); Continuous->setText( tr( "Continuous" ) ); - - bg = new QButtonGroup(2, Qt::Horizontal, "Scroll", this); + bg = new QButtonGroup(2, Qt::Horizontal, "Background", this); vl->addWidget( bg ); - // scrollinplace = new QCheckBox( bg ); - // scrollinplace->setText( tr( "In Place" ) ); +// QLabel* TextLabel = new QLabel( bg ); +// TextLabel->setText( tr( "Copy an image to \"background\" in\n~/Applications/uqtreader/Theme/" ) ); + #ifdef USECOMBO - scrolltype = new QComboBox( bg ); + bgtype = new QComboBox( bg ); #else - scrolltype = new MenuButton( this); + bgtype = new MenuButton( this); #endif - scrolltype->insertItem("In Place"); - scrolltype->insertItem("Rolling (moving bg)"); - scrolltype->insertItem("Rolling (window)"); - scrolltype->insertItem("Rolling (static bg)"); - scrolltype->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + bgtype->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + + bgtype->insertItem( tr("Centred") ); + bgtype->insertItem( tr("Tiled") ); + bgtype->insertItem( tr("Fitted") ); + DoubleBuffer = new QCheckBox( bg ); + DoubleBuffer->setText( tr( "Double Buffer" ) ); + QLabel* TextLabel = new QLabel( bg ); + TextLabel->setText( tr( "Minibar Colour" ) ); #ifdef USECOMBO - scrollcolor = new QComboBox( bg ); + minibarcol = new QComboBox( bg ); #else - scrollcolor = new MenuButton( this); + minibarcol = new MenuButton( this); #endif - populate_colours(scrollcolor); - scrollcolor->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + populate_colours(minibarcol); + minibarcol->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); +} + +CMiscPrefs::~CMiscPrefs() +{ + // no need to delete child widgets, Qt does it all for us +} + +CScrollPrefs::CScrollPrefs( QWidget* parent, const char* name, WFlags fl ) + : QWidget( parent, name, fl ) +{ + + QHBoxLayout* hl = new QHBoxLayout(this); + hl->setMargin( 0 ); + + QButtonGroup* bg = new QButtonGroup(2, Qt::Horizontal, "Scroll", this); + hl->addWidget( bg ); + // scrollinplace = new QCheckBox( bg ); + // scrollinplace->setText( tr( "In Place" ) ); QLabel* TextLabel = new QLabel( bg ); TextLabel->setText( tr( "Scroll step" ) ); // gl->addWidget(TextLabel, 2, 0); scrollstep = new QSpinBox( bg ); scrollstep->setRange(1, 10); scrollstep->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); TextLabel = new QLabel( bg ); - TextLabel->setText( tr( "Minibar Colour" ) ); + TextLabel->setText( tr( "Scroll type" ) ); #ifdef USECOMBO - minibarcol = new QComboBox( bg ); + scrolltype = new QComboBox( bg ); #else - minibarcol = new MenuButton( this); + scrolltype = new MenuButton( this); #endif - populate_colours(minibarcol); - minibarcol->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + scrolltype->insertItem("In Place"); + scrolltype->insertItem("Rolling (moving bg)"); + scrolltype->insertItem("Rolling (window)"); + scrolltype->insertItem("Rolling (static bg)"); + scrolltype->insertItem("Send to output"); + scrolltype->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + TextLabel = new QLabel( bg ); + TextLabel->setText( tr( "Colour of scroll\nprogress indicator" ) ); - bg = new QButtonGroup(2, Qt::Vertical, "Background", this); - vl->addWidget( bg ); +#ifdef USECOMBO + scrollcolor = new QComboBox( bg ); +#else + scrollcolor = new MenuButton( this); +#endif + populate_colours(scrollcolor); + scrollcolor->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); -// QLabel* TextLabel = new QLabel( bg ); -// TextLabel->setText( tr( "Copy an image to \"background\" in\n~/Applications/uqtreader/Theme/" ) ); + TextLabel = new QLabel( bg ); + TextLabel->setText( tr( "Output" ) ); #ifdef USECOMBO - bgtype = new QComboBox( bg ); + outcodec = new QComboBox( bg ); #else - bgtype = new MenuButton( this); + outcodec = new MenuButton( this); #endif - bgtype->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); - - bgtype->insertItem( tr("Centred") ); - bgtype->insertItem( tr("Tiled") ); - bgtype->insertItem( tr("Fitted") ); +#ifdef USEQPE +#ifdef OPIE + QString codecpath(getenv("OPIEDIR")); +#else + QString codecpath(getenv("QTDIR")); +#endif + codecpath += "/plugins/reader/outcodecs"; +#else + QString codecpath(getenv("READERDIR")); + codecpath += "/outcodecs"; +#endif + QDir ocd(codecpath, "lib*.so"); + for (int i = 0; i < ocd.count(); ++i) + { + QString tmp(ocd[i]); + outcodec->insertItem(tmp.mid(3,tmp.length()-6)); + } + outcodec->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); } -CMiscPrefs::~CMiscPrefs() +CScrollPrefs::~CScrollPrefs() { // no need to delete child widgets, Qt does it all for us } + CPrefs::CPrefs( int w, bool fs, QWidget* parent, const char* name) : QDialog(parent, name, true) { setCaption(tr( "OpieReader Settings" ) ); QTabWidget* td = new QTabWidget(this); layout = new CLayoutPrefs(this); layout2 = new CLayoutPrefs2(w, this); + scroll = new CScrollPrefs(this); misc = new CMiscPrefs(this); // button = new CButtonPrefs(kmap, this); inter = new CInterPrefs(this); td->addTab(layout, tr("Layout")); td->addTab(layout2, tr("Layout(2)")); td->addTab(inter, tr("Locale")); + td->addTab(scroll, tr("Scroll")); td->addTab(misc, tr("Misc")); // td->addTab(button, tr("Buttons")); QVBoxLayout* v = new QVBoxLayout(this); v->addWidget(td); if (fs) showMaximized(); } /* Unicode Ideo/Word Width Encoding */ #include "CEncoding_tables.h" CInterPrefs::CInterPrefs( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QHBoxLayout* hb = new QHBoxLayout(this); QGroupBox* gb = new QGroupBox(1, Qt::Horizontal, tr("International"), this); hb->addWidget(gb); QLabel *TextLabel; ideogram = new QCheckBox( gb ); ideogram->setText( tr( "Ideograms" ) ); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Ideogram Width" ) ); ideogramwidth = new QSpinBox( gb ); ideogramwidth->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); ideogramwidth->setRange(1,200); propfontchange = new QCheckBox( gb ); propfontchange->setText( tr( "Apply font\nto dialogs" ) ); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Encoding" ) ); #ifdef USECOMBO encoding = new QComboBox(gb); #else encoding = new MenuButton(gb); #endif encoding->insertItem("Ascii"); encoding->insertItem("UTF-8"); encoding->insertItem("UCS-2(BE)"); encoding->insertItem("USC-2(LE)"); encoding->insertItem("Palm"); for (unicodetable::iterator iter = unicodetable::begin(); iter != unicodetable::end(); iter++) { encoding->insertItem(iter->mime); } QVBoxLayout* vb = new QVBoxLayout; gb = new QGroupBox(1, Qt::Horizontal, "Dictionary", this); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Application" ) ); application = new QLineEdit(gb); application->setFixedWidth(80); TextLabel = new QLabel( gb ); TextLabel->setText( tr( "Message" ) ); message = new QLineEdit(gb); message->setFixedWidth(80); // message->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); twotouch = new QCheckBox( gb ); twotouch->setText( tr( "Two/One\nTouch" ) ); SwapMouse = new QCheckBox( gb ); SwapMouse->setText("Swap Tap\nActions"); vb->addWidget(gb); // vb->addStretch(); hb->addLayout(vb); } CInterPrefs::~CInterPrefs() { // no need to delete child widgets, Qt does it all for us } diff --git a/noncore/apps/opie-reader/Prefs.h b/noncore/apps/opie-reader/Prefs.h index cf12b70..103484e 100644 --- a/noncore/apps/opie-reader/Prefs.h +++ b/noncore/apps/opie-reader/Prefs.h @@ -1,385 +1,430 @@ /**************************************************************************** ** Form interface generated from reading ui file 'Prefs.ui' ** ** Created: Tue Feb 11 23:53:32 2003 ** by: The User Interface Compiler (uic) ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ #ifndef CPREFS_H #define CPREFS_H #include <qvariant.h> #include <qwidget.h> #include <qtabdialog.h> #include <qtabwidget.h> #include <qspinbox.h> #include <qcheckbox.h> #include <qlineedit.h> #define USECOMBO #ifdef USECOMBO #include <qcombobox.h> #else #include <qpe/menubutton.h> #endif #include "orkey.h" class QVBoxLayout; class QHBoxLayout; class QGridLayout; //class QCheckBox; class QLabel; //class QSpinBox; class QListViewItem; class CLayoutPrefs : public QWidget { public: friend class CPrefs; CLayoutPrefs( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CLayoutPrefs(); QCheckBox* StripCR; QCheckBox* Dehyphen; QCheckBox* SingleSpace; QCheckBox* Unindent; QCheckBox* Reparagraph; QCheckBox* DoubleSpace; QCheckBox* Remap; QCheckBox* Embolden; QCheckBox* FullJustify; QCheckBox* FixGraphics; QCheckBox* hyphenate; // QCheckBox* customhyphen; QCheckBox* prepalm; QCheckBox* pkern; // QCheckBox* Inverse; // QCheckBox* Negative; + QCheckBox* InlineTables; + QCheckBox* Underlinelinks; }; class CLayoutPrefs2 : public QWidget { public: friend class CPrefs; CLayoutPrefs2( int w, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CLayoutPrefs2(); QSpinBox* ParaLead; QSpinBox* LineLead; QSpinBox* Indent; QSpinBox *TopMargin, *BottomMargin, *LeftMargin, *RightMargin, *gfxzoom, *pageoverlap; #ifdef USECOMBO QComboBox *Markup, *fontselector, *fgsel, *bgsel; #else MenuButton *Markup, *fontselector, *fgsel, *bgsel; #endif }; /* class CPluckerPrefs : public QWidget { public: friend class CPrefs; CPluckerPrefs( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CPluckerPrefs(); QCheckBox* Depluck; QCheckBox* Dejpluck; QCheckBox* Continuous; + QCheckBox* DoubleBuffer; protected: QHBoxLayout* Layout5; QVBoxLayout* Layout11; QGridLayout* Layout4; }; */ class CMiscPrefs : public QWidget { public: friend class CPrefs; CMiscPrefs( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CMiscPrefs(); - QCheckBox *annotation, *dictionary, *clipboard; - QCheckBox *Depluck, *Dejpluck, *Continuous; + QCheckBox *annotation, *dictionary, *clipboard, *boutput; + QCheckBox *Depluck, *Dejpluck, *Continuous, *DoubleBuffer; + +#ifdef USECOMBO + QComboBox *bgtype, *minibarcol; +#else + MenuButton *bgtype, *minibarcol; +#endif +}; + +class CScrollPrefs : public QWidget +{ + +public: + + friend class CPrefs; + + CScrollPrefs( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); + ~CScrollPrefs(); QSpinBox *scrollstep; #ifdef USECOMBO - QComboBox *scrollcolor, *bgtype, *scrolltype, *minibarcol; + QComboBox *scrollcolor, *scrolltype, *outcodec; #else - MenuButton *scrollcolor, *bgtype, *scrolltype, *minibarcol; + MenuButton *scrollcolor, *scrolltype, *outcodec; #endif }; /* class QListView; class QListViewItem; -class CButtonPrefs : public QWidget +sclass CButtonPrefs : public QWidget { Q_OBJECT QMap<orKey, int> *kmap; QMap<orKey, QListViewItem*> listmap; QListView* lb; void keyPressEvent(QKeyEvent* e); #ifdef USECOMBO void populate(QComboBox*); #else void populate(MenuButton*); #endif public: friend class CPrefs; CButtonPrefs( QMap<orKey, int>*, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CButtonPrefs(); #ifdef USECOMBO QComboBox *action; #else MenuButton *action; #endif QSpinBox* debounce; // QCheckBox *leftScroll, *rightScroll, *upScroll, *downScroll; private slots: void erasemapping(QListViewItem*); }; */ class CInterPrefs : public QWidget { public: friend class CPrefs; CInterPrefs( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CInterPrefs(); QCheckBox *ideogram, *propfontchange, *SwapMouse, *twotouch; #ifdef USECOMBO QComboBox* encoding; #else MenuButton* encoding; #endif QSpinBox* ideogramwidth; QLineEdit *application, *message; }; class CPrefs : public QDialog { Q_OBJECT CLayoutPrefs* layout; CLayoutPrefs2* layout2; CMiscPrefs* misc; - // CButtonPrefs* button; + CScrollPrefs* scroll; CInterPrefs* inter; void keyPressEvent(QKeyEvent* e) { switch (e->key()) { case Key_Escape: e->accept(); reject(); break; case Key_Space: case Key_Return: e->accept(); accept(); break; default: QWidget::keyPressEvent(e); } } public: CPrefs(int w, bool fs = true, QWidget* parent = 0, const char* name = 0); ~CPrefs() { } bool hyphenate() { return layout->hyphenate->isChecked(); } void hyphenate(bool _v) { layout->hyphenate->setChecked(_v); } /* bool customhyphen() { return layout->customhyphen->isChecked(); } void customhyphen(bool _v) { layout->customhyphen->setChecked(_v); } */ bool StripCR() { return layout->StripCR->isChecked(); } + bool InlineTables() { return layout->InlineTables->isChecked(); } bool repalm() { return layout->prepalm->isChecked(); } + bool UnderlineLink() { return layout->Underlinelinks->isChecked(); } bool kern() { return layout->pkern->isChecked(); } bool Dehyphen() { return layout->Dehyphen->isChecked(); } bool SingleSpace() { return layout->SingleSpace->isChecked(); } bool Unindent() { return layout->Unindent->isChecked(); } bool Reparagraph() { return layout->Reparagraph->isChecked(); } bool DoubleSpace() { return layout->DoubleSpace->isChecked(); } bool Remap() { return layout->Remap->isChecked(); } bool Embolden() { return layout->Embolden->isChecked(); } bool FullJustify() { return layout->FullJustify->isChecked(); } // bool Inverse() { return layout->Inverse->isChecked(); } // bool Negative() { return layout->Negative->isChecked(); } bool FixGraphics() { return layout->FixGraphics->isChecked(); } int ParaLead() { return layout2->ParaLead->value(); } int LineLead() { return layout2->LineLead->value(); } int TopMargin() { return layout2->TopMargin->value(); } int BottomMargin() { return layout2->BottomMargin->value(); } int LeftMargin() { return layout2->LeftMargin->value(); } int RightMargin() { return layout2->RightMargin->value(); } int Indent() { return layout2->Indent->value(); } int Markup() { return layout2->Markup->currentItem(); } QString Font() { return layout2->fontselector->currentText(); } void StripCR(bool v) { layout->StripCR->setChecked(v); } + void InlineTables(bool v) { layout->InlineTables->setChecked(v); } void repalm(bool v) { layout->prepalm->setChecked(v); } + void UnderlineLink(bool v) { layout->Underlinelinks->setChecked(v); } void kern(bool v) { layout->pkern->setChecked(v); } void Dehyphen(bool v) { layout->Dehyphen->setChecked(v); } void SingleSpace(bool v) { layout->SingleSpace->setChecked(v); } void Unindent(bool v) { layout->Unindent->setChecked(v); } void Reparagraph(bool v) { layout->Reparagraph->setChecked(v); } void DoubleSpace(bool v) { layout->DoubleSpace->setChecked(v); } void Remap(bool v) { layout->Remap->setChecked(v); } void Embolden(bool v) { layout->Embolden->setChecked(v); } void FullJustify(bool v) { layout->FullJustify->setChecked(v); } // void Negative(bool v) { layout->Negative->setChecked(v); } // void Inverse(bool v) { layout->Inverse->setChecked(v); } void FixGraphics(bool v) { layout->FixGraphics->setChecked(v); } void ParaLead(int v) { layout2->ParaLead->setValue(v); } void LineLead(int v) { layout2->LineLead->setValue(v); } void TopMargin(int v) { layout2->TopMargin->setValue(v); } void BottomMargin(int v) { layout2->BottomMargin->setValue(v); } void LeftMargin(int v) { layout2->LeftMargin->setValue(v); } void RightMargin(int v) { layout2->RightMargin->setValue(v); } void Indent(int v) { layout2->Indent->setValue(v); } #ifdef USECOMBO void Markup(int v) { layout2->Markup->setCurrentItem(v); } #else void Markup(int v) { layout2->Markup->select(v); } #endif #ifdef USECOMBO void bgtype(int v) { misc->bgtype->setCurrentItem(v); } - void scrollcolor(int v) { misc->scrollcolor->setCurrentItem(v); } + void scrollcolor(int v) { scroll->scrollcolor->setCurrentItem(v); } void minibarcol(int v) { misc->minibarcol->setCurrentItem(v); } #else void bgtype(int v) { misc->bgtype->select(v); } - void scrollcolor(int v) { misc->scrollcolor->select(v); } + void scrollcolor(int v) { scroll->scrollcolor->select(v); } void minibarcol(int v) { misc->minibarcol->select(v); } #endif int bgtype() { return misc->bgtype->currentItem(); } - int scrollcolor() { return misc->scrollcolor->currentItem(); } + int scrollcolor() { return scroll->scrollcolor->currentItem(); } int minibarcol() { return misc->minibarcol->currentItem(); } #ifdef USECOMBO void foreground(int v) { layout2->fgsel->setCurrentItem(v); } #else void foreground(int v) { layout2->fgsel->select(v); } #endif int foreground() { return layout2->fgsel->currentItem(); } #ifdef USECOMBO void background(int v) { layout2->bgsel->setCurrentItem(v); } #else void background(int v) { layout2->bgsel->select(v); } #endif int background() { return layout2->bgsel->currentItem(); } - #ifdef USECOMBO void Font(QString& s) { for (int i = 1; i <= layout2->fontselector->count(); i++) { if (layout2->fontselector->text(i) == s) { layout2->fontselector->setCurrentItem(i); break; } } } #else void Font(QString& s) { layout2->fontselector->select(s); } #endif +#ifdef USECOMBO + void outcodec(QString& s) + { + for (int i = 1; i <= scroll->outcodec->count(); i++) + { + if (scroll->outcodec->text(i) == s) + { + scroll->outcodec->setCurrentItem(i); + break; + } + } + } +#else + void outcodec(QString& s) { scroll->outcodec->select(s); } +#endif + QString outcodec() { return scroll->outcodec->currentText(); } + + void miscoutput(bool v) { return misc->boutput->setChecked(v); } + bool miscoutput() { return misc->boutput->isChecked(); } + bool Depluck() { return misc->Depluck->isChecked(); } void Depluck(bool v) { misc->Depluck->setChecked(v); } bool Dejpluck() { return misc->Dejpluck->isChecked(); } void Dejpluck(bool v) { misc->Dejpluck->setChecked(v); } bool Continuous() { return misc->Continuous->isChecked(); } void Continuous(bool v) { misc->Continuous->setChecked(v); } + bool DoubleBuffer() { return misc->DoubleBuffer->isChecked(); } + void DoubleBuffer(bool v) { misc->DoubleBuffer->setChecked(v); } bool SwapMouse() { return inter->SwapMouse->isChecked(); } void SwapMouse(bool v) { inter->SwapMouse->setChecked(v); } void dictApplication(const QString& v) { inter->application->setText(v); } QString dictApplication() { return inter->application->text(); } void dictMessage(const QString& v) { inter->message->setText(v); } QString dictMessage() { return inter->message->text(); } void miscannotation(bool v) { misc->annotation->setChecked(v); } void miscdictionary(bool v) { misc->dictionary->setChecked(v); } void miscclipboard(bool v) { misc->clipboard->setChecked(v); } bool miscannotation() { return misc->annotation->isChecked(); } bool miscdictionary() { return misc->dictionary->isChecked(); } bool miscclipboard() { return misc->clipboard->isChecked(); } /* int Debounce() { return button->debounce->value(); } void Debounce(int v) { button->debounce->setValue(v); } */ /* bool leftScroll() { return button->leftScroll->isChecked(); } void leftScroll(bool v) { button->leftScroll->setChecked(v); } bool rightScroll() { return button->rightScroll->isChecked(); } void rightScroll(bool v) { button->rightScroll->setChecked(v); } bool upScroll() { return button->upScroll->isChecked(); } void upScroll(bool v) { button->upScroll->setChecked(v); } bool downScroll() { return button->downScroll->isChecked(); } void downScroll(bool v) { button->downScroll->setChecked(v); } */ int gfxsize() { return layout2->gfxzoom->value()/10; } void gfxsize(int v) { layout2->gfxzoom->setValue(10*v); } int pageoverlap() { return layout2->pageoverlap->value(); } void pageoverlap(int v) { layout2->pageoverlap->setValue(v); } bool twotouch() { return inter->twotouch->isChecked(); } void twotouch(bool v) { inter->twotouch->setChecked(v); } bool ideogram() { return inter->ideogram->isChecked(); } void ideogram(bool v) { inter->ideogram->setChecked(v); } int ideogramwidth() { return inter->ideogramwidth->value(); } void ideogramwidth(int v) { inter->ideogramwidth->setValue(v); } bool propfontchange() { return inter->propfontchange->isChecked(); } void propfontchange(bool v) { inter->propfontchange->setChecked(v); } int encoding() { return inter->encoding->currentItem(); } - int scrolltype() { return misc->scrolltype->currentItem(); } + int scrolltype() { return scroll->scrolltype->currentItem(); } #ifdef USECOMBO void encoding(int v) { inter->encoding->setCurrentItem(v); } - void scrolltype(int v) { misc->scrolltype->setCurrentItem(v); } + void scrolltype(int v) { scroll->scrolltype->setCurrentItem(v); } #else void encoding(int v) { inter->encoding->select(v); } - void scrolltype(int v) { misc->scrolltype->select(v); } + void scrolltype(int v) { scroll->scrolltype->select(v); } #endif - void scrollstep(int v) { misc->scrollstep->setValue(v); } - int scrollstep() { return misc->scrollstep->value(); } + void scrollstep(int v) { scroll->scrollstep->setValue(v); } + int scrollstep() { return scroll->scrollstep->value(); } }; #endif // CPREFS_H diff --git a/noncore/apps/opie-reader/QTReader.cpp b/noncore/apps/opie-reader/QTReader.cpp index 33884a0..0c56dd4 100644 --- a/noncore/apps/opie-reader/QTReader.cpp +++ b/noncore/apps/opie-reader/QTReader.cpp @@ -1,2985 +1,3492 @@ /**************************************************************************** ** $Id$ ** ** Copyright (C) 1992-2000 Trolltech AS. All rights reserved. ** ** This file is part of an example program for Qt. This example ** program may be used, distributed and modified without limitation. ** *****************************************************************************/ const int _SBARHEIGHT = 3; #include <qpainter.h> //#include <qdirectpainter_qws.h> #include <qimage.h> #include <qtimer.h> #include "config.h" #include "QTReader.h" //#include "QTReaderApp.h" #include "CDrawBuffer.h" #ifdef USEQPE #include <qpe/qpeapplication.h> #endif #include <math.h> #include <ctype.h> #include <stdio.h> //for sprintf #ifdef USEQPE #include <qpe/config.h> #include <qpe/applnk.h> #include <qpe/global.h> #include <qpe/qcopenvelope_qws.h> #endif #include <qfileinfo.h> #include <qdir.h> +#include "TableDialog.h" +#include "outputcodec.h" +/* #ifdef _UNICODE const char *QTReader::fonts[] = { "unifont", "Courier", "Times", 0 }; #else const char *QTReader::fonts[] = { "Helvetica", "Courier", "Times", 0 }; #endif +*/ //const int QTReader::fontsizes[] = { 8, 10, 12, 14, 18, 24, 30, 40, 50, 60, 70, 80, 90, 100, 0 }; //const tchar *QTReader::fonts[] = { "unifont", "fixed", "micro", "smoothtimes", "Courier", "Times", 0 }; //const int QTReader::fontsizes[] = {10,16,17,22,0}; //const tchar *QTReader::fonts[] = { "verdana", "Courier", "Times", 0 }; //const int QTReader::fontsizes[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,0}; tchar QTReader::pluckernextpart[] = { 'C','l','i','c','k',' ','h','e','r','e',' ','f','o','r',' ','t','h','e',' ','n','e','x','t',' ','p','a','r','t',0 }; tchar QTReader::jplucknextpart[] = { 'N','e','x','t',' ','P','a','r','t',' ','>','>',0 }; //tchar QTReader::jplucknextpart[] = { 10,'#',10,'N','e','x','t',' ','P','a','r','t',' ','>','>',0 }; - QTReader::QTReader( QWidget *parent, const char *name, WFlags f) : - QWidget(parent, name, f), + QWidget(parent, name, f | WRepaintNoErase | WResizeNoErase), + m_outofdate(true), m_default_fg(0,0,0), m_default_bg(255,255,255), m_bg(255,255,255), m_delay(100), m_scrolldy1(0), m_scrolldy2(0), m_totalscroll(0), m_autoScroll(false), //textarray(NULL), //locnarray(NULL), numlines(0), m_fontname("unifont"), m_fm(NULL), mouseUpOn(true), m_twotouch(true), m_touchone(true), bDoUpdates(false), #ifdef _SCROLLPIPE m_pipeout(NULL), #endif m_left_border(2), m_right_border(2), m_rotated(true), pBkmklist(NULL), m_scrollpos(0), // bNegative(false), bInverse(false), m_highlightfilter(NULL), m_bgIsScaled(false), m_scrollstep(2), m_topmargin(5), m_bottommargin(5), m_reparastring("{\\n[\\n ]}"), m_currentlinkstyle(NULL), m_currentlinkoffset(-1), m_currentlink(-1) { + m_output = NULL; m_overlap = 1; setKeyCompression ( true ); -#ifdef DOUBLEBUFFER - dbuff = new QPixmap(); - dbp = new QPainter(); - // if (painter->isActive()) painter->end(); - // painter->begin(frame); -#endif -// init(); + dbuff = NULL; + dbp = NULL; } /* QTReader::QTReader( const QString& filename, QWidget *parent=0, const tchar *name=0, WFlags f = 0) : QWidget(parent, name, f), m_textfont(0), m_textsize(1), textarray(NULL), numlines(0), bstripcr(true), bunindent(false), brepara(false), bdblspce(false), btight(false), bindenter(0), m_fm(NULL) { init(); -// // qDebug("Load_file(1)"); +// // qDeb2ug("Load_file(1)"); load_file((const tchar*)filename); } */ /* void QTReader::mouseMoveEvent(QMouseEvent* _e) { mouseUpOn = !(_e->pos().x() == -1); qDebug("MouseMove:[%d, %d]", _e->pos().x(), _e->pos().y()); } */ long QTReader::real_delay() { return m_scrollstep*( 8976 + m_delay ) / ( m_linespacing * m_linespacing ); } void QTReader::mousePressEvent( QMouseEvent* _e ) { - buffdoc.unsuspend(); + m_drageligible = false; + qDebug("Mouse pressed at (%u, %u)", _e->x(), _e->y()); int x, y, ht, wh; if (m_rotated) { x = _e->y(); y = width()-_e->x(); ht = width(); wh = height(); } else { x = _e->x(); y = _e->y(); ht = height(); wh = width(); } + if (x >= m_left_border && x <= wh - m_right_border && y >= m_topmargin && y <= ht-m_bottommargin) + { if (_e->button() == RightButton) { // qDebug("MousePress"); mouseUpOn = false; if (m_swapmouse) { int lineno = 0; /* int hgt = textarray[0]->lineSpacing(); while ((hgt < y) && (lineno < numlines)) { hgt += textarray[++lineno]->lineSpacing(); } */ - size_t startpos, startoffset, tgt, tgtoffset, pictgt; + size_t startpos, startoffset, tgt, tgtoffset, pictgt, tabtgt; QImage* img; - getcurrentpos(x, y, wh, ht, lineno, startpos, startoffset, tgt, tgtoffset, pictgt, img); + getcurrentpos(x, y, wh, ht, lineno, startpos, startoffset, tgt, tgtoffset, pictgt, img, tabtgt); processmousewordevent(startpos, startoffset, _e, lineno); } else + { processmousepositionevent(_e); } } + } + else + { + int ln = -1; + int mp; + int sectionsize = (buffdoc.endSection()-buffdoc.startSection()); + switch (m_scrollpos) + { + case 1: + { + if (m_rotated) + { + if (_e->x() < m_bottommargin) + { + ln = height(); + mp = _e->y(); + } + } + else + { + if (_e->y() > height()-m_bottommargin) + { + ln = width(); + mp = _e->x(); + } + } + } + break; + case 2: + { + if (m_rotated) + { + if (_e->y() > height() - m_right_border) + { + ln = width(); + mp = width()-_e->x(); + } + } + else + { + if (_e->x() > width() - m_right_border) + { + ln = height(); + mp = _e->y(); + } + } + } + break; + case 3: + { + if (m_rotated) + { + if (_e->y() < m_left_border) + { + ln = width(); + mp = width()-_e->x(); + } + } + else + { + if (_e->x() < m_left_border) + { + ln = height(); + mp = _e->y(); + } + } + } + break; + case 0: + default: + ln = -1; + break; + } + if (ln >= 0) + { + int dp = (sectionsize*mp+ln/2)/ln + buffdoc.startSection(); + int winsize = locnarray[numlines]-locnarray[0]; + int slidersize = 10*(sectionsize+ln/2)/ln; + if (slidersize > winsize) + { + int mid = (locnarray[0] + locnarray[numlines])/2; + slidersize /= 2; + if (dp < mid-slidersize) + { + dopageup(); + } + else if (dp > mid+slidersize) + { + dopagedn(); + } + //if (mid-slidersize < dp && dp < mid+slidersize) + else + { + m_drageligible = true; + } + } + else + { + if (dp < locnarray[0]) + { + dopageup(); + } + else if (dp > locnarray[numlines]) + { + dopagedn(); + } + //if (locnarray[0] < dp && dp < locnarray[numlines]) + else + { + m_drageligible = true; + } + } + qDebug("Drag eligible:%s", (m_drageligible) ? "true" : "false"); + } + else + { + if (m_scrollpos == 1) + { + if (x < m_left_border) + { + lineUp(); + } + if (y > ht - m_bottommargin) + { + lineDown(); + } + } + else if (m_scrollpos != 0) + { + if (y < m_topmargin) + { + lineUp(); + } + if (y > ht - m_bottommargin) + { + lineDown(); + } + } + } + } +} void QTReader::processmousepositionevent( QMouseEvent* _e ) { int x, y, ht, wh; if (m_rotated) { x = _e->y(); y = width()-_e->x(); ht = width(); wh = height(); } else { x = _e->x(); y = _e->y(); ht = height(); wh = width(); } if (buffdoc.hasnavigation()) { if (y > (2*ht)/3) { goDown(); } else if (y < ht/3) { goUp(); } else { if (x < wh/3) { goBack(); } else if (x > (2*wh)/3) { goForward(); } else { goHome(); } } } else { if (y > ht/2) { goDown(); } else { goUp(); } } } void QTReader::goHome() { if (buffdoc.hasnavigation()) { size_t current=pagelocate(); size_t home=buffdoc.getHome(); if (current!=home) { buffdoc.saveposn(m_lastfile, current); locate(home); } } else locate(0); } void QTReader::goBack() { if (buffdoc.hasnavigation()) { size_t target = pagelocate(); QString nxt = m_lastfile; buffdoc.writeposn(m_lastfile, target); linkType lt = buffdoc.back(nxt, target); if ((lt & eFile) != 0) { if (nxt != m_lastfile) { emit NewFileRequest(nxt); } locate(target); } else if ((lt & eLink) != 0) { locate(target); } } } void QTReader::goForward() { if (buffdoc.hasnavigation()) { size_t target = pagelocate(); QString nxt = m_lastfile; linkType lt = buffdoc.forward(nxt, target); if ((lt & eFile) != 0) { if (nxt != m_lastfile) { emit NewFileRequest(nxt); } locate(target); } else if ((lt & eLink) != 0) { locate(target); } } } -linkType QTReader::getcurrentpos(int x, int y, int w, int h, int& lineno, size_t& start, size_t& offset, size_t& tgt, size_t& tgtoffset, size_t& pictgt, QImage*& img) +linkType QTReader::getcurrentpos(int x, int y, int w, int h, int& lineno, size_t& start, size_t& offset, size_t& tgt, size_t& tgtoffset, size_t& pictgt, QImage*& img, size_t& tabtgt) { int ht; if (m_scrolldy == m_topmargin) { lineno = 0; ht = textarray[0]->lineSpacing()-m_scrolldy1 + m_topmargin; } else { if (y >= m_scrolldy) { lineno = 0; ht = textarray[0]->lineSpacing()-m_scrolldy1+m_scrolldy + m_topmargin; } else { lineno = 0; ht = textarray[0]->lineSpacing()-m_scrolldy1+m_scrolldy+m_topmargin; while ((ht < h) && (lineno < numlines-1)) { ht += textarray[++lineno]->lineSpacing(); } ht = textarray[lineno]->lineSpacing(); } } while ((ht < y) && (lineno < numlines-1)) { ht += textarray[++lineno]->lineSpacing(); } if (ht < y && textarray[numlines]->showPartial()) lineno = numlines; start = locnarray[lineno]; int availht = ((m_rotated) ? width() : height()) - m_topmargin - m_bottommargin; if (m_bMonoSpaced) { offset = (x - textarray[lineno]->offset(w, m_left_border, m_right_border, availht))/m_charWidth; } else { int i; CDrawBuffer* t = textarray[lineno]; x = x - t->offset(width(), m_left_border, m_right_border, availht); for (i = t->length(); i > 0 && t->width(availht, i, true, w, m_left_border, m_right_border) > x; i--); offset = i; } - return textarray[lineno]->getLinkType(offset, tgt, tgtoffset, pictgt, img); + return textarray[lineno]->getLinkType(offset, tgt, tgtoffset, pictgt, img, tabtgt); } void QTReader::suspend() { buffdoc.suspend(); /*#ifdef OPIE if (memcmp("/mnt/", m_lastfile.latin1(), 5) == 0) buffdoc.suspend(); #else if (memcmp("/usr/mnt.rom/", m_lastfile.latin1(), 13) == 0) buffdoc.suspend(); #endif */ } +void QTReader::setDoubleBuffer(bool _b) +{ + m_doubleBuffered = _b; + if (_b || m_rotated) + { + if (dbuff == NULL) + { + dbuff = new QPixmap(); + dbp = new QPainter(); + } + if (m_rotated) + { + dbuff->resize(height(), width()); + } + else + { + dbuff->resize(width(), height()); + } + m_outofdate = true; + } + else + { + if (dbuff != NULL) + { + delete dbuff; + delete dbp; + } + dbuff = NULL; + dbp = NULL; + } +} + void QTReader::setTwoTouch(bool _b) { setBackgroundColor( m_bg ); m_twotouch = m_touchone = _b; } void QTReader::setContinuous(bool _b) { - buffdoc.unsuspend(); buffdoc.setContinuous(m_continuousDocument = _b); } void QTReader::processmousewordevent(size_t startpos, size_t startoffset, QMouseEvent* _e, int lineno) { unsigned long wrdstart, wrdend; QString wrd; int availht = ((m_rotated) ? width() : height()) - m_topmargin - m_bottommargin; if (m_twotouch) { if (m_touchone) { m_touchone = false; m_startpos = startpos; m_startoffset = startoffset; setBackgroundColor( lightGray ); } else { m_touchone = true; setBackgroundColor( m_bg ); size_t endpos, endoffset; endpos = startpos; endoffset = startoffset; size_t currentpos = locate(); if (endpos >= m_startpos) { jumpto(m_startpos); for (int i = 0; i < m_startoffset; i++) { getch(); } wrdstart = buffdoc.explocate(); if (m_startpos == endpos) { for (int i = m_startoffset; i <= endoffset; i++) { wrd += QChar(getch()); } } else { while (buffdoc.explocate() <= endpos) { wrd += QChar(getch()); } for (int i = 0; i < endoffset; i++) { wrd += QChar(getch()); } } wrdend = buffdoc.explocate(); jumpto(currentpos); } } } else if (m_bMonoSpaced) { int chno = (m_rotated) ? (_e->y()-textarray[lineno]->offset(height(), m_left_border, m_right_border, availht))/m_charWidth : (_e->x()-textarray[lineno]->offset(width(), m_left_border, m_right_border, availht))/m_charWidth; if (chno < ustrlen(textarray[lineno]->data())) { wrd[0] = textarray[lineno]->data()[chno]; } } else { CDrawBuffer* t = textarray[lineno]; int first = 0; int tgt = (m_rotated) ? _e->y() - t->offset(height(), m_left_border, m_right_border, availht) : _e->x() - t->offset(width(), m_left_border, m_right_border, availht); while (1) { int i = first+1; int availht = ((m_rotated) ? width() : height()) - m_topmargin - m_bottommargin; while (QChar((*t)[i]).isLetter() && (*t)[i] != 0) i++; if (t->width(availht, i, true, (m_rotated) ? height() : width(), m_left_border, m_right_border) > tgt) { wrd = toQString(t->data()+first, i - first); // qDebug("Got %s", (const char *)wrd); break; } while (!QChar((*t)[i]).isLetter() && (*t)[i] != 0) i++; if ((*t)[i] == 0) break; first = i; } } if (!wrd.isEmpty()) { - qDebug("Selecteed:%s", (const char*)wrd); + qDebug("Selected:%s", (const char*)wrd); if (m_twotouch) { emit OnWordSelected(wrd, wrdstart, wrdend, wrd); } else { QString line = toQString(textarray[lineno]->data()); emit OnWordSelected(wrd, locnarray[lineno], locnarray[lineno]+line.length(), line); } } } +#ifdef USETIMER +void QTReader::actionDrag() +{ + if (m_drageligible) + { + int fivepages = 5*((2*width()+m_textsize/2)/m_textsize)*((height()+m_textsize/2)/m_textsize); + if (m_dragtarget > fivepages && locnarray[numlines] < m_dragtarget - fivepages) + { + int tgt = m_dragtarget - fivepages/2; + //qDebug("Jumping to %u (%u)", tgt, fivepages); + if (tgt < buffdoc.startSection()) + { + tgt = buffdoc.startSection(); + } + locate(tgt); + drawFonts(); + } + else if (locnarray[0] > m_dragtarget+fivepages) + { + int tgt = m_dragtarget + fivepages/2; + //qDebug("Jumping to %u (%u)", tgt, fivepages); + if (tgt > buffdoc.endSection()) + { + dopageup(); + } + else + { + locate(tgt); + drawFonts(); + } + } + else if (locnarray[numlines] <= m_dragtarget) + { + dopagedn(); + } + else if (locnarray[0] > m_dragtarget) + { + dopageup(); + } + } + else + { + m_dragtimer->stop(); + } +} +#endif + +void QTReader::mouseMoveEvent( QMouseEvent* _e ) +{ + if (m_drageligible) + { + int ht; + int mp; + int sectionsize = (buffdoc.endSection()-buffdoc.startSection()); + //qDebug("Mouse moved to (%u, %u)", _e->x(), _e->y()); + switch (m_scrollpos) + { + case 1: + { + if (m_rotated) + { + ht = height(); + mp = _e->y(); + } + else + { + ht = width(); + mp = _e->x(); + } + } + break; + case 2: + case 3: + { + if (m_rotated) + { + ht = width(); + mp = width()-_e->x(); + } + else + { + ht = height(); + mp = _e->y(); + } + } + break; + case 0: + default: + ht = -1; + break; + } + if (ht >= 0) + { +#ifdef USETIMER + m_dragtarget = (sectionsize*mp+ht/2)/ht + buffdoc.startSection(); + if (!m_dragtimer->isActive()) + { + m_dragtimer->start(0, false); + } +#else + int dp = (sectionsize*mp+ht/2)/ht + buffdoc.startSection(); + locate(dp); +#endif + } + } +} + void QTReader::mouseReleaseEvent( QMouseEvent* _e ) { - buffdoc.unsuspend(); + qDebug("Mouse released at (%u, %u)", _e->x(), _e->y()); + if (m_drageligible) + { + m_drageligible = false; + } + else + { int x, y, ht, wh; if (m_rotated) { x = _e->y(); y = width()-_e->x(); ht = width(); wh = height(); } else { x = _e->x(); y = _e->y(); ht = height(); wh = width(); } if (_e->button() == LeftButton) { if (mouseUpOn) { // qDebug("MouseRelease"); + /* switch(m_scrollpos) { case 1: // Bottom if (y > ht - 5) { locate(buffdoc.startSection()+((buffdoc.endSection()-buffdoc.startSection())*x+wh/2)/wh); return; } break; case 2: // right if (x > wh - m_right_border) { locate(buffdoc.startSection()+((buffdoc.endSection()-buffdoc.startSection())*y+ht/2)/ht); return; } break; case 3: // left if (x < m_left_border) { locate(buffdoc.startSection()+((buffdoc.endSection()-buffdoc.startSection())*y+ht/2)/ht); return; } break; case 0: default: break; } + */ if (textarray[0] != NULL) { QString line; // int lineno = _e->y()/m_linespacing; int lineno = 0; /* int ht = textarray[0]->lineSpacing(); while ((ht < y) && (lineno < numlines)) { ht += textarray[++lineno]->lineSpacing(); } */ - size_t startpos, startoffset, tgt, tgtoffset, pictgt; + size_t startpos, startoffset, tgt, tgtoffset, pictgt, tabtgt; QImage* img; if (m_currentlinkstyle != NULL) { textarray[m_currentlink]->invertLink(m_currentlinkoffset); m_currentlinkstyle = NULL; m_currentlink = -1; m_currentlinkoffset = -1; } - linkType glt = getcurrentpos(x, y, wh, ht, lineno, startpos, startoffset, tgt, tgtoffset, pictgt, img); + linkType glt = getcurrentpos(x, y, wh, ht, lineno, startpos, startoffset, tgt, tgtoffset, pictgt, img, tabtgt); + if (bNoInlineTables && ((glt & eTable) != 0)) + { + size_t currentpos = locate(); + QString tabtext = buffdoc.getTableAsHtml(tabtgt); + qDebug("TABLE:%u:%u:%s", currentpos, tabtgt, (const char*)tabtext); + QFont f(m_fontname, m_fontControl.currentsize()); +#ifdef USEQPE + CTableDialog td(f, tabtext, true, this); +#else + CTableDialog td(f, tabtext, false, this); +#endif + td.exec(); + jumpto(currentpos); + } if ((glt & eLink) != 0) { if ((glt & ePicture) != 0) { qDebug("Big Picture:%x", pictgt); if (QMessageBox::warning(this, PROGNAME, "Show picture or goto link?", "Show", "Goto Link") == 0) { QImage* pm = buffdoc.getPicture(pictgt); if (pm != NULL) { emit OnShowPicture(*pm); delete pm; return; } } } else if (img != NULL) { if (QMessageBox::warning(this, PROGNAME, "Show picture or goto link?", "Show", "Goto Link") == 0) { emit OnShowPicture(*img); return; } } size_t saveposn = pagelocate(); QString href, nm; linkType lt = buffdoc.hyperlink(tgt, tgtoffset, href, nm); qDebug("URL(1):%s", (const char*)href); if ((lt & eFile) != 0) { buffdoc.saveposn(m_lastfile, saveposn); #ifdef USEQPE { QCopEnvelope e("QPE/System", "busy()"); } #endif ResetScroll(); if (!href.isEmpty()) { - if (!buffdoc.getFile(href)) + if (!buffdoc.getFile(href, nm)) { emit NewFileRequest(href); } else { + qDebug("BEFORE:%u", pagelocate()); + buffdoc.resetPos(); ResetScroll(); fillbuffer(); + qDebug("AFTER:%u", pagelocate()); + m_outofdate = true; update(); } } if (!nm.isEmpty()) { qDebug("QTReader:Finding %s", (const char*)nm); if (buffdoc.findanchor(nm)) { + buffdoc.resetPos(); fillbuffer(); + m_outofdate = true; update(); } } //fillbuffer(); //update(); #ifdef USEQPE { QCopEnvelope e("QPE/System", "notBusy()"); } #endif } else if ((lt & eLink) != 0) { buffdoc.saveposn(m_lastfile, saveposn); ResetScroll(); fillbuffer(); + m_outofdate = true; update(); } else { if ((lt & ePicture) != 0) { QImage* pm = buffdoc.getPicture(tgt); if (pm != NULL) { emit OnShowPicture(*pm); delete pm; } } else { // QString anchortext = textarray[lineno]->getanchortext(startoffset); if (!href.isEmpty()) { emit OnURLSelected(href, tgt); } } - locate(pagelocate()); } return; } else if ((glt & ePicture) != 0) { qDebug("Big Picture:%x", pictgt); QImage* pm = buffdoc.getPicture(pictgt); if (pm != NULL) { emit OnShowPicture(*pm); delete pm; } else { - locate(pagelocate()); + update(); } return; } else if (img != NULL) { emit OnShowPicture(*img); return; } if (m_swapmouse) processmousepositionevent(_e); else processmousewordevent(startpos, startoffset, _e, lineno); } } else { mouseUpOn = true; } } } +} void QTReader::focusInEvent(QFocusEvent* e) { - if (m_autoScroll) timer->start(real_delay(), false); + if (m_autoScroll && (m_scrolltype != 4)) timer->start(real_delay(), false); update(); } void QTReader::focusOutEvent(QFocusEvent* e) { if (m_autoScroll) { + if (m_scrolltype != 4) + { timer->stop(); + } + else + { + m_autoScroll = false; + } // m_scrolldy1 = m_scrolldy2 = 0; } } #include <qapplication.h> #include <qdrawutil.h> #ifndef _WINDOWS #include <unistd.h> #endif void QTReader::goDown() { if (m_bpagemode) { dopagedn(); } else { lineDown(); } } void QTReader::goUp() { if (m_bpagemode) { dopageup(); } else { lineUp(); } } void QTReader::NavUp() { - buffdoc.unsuspend(); if (buffdoc.hasnavigation()) { /* size_t target = pagelocate(); if (buffdoc.back(target)) { locate(target); } */ locate(buffdoc.startSection()); } else { goUp(); } } void QTReader::NavDown() { - buffdoc.unsuspend(); if (buffdoc.hasnavigation()) { /* size_t target = pagelocate(); if (buffdoc.forward(target)) { locate(target); } */ dopageup(buffdoc.endSection()); } else { goDown(); } } void QTReader::zoomin() { if (m_fontControl.increasesize()) { bool sc = m_autoScroll; setautoscroll(false); setfont(); - locate(pagelocate()); - repaint(); + refresh(); setautoscroll(sc); } } void QTReader::zoomout() { if (m_fontControl.decreasesize()) { bool sc = m_autoScroll; setautoscroll(false); setfont(); - locate(pagelocate()); - repaint(); + refresh(); setautoscroll(sc); } } void QTReader::reduceScroll() { if (m_delay < 59049) { m_delay = (3*m_delay)/2; timer->changeInterval(real_delay()); } else { m_delay = 59049; } } void QTReader::increaseScroll() { if (m_delay > 454) { m_delay = (2*m_delay)/3; timer->changeInterval(real_delay()); } else { m_delay = 454; } } void QTReader::keyPressEvent(QKeyEvent* e) { - buffdoc.unsuspend(); //((QTReaderApp*)parent()->parent())->handlekey(e); emit HandleKeyRequest(e); // e->ignore(); return; #ifdef _SCROLLPIPE if (m_isPaused) { m_isPaused = false; if (e->key() != Key_Space) { m_autoScroll = false; if (m_pipeout != NULL) { pclose(m_pipeout); m_pipeout = NULL; } //((QTReaderApp*)parent()->parent())->setScrollState(m_autoScroll); emit SetScrollState(m_autoScroll); QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; } else { timer->start(real_delay(), false); } e->accept(); return; } #endif } void QTReader::CalculateScrollParameters() { int bmargin = ((m_scrollpos == 1) ? _SBARHEIGHT : 0); if (bmargin < m_bottommargin) bmargin = m_bottommargin; switch (m_scrolltype) { case 0: { if (m_scrolldy == m_topmargin) { m_scrolldy1 = 0; m_scrolldy2 = 0; m_totalscroll = 0; return; } if (m_scrolldy < textarray[0]->lineSpacing()) { m_scrolldy2 = m_scrolldy; return; } int ht = m_scrolldy - m_scrolldy1; int i; for (i = 0; (ht < ((m_rotated) ? width() : height())-bmargin) && (i < numlines); i++) { ht += textarray[i]->lineSpacing(); } ht = 0; int j; i--; for (j = i; j < numlines; j++) { ht += textarray[j]->lineSpacing(); } ht -= ( textarray[i]->lineExtraSpacing() + (i != 0) ? textarray[numlines-1]->lineExtraSpacing() : 0 )/2-2; m_scrolldy2 = m_scrolldy-ht; } break; case 1: case 2: case 3: { int ypos = m_topmargin; for (int i = 0; i < numlines; i++) { ypos += textarray[i]->lineSpacing(); } ypos -= ( textarray[0]->lineExtraSpacing() + ((numlines > 1) ? textarray[numlines-1]->lineExtraSpacing() : 0) )/2 + m_scrolldy1 - 2; m_scrolldy2 = ((m_rotated) ? width() : height()) - ypos - bmargin; } break; } } void QTReader::setautoscroll(bool _sc) { + m_outofdate = true; if (_sc == m_autoScroll) return; if (m_autoScroll) { m_autoScroll = false; #ifdef USEQPE QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; #endif #ifdef _SCROLLPIPE if (m_pipeout != NULL) { pclose(m_pipeout); m_pipeout = NULL; } #endif // m_scrolldy1 = 0; //refresh(); } else { CDrawBuffer* reusebuffer = textarray[numlines]; if (reusebuffer == NULL || reusebuffer->eof()) return; +#ifndef __STATIC + if ((m_scrolltype == 4) && !checkoutput()) return; +#endif m_autoScroll = true; CalculateScrollParameters(); #ifdef _SCROLLPIPE if (!m_pipetarget.isEmpty()) { // qDebug("Opening pipe to %s", (const char*)m_pipetarget); m_pipeout = popen((const char*)m_pipetarget, "w"); m_isPaused = false; } #endif autoscroll(); #ifdef USEQPE QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Disable; // light is even not dimmed #endif } } bool QTReader::getline(CDrawBuffer *buff) { - buffdoc.unsuspend(); bool bRet; int availht = ((m_rotated) ? width() : height()) - m_topmargin - m_bottommargin; if (m_bMonoSpaced) { bRet = buffdoc.getline(buff ,(m_rotated) ? height() : width(), m_charWidth, m_left_border, m_right_border, availht); } else { bRet = buffdoc.getline(buff, (m_rotated) ? height() : width(), m_left_border, m_right_border, hyphenate, availht); } buff->resize(availht); return bRet; } void QTReader::doscroll() { if (!m_autoScroll) { timer->stop(); return; } switch (m_scrolltype) { case 0: doinplacescroll(); break; case 1: dorollingscroll(false); break; case 2: dorollingscroll(true); break; case 3: dostaticscroll(); break; } } void QTReader::doinplacescroll() { QPainter p( this ); // p.setBackgroundMode(OpaqueMode); int wh, ht; int bmargin = ((m_scrollpos == 1) ? _SBARHEIGHT : 0); if (bmargin < m_bottommargin) bmargin = m_bottommargin; if (m_rotated) { ht = width()-bmargin; wh = height(); } else { ht = height()-bmargin; wh = width(); } int lastdy = m_scrolldy; m_scrolldy += m_scrollstep; if ((m_scrolldy1 = m_scrolldy1+m_scrollstep) >= textarray[0]->lineSpacing()) { int ht = textarray[0]->lineSpacing(); #ifdef _SCROLLPIPE if (m_pipeout != NULL) { QString outstr = toQString(textarray[0]->data()); if (!outstr.isEmpty()) { fprintf(m_pipeout, "%s\n", (const char*)outstr); fflush(m_pipeout); } else if (m_pauseAfterEachPara) { m_isPaused = true; timer->stop(); } } #endif CDrawBuffer* buff = textarray[0]; for (int i = 1; i <= numlines; i++) { textarray[i-1] = textarray[i]; locnarray[i-1] = locnarray[i]; } textarray[numlines] = buff; --numlines; m_scrolldy1 -= ht; } if ((m_scrolldy2 = m_scrolldy2+m_scrollstep) >= textarray[numlines]->lineSpacing()) { m_scrolldy2 -= textarray[numlines]->lineSpacing(); numlines++; if (textarray[numlines] == NULL) { textarray[numlines] = new CDrawBuffer(&m_fontControl); } locnarray[numlines] = locate(); int ch = getline(textarray[numlines]); if (m_rotated) { blitRot(width()-m_scrolldy, 0, height(), -1, textarray[numlines-1]); } else { if (m_bgpm.isNull()) { p.fillRect(m_left_border,m_scrolldy-textarray[numlines-1]->lineSpacing(),width()-(m_left_border+m_right_border),textarray[numlines-1]->lineSpacing(),m_bg); } else { int h_tmp = textarray[numlines-1]->lineSpacing(); bitBlt(this, m_left_border, m_scrolldy-h_tmp, dbuff, m_left_border, m_scrolldy-h_tmp, width()-(m_left_border+m_right_border), h_tmp); } textarray[numlines-1]->render(&p, m_scrolldy -textarray[numlines-1]->lineSpacing()+ textarray[numlines-1]->ascent(), m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg, height()-m_topmargin-m_bottommargin); } mylastpos = locate(); if (!ch) { - /* - if (m_rotated) - { - blitRot2(0,0,height(),width()-m_scrolldy,NULL); -// blitRot2(0,0,0,height(),width()-m_scrolldy,NULL); - } - else - { - if (m_bgpm.isNull()) - { - p.fillRect(0,m_scrolldy,width(),height()-m_scrolldy,m_bg); - } - else - { - bitBlt(this, 0, m_scrolldy, dbuff, 0, m_scrolldy, width(), height()-m_scrolldy); - } - } - */ m_scrolldy = m_topmargin; m_autoScroll = false; #ifdef _SCROLLPIPE for (int i = 0; i < numlines; i++) { if (m_pipeout != NULL) { QString outstr = toQString(textarray[i]->data()); if (!outstr.isEmpty()) { fprintf(m_pipeout, "%s\n", (const char*)outstr); fflush(m_pipeout); } } } #endif - //((QTReaderApp*)parent()->parent())->setScrollState(m_autoScroll); emit SetScrollState(m_autoScroll); #ifdef USEQPE QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; #endif } if (m_scrolldy > ht-textarray[numlines]->lineSpacing()) { if (m_rotated) { if (m_bgpm.isNull()) { p.fillRect(bmargin, m_left_border, ht-m_scrolldy, wh-(m_left_border+m_right_border), m_bg); } else { blitRot(bmargin, 0,height(), ht-m_scrolldy, NULL); } } else if (m_bgpm.isNull()) { p.fillRect(m_left_border,m_scrolldy,width()-(m_left_border+m_right_border),height()-m_scrolldy,m_bg); } else { bitBlt(this,m_left_border,m_scrolldy,dbuff,m_left_border,m_scrolldy,width()-(m_left_border+m_right_border), height()-m_scrolldy); } m_scrolldy = m_topmargin; m_scrolldy2 = 0; } redrawScroll(&p); emitRedraw(); lastdy = -1; } // else { if (m_rotated) { if (lastdy >= 0) { if (m_bgpm.isNull()) { p.fillRect(width()-lastdy, m_left_border, m_scrollstep, wh-(m_left_border+m_right_border),m_bg); } else { blitRot(width()-lastdy,m_left_border,wh-(m_left_border+m_right_border), m_scrollstep, NULL); } } p.fillRect(width()-m_scrolldy, m_left_border, 1,wh-(m_left_border+m_right_border),m_scrollcolor); } else { if (lastdy >= 0) { if (m_bgpm.isNull()) { p.fillRect(m_left_border,lastdy,width()-(m_left_border+m_right_border),m_scrollstep,m_bg); } else { bitBlt(this, m_left_border, lastdy, dbuff, m_left_border, lastdy, width()-(m_left_border+m_right_border), m_scrollstep); } } p.fillRect(m_left_border,m_scrolldy,width()-(m_left_border+m_right_border),1,m_scrollcolor); } } } void QTReader::dorollingscroll(bool _statbord) { bool bredrawscroll = false; QPainter p( this ); // 2 = right, 3 = left int tmargin = (_statbord) ? m_topmargin : 0; int lmargin = (m_scrollpos == 3 || _statbord) ? m_left_border : 0; int rmargin = (m_scrollpos == 2 || _statbord) ? m_right_border : 0; int hmargin = ((m_scrollpos == 1) ? _SBARHEIGHT : 0); if (hmargin < m_bottommargin) hmargin = m_bottommargin; if (m_rotated) { m_totalscroll = (m_totalscroll+m_scrollstep) % width(); bitBlt(this, m_scrollstep+hmargin, lmargin, this, hmargin, lmargin, width()-tmargin-hmargin, height()-(lmargin+rmargin)); if (!m_bgpm.isNull()) { blitRot(hmargin, tmargin, height(), m_scrollstep, NULL); } else { p.fillRect(hmargin, rmargin, m_scrollstep, height()-lmargin-rmargin, m_bg); } } else { m_totalscroll = (m_totalscroll+m_scrollstep) % height(); bitBlt(this,lmargin,tmargin,this,lmargin,tmargin+m_scrollstep,width()-(lmargin+rmargin),height() - tmargin - hmargin - m_scrollstep); if (m_bgpm.isNull()) { p.fillRect(0, height() - (m_scrollstep+1) - hmargin, width(), (m_scrollstep+1), m_bg); } else { int loff = (_statbord) ? 0 : m_totalscroll; bitBlt(this,0,height() - (m_scrollstep+1) - hmargin, dbuff, 0, (loff+height() - (m_scrollstep+1) - hmargin) % height(), width(), (m_scrollstep+1)); } } if ((m_scrolldy1 = m_scrolldy1+m_scrollstep) >= textarray[0]->lineSpacing()) { int ht = textarray[0]->lineSpacing(); bredrawscroll = true; #ifdef _SCROLLPIPE if (m_pipeout != NULL) { QString outstr = toQString(textarray[0]->data()); if (!outstr.isEmpty()) { fprintf(m_pipeout, "%s\n", (const char*)outstr); fflush(m_pipeout); } else if (m_pauseAfterEachPara) { m_isPaused = true; timer->stop(); } } #endif CDrawBuffer* buff = textarray[0]; for (int i = 1; i <= numlines; i++) { textarray[i-1] = textarray[i]; locnarray[i-1] = locnarray[i]; } textarray[numlines] = buff; --numlines; m_scrolldy1 -= ht; } if ((m_scrolldy2 = m_scrolldy2+m_scrollstep) >= textarray[numlines]->lineSpacing()) { bredrawscroll = true; m_scrolldy2 -= textarray[numlines]->lineSpacing(); numlines++; if (textarray[numlines] == NULL) { textarray[numlines] = new CDrawBuffer(&m_fontControl); } locnarray[numlines] = locate(); int ch = getline(textarray[numlines]); if (m_rotated) { blitRot(hmargin, 0, height(), -1, textarray[numlines-1]); } else { // textarray[numlines-1]->render(&p, height() - textarray[numlines-1]->descent() - 2 - hmargin, m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg); textarray[numlines-1]->render(&p, height() - textarray[numlines-1]->descent() - textarray[numlines-1]->lineExtraSpacing() - 1 - hmargin, m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg, height()-m_topmargin-m_bottommargin); } mylastpos = locate(); if (!ch) { redrawScroll(&p); emitRedraw(); m_autoScroll = false; #ifdef _SCROLLPIPE for (int i = 0; i < numlines; i++) { if (m_pipeout != NULL) { QString outstr = toQString(textarray[i]->data()); if (!outstr.isEmpty()) { fprintf(m_pipeout, "%s\n", (const char*)outstr); fflush(m_pipeout); } } } #endif emit SetScrollState(m_autoScroll); #ifdef USEQPE QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; #endif return; } } if (!bredrawscroll && ((m_scrolldy2/m_scrollstep) % 10 == 5) && textarray[numlines]->showPartial()) { if (m_rotated) { blitRot(hmargin + m_scrolldy2 - textarray[numlines]->lineSpacing(), 0, height(), -1, textarray[numlines]); } else { textarray[numlines]->render( &p, height() + textarray[numlines]->lineSpacing() - textarray[numlines]->descent() - 2 - hmargin-m_scrolldy2, m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg, height()-m_topmargin-m_bottommargin); } } if (m_scrollpos != 0) { redrawScroll(&p); } if (bredrawscroll) emitRedraw(); } void QTReader::dostaticscroll() { redrawall(); bool bredraw = false; if ((m_scrolldy1 = m_scrolldy1+m_scrollstep) >= textarray[0]->lineSpacing()) { int ht = textarray[0]->lineSpacing(); bredraw = true; #ifdef _SCROLLPIPE if (m_pipeout != NULL) { QString outstr = toQString(textarray[0]->data()); if (!outstr.isEmpty()) { fprintf(m_pipeout, "%s\n", (const char*)outstr); fflush(m_pipeout); } else if (m_pauseAfterEachPara) { m_isPaused = true; timer->stop(); } } #endif CDrawBuffer* buff = textarray[0]; for (int i = 1; i <= numlines; i++) { textarray[i-1] = textarray[i]; locnarray[i-1] = locnarray[i]; } textarray[numlines] = buff; --numlines; m_scrolldy1 -= ht; } if ((m_scrolldy2 = m_scrolldy2 + m_scrollstep) >= textarray[numlines]->lineSpacing()) { bredraw = true; m_scrolldy2 -= textarray[numlines]->lineSpacing(); numlines++; if (textarray[numlines] == NULL) { textarray[numlines] = new CDrawBuffer(&m_fontControl); } locnarray[numlines] = locate(); int ch = getline(textarray[numlines]); mylastpos = locate(); if (!ch) { redrawall(); emitRedraw(); m_autoScroll = false; #ifdef _SCROLLPIPE for (int i = 0; i < numlines; i++) { if (m_pipeout != NULL) { QString outstr = toQString(textarray[i]->data()); if (!outstr.isEmpty()) { fprintf(m_pipeout, "%s\n", (const char*)outstr); fflush(m_pipeout); } } } #endif emit SetScrollState(m_autoScroll); #ifdef USEQPE QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; #endif return; } } if (bredraw) emitRedraw(); } void QTReader::redrawScroll(QPainter* p) { int offset = (m_scrolltype == 1) ? m_totalscroll : 0; switch (m_scrollpos) { case 1: { int hmargin = ((m_scrollpos == 1) ? _SBARHEIGHT : 0); if (hmargin < m_bottommargin) hmargin = m_bottommargin; if (m_rotated) { if (m_bgpm.isNull()) { p->fillRect(0,0,hmargin,height(),m_bg); } else { blitRot(0,0, height(), hmargin, NULL); } } else { if (m_bgpm.isNull()) { p->fillRect(0,height() - hmargin,width(),hmargin,m_bg); } else { int toffset = (offset+height()-hmargin) % height(); if (toffset+hmargin > height()) { int fp = height()-toffset; bitBlt(this, 0,height() - hmargin, dbuff, 0, toffset, width(), fp); bitBlt(this, 0,height()-hmargin+fp, dbuff, 0, 0, width(), hmargin-fp); } else { bitBlt(this, 0,height() - hmargin, dbuff, 0, toffset, width(), hmargin); } } } } break; case 2: //right if (m_rotated) { if (m_bgpm.isNull()) { p->fillRect(0,height()-m_right_border,width(),m_right_border,m_bg); } else { blitRot(0,height()-m_right_border, m_right_border, width(), NULL); } } else { if (m_bgpm.isNull()) { p->fillRect(width()-m_right_border,0,m_right_border,height(),m_bg); } else { int x = width() - m_right_border; int fp = height()-offset; bitBlt(this, x, 0, dbuff, x, offset, m_right_border, fp); bitBlt(this, x, fp, dbuff, x, 0, m_right_border, height()-fp); } } break; case 3: //left if (m_rotated) { if (m_bgpm.isNull()) { p->fillRect(0,0,width(),m_left_border,m_bg); } else { blitRot(0,0, m_left_border, width(), NULL); } } else { if (m_bgpm.isNull()) { p->fillRect(0,0,m_left_border,height(),m_bg); } else { int fp = height()-offset; bitBlt(this, 0, 0, dbuff, 0, offset, m_left_border, fp); bitBlt(this, 0, fp, dbuff, 0, 0, m_left_border, height()-fp); } } break; case 0: default: break; } if (m_scrollpos != 0) DrawScroll(p, width(), height()); } void QTReader::autoscroll() { - drawBackground(); + if (m_scrolltype == 4) + { + readAloud(); + } + else + { + if (dbuff != NULL) + { + dbp->begin(dbuff); + drawBackground(dbp); dbp->end(); + } timer->start(real_delay(), false); } +} void QTReader::setfont() { // m_fontControl.Change m_charWidth = (m_charpc*m_fontControl.currentsize())/100; if (m_charWidth <= 0) m_charWidth = 1; m_ascent = m_fontControl.ascent(); m_descent = m_fontControl.descent(); m_linespacing = m_fontControl.lineSpacing(); } void QTReader::DrawStraight(QPainter* p, int w, int h) { if (m_scrolldy == m_topmargin) { int ypos = textarray[0]->ascent()-m_scrolldy1+m_topmargin; textarray[0]->render( p, ypos, m_bMonoSpaced, m_charWidth, w, m_left_border, m_right_border, m_bg, h-m_topmargin-m_bottommargin); int i; for (i = 1; i < numlines; i++) { ypos += (textarray[i-1]->descent() + textarray[i]->ascent())+ (textarray[i-1]->lineExtraSpacing() + textarray[i]->lineExtraSpacing())/2; textarray[i]->render( p, ypos, m_bMonoSpaced, m_charWidth, w, m_left_border, m_right_border, m_bg, h-m_topmargin-m_bottommargin); } if (textarray[i]->showPartial()) { ypos += (textarray[i-1]->descent() + textarray[i]->ascent())+ (textarray[i-1]->lineExtraSpacing() + textarray[i]->lineExtraSpacing())/2; textarray[i]->render( p, ypos, m_bMonoSpaced, m_charWidth, w, m_left_border, m_right_border, m_bg, h-m_topmargin-m_bottommargin); } } else { int ypos = textarray[0]->ascent()-m_scrolldy1+m_scrolldy+m_topmargin; textarray[0]->render( p, ypos, m_bMonoSpaced, m_charWidth, w, m_left_border, m_right_border, m_bg, h-m_topmargin-m_bottommargin); // p->fillRect(m_border, 0, w-2*m_border, m_scrolldy, m_bg); for (int i = 1; i < numlines; i++) { ypos += (textarray[i-1]->descent() + textarray[i]->ascent())+ (textarray[i-1]->lineExtraSpacing() + textarray[i]->lineExtraSpacing())/2; if (ypos+textarray[i]->descent() > h) { ypos = textarray[i]->ascent(); } textarray[i]->render( p, ypos, m_bMonoSpaced, m_charWidth, w, m_left_border, m_right_border, m_bg, h-m_topmargin-m_bottommargin); } p->fillRect(m_left_border,m_scrolldy,w-(m_left_border+m_right_border),1,m_scrollcolor); } bool wasrotated = m_rotated; m_rotated = false; DrawScroll(p, w, h); m_rotated = wasrotated; } void QTReader::redrawall() { if (m_rotated) { -#ifdef DOUBLEBUFFER - drawBackground(); + if (dbuff != NULL) + { + dbp->begin(dbuff); + drawBackground(dbp); DrawStraight(dbp, height(), width()); dbp->end(); QWMatrix m; m.rotate(90); QPixmap rp = dbuff->xForm(m); bitBlt(this, 0,0,&rp,0,0,-1,-1); -#else + } + else + { + qDebug("This shouldn't happen but it doesn't matter if it does (rotated == double buffered)"); QPixmap dbuff(height(), width()); QPainter dbp(&dbuff); - // dbp.setBackgroundMode(OpaqueMode); - dbp.fillRect(dbuff.rect(), m_bg); + drawBackground(&dbp); DrawStraight(&dbp, height(), width()); QWMatrix m; m.rotate(90); QPixmap rp = dbuff.xForm(m); bitBlt(this, 0,0,&rp,0,0,-1,-1); -#endif + } } else { -#ifdef DOUBLEBUFFER - drawBackground(); + if (dbuff != NULL) + { + dbp->begin(dbuff); + drawBackground(dbp); DrawStraight(dbp, width(), height()); dbp->end(); bitBlt(this, 0,0,dbuff,0,0,-1,-1); -#else - DrawStraight(p, width(), height()); -#endif + } + else + { + QPainter p(this); + drawBackground(&p); + DrawStraight(&p, width(), height()); + } } } void QTReader::drawFonts() { if (bDoUpdates) { int hmargin = ((m_scrollpos == 1) ? _SBARHEIGHT : 0); if (hmargin < m_bottommargin) hmargin = m_bottommargin; // qDebug("How refreshing..."); - if (buffdoc.empty()) return; - setfont(); - // if (!m_autoScroll) m_scrolldy1 = 0; -#ifdef ROTATION_ENABLED - if (m_lastwidth != ((m_rotated) ? height() : width())) + if (buffdoc.empty()) { - m_scrolldy = m_topmargin; - // qDebug("Not Optimised %d", m_lastwidth); - m_lastwidth = ((m_rotated) ? height() : width()); - m_lastheight = ((m_rotated) ? width() : height()); - buffdoc.setwidth(m_lastwidth-(m_left_border+m_right_border)); - locate(pagelocate()); - // qDebug("Not Optimised %d", m_lastwidth); + if (dbuff != NULL) + { + dbp->begin(dbuff); + drawBackground(dbp); + dbp->end(); } else { - int newht = ((m_rotated) ? width() : height()); - if (m_lastheight > newht) - { - // qDebug("Optimised < %d %d %d", numlines, m_lastheight, newht); - m_scrolldy = m_topmargin; - int ypos = m_scrolldy1+m_topmargin; - for (int i = 0; i < numlines; i++) - { - if ((ypos += textarray[i]->lineSpacing()) > newht - hmargin) - { - numlines = i; - jumpto(mylastpos = locnarray[i+1]); - break; - } + QPainter p(this); + drawBackground(&p); } - // qDebug("Optimised < %d", numlines); - m_lastheight = newht; + return; } - else if (m_lastheight < newht) + setfont(); + // if (!m_autoScroll) m_scrolldy1 = 0; + if (dbuff != NULL && (dbuff->width() != width() || dbuff->height() != height())) { - m_scrolldy = m_topmargin; - // qDebug("Optimised > %d", numlines); - int ypos = m_scrolldy1+m_topmargin; - for (int i = 0; i <= numlines; i++) + qDebug("Oh no! A resize event was missed..."); + if (m_rotated) { - ypos += textarray[i]->lineSpacing(); - } - fillbuffer(numlines+1, ypos, newht); - // qDebug("Optimised > %d", numlines); + dbuff->resize(height(), width()); } - if (numlines > 0) + else { - redrawall(); + dbuff->resize(width(), height()); } + m_lastwidth = 0; } -#else - if (m_lastwidth != width()) + if (m_lastwidth != ((m_rotated) ? height() : width())) { + m_scrolldy = m_topmargin; // qDebug("Not Optimised %d", m_lastwidth); - m_lastwidth = width(); - m_lastheight = height(); + m_lastwidth = ((m_rotated) ? height() : width()); + m_lastheight = ((m_rotated) ? width() : height()); buffdoc.setwidth(m_lastwidth-(m_left_border+m_right_border)); - locate(pagelocate()); + buffdoc.locate(pagelocate()); + fillbuffer(); + redrawall(); // qDebug("Not Optimised %d", m_lastwidth); } else { - int newht = height(); + int newht = ((m_rotated) ? width() : height()); if (m_lastheight > newht) { // qDebug("Optimised < %d %d %d", numlines, m_lastheight, newht); - int ypos = m_topmargin; + m_scrolldy = m_topmargin; + int ypos = m_scrolldy1+m_topmargin; for (int i = 0; i < numlines; i++) { if ((ypos += textarray[i]->lineSpacing()) > newht - hmargin) { numlines = i; jumpto(mylastpos = locnarray[i+1]); break; } } // qDebug("Optimised < %d", numlines); m_lastheight = newht; } else if (m_lastheight < newht) { + m_scrolldy = m_topmargin; // qDebug("Optimised > %d", numlines); - int ypos = m_topmargin; + int ypos = m_scrolldy1+m_topmargin; for (int i = 0; i <= numlines; i++) { ypos += textarray[i]->lineSpacing(); } fillbuffer(numlines+1, ypos, newht); // qDebug("Optimised > %d", numlines); } if (numlines > 0) { - int ypos = textarray[0]->ascent()+m_topmargin; - textarray[0]->render( p, ypos, m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg, height()-m_topmargin-m_bottommargin); -// int last = (m_showlast) ? numlines : numlines-1; -// for (int i = 1; i <= last; i++) - for (int i = 1; i < numlines; i++) - { -// ypos += (textarray[i-1]->lineSpacing() + textarray[i]->lineSpacing())/2; - ypos += (textarray[i-1]->descent() + textarray[i]->ascent())+ - (textarray[i-1]->lineExtraSpacing() + textarray[i]->lineExtraSpacing())/2; - textarray[i]->render( p, ypos, m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg, height()-m_topmargin-m_bottommargin); - } -// mylastpos = locate(); + redrawall(); } } -#endif emitRedraw(); } /* else { qDebug("Not so refreshing..."); } */ } void QTReader::DrawScroll( QPainter *p, int _w, int _h ) { if (!buffdoc.empty()) { QBrush checkered = QBrush( Dense4Pattern ); checkered.setColor(m_scrollbarcolor); switch (m_scrollpos) { case 1: if (m_rotated) { p->fillRect(0, 0, 2, _h, checkered); } else { p->fillRect(0, _h-2, _w, 2, checkered); } break; case 2: if (m_rotated) { p->fillRect(0, _h-2, _w, 2, checkered); } else { p->fillRect(_w-2, 0, 2, _h, checkered); } break; case 3: if (m_rotated) { p->fillRect(0, 0, _w, 2, checkered); } else { p->fillRect(0, 0, 2, _h, checkered); } break; case 0: default: break; } switch (m_scrollpos) { case 1: { int ht; if (m_rotated) { ht = _h; } else { ht = _w; } int sectionsize = (buffdoc.endSection()-buffdoc.startSection()); int mid = (ht*(locnarray[numlines]+locnarray[0]-2*buffdoc.startSection())+sectionsize)/(2*sectionsize); int sliderheight = ((locnarray[numlines]-locnarray[0])*ht+sectionsize/2)/sectionsize; int sliderpos; if (sliderheight < 10) { sliderheight = 10; sliderpos = mid-5; } else { sliderpos = (ht*(locnarray[0]-buffdoc.startSection())+sectionsize/2)/sectionsize; } if (m_rotated) { p->fillRect(0, sliderpos, 3, sliderheight, m_scrollbarcolor); } else { p->fillRect(sliderpos, _h-3, sliderheight, 3, m_scrollbarcolor); } } break; case 2: case 3: { int ht; if (m_rotated) { ht = _w; } else { ht = _h; } int sectionsize = (buffdoc.endSection()-buffdoc.startSection()); int mid = (ht*(locnarray[numlines]+locnarray[0]-2*buffdoc.startSection())+sectionsize)/(2*sectionsize); int sliderheight = ((locnarray[numlines]-locnarray[0])*ht+sectionsize/2)/sectionsize; int sliderpos; if (sliderheight < 10) { sliderheight = 10; sliderpos = mid-5; } else { sliderpos = (ht*(locnarray[0]-buffdoc.startSection())+sectionsize/2)/sectionsize; } if (m_rotated) { int hoff; if (m_scrollpos == 2) //right { hoff = _h-3; } else { hoff = 0; } p->fillRect(ht-sliderpos-sliderheight, hoff, sliderheight, 3, m_scrollbarcolor); } else { int hoff; if (m_scrollpos == 2) //right { hoff = _w-3; } else { hoff = 0; } p->fillRect(hoff, sliderpos, 3, sliderheight, m_scrollbarcolor); } } break; case 0: default: break; } } } /* void QTReader::DrawScroll( QPainter *p ) { if (m_border > 5 && !buffdoc.empty()) { int ht, wh; if (m_rotated) { ht = width(); wh = height()g; p->fillRect(0, wh-2, ht, 2, cyan); } else { ht = height(); wh = width(); p->fillRect(wh-2, 0, 2, ht, cyan); } int sectionsize = (buffdoc.endSection()-buffdoc.startSection()); int mid = (ht*(locnarray[numlines]+locnarray[0]-2*buffdoc.startSection())+sectionsize)/(2*sectionsize); if (m_rotated) { p->fillRect(ht-mid-5, wh-2, 10, 2, yellow); p->fillRect(ht-(ht*(locnarray[numlines]-buffdoc.startSection())+sectionsize/2)/sectionsize, wh-2, ((locnarray[numlines]-locnarray[0])*ht+sectionsize/2)/sectionsize, 2, magenta); } else { p->fillRect(wh-2, mid-5, 2, 10, yellow); p->fillRect(wh-2, (ht*(locnarray[0]-buffdoc.startSection())+sectionsize/2)/sectionsize, 2, ((locnarray[numlines]-locnarray[0])*ht+sectionsize/2)/sectionsize, magenta); } } } */ QString QTReader::firstword() { if (m_bMonoSpaced) { return toQString(textarray[0]->data()); } else { int start, end, len, j; for (j = 0; j < numlines; j++) { len = textarray[j]->length(); for (start = 0; start < len && !isalpha((*textarray[j])[start]); start++); if (start < len) break; } if (j < numlines) { QString ret = ""; for (end = start; end < len && isalpha((*textarray[j])[end]); end++) ret += (*textarray[j])[end]; if (ret.isEmpty()) ret = "Current position"; return ret; } else return "Current position"; } } // // Construct the QTReader with buttons. // bool QTReader::ChangeFont(int tgt) { return m_fontControl.ChangeFont(m_fontname, tgt); } void QTReader::init() { - buffdoc.unsuspend(); setBackgroundColor( m_bg ); buffdoc.setfilter(getfilter()); ChangeFont(m_textsize); setFocusPolicy(QWidget::StrongFocus); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(doscroll())); +#ifdef USETIMER + m_dragtimer = new QTimer(this); + connect(m_dragtimer, SIGNAL(timeout()), this, SLOT(actionDrag())); +#endif // QMessageBox::information(this, "init", m_lastfile, 1); setfont(); } // // Clean up // QTReader::~QTReader() { -#ifdef DOUBLEBUFFER + if (m_output != NULL) + { + delete m_output; + } + if (dbuff != NULL) + { delete dbuff; delete dbp; -#endif + } #ifdef USEQPE if (m_autoScroll) { QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; } #endif #ifdef _SCROLLPIPE if (m_pipeout != NULL) { fclose(m_pipeout); } #endif } // // Called when the print button is clicked. // /* void QTReader::printIt() { #ifndef QT_NO_PRINTER if ( printer->setup( this ) ) { QPainter paint; if ( !paint.begin( printer ) ) return; drawIt( &paint ); } #endif } */ // // Called when the widget needs to be updated. // -void QTReader::paintEvent( QPaintEvent * ) +void QTReader::paintEvent( QPaintEvent * p ) +{ + if ((dbuff != NULL) && !m_outofdate) + { + if (m_rotated) + { + if ((p->rect().width() != width()) || (p->rect().height() != height())) + { + qDebug("Partial paint"); + QRect r; + r.setTop(width()-p->rect().right()-1); + r.setLeft(p->rect().top()); + r.setHeight(p->rect().width()); + r.setWidth(p->rect().height()); + QPixmap p1(r.width(), r.height()); + bitBlt(&p1, QPoint(0, 0), dbuff, r); + QWMatrix m; + m.rotate(90); + QPixmap p2 = p1.xForm(m); + bitBlt(this, p->rect().left(), p->rect().top(), &p2, 0, 0, -1, -1); + } + else + { + qDebug("Full paint"); + QWMatrix m; + m.rotate(90); + QPixmap rp = dbuff->xForm(m); + bitBlt(this, 0,0,&rp,0,0,-1,-1); + } + } + else + { + //bitBlt(this, 0,0,dbuff,0,0,-1,-1); + bitBlt(this,p->rect().topLeft(),dbuff,p->rect()); + } + } + else { drawFonts(); } + m_outofdate = false; +} // // Called when the widget has been resized. // Moves the button group to the upper right corner // of the widget. /* void QTReader::resizeEvent( QResizeEvent * ) { // // qDebug("resize:(%u,%u)", width(), height()); // bgroup->move( width()-bgroup->width(), 0 ); } */ // // Create and display our widget. // /* int main( int argc, tchar **argv ) { QApplication app( argc, argv ); QTReader draw; app.setMainWidget( &draw ); draw.setCaption("Qt Example - Drawdemo"); draw.show(); return app.exec(); } */ +bool QTReader::locate(unsigned long n) +{ + m_outofdate = true; + m_lastwidth = 0; + locnarray[0] = n; + ResetScroll(); + update(); + return true; +} +/* bool QTReader::locate(unsigned long n) { //printf("Locate\n"); - buffdoc.unsuspend(); buffdoc.locate(n); // // qDebug("&buffdoc.located"); ResetScroll(); fillbuffer(); + m_outofdate = true; // // qDebug("&Buffer filled"); update(); // // qDebug("&Located"); emitRedraw(); return true; } - +*/ unsigned int QTReader::screenlines() { // int linespacing = (tight) ? m_ascent : m_ascent+m_descent; // return (height()-m_descent)/(m_linespacing); return (height()-2)/(m_linespacing); }; bool QTReader::fillbuffer(int reuse, int ht, int newht) { - buffdoc.unsuspend(); int hmargin = ((m_scrollpos == 1) ? _SBARHEIGHT : 0); if (hmargin < m_bottommargin) hmargin = m_bottommargin; if (ht < 0) ht = m_topmargin; if (buffdoc.empty()) return false; if (newht < 0) m_lastheight = (m_rotated) ? width() : height(); else m_lastheight = newht; int ch; bool ret = false; unsigned int oldpagepos = locnarray[reuse]; int lastypos = ht, ypos = ht; numlines = reuse; while (ypos < m_lastheight - hmargin || numlines < 2) { lastypos = ypos; if (textarray[numlines] == NULL) { textarray[numlines] = new CDrawBuffer(&m_fontControl); } locnarray[numlines] = locate(); int ch = getline(textarray[numlines]); ypos += textarray[numlines]->lineSpacing(); + /* + QString tmp = toQString(textarray[numlines]->data()); + printf("[%u, %u, %u](%s):%s\n", lastypos, m_lastheight-hmargin, ypos, + ((textarray[numlines]->showPartial()) ? "TRUE" : "FALSE"), + (const char*)tmp); + */ numlines++; if (!ch) { if (numlines - reuse == 1 /*&& locnarray[numlines] == buffdoc.locate()*/) { qDebug("FALSE"); + if (oldpagepos < buffdoc.endSection()) locate(oldpagepos); + else + dopageup(buffdoc.endSection()); return false; } else { qDebug("TRUE"); --numlines; mylastpos = locate(); return true; } } if (numlines > 1 && textarray[numlines-2]->isBop()) { --numlines; mylastpos = locate(); return true; } } --numlines; mylastpos = locate(); m_scrollpart = m_lastheight - lastypos - hmargin; if (m_autoScroll) { CalculateScrollParameters(); } return true; } void QTReader::dopagedn() { // qDebug("HEIGHT(2):%d", m_lastheight); - buffdoc.unsuspend(); ResetScroll(); int skip = 0, ypos = m_topmargin; if (locate() != mylastpos) { jumpto(mylastpos); } CDrawBuffer* reusebuffer = textarray[numlines]; if (reusebuffer != NULL) { if (reusebuffer->eof()) return; for (int i = 0; i <= m_overlap; i++) { int offset = numlines - m_overlap + i; reusebuffer = textarray[offset]; size_t reuselocn = locnarray[offset]; textarray[offset] = textarray[i]; textarray[i] = reusebuffer; // reusebuffer->empty(); locnarray[offset] = locnarray[i]; locnarray[i] = reuselocn; ypos += textarray[i]->lineSpacing(); skip++; } } if (numlines <= 1) { skip = 0; ypos = 0; qDebug("Doing extra skip"); } if (fillbuffer(skip, ypos)) { drawFonts(); } } void QTReader::dopageup() { dopageup(locnarray[(m_overlap < numlines) ? m_overlap : numlines/2]); } bool QTReader::synch(size_t start, size_t end) { jumpto(start); while (start++ < end) { tchar ch = getch(); if (ch == 10) return true; - if (ch == UEOF) return false; - if (ch == 6) return false; + if ((ch == UEOF) || (ch == 6)) + { + return false; + } } return false; } void QTReader::dopageup(unsigned int target) { - buffdoc.unsuspend(); ResetScroll(); CBufferFace<CDrawBuffer*> buff; CBufferFace<size_t> loc; - size_t delta, guess = 2*(locate()-pagelocate()), lastdelta = 0; + qDebug("dopageup:: locate():%u pagelocate():%u guess:%u", locate(), pagelocate(), guess); bool ch = true; int nbfl, ypos = m_topmargin; if (guess < 128) guess = 128; while (1) { // qDebug("Guess:%u", guess); ch = true; if (target < guess) { delta = 0; // 0 is a flag to say don't guess any more jumpto( (m_continuousDocument) ? 0 : buffdoc.startSection() ); } else if (!m_continuousDocument && (target - guess < buffdoc.startSection())) { delta = 0; // 0 is a flag to say don't guess any more + qDebug("Jumping to startsection:%d", buffdoc.startSection()); jumpto(buffdoc.startSection()); } else { delta = guess; if (!synch(target-delta, target-lastdelta)) { lastdelta = delta; if (guess < 4000) { guess <<= 1; continue; } else { jumpto(target-delta); } } } nbfl = 0; ypos = m_topmargin; while (locate() < target) { if (buff[nbfl] == NULL) buff[nbfl] = new CDrawBuffer(&m_fontControl); loc[nbfl] = locate(); ch = getline(buff[nbfl]); ypos += buff[nbfl]->lineSpacing(); nbfl++; if (!ch) break; } if (guess < 4000 && ypos < ((m_rotated) ? width() : height())-(m_bottommargin) && (delta != 0)) { for (int i = 0; i < nbfl; i++) { delete buff[i]; buff[i] = NULL; } guess <<= 1; continue; } break; } if (ch) { if (buff[nbfl] == NULL) buff[nbfl] = new CDrawBuffer(&m_fontControl); loc[nbfl] = locate(); int ch = getline(buff[nbfl]); nbfl++; } /* ypos = 0; numlines = 0; while (ypos < height() && numlines <= nbfl-1) { ypos += buff[nbfl - numlines - 1]->lineSpacing(); numlines++; } --numlines; */ ypos = m_topmargin; numlines = 0; while (ypos < ((m_rotated) ? width() : height())-m_bottommargin && numlines+2 <= nbfl) { ypos += buff[nbfl - numlines - 2]->lineSpacing(); numlines++; } if (numlines > 0) --numlines; if (numlines == 0 && nbfl > 1) numlines = 1; int offset = nbfl-1; offset -= numlines; ypos = m_topmargin; for (int i = 0; i <= numlines; i++) { delete textarray[i]; textarray[i] = buff[offset+i]; locnarray[i] = loc[offset + i]; ypos += textarray[i]->lineSpacing(); } #ifdef _WINDOWS for (i = 0; i < nbfl - numlines - 1; i++) #else for (int i = 0; i < nbfl - numlines - 1; i++) #endif { delete buff[i]; } while (ypos < ((m_rotated) ? width() : height())-m_bottommargin) { numlines++; locnarray[numlines] = locate(); if (textarray[numlines] == NULL) textarray[numlines] = new CDrawBuffer(&m_fontControl); if (!getline(textarray[numlines])) break; ypos += textarray[numlines]->lineSpacing(); } mylastpos = locate(); CalculateScrollParameters(); drawFonts(); // repaint(); } bool QTReader::load_file(const char *newfile, unsigned int _lcn) { // QMessageBox::information(this, "Name", name, 1); // QMessageBox::information(this, "load_file", newfile, 1); int prog = 0; bool bRC = false; unsigned int lcn = _lcn; + bDoUpdates = false; ResetScroll(); - if (m_lastfile == newfile) + if (m_lastfile == newfile && lcn == 0) { lcn = m_lastposn; } // QMessageBox::information(0, "Opening...", newfile); if (m_rotated) { m_lastwidth = height(); m_lastheight = width(); } else { m_lastwidth = width(); m_lastheight = height(); } if (buffdoc.openfile(this,newfile) == 0) { m_lastfile = newfile; buffdoc.setwidth(m_lastwidth-(m_left_border+m_right_border)); bRC = true; buffdoc.setContinuous(m_continuousDocument); qDebug("buffdoc.openfile done"); - locate(lcn); - qDebug("buffdoc.locate done"); } setfilter(getfilter()); qDebug("Updated"); + bDoUpdates = true; + locate(lcn); return bRC; } void QTReader::lineDown() { int ypos = m_topmargin; ResetScroll(); int offset = numlines; for (int i = 0; i <= numlines; i++) { if ((ypos += textarray[numlines-i]->lineSpacing()) > ((m_rotated) ? width() : height())) { offset = i-1; break; } } offset = numlines - offset; #ifdef _WINDOWS for (i = offset; i <= numlines; i++) #else for (int i = offset; i <= numlines; i++) #endif { CDrawBuffer* buff = textarray[i-offset]; textarray[i-offset] = textarray[i]; locnarray[i-offset] = locnarray[i]; textarray[i] = buff; } numlines = numlines - offset + 1; locnarray[numlines] = locate(); if (textarray[numlines] == NULL) { textarray[numlines] = new CDrawBuffer(&m_fontControl); } getline(textarray[numlines]); mylastpos = locate(); + m_outofdate = true; update(); } /* void QTReader::lineUp() { CBuffer** buff = textarray; unsigned int *loc = new unsigned int[numlines]; int cbptr = 0; if (locate() != mylastpos) jumpto(mylastpos); unsigned int target = locnarray[numlines-1]; if (buffdoc.hasrandomaccess()) { unsigned int delta = locate()-pagelocate(); if (delta < 64) delta = 64; do { delta <<= 1; if (delta >= target) { delta = target; jumpto(0); for (int i = 0; i < numlines; i++) { loc[i] = locate(); getline(buff[i]); } break; } jumpto(target-delta); do { buffdoc.getline(buff[0],width()); #ifdef WS //printf("Trying:%s\n",buff[0]); #endif if (locate() > target) continue; } while (!buffdoc.iseol()); for (int i = 0; i < numlines; i++) { loc[i] = locate(); buffdoc.getline(buff[i],width()); #ifdef WS //printf("Filling:%s\n",buff[i]); #endif } } while (locate() >= target && delta < 4096); #ifdef WS //printf("Delta:%u\n",delta); #endif } else { jumpto(0); for (int i = 0; i < numlines; i++) { loc[i] = locate(); buffdoc.getline(buff[i],width()); } } cbptr = 0; while (locate() < target) { loc[cbptr] = locate(); buffdoc.getline(buff[cbptr], width()); #ifdef WS //printf("Adding:%s\n",buff[cbptr]->data()); #endif cbptr = (cbptr+1) % numlines; } pagepos = loc[cbptr]; textarray = new CBuffer*[numlines]; for (int i = 0; i < numlines; i++) { int j = (cbptr+i)%numlines; textarray[i] = buff[j]; locnarray[i] = loc[j]; } delete [] buff; delete [] loc; mylastpos = locate(); update(); } */ void QTReader::ResetScroll() { m_totalscroll = 0; m_scrolldy1 = 0; m_scrolldy = m_topmargin; if (m_autoScroll && ((m_scrolltype == 0) || !m_bgpm.isNull())) { setautoscroll(false); } } void QTReader::lineUp() { dopageup(locnarray[numlines-1]); /* buffdoc.unsuspend(); ResetScroll(); CDrawBuffer* buff = textarray[numlines]; unsigned int loc; unsigned int end = locnarray[numlines]; int cbptr = 0; if (locate() != mylastpos) jumpto(mylastpos); unsigned int target = locnarray[0]; if (target == 0) return; if (!m_continuousDocument && (target == buffdoc.startSection())) return; if (buffdoc.hasrandomaccess()) { unsigned int delta = locate()-pagelocate(); if (delta < 64) delta = 64; do { delta <<= 1; if (delta >= target) { delta = target; jumpto(0); loc = locate(); getline(buff); break; } else if (!m_continuousDocument && (target - delta < buffdoc.startSection())) { delta = target-buffdoc.startSection(); jumpto(buffdoc.startSection()); loc = locate(); getline(buff); break; } jumpto(target-delta); do { getline(buff); #ifdef WS //printf("Trying:%s\n",buff[0]); #endif if (locate() > target) continue; } while (!buffdoc.iseol()); loc = locate(); getline(buff); } while (locate() >= target && delta < 4096); } else { jumpto(0); loc = locate(); getline(buff); } cbptr = 0; while (locate() < target) { loc = locate(); getline(buff); } for (int i = numlines; i > 0; i--) { textarray[i] = textarray[i-1]; locnarray[i] = locnarray[i-1]; } textarray[0] = buff; locnarray[0] = loc; int start = numlines; int ypos = m_topmargin; #ifdef _WINDOWS for (i = 0; i <= numlines; i++) #else for (int i = 0; i <= numlines; i++) #endif { ypos += textarray[i]->lineSpacing(); if (ypos > ((m_rotated) ? width() : height())) { start = i; ypos -= textarray[i]->lineSpacing(); break; } } jumpto(locnarray[start]); fillbuffer(start, ypos); repaint(); */ } bool QTReader::empty() { return buffdoc.empty(); } MarkupType QTReader::PreferredMarkup() { MarkupType m = buffdoc.PreferredMarkup(); if (m == cTEXT) { int ext = m_lastfile.findRev('.'); if (ext >= 0) { QString ft = m_lastfile.right(m_lastfile.length()-ext-1).upper(); if (ft.left(3) == "HTM") { m = cHTML; } } } return m; } -#ifdef DOUBLEBUFFER + void QTReader::resizeEvent( QResizeEvent * p ) { + qDebug("Resizing"); + m_outofdate = true; + if (dbuff != NULL) + { if (m_rotated) { dbuff->resize(p->size().height(),p->size().width()); } else { dbuff->resize(p->size()); } + } m_bgIsScaled = false; if (m_bgtype == bgStretched) { emit RefreshBitmap(); } { int h, w; if (m_rotated) { h = p->size().width(); w = p->size().height(); } else { w = p->size().width(); h = p->size().height(); } m_topmargin = (h*m_abstopmargin+500)/1000; m_bottommargin = (h*m_absbottommargin+500)/1000; m_left_border = (w*m_absleft_border+500)/1000; m_right_border = (w*m_absright_border+500)/1000; - - qDebug("Top margin:%u", m_topmargin ); - qDebug("Bottom margin:%u", m_bottommargin ); - qDebug("Left margin:%u", m_left_border ); - qDebug("Right margin:%u", m_right_border ); + } + if (dbuff != NULL && buffdoc.empty()) + { + dbp->begin(dbuff); + drawBackground(dbp); + dbp->end(); } } -#endif void QTReader::setrotated(bool sfs) { + qDebug("Rotating"); m_rotated = sfs; -#ifdef DOUBLEBUFFER - if (m_rotated) - { - dbuff->resize(height(), width()); - } - else - { - dbuff->resize(width(), height()); - } + setDoubleBuffer(m_doubleBuffered); m_bgIsScaled = false; -#endif + m_outofdate = true; + /* int h, w; if (m_rotated) { h = width(); w = height(); } else { w = width(); h = height(); } m_topmargin = (h*m_abstopmargin+500)/1000; m_bottommargin = (h*m_absbottommargin+500)/1000; m_left_border = (w*m_absleft_border+500)/1000; m_right_border = (w*m_absright_border+500)/1000; qDebug("Top margin:%u", m_topmargin ); qDebug("Bottom margin:%u", m_bottommargin ); qDebug("Left margin:%u", m_left_border ); qDebug("Right margin:%u", m_right_border ); + */ } -void QTReader::drawBackground() +void QTReader::drawBackground(QPainter *p) { - dbp->begin(dbuff); - // dbp->setBackgroundMode(OpaqueMode); - dbp->setBackgroundColor(m_bg); - dbp->eraseRect(dbuff->rect()); + // p->setBackgroundMode(OpaqueMode); + p->setBackgroundColor(m_bg); + if (dbuff != NULL) + { + p->eraseRect(dbuff->rect()); + } + else + { + if (m_rotated) + { + p->eraseRect(0,0,height(),width()); + } + else + { + p->eraseRect(rect()); + } + } if (!m_bgpm.isNull()) { - // dbp->setBackgroundMode(TransparentMode); + // p->setBackgroundMode(TransparentMode); switch (m_bgtype) { case bgCentred: { + if (dbuff == NULL) + { + p->drawPixmap(width(),height(),m_bgpm); + } + else + { int w = (dbuff->rect().width()-m_bgpm.width())/2; int h = (dbuff->rect().height()-m_bgpm.height())/2; - dbp->drawPixmap(w,h,m_bgpm); + p->drawPixmap(w,h,m_bgpm); + } } break; case bgTiled: { - dbp->drawTiledPixmap(0,0,dbuff->rect().width(),dbuff->rect().height(),m_bgpm); - /* - for (int h = 0; h < dbuff->rect().height(); h += m_bgpm.height()) - { - for (int w = 0; w < dbuff->rect().width(); w += m_bgpm.width()) + if (dbuff == NULL) { - dbp->drawPixmap(w,h,m_bgpm); + p->drawTiledPixmap(0,0,width(),height(),m_bgpm); } + else + { + p->drawTiledPixmap(0,0,dbuff->rect().width(),dbuff->rect().height(),m_bgpm); } - */ } break; case bgStretched: { if (!m_bgIsScaled) { m_bgIsScaled = true; QImage im = m_bgpm.convertToImage(); + if (dbuff == NULL) + { + m_bgpm.convertFromImage(im.smoothScale(width(),height())); + } + else + { m_bgpm.convertFromImage(im.smoothScale(dbuff->rect().width(), dbuff->rect().height())); } - dbp->drawPixmap(0,0,m_bgpm); + } + p->drawPixmap(0,0,m_bgpm); } break; default: qDebug("Unknown background type"); } - // dbp->setBackgroundMode(OpaqueMode); + // p->setBackgroundMode(OpaqueMode); } } void QTReader::blitRot(int dx, int dy, int sw, int sh, CDrawBuffer* txt) { if (txt != NULL) { sh = txt->lineSpacing(); } int sy = width()-dx-sh; if (m_autoScroll && !(m_scrolltype == 0)) { sy = (sy+m_totalscroll+1)%width(); } QPixmap pm(sw, sh); QPainter pd(&pm, this); if (m_bgpm.isNull()) { pd.eraseRect(pm.rect()); } else { if (sy+pm.height() > dbuff->height()) { // pd.eraseRect(pm.rect()); int fh = dbuff->height() - sy; if (sy+fh > dbuff->height()) { qDebug("Oh no!"); } if (fh > pm.height()) { qDebug("Oh no! - 2"); } bitBlt(&pm,0,0,dbuff,dy,sy,pm.width(),fh); bitBlt(&pm,0,fh,dbuff,dy,0,pm.width(),pm.height()-fh); } else { bitBlt(&pm,0,0,dbuff,dy,sy,pm.width(),pm.height()); } } if (txt != NULL) { // txt->render(&pd, txt->lineSpacing() - txt->descent() - txt->lineExtraSpacing(), m_bMonoSpaced, m_charWidth, sw, m_left_border, m_right_border, m_bg); txt->render(&pd, txt->lineSpacing() - txt->descent() - txt->lineExtraSpacing(), m_bMonoSpaced, m_charWidth, sw, m_left_border, m_right_border, m_bg, width()-m_topmargin-m_bottommargin); } QWMatrix m; m.rotate(90); QPixmap rp = pm.xForm(m); /* p.drawPixmap(QPoint(dx, dy), rp); */ bitBlt(this, dx, dy, &rp, 0, 0, -1, -1, CopyROP); } QString QTReader::about() { - return QString("QTReader widget (c) Tim Wentford\n")+buffdoc.about() + "\nMini-scrollbar by Markus Gritsch\nNavigation History fixes by Frantisek Dufka"; + QString ab = QString("QTReader widget (c) Tim Wentford\n")+buffdoc.about() + "\nMini-scrollbar by Markus Gritsch\nNavigation History fixes by Frantisek Dufka"; + if (m_output != NULL) + { + ab += QString("\n") + m_output->about(); + } + return ab; } void QTReader::getNextLink() { if (m_scrolldy != 0) { setautoscroll(false); ResetScroll(); redrawall(); } bool redraw = false; bool found = false; if (m_currentlink >= 0) { m_currentlinkoffset = textarray[m_currentlink]->invertLink(m_currentlinkoffset); if ((m_currentlinkstyle = textarray[m_currentlink]->getNextLink(m_currentlinkoffset)) != NULL) { qDebug("Found a link at %u", m_currentlinkoffset); int offset = textarray[m_currentlink]->invertLink(m_currentlinkoffset); qDebug("Finishes at %u", offset); found = true; } redraw = true; drawSingleLine(m_currentlink); // if (found) return; } if (!found) { m_currentlinkoffset = -1; for (int i = m_currentlink+1; i < numlines; ++i) { if ((m_currentlinkstyle = textarray[i]->getNextLink(m_currentlinkoffset)) != NULL) { m_currentlink = i; qDebug("Found a link at %u", m_currentlinkoffset); int offset = textarray[m_currentlink]->invertLink(m_currentlinkoffset); qDebug("Finishes at %u", offset); //drawSingleLine(i); redraw = true; found = true; drawSingleLine(m_currentlink); break; } } } if (redraw) { // redrawall(); } if (!found) { m_currentlink = -1; m_currentlinkstyle = NULL; m_currentlinkoffset = -1; dopagedn(); } } void QTReader::emitRedraw() { m_currentlinkstyle = NULL; m_currentlink = -1; m_currentlinkoffset = -1; emit OnRedraw(); }; void QTReader::drawSingleLine(int lineno) { QPainter p( this ); int ypos = textarray[0]->ascent()+m_topmargin; if (lineno == 0) { if (m_rotated) { blitRot(width()-(ypos+textarray[lineno]->descent()+textarray[lineno]->lineExtraSpacing()), 0, height(), -1, textarray[lineno]); } else { if (m_bgpm.isNull()) { p.fillRect(m_left_border,ypos-textarray[lineno]->ascent(),width()-(m_left_border+m_right_border),textarray[lineno]->lineSpacing(),m_bg); } else { bitBlt(this, m_left_border, ypos-textarray[lineno]->ascent(), dbuff, m_left_border, ypos-textarray[lineno]->ascent(), width()-(m_left_border+m_right_border), textarray[lineno]->lineSpacing()); } textarray[lineno]->render( &p, ypos, m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg, height()-m_topmargin-m_bottommargin); } } for (int i = 1; i < numlines; i++) { ypos += (textarray[i-1]->descent() + textarray[i]->ascent())+ (textarray[i-1]->lineExtraSpacing() + textarray[i]->lineExtraSpacing())/2; if (i == lineno) { if (m_rotated) { blitRot(width()-(ypos+textarray[i]->descent()+textarray[i]->lineExtraSpacing()), 0, height(), -1, textarray[i]); } else { if (m_bgpm.isNull()) { p.fillRect(m_left_border,ypos-textarray[lineno]->ascent(),width()-(m_left_border+m_right_border),textarray[lineno]->lineSpacing(),m_bg); } else { bitBlt(this, m_left_border, ypos-textarray[lineno]->ascent(), dbuff, m_left_border, ypos-textarray[lineno]->ascent(), width()-(m_left_border+m_right_border), textarray[lineno]->lineSpacing()); } textarray[i]->render( &p, ypos, m_bMonoSpaced, m_charWidth, width(), m_left_border, m_right_border, m_bg, height()-m_topmargin-m_bottommargin); } } } } void QTReader::gotoLink() { if (m_currentlinkstyle == NULL) return; textarray[m_currentlink]->invertLink(m_currentlinkoffset); size_t saveposn = pagelocate(); QString href, nm; unsigned long tgt = m_currentlinkstyle->getData(); unsigned long tgtoffset = m_currentlinkstyle->getOffset(); linkType lt = buffdoc.hyperlink(tgt, tgtoffset, href, nm); qDebug("URL(1):%s", (const char*)href); if ((lt & eFile) != 0) { buffdoc.saveposn(m_lastfile, saveposn); #ifdef USEQPE { QCopEnvelope e("QPE/System", "busy()"); } #endif ResetScroll(); if (!href.isEmpty()) { - if (!buffdoc.getFile(href)) + if (!buffdoc.getFile(href, nm)) { emit NewFileRequest(href); } else { ResetScroll(); fillbuffer(); + m_outofdate = true; update(); } } if (!nm.isEmpty()) { qDebug("QTReader:Finding %s", (const char*)nm); if (buffdoc.findanchor(nm)) { + buffdoc.resetPos(); fillbuffer(); + m_outofdate = true; update(); } } //fillbuffer(); //update(); #ifdef USEQPE { QCopEnvelope e("QPE/System", "notBusy()"); } #endif } else if ((lt & eLink) != 0) { buffdoc.saveposn(m_lastfile, saveposn); ResetScroll(); fillbuffer(); + m_outofdate = true; update(); } else { if ((lt & ePicture) != 0) { QImage* pm = buffdoc.getPicture(tgt); if (pm != NULL) { emit OnShowPicture(*pm); delete pm; } } else { // QString anchortext = textarray[lineno]->getanchortext(startoffset); if (!href.isEmpty()) { emit OnURLSelected(href, tgt); + refresh(); } } - locate(pagelocate()); } m_currentlinkstyle = NULL; m_currentlink = -1; m_currentlinkoffset = -1; } void QTReader::refresh(bool full) { + qDebug("Refreshing"); int h, w; if (m_rotated) { h = width(); w = height(); } else { w = width(); h = height(); } m_topmargin = (h*m_abstopmargin+500)/1000; m_bottommargin = (h*m_absbottommargin+500)/1000; m_left_border = (w*m_absleft_border+500)/1000; m_right_border = (w*m_absright_border+500)/1000; qDebug("Top margin:%u", m_topmargin ); qDebug("Bottom margin:%u", m_bottommargin ); qDebug("Left margin:%u", m_left_border ); qDebug("Right margin:%u", m_right_border ); if (full && m_highlightfilter) m_highlightfilter->refresh(pagelocate()); + m_outofdate = true; locate(pagelocate()); } + +#include "striphtml.h" + +CFilterChain* QTReader::getfilter() +{ + CFilterChain * filt = new CFilterChain(getencoding()); + if (bstripcr) filt->addfilter(new stripcr); + + if (btextfmt || (bautofmt && (PreferredMarkup() == cTEXT))) filt->addfilter(new textfmt); + if (bpeanut || (bautofmt && (PreferredMarkup() == cPML))) filt->addfilter(new PeanutFormatter); + // if (bstriphtml || (bautofmt && (PreferredMarkup() == cHTML))) filt->addfilter(new striphtml(m_lastfile)); + +#ifdef __STATIC + if (bstriphtml || (bautofmt && (PreferredMarkup() == cHTML))) filt->addfilter(new striphtml(m_lastfile)); + if (bautofmt && (PreferredMarkup() == cCHM)) + { + striphtml* f = new striphtml(m_lastfile); + f->setchm(true); + filt->addfilter(f); + } +#else + if (bstriphtml || (bautofmt && (PreferredMarkup() == cHTML))) filt->addfilter(new ExternFilter("HTMLfilter", m_lastfile)); + if (bautofmt && (PreferredMarkup() == cCHM)) + { + ExternFilter* f = new ExternFilter("HTMLfilter",m_lastfile); + ((striphtml*)f->filter())->setchm(true); + filt->addfilter(f); + } +#endif + m_highlightfilter = new HighlightFilter(this); + filt->addfilter(m_highlightfilter); + + if (bdehyphen) filt->addfilter(new dehyphen); + if (bunindent) filt->addfilter(new unindent); + if (brepara) filt->addfilter(new repara(m_reparastring)); + if (bonespace) filt->addfilter(new OnePara); + if (bindenter) filt->addfilter(new indenter(bindenter)); + if (bdblspce) filt->addfilter(new dblspce); + if (bdepluck) filt->addfilter(new DePluck(pluckernextpart)); + if (bdejpluck) filt->addfilter(new DePluck(jplucknextpart)); + if (brepalm) filt->addfilter(new repalm); + if (bunderlineLink) filt->addfilter(new underlineLink); + if (bkern) filt->addfilter(new kern); + if (bremap) filt->addfilter(new remap); + if (bmakebold) filt->addfilter(new embolden); + if (bfulljust) filt->addfilter(new FullJust); + int r,g,b; + m_default_bg.rgb(&r, &g, &b); + if (r != 255 || g != 255 || b != 255) + filt->addfilter(new setbg(r,g,b)); + m_default_fg.rgb(&r, &g, &b); + if (r != 0 || g != 0 || b != 0) + filt->addfilter(new setfg(r,g,b)); + // if (bNegative) filt->addfilter(new makeNegative); + if (bInverse) filt->addfilter(new makeInverse); + if (bNoInlineTables) filt->addfilter(new tableLink); + return filt; +} + +void QTReader::readAloud() +{ +#ifdef __STATIC + return; +#else + CBuffer para; + jumpto(pagelocate()); + while (m_autoScroll && (buffdoc.getpara(para) != -1)) + { + if (para.length() > 0) + { + unsigned long lastpos = buffdoc.explocate(); + while (lastpos > mylastpos) + { + dopagedn(); + qApp->processEvents(); + } + jumpto(lastpos); + QString txt = toQString(para.data()); + + doOutput(txt); + } + qApp->processEvents(); + } +#endif +} + +bool QTReader::doOutput(const QString& wrd) +{ + if (m_output != NULL) + { + m_output->output(wrd); + return true; + } + else + { + return false; + } +} + +bool QTReader::checkoutput() +{ + if (m_output == NULL) + { + m_output = new outputcodec(m_outputName); + if (reinterpret_cast<outputcodec*>(m_output)->getStatus() != 0) + { + delete m_output; + m_output = NULL; + QMessageBox::warning(this, PROGNAME, QString("Couldn't find output codec\n")+m_outputName); + return false; + } + } + return true; +} diff --git a/noncore/apps/opie-reader/QTReader.h b/noncore/apps/opie-reader/QTReader.h index 3bcdde4..9daa07a 100644 --- a/noncore/apps/opie-reader/QTReader.h +++ b/noncore/apps/opie-reader/QTReader.h @@ -1,415 +1,375 @@ #ifndef __QTREADER_H #define __QTREADER_H //#define _SCROLLPIPE #include <qwidget.h> //#include <qpainter.h> #include "my_list.h" #include "BuffDoc.h" #include "FontControl.h" //#include <qtimer.h> class CDrawBuffer; //class CBuffer; #include <qpixmap.h> class QPainter; class QTimer; class QImage; #include "BGType.h" -#include "striphtml.h" -#define ROTATION_ENABLED #define SPECIALSCROLL -#define DOUBLEBUFFER -#ifdef DOUBLEBUFFER + class QPainter; -#endif +class COutput; class CStyle; +#define USETIMER class QTReader : public QWidget { Q_OBJECT friend class QTReaderApp; -#ifdef DOUBLEBUFFER +#ifdef USETIMER + QTimer* m_dragtimer; + unsigned long m_dragtarget; +#endif + COutput* m_output; + bool checkoutput(); + bool m_outofdate, m_drageligible; QPixmap *dbuff; QPainter* dbp; -#endif void drawSingleLine(int lineno); void gotoLink(); void emitRedraw(); CStyle* m_currentlinkstyle; int m_currentlink; int m_currentlinkoffset; QPixmap m_bgpm; bool m_bgIsScaled; bground m_bgtype; int m_scrollpos; unsigned short m_scrollstep; void blitRot(int dx, int sx, int sw, int sh, CDrawBuffer* txt); void setBackgroundBitmap(const QPixmap& _pm, bground bg) { m_bgpm = _pm; m_bgtype = bg; m_bgIsScaled = false; } QColor m_bg, m_default_bg, m_default_fg, m_negative_fg; static tchar pluckernextpart[]; static tchar jplucknextpart[]; CList<Bkmk>* pBkmklist; void setHyphenThreshold(int _v) { buffdoc.setHyphenThreshold(_v); } void ResetScroll(); void increaseScroll(); void reduceScroll(); void drawText(QPainter& p, int x, int y, tchar* text); void DrawScroll( QPainter *p, int w, int h ); void dorollingscroll(bool); void doinplacescroll(); void dostaticscroll(); void suspend(); void redrawScroll(QPainter* p); int m_delay, m_scrolltype; unsigned int m_overlap; bool m_autoScroll, m_swapmouse; - void drawBackground(); -#ifdef ROTATION_ENABLED + void drawBackground(QPainter*); bool m_rotated; void setrotated(bool); -#endif void autoscroll(); QTimer* timer; int m_scrolldy1, m_scrolldy2, m_encd, m_scrollpart, m_totalscroll; void focusInEvent(QFocusEvent*); void focusOutEvent(QFocusEvent*); void processmousepositionevent( QMouseEvent* _e ); void processmousewordevent(size_t startpos, size_t startoffset, QMouseEvent* _e, int lineno); bool ChangeFont(int); bool getline(CDrawBuffer*); int m_charWidth; int m_charpc; unsigned short m_absleft_border, m_absright_border; unsigned short m_left_border, m_right_border; FontControl m_fontControl; void setBaseSize(unsigned char _s) { m_fontControl.setBaseSize(_s); } unsigned char getBaseSize() { return m_fontControl.getBaseSize(); } + QString m_outputName; #ifdef _SCROLLPIPE FILE* m_pipeout; QString m_pipetarget; bool m_isPaused; bool m_pauseAfterEachPara; #endif public: QTReader( QWidget *parent=0, const char *name=0, WFlags f = 0); // QTReader( const QString& filename, QWidget *parent=0, const tchar *name=0, WFlags f = 0); ~QTReader(); QString about(); + void readAloud(); CList<Bkmk>* Bkmklist() { return pBkmklist; } void setBackground(const QColor& _c) { m_default_bg = _c; reset_bg(); } void setForeground(const QColor& _c) { m_default_fg = _c; int r,g,b; m_default_fg.rgb(&r, &g, &b); r = 255-r; g = 255-g; b = 255-b; m_negative_fg.setRgb(r,g,b); } void zoomin(); void zoomout(); void setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen) { buffdoc.setSaveData(data, len, src, srclen); } void putSaveData(unsigned char*& src, unsigned short& srclen) { buffdoc.putSaveData(src, srclen); } bool empty(); void setContinuous(bool _b); void toggle_autoscroll(); void setautoscroll(bool); void disableAutoscroll() { m_autoScroll = false; } void copy() { /* size_t nd = locate(); jumpto(m_mark); QString text; while (m_mark < nd) { text += buffdoc.getch(); m_mark++; } QApplication::clipboard()->setText(text); jumpto(nd); */ }; void clear() {}; - void setText(const QString& n, const QString& s) { m_string = n; load_file((const char*)s); }; + void setText(const QString& n, const QString& s, unsigned int lcn = 0) { m_string = n; load_file((const char*)s, lcn); }; /* void setText(bool oldfile) { if (oldfile) { m_string = m_lastfile; load_file((const tchar*)m_string); } else { m_string = QString::null; } }; */ void setlead(int _lead) { m_fontControl.setlead(_lead); } int getlead() { return m_fontControl.getlead(); } void setextraspace(int _lead) { m_fontControl.setextraspace(_lead); } int getextraspace() { return m_fontControl.getextraspace(); } void setpagemode(bool _b) { m_bpagemode = _b; } void setmono(bool _b) { m_bMonoSpaced = _b; ChangeFont(m_fontControl.currentsize()); locate(pagelocate()); } void setencoding(int _f) { m_encd = _f; setfilter(getfilter()); } MarkupType PreferredMarkup(); CEncoding* getencoding() { // qDebug("m_encd:%d", m_encd); switch (m_encd) { case 4: // qDebug("palm"); return new CPalm; case 1: // qDebug("utf8"); return new CUtf8; case 2: // qDebug("ucs16be"); return new CUcs16be; case 3: // qDebug("ucs16le"); return new CUcs16le; case 0: // qDebug("ascii"); return new CAscii; default: return new CGeneral8Bit(m_encd-MAX_ENCODING+1); } } HighlightFilter* m_highlightfilter; - CFilterChain* getfilter() - { - CFilterChain * filt = new CFilterChain(getencoding()); - if (bstripcr) filt->addfilter(new stripcr); - - if (btextfmt || (bautofmt && (PreferredMarkup() == cTEXT))) filt->addfilter(new textfmt); - if (bpeanut || (bautofmt && (PreferredMarkup() == cPML))) filt->addfilter(new PeanutFormatter); - // if (bstriphtml || (bautofmt && (PreferredMarkup() == cHTML))) filt->addfilter(new striphtml(m_lastfile)); - -#ifdef __STATIC - if (bstriphtml || (bautofmt && (PreferredMarkup() == cHTML))) filt->addfilter(new striphtml(m_lastfile)); - if (bautofmt && (PreferredMarkup() == cCHM)) - { - filt->addfilter(new striphtml(m_lastfile)); - } -#else - if (bstriphtml || (bautofmt && (PreferredMarkup() == cHTML))) filt->addfilter(new ExternFilter("HTMLfilter", m_lastfile)); - if (bautofmt && (PreferredMarkup() == cCHM)) - { - ExternFilter* f = new ExternFilter("HTMLfilter",m_lastfile); - ((striphtml*)f->filter())->setchm(true); - filt->addfilter(f); - } -#endif - m_highlightfilter = new HighlightFilter(this); - filt->addfilter(m_highlightfilter); - - if (bdehyphen) filt->addfilter(new dehyphen); - if (bunindent) filt->addfilter(new unindent); - if (brepara) filt->addfilter(new repara(m_reparastring)); - if (bonespace) filt->addfilter(new OnePara); - if (bindenter) filt->addfilter(new indenter(bindenter)); - if (bdblspce) filt->addfilter(new dblspce); - if (bdepluck) filt->addfilter(new DePluck(pluckernextpart)); - if (bdejpluck) filt->addfilter(new DePluck(jplucknextpart)); - if (brepalm) filt->addfilter(new repalm); - if (bkern) filt->addfilter(new kern); - if (bremap) filt->addfilter(new remap); - if (bmakebold) filt->addfilter(new embolden); - if (bfulljust) filt->addfilter(new FullJust); - int r,g,b; - m_default_bg.rgb(&r, &g, &b); - if (r != 255 || g != 255 || b != 255) - filt->addfilter(new setbg(r,g,b)); - m_default_fg.rgb(&r, &g, &b); - if (r != 0 || g != 0 || b != 0) - filt->addfilter(new setfg(r,g,b)); - // if (bNegative) filt->addfilter(new makeNegative); - if (bInverse) filt->addfilter(new makeInverse); - return filt; - } - + CFilterChain* getfilter(); private slots: +#ifdef USETIMER + void actionDrag(); +#endif void dopageup(); void lineDown(); void lineUp(); void dopagedn(); void goHome(); void goBack(); void goForward(); void doscroll(); void paintEvent( QPaintEvent * ); -#ifdef DOUBLEBUFFER + void resizeEvent( QResizeEvent * p ); -#endif + void keyPressEvent(QKeyEvent*); private: // void drawIt( QPainter * ); void redrawall(); void drawFonts(); void DrawStraight(QPainter* p, int w, int h); QColor m_scrollcolor, m_scrollbarcolor; void setTwoTouch(bool _b); void init(); + void mouseMoveEvent( QMouseEvent* ); void mousePressEvent( QMouseEvent* ); void mouseReleaseEvent( QMouseEvent* ); // void mouseDoubleClickEvent( QMouseEvent* ); QString m_string, m_fontname, m_reparastring; void setfont(); + bool m_doubleBuffered; + + void setDoubleBuffer(bool _b); //myoutput stuff private: #ifdef SPECIALSCROLL int m_scrolldy; #endif bool mouseUpOn; - linkType getcurrentpos(int x, int y, int w, int h, int& lineno, size_t& start, size_t& offset, size_t& tgt, size_t& tgtoffset, size_t& pictgt, QImage*&); + linkType getcurrentpos(int x, int y, int w, int h, int& lineno, size_t& start, size_t& offset, size_t& tgt, size_t& tgtoffset, size_t& pictgt, QImage*&, size_t&); bool m_twotouch, m_touchone; size_t m_startpos, m_startoffset; void dopageup(unsigned int); long real_delay(); int m_textsize; int m_lastwidth, m_lastheight; CBufferFace<CDrawBuffer*> textarray; CBufferFace<size_t> locnarray; unsigned int numlines; // bool m_showlast; - bool bstripcr, btextfmt, bstriphtml, bdehyphen, bdepluck, bdejpluck, bunindent, brepara, bdblspce, btight, bmakebold, bremap, bpeanut, bautofmt, bonespace, bfulljust, /*bNegative,*/ bInverse; - bool bkern, brepalm; + bool bstripcr, btextfmt, bstriphtml, bdehyphen, bdepluck, bdejpluck, bunindent, brepara, bdblspce, btight, bmakebold, bremap, bpeanut, bautofmt, bonespace, bfulljust, /*bNegative,*/ bInverse, bNoInlineTables; + bool bkern, brepalm, bunderlineLink; bool m_bpagemode, m_bMonoSpaced, m_continuousDocument; unsigned char bindenter; QString m_lastfile; size_t m_lastposn; bool bDoUpdates; public: + bool doOutput(const QString& wrd); void setDoUpdates(bool b) { bDoUpdates = b; } void setStripCR(bool b) { bstripcr = b; } void NavUp(); void NavDown(); tchar getch() { return buffdoc.getch(); } bool synch(size_t, size_t); bool tight; bool load_file(const char *newfile, unsigned int lcn=0); BuffDoc buffdoc; CList<Bkmk>* getbkmklist() { return buffdoc.getbkmklist(); } bool locate(unsigned long n); void jumpto(unsigned long n) { buffdoc.locate(n); } unsigned long locate() { return buffdoc.locate(); } unsigned long explocate() { return buffdoc.explocate(); } unsigned long pagelocate() { return locnarray[0]; } unsigned long mylastpos; void getNextLink(); void setfilter(CFilterChain *f) { buffdoc.setfilter(f); if (bDoUpdates) locate(pagelocate()); } void restore() { jumpto(mylastpos); } void goUp(); void refresh(bool full = false); void goDown(); // bool bold; int textsize() { return m_textsize; } void textsize(int ts) { m_textsize = ts; } bool fillbuffer(int ru = 0, int ht = -1, int newht = -1); void CalculateScrollParameters(); unsigned int screenlines(); void sizes(unsigned long& fs, unsigned long& ts) { buffdoc.sizes(fs,ts); } static const char *fonts[]; // unsigned int *fontsizes; int m_ascent, m_descent, m_linespacing; int m_topmargin, m_bottommargin; int m_abstopmargin, m_absbottommargin; QFontMetrics* m_fm; QString firstword(); bool hyphenate; void reset_bg() { int r,g,b; m_default_bg.rgb(&r, &g, &b); if (bInverse) { r = 255-r; g = 255-g; b = 255-b; } m_bg.setRgb(r,g,b); /* int h,s,v; m_bg.hsv(&h, &s, &v); if (bNegative) { v = 255-v; m_bg.setHsv(h,s,v); } */ setBackgroundColor( m_bg ); } void setInverse(bool b) { bInverse = b; reset_bg(); } /* void setNegative() { bNegative = !bNegative; reset_bg(); } */ signals: void OnRedraw(); void OnWordSelected(const QString&, size_t, size_t, const QString&); void OnShowPicture(QImage&); void OnURLSelected(const QString&, const size_t); void NewFileRequest(const QString&); void HandleKeyRequest(QKeyEvent*); void SetScrollState(bool); void RefreshBitmap(); }; #endif diff --git a/noncore/apps/opie-reader/QTReaderApp.cpp b/noncore/apps/opie-reader/QTReaderApp.cpp index 876b65a..6753698 100644 --- a/noncore/apps/opie-reader/QTReaderApp.cpp +++ b/noncore/apps/opie-reader/QTReaderApp.cpp @@ -1,4963 +1,5069 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. Allrights reserved. ** ** This file is part of Qt Palmtop Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ + #include <qregexp.h> #include <qclipboard.h> #include <qwidgetstack.h> #ifdef USEQPE #include <qpe/qpemenubar.h> #include <qpe/qpetoolbar.h> #endif #include <qmenubar.h> #include <qtoolbar.h> #ifdef USEQPE #include <qpe/menubutton.h> #endif #include <qcombobox.h> #include <qpopupmenu.h> #include <qaction.h> #include <qapplication.h> #include <qlineedit.h> #include <qtoolbutton.h> #include <qspinbox.h> #include <qobjectlist.h> #include <qstatusbar.h> #ifdef USEQPE #include <qpe/global.h> #include <qpe/applnk.h> #endif #include <qfileinfo.h> #include <stdlib.h> //getenv #include <qprogressbar.h> #ifdef USEQPE #include <qpe/config.h> #endif #include <qbuttongroup.h> #include <qradiobutton.h> #ifdef USEQPE #include <qpe/qcopenvelope_qws.h> #endif #include "QTReader.h" #include "GraphicWin.h" #include "Bkmks.h" #include "cbkmkselector.h" #include "infowin.h" #include "ToolbarPrefs.h" #include "Prefs.h" #include "CAnnoEdit.h" #include "QFloatBar.h" #include "FixedFont.h" #include "URLDialog.h" #include "util.h" #include <qfontdatabase.h> + #ifdef USEQPE #include <qpe/resource.h> #ifdef OPIE -//#include <qpe/applnk.h> +#if defined(OPIEFILEDIALOG) +#include <qpe/applnk.h> #include <opie2/ofiledialog.h> using namespace Opie::Ui; #else #include "fileBrowser.h" #endif #else +#include "fileBrowser.h" +#endif +#else #include "qfiledialog.h" #endif #include "QTReaderApp.h" #include "CDrawBuffer.h" #include "Filedata.h" #include "names.h" #include "CEncoding_tables.h" #include "CloseDialog.h" #include "ButtonPrefs.h" -bool CheckVersion(int&, int&, char&); +bool CheckVersion(int&, int&, char&, QWidget*); #ifdef _WINDOWS #define PICDIR "c:\\uqtreader\\pics\\" #else #ifdef USEQPE #define USEMSGS #define PICDIR "opie-reader/" #else //#define PICDIR "/home/tim/uqtreader/pics/" QString picdir() { QString hd(getenv("READERDIR")); return hd + "/pics"; } #define PICDIR picdir() #endif #endif unsigned long QTReaderApp::m_uid = 0; void QTReaderApp::setScrollState(bool _b) { m_scrollButton->setOn(_b); } #ifdef USEQPE #define geticon(iconname) Resource::loadPixmap( iconname ) #define getmyicon(iconname) Resource::loadPixmap( PICDIR iconname ) #else //#define geticon(iconname) QPixmap(PICDIR iconname ".png") #define geticon(iconname) QPixmap(PICDIR +"/"+iconname+".png") #define getmyicon(iconname) geticon(iconname) //#define geticon(iconname) QIconSet( QPixmap(PICDIR iconname) ) #endif #ifndef _WINDOWS #include <unistd.h> #endif #include <stddef.h> #ifndef _WINDOWS #include <dirent.h> #endif void QTReaderApp::listBkmkFiles() { bkmkselector->clear(); bkmkselector->setText("Cancel"); #ifndef USEQPE int cnt = 0; QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } d.setFilter( QDir::Files | QDir::NoSymLinks ); // d.setSorting( QDir::Size | QDir::Reversed ); const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); // create list iterator QFileInfo *fi; // pointer for traversing - while ( (fi=it.current()) ) { // for each file... - bkmkselector->insertItem(fi->fileName()); - cnt++; + bkmkselector->insertItem(fi->fileName(), cnt++); //qDebug( "%10li %s", fi->size(), fi->fileName().data() ); ++it; // goto next list element } #else /* USEQPE */ int cnt = 0; DIR *d; d = opendir((const char *)Global::applicationFileName(APPDIR,"")); while(1) { struct dirent* de; struct stat buf; de = readdir(d); if (de == NULL) break; if (lstat((const char *)Global::applicationFileName(APPDIR,de->d_name),&buf) == 0 && S_ISREG(buf.st_mode)) { - bkmkselector->insertItem(de->d_name); - cnt++; + bkmkselector->insertItem(de->d_name, cnt++); } } closedir(d); #endif if (cnt > 0) { //tjw menu->hide(); editorStack->raiseWidget( bkmkselector ); hidetoolbars(); m_nBkmkAction = cRmBkmkFile; } else QMessageBox::information(this, PROGNAME, "No bookmark files"); } void QTReaderApp::hidetoolbars() { if (m_scrollbar != NULL) m_scrollbar->hide(); if (m_prog != NULL) m_prog->hide(); -#ifdef USEQPE +#if defined(USEQPE) menubar->hide(); #endif if (m_scrollbar != NULL) m_scrollbar->hide(); if (fileBar != NULL) fileBar->hide(); if (viewBar != NULL) viewBar->hide(); if (navBar != NULL) navBar->hide(); if (markBar != NULL) markBar->hide(); if (m_fontVisible) m_fontBar->hide(); if (regVisible) { #ifdef USEQPE Global::hideInputMethod(); #endif regBar->hide(); } if (searchVisible) { #ifdef USEQPE Global::hideInputMethod(); #endif searchBar->hide(); } } QTReaderApp::QTReaderApp( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), m_dontSave(false), fileBar(NULL), navBar(NULL), viewBar(NULL), markBar(NULL), m_scrollbar(NULL), m_localscroll(2), m_hidebars(false), m_kmapchanged(false) { { setKeyCompression ( true ); #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); QFileInfo fi(d, ".keymap"); FILE* f = fopen((const char *)fi.absFilePath(), "r"); #else /* USEQPE */ FILE* f = fopen((const char *)Global::applicationFileName(APPDIR,".keymap"), "r"); #endif /* USEQPE */ if (f != NULL) { uint cnt; if ((fread(&cnt, sizeof(cnt), 1, f) != 0) && (cnt == KEYMAPVERSION)) { if (fread(&cnt, sizeof(cnt), 1, f) == 0) cnt = 0; for (uint i = 0; i != cnt; i++) { orKey key; int data; fread(&key, sizeof(key), 1, f); fread(&data, sizeof(data), 1, f); kmap[key] = data; } } fclose(f); } } m_url_clipboard = false; m_url_localfile = false; m_url_globalfile = false; ftime(&m_lastkeytime); //// qDebug("Application directory = %s", (const tchar *)QPEApplication::documentDir()); //// qDebug("Application directory = %s", (const tchar *)Global::applicationFileName("uqtreader","bkmks.xml")); m_bcloseDisabled = true; m_disableesckey = false; pBkmklist = NULL; pOpenlist = NULL; // doc = 0; m_fBkmksChanged = false; QString lang = getenv( "LANG" ); QString rot = getenv( "QWS_DISPLAY" ); /* int m_rot = 0; if (rot.contains("Rot90")) { m_rot = 90; } else if (rot.contains("Rot180")) { m_rot = 180; } else if (rot.contains("Rot270")) { m_rot = 270; } // qDebug("Initial Rotation(%d):%s", m_rot, (const char*)rot); */ m_autogenstr = "^ *[A-Z].*[a-z] *$"; #ifdef USEQPE setIcon( Resource::loadPixmap( PICDIR "uqtreader") ); #else setIcon( QPixmap (PICDIR + "/uqtreader.png") ); #endif /* USEQPE */ // QPEToolBar *bar = new QPEToolBar( this ); // menubar = new QPEToolBar( this ); #ifdef USEQPE Config config( APPDIR ); #else QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } QFileInfo fi(d, INIFILE); // qDebug("Path:%s", (const char*)fi.absFilePath()); Config config(fi.absFilePath()); #endif config.setGroup("Toolbar"); m_tbmovesave = m_tbmove = config.readBoolEntry("Movable", false); m_tbpolsave = m_tbpol = (ToolbarPolicy)config.readNumEntry("Policy", 1); m_tbposition = (ToolBarDock)config.readNumEntry("Position", 2); m_qtscroll = config.readNumEntry("QTScrollBar", false); m_localscroll = config.readNumEntry("LocalScrollBar", false); // fileBar = new QToolBar("File", this); // QToolBar* viewBar = new QToolBar("File", this); // QToolBar* navBar = new QToolBar("File", this); // QToolBar* markBar = new QToolBar("File", this); -#ifdef USEQPE +#if defined(USEQPE) menubar = new QToolBar("Menus", this, m_tbposition); mb = new QPEMenuBar( menubar ); #else mb = new QMenuBar( this ); #endif -#ifdef USEQPE +#if defined(USEQPE) QPopupMenu* tmp = new QPopupMenu(mb); mb->insertItem( geticon( "AppsIcon" ), tmp ); #else QMenuBar* tmp = mb; #endif QPopupMenu *file = new QPopupMenu( mb ); tmp->insertItem( tr( "File" ), file ); QPopupMenu *navigation = new QPopupMenu(mb); tmp->insertItem( tr( "Navigation" ), navigation ); QPopupMenu *view = new QPopupMenu( mb ); tmp->insertItem( tr( "View" ), view ); QPopupMenu *marks = new QPopupMenu( this ); tmp->insertItem( tr( "Marks" ), marks ); QPopupMenu *settings = new QPopupMenu( this ); tmp->insertItem( tr( "Settings" ), settings ); // addToolBar(menubar, "Menus",QMainWindow::Top); // addToolBar(fileBar, "Toolbar",QMainWindow::Top); // QPopupMenu *edit = new QPopupMenu( this ); /* QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); a->addTo( bar ); a->addTo( file ); */ QWidget* widge = new QWidget(this); setCentralWidget( widge ); QVBoxLayout* vlayout = new QVBoxLayout(widge); m_layout = new QBoxLayout(QBoxLayout::LeftToRight); m_prog = new QLabel(widge); vlayout->addLayout(m_layout, 1); vlayout->addWidget(m_prog); editorStack = new QWidgetStack( widge ); // setCentralWidget( editorStack ); searchVisible = FALSE; regVisible = FALSE; m_fontVisible = false; m_buttonprefs = new CButtonPrefs(&kmap, this); editorStack->addWidget(m_buttonprefs, get_unique_id()); connect( m_buttonprefs, SIGNAL( Closed() ), this, SLOT( infoClose() ) ); m_annoWin = new CAnnoEdit(editorStack); editorStack->addWidget(m_annoWin, get_unique_id()); connect( m_annoWin, SIGNAL( finished(const QString&, const QString&) ), this, SLOT( addAnno(const QString&, const QString&) ) ); connect( m_annoWin, SIGNAL( cancelled() ), this, SLOT( infoClose() ) ); m_infoWin = new infowin(editorStack); editorStack->addWidget(m_infoWin, get_unique_id()); connect( m_infoWin, SIGNAL( Close() ), this, SLOT( infoClose() ) ); m_graphicwin = new GraphicWin(editorStack); editorStack->addWidget(m_graphicwin, get_unique_id()); connect( m_graphicwin, SIGNAL( Closed() ), this, SLOT( infoClose() ) ); // bkmkselector = new QListBox(editorStack, "Bookmarks"); bkmkselector = new CBkmkSelector(editorStack, "Bookmarks"); // connect(bkmkselector, SIGNAL( selected(const QString&) ), this, SLOT( gotobkmk(const QString&) ) ); connect(bkmkselector, SIGNAL( selected(int) ), this, SLOT( gotobkmk(int) ) ); connect(bkmkselector, SIGNAL( cancelled() ), this, SLOT( cancelbkmk() ) ); editorStack->addWidget( bkmkselector, get_unique_id() ); /* importSelector = new FileSelector( "*", editorStack, "importselector", false ); connect( importSelector, SIGNAL( fileSelected( const DocLnk &) ), this, SLOT( importFile( const DocLnk & ) ) ); editorStack->addWidget( importSelector, get_unique_id() ); // don't need the close visible, it is redundant... importSelector->setCloseVisible( FALSE ); */ // qDebug("Reading file list"); readfilelist(); reader = new QTReader( editorStack ); reader->setDoUpdates(false); #ifdef USEQPE ((QPEApplication*)qApp)->setStylusOperation(reader, QPEApplication::RightOnHold); #endif // qDebug("Reading config"); // Config config( APPDIR ); config.setGroup( "View" ); +#if defined(USEQPE) && defined(USENEWFULLSCREEN) + m_usenewfullscreen = config.readBoolEntry("NewFullScreen", false); +#endif m_debounce = config.readNumEntry("Debounce", 0); m_buttonprefs->Debounce(m_debounce); #ifdef USEQPE m_bFloatingDialog = config.readBoolEntry("FloatDialogs", false); #else m_bFloatingDialog = config.readBoolEntry("FloatDialogs", true); #endif reader->setStripCR(config.readBoolEntry( "StripCr", true )); reader->bfulljust = config.readBoolEntry( "FullJust", false ); /* bool btmp = config.readBoolEntry("Negative", false); if (btmp) reader->setNegative(); */ reader->bInverse = config.readBoolEntry("Inverse", false); reader->m_fontControl.FixGraphics(config.readBoolEntry( "FixGraphics", false )); reader->setextraspace(config.readNumEntry( "ExtraSpace", 0 )); reader->setlead(config.readNumEntry( "ExtraLead", 0 )); reader->btextfmt = config.readBoolEntry( "TextFmt", false ); reader->bautofmt = config.readBoolEntry( "AutoFmt", true ); reader->bstriphtml = config.readBoolEntry( "StripHtml", false ); + reader->bNoInlineTables = config.readBoolEntry( "NoInlineTables", false ); reader->bpeanut = config.readBoolEntry( "Peanut", false ); reader->bdehyphen = config.readBoolEntry( "Dehyphen", false ); reader->bdepluck = config.readBoolEntry( "Depluck", false ); reader->bdejpluck = config.readBoolEntry( "Dejpluck", false ); reader->bonespace = config.readBoolEntry( "OneSpace", false ); reader->bunindent = config.readBoolEntry( "Unindent", false ); reader->brepara = config.readBoolEntry( "Repara", false ); reader->m_reparastring = config.readEntry( "ReparaString", "\\n{[\\n \\t]}"); m_bgtype = (bground)config.readNumEntry( "BackgroundType" , 0 ); m_themename = config.readEntry("Theme", QString::null ); reader->bdblspce = config.readBoolEntry( "DoubleSpace", false ); reader->bindenter = config.readNumEntry( "Indent", 0 ); reader->m_textsize = config.readNumEntry( "FontSize", 12 ); reader->m_delay = config.readNumEntry( "ScrollDelay", 5184); reader->m_scrollstep = config.readNumEntry( "ScrollStep", 1); + reader->m_outputName = config.readEntry( "OutputCodec", ""); + reader->m_lastfile = config.readEntry( "LastFile", QString::null ); reader->m_lastposn = config.readNumEntry( "LastPosn", 0 ); reader->m_bpagemode = config.readBoolEntry( "PageMode", true ); reader->m_bMonoSpaced = config.readBoolEntry( "MonoSpaced", false); reader->m_rotated = config.readBoolEntry( "IsRotated", false ); reader->m_scrolltype = config.readNumEntry( "ScrollType", 0 ); m_statusstring = config.readEntry("StatusContent", "%P%% Doc:%d/%D %p%% %z%%"); m_statusishidden = config.readBoolEntry("StatusHidden", false); m_background = config.readNumEntry( "Background", 0 ); reader->setBackground(getcolour(m_background)); m_foreground = config.readNumEntry( "Foreground", 1 ); reader->setForeground(getcolour(m_foreground)); m_scrollcolor = config.readNumEntry( "ScrollColour", 5 ); setscrollcolour(); m_scrollbarcolor = config.readNumEntry( "ScrollBarColour", 5 ); setscrollbarcolour(); reader->hyphenate = config.readBoolEntry( "Hyphenate", false ); reader->m_swapmouse = config.readBoolEntry( "SwapMouse", false); reader->m_fontname = config.readEntry( "Fontname", "helvetica" ); reader->m_encd = config.readNumEntry( "Encoding", 0 ); reader->m_charpc = config.readNumEntry( "CharSpacing", 100 ); reader->m_overlap = config.readNumEntry( "Overlap", 0 ); reader->m_abstopmargin = config.readNumEntry( "Top Margin", 100 ); reader->m_absbottommargin = config.readNumEntry( "Bottom Margin", 100 ); reader->m_absleft_border = config.readNumEntry( "Left Margin", 100 ); reader->m_absright_border = config.readNumEntry( "Right Margin", 100 ); m_scrollishidden = config.readBoolEntry( "HideScrollBar", false ); + m_hidebars = config.readBoolEntry( "HideToolBar", false ); reader->brepalm = config.readBoolEntry( "Repalm", false ); + reader->bunderlineLink = config.readBoolEntry( "UnderlineLink", true ); reader->bkern = config.readBoolEntry( "Kern", false ); reader->bremap = config.readBoolEntry( "Remap", true ); reader->bmakebold = config.readBoolEntry( "MakeBold", false ); reader->setContinuous(config.readBoolEntry( "Continuous", true )); + reader->setDoubleBuffer(config.readBoolEntry("DoubleBuffer", true)); m_targetapp = config.readEntry( "TargetApp", QString::null ); m_targetmsg = config.readEntry( "TargetMsg", QString::null ); #ifdef _SCROLLPIPE reader->m_pipetarget = config.readEntry( "PipeTarget", QString::null ); reader->m_pauseAfterEachPara = config.readBoolEntry( "PauseAfterPara", true ); #endif m_twoTouch = config.readBoolEntry( "TwoTouch", false); m_doAnnotation = config.readBoolEntry( "Annotation", false); m_doDictionary = config.readBoolEntry( "Dictionary", false); m_doClipboard = config.readBoolEntry( "Clipboard", false); + m_doOutput = config.readBoolEntry( "OutputTgt", false); /* m_spaceTarget = (ActionTypes)config.readNumEntry("SpaceTarget", cesAutoScroll); m_escapeTarget = (ActionTypes)config.readNumEntry("EscapeTarget", cesNone); m_returnTarget = (ActionTypes)config.readNumEntry("ReturnTarget", cesFullScreen); m_leftTarget = (ActionTypes)config.readNumEntry("LeftTarget", cesZoomOut); m_rightTarget = (ActionTypes)config.readNumEntry("RightTarget", cesZoomIn); m_upTarget = (ActionTypes)config.readNumEntry("UpTarget", cesPageUp); m_downTarget = (ActionTypes)config.readNumEntry("DownTarget", cesPageDown); m_leftScroll = config.readBoolEntry("LeftScroll", false); m_rightScroll = config.readBoolEntry("RightScroll", false); m_upScroll = config.readBoolEntry("UpScroll", true); m_downScroll = config.readBoolEntry("DownScroll", true); */ m_propogatefontchange = config.readBoolEntry( "RequestorFontChange", false); reader->setBaseSize(config.readNumEntry( "Basesize", 10 )); reader->setHyphenThreshold(config.readNumEntry( "HyphenThreshold", 50 )); // reader->buffdoc.setCustomHyphen(config.readBoolEntry( "CustomHyphen", false )); #ifndef USEQPE config.setGroup( "Geometry" ); setGeometry(0,0, config.readNumEntry( "width", QApplication::desktop()->width()/2 ), config.readNumEntry( "height", QApplication::desktop()->height()/2 )); move( config.readNumEntry( "x", 20 ), config.readNumEntry( "y", 20 )); #else m_grabkeyboard = config.readBoolEntry( "GrabKeyboard", false); #endif setTwoTouch(m_twoTouch); connect( reader, SIGNAL( OnShowPicture(QImage&) ), this, SLOT( showgraphic(QImage&) ) ); connect( reader, SIGNAL( OnRedraw() ), this, SLOT( OnRedraw() ) ); connect( reader, SIGNAL( OnWordSelected(const QString&, size_t, size_t, const QString&) ), this, SLOT( OnWordSelected(const QString&, size_t, size_t, const QString&) ) ); connect( reader, SIGNAL( OnURLSelected(const QString&, const size_t) ), this, SLOT( OnURLSelected(const QString&, const size_t) ) ); connect( reader, SIGNAL( NewFileRequest(const QString&) ), this, SLOT( forceopen(const QString&) ) ); connect( reader, SIGNAL( HandleKeyRequest(QKeyEvent*) ), this, SLOT( handlekey(QKeyEvent*) ) ); connect( reader, SIGNAL( SetScrollState(bool) ), this, SLOT( setScrollState(bool) ) ); connect( reader, SIGNAL(RefreshBitmap()), this, SLOT(setBackgroundBitmap())); editorStack->addWidget( reader, get_unique_id() ); m_preferences_action = new QAction( tr( "Configuration" ), geticon( "SettingsIcon" ), QString::null, 0, this, NULL); connect( m_preferences_action, SIGNAL( activated() ), this, SLOT( showprefs() ) ); m_preferences_action->addTo( settings ); m_saveconfig_action = new QAction( tr( "Save Config" ), QString::null, 0, this, NULL); connect( m_saveconfig_action, SIGNAL( activated() ), this, SLOT( SaveConfig() ) ); m_saveconfig_action->addTo( settings ); m_loadconfig_action = new QAction( tr( "Load Config" ), QString::null, 0, this, NULL); connect( m_loadconfig_action, SIGNAL( activated() ), this, SLOT( LoadConfig() ) ); m_loadconfig_action->addTo( settings ); m_tidyconfig_action = new QAction( tr( "Delete Config" ), QString::null, 0, this, NULL); connect( m_tidyconfig_action, SIGNAL( activated() ), this, SLOT( TidyConfig() ) ); m_tidyconfig_action->addTo( settings ); settings->insertSeparator(); m_toolbarprefs_action = new QAction( tr( "Toolbars" ), QString::null, 0, this, NULL); connect( m_toolbarprefs_action, SIGNAL( activated() ), this, SLOT( showtoolbarprefs() ) ); m_toolbarprefs_action->addTo( settings ); m_buttonprefs_action = new QAction( tr( "Buttons" ), QString::null, 0, this, NULL); connect( m_buttonprefs_action, SIGNAL( activated() ), this, SLOT( showbuttonprefs() ) ); m_buttonprefs_action->addTo( settings ); m_loadtheme_action = new QAction( tr( "Load Theme" ), QString::null, 0, this, NULL); connect( m_loadtheme_action, SIGNAL( activated() ), this, SLOT( LoadTheme() ) ); m_loadtheme_action->addTo( settings ); m_repara_action = new QAction( tr( "EOP Marker" ), QString::null, 0, this, NULL); connect( m_repara_action, SIGNAL( activated() ), this, SLOT( reparastring() ) ); m_repara_action->addTo(settings); #ifdef USEQPE m_grab_action = new QAction( tr( "Grab Buttons" ), QString::null, 0, this, NULL, true ); connect( m_grab_action, SIGNAL( toggled(bool) ), this, SLOT( setgrab(bool) ) ); m_grab_action->setOn(m_grabkeyboard); m_grab_action->addTo( settings ); #endif m_open_action = new QAction( tr( "Open" ), geticon( "fileopen" ), QString::null, 0, this, 0 ); connect( m_open_action, SIGNAL( activated() ), this, SLOT( fileOpen() ) ); m_open_action->addTo( file ); m_close_action = new QAction( tr( "Close" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( m_close_action, SIGNAL( activated() ), this, SLOT( fileClose() ) ); m_close_action->addTo( file ); #ifdef _SCRIPT a = new QAction( tr( "Run Script" ), QString::null, 0, this, NULL); connect( a, SIGNAL( activated() ), this, SLOT( RunScript() ) ); a->addTo( file ); #endif /* a = new QAction( tr( "Revert" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileRevert() ) ); a->addTo( file ); a = new QAction( tr( "Cut" ), geticon( "cut" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); a->addTo( filebar() ); a->addTo( edit ); */ m_info_action = new QAction( tr( "Info" ), geticon( "UtilsIcon" ), QString::null, 0, this, NULL); connect( m_info_action, SIGNAL( activated() ), this, SLOT( showinfo() ) ); m_info_action->addTo( file ); m_touch_action = new QAction( tr( "Two/One Touch" ), geticon( "1to1" ), QString::null, 0, this, NULL, true ); connect( m_touch_action, SIGNAL( toggled(bool) ), this, SLOT( setTwoTouch(bool) ) ); m_touch_action->setOn(m_twoTouch); m_touch_action->addTo( file ); m_find_action = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, NULL); connect( m_find_action, SIGNAL( activated() ), this, SLOT( editFind() ) ); file->insertSeparator(); // a->addTo( bar ); m_find_action->addTo( file ); m_exportlinks_action = new QAction( tr( "Export Links" ), QString::null, 0, this, NULL); connect( m_exportlinks_action, SIGNAL( activated() ), this, SLOT( ExportLinks() ) ); m_exportlinks_action->addTo( file ); m_scrollButton = new QAction( tr( "Scroll" ), getmyicon( "panel-arrow-down" ), QString::null, 0, this, 0, true ); connect( m_scrollButton, SIGNAL( toggled(bool) ), this, SLOT( autoScroll(bool) ) ); m_scrollButton->addTo(navigation); m_scrollButton->setOn(false); m_start_action = new QAction( tr( "Goto Start" ), geticon( "start" ), QString::null, 0, this, NULL); connect( m_start_action, SIGNAL( activated() ), this, SLOT( gotoStart() ) ); m_start_action->addTo(navigation); m_end_action = new QAction( tr( "Goto End" ), geticon( "finish" ), QString::null, 0, this, NULL); connect( m_end_action, SIGNAL( activated() ), this, SLOT( gotoEnd() ) ); m_end_action->addTo(navigation); m_jump_action = new QAction( tr( "Jump" ), geticon( "rotate" ), QString::null, 0, this, NULL); connect( m_jump_action, SIGNAL( activated() ), this, SLOT( jump() ) ); m_jump_action->addTo(navigation); m_pageline_action = new QAction( tr( "Page/Line Scroll" ), geticon( "pass" ), QString::null, 0, this, NULL, true ); connect( m_pageline_action, SIGNAL( toggled(bool) ), this, SLOT( pagemode(bool) ) ); m_pageline_action->addTo(navigation); m_pageline_action->setOn(reader->m_bpagemode); m_pageup_action = new QAction( tr( "Up" ), geticon( "up" ), QString::null, 0, this, 0 ); connect( m_pageup_action, SIGNAL( activated() ), this, SLOT( pageup() ) ); m_pageup_action->addTo( navigation ); m_pagedn_action = new QAction( tr( "Down" ), geticon( "down" ), QString::null, 0, this, 0 ); connect( m_pagedn_action, SIGNAL( activated() ), this, SLOT( pagedn() ) ); m_pagedn_action->addTo( navigation ); m_back_action = new QAction( tr( "Back" ), geticon( "back" ), QString::null, 0, this, 0 ); connect( m_back_action, SIGNAL( activated() ), reader, SLOT( goBack() ) ); m_back_action->addTo( navigation ); m_home_action = new QAction( tr( "Home" ), geticon( "home" ), QString::null, 0, this, 0 ); connect( m_home_action, SIGNAL( activated() ), reader, SLOT( goHome() ) ); m_home_action->addTo( navigation ); m_forward_action = new QAction( tr( "Forward" ), geticon( "forward" ), QString::null, 0, this, 0 ); connect( m_forward_action, SIGNAL( activated() ), reader, SLOT( goForward() ) ); m_forward_action->addTo( navigation ); /* a = new QAction( tr( "Find" ), QString::null, 0, this, NULL, true ); // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) ); a->addTo( file ); a = new QAction( tr( "Find Again" ), QString::null, 0, this, NULL, true ); // connect( a, SIGNAL( activated() ), this, SLOT( pagedn() ) ); a->addTo( file ); */ // file->insertSeparator(); #ifdef _SCROLLPIPE QActionGroup* ag = new QActionGroup(this); ag->setExclusive(false); spacemenu = new QPopupMenu(this); file->insertItem( tr( "Scrolling" ), spacemenu ); a = new QAction( tr( "Set Target" ), QString::null, 0, ag, NULL); connect( a, SIGNAL( activated() ), this, SLOT( setpipetarget() ) ); a = new QAction( tr( "Pause Paras" ), QString::null, 0, ag, NULL, true ); connect( a, SIGNAL( toggled(bool) ), this, SLOT( setpause(bool) ) ); a->setOn(reader->m_pauseAfterEachPara); ag->addTo(spacemenu); // file->insertSeparator(); #endif /* a = new QAction( tr( "Import" ), QString::null, 0, this, NULL ); connect( a, SIGNAL( activated() ), this, SLOT( importFiles() ) ); a->addTo( file ); */ /* a = new QAction( tr( "Paste" ), geticon( "paste" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); a->addTo( fileBar ); a->addTo( edit ); */ // a = new QAction( tr( "Find..." ), geticon( "find" ), QString::null, 0, this, 0 ); m_fullscreen = false; m_actFullscreen = new QAction( tr( "Fullscreen" ), geticon( "fullscreen" ), QString::null, 0, this, NULL, true ); connect( m_actFullscreen, SIGNAL( toggled(bool) ), this, SLOT( setfullscreen(bool) ) ); m_actFullscreen->setOn(m_fullscreen); m_actFullscreen->addTo( view ); m_rotate_action = new QAction( tr( "Rotate" ), geticon( "repeat" ), QString::null, 0, this, NULL, true ); connect( m_rotate_action, SIGNAL( toggled(bool) ), this, SLOT( setrotated(bool) ) ); m_rotate_action->setOn(reader->m_rotated); m_rotate_action->addTo( view ); m_inverse_action = new QAction( tr( "Invert" ), getmyicon( "invert" ), QString::null, 0, this, NULL, true ); connect( m_inverse_action, SIGNAL( toggled(bool) ), this, SLOT( setinverted(bool) ) ); m_inverse_action->setOn(reader->bInverse); m_inverse_action->addTo( view ); view->insertSeparator(); m_zoomin_action = new QAction( tr( "Zoom In" ), geticon( "zoom" ), QString::null, 0, this); connect( m_zoomin_action, SIGNAL( activated() ), this, SLOT( zoomin() ) ); m_zoomin_action->addTo( view ); m_zoomout_action = new QAction( tr( "Zoom Out" ), geticon( "mag" ), QString::null, 0, this); connect( m_zoomout_action, SIGNAL( activated() ), this, SLOT( zoomout() ) ); m_zoomout_action->addTo( view ); view->insertSeparator(); m_setfont_action = new QAction( tr( "Set Font" ), getmyicon( "font" ), QString::null, 0, this); connect( m_setfont_action, SIGNAL( activated() ), this, SLOT( setfont() ) ); m_setfont_action->addTo( view ); view->insertSeparator(); m_setenc_action = new QAction( tr( "Set Encoding" ), getmyicon( "charset" ), QString::null, 0, this); connect( m_setenc_action, SIGNAL( activated() ), this, SLOT( chooseencoding() ) ); m_setenc_action->addTo( view ); m_setmono_action = new QAction( tr( "Ideogram" ), getmyicon( "ideogram" ), QString::null, 0, this, NULL, true); connect( m_setmono_action, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) ); m_setmono_action->addTo( view ); m_setmono_action->setOn(reader->m_bMonoSpaced); // a = new QAction( tr( "Zoom" ), QString::null, 0, this, NULL, true ); // a = new QAction( tr( "Zoom" ), geticon( "mag" ), QString::null, 0, this, 0 ); // a->addTo( filebar() ); // view->insertSeparator(); /* a = new QAction( tr( "Ideogram/Word" ), QString::null, 0, this, NULL, true ); connect( a, SIGNAL( toggled(bool) ), this, SLOT( monospace(bool) ) ); a->setOn(reader->m_bMonoSpaced); a->addTo( view ); */ /* a = new QAction( tr( "Set Width" ), QString::null, 0, this, NULL); connect( a, SIGNAL( activated() ), this, SLOT( setspacing() ) ); a->addTo( view ); */ m_mark_action = new QAction( tr( "Bookmark" ), getmyicon( "bookmark" ), QString::null, 0, this, NULL); connect( m_mark_action, SIGNAL( activated() ), this, SLOT( addbkmk() ) ); m_mark_action->addTo( marks ); m_annotate_action = new QAction( tr( "Annotate" ), getmyicon( "annotate" ), QString::null, 0, this, NULL); connect( m_annotate_action, SIGNAL( activated() ), this, SLOT( addanno() ) ); m_annotate_action->addTo( marks ); m_goto_action = new QAction( tr( "Goto" ), getmyicon( "bookmark_goto" ), QString::null, 0, this, NULL, false ); connect( m_goto_action, SIGNAL( activated() ), this, SLOT( do_gotomark() ) ); m_goto_action->addTo( marks ); m_delete_action = new QAction( tr( "Delete" ), getmyicon( "bookmark_delete" ), QString::null, 0, this, NULL); connect( m_delete_action, SIGNAL( activated() ), this, SLOT( do_delmark() ) ); m_delete_action->addTo( marks ); m_autogen_action = new QAction( tr( "Autogen" ), geticon( "exec" ), QString::null, 0, this, NULL, false ); connect( m_autogen_action, SIGNAL( activated() ), this, SLOT( do_autogen() ) ); marks->insertSeparator(); m_autogen_action->addTo( marks ); m_clear_action = new QAction( tr( "Clear" ), getmyicon( "bookmark_clear" ), QString::null, 0, this, NULL); connect( m_clear_action, SIGNAL( activated() ), this, SLOT( clearBkmkList() ) ); m_clear_action->addTo( marks ); m_save_action = new QAction( tr( "Save" ), getmyicon( "bookmark_save" ), QString::null, 0, this, NULL ); connect( m_save_action, SIGNAL( activated() ), this, SLOT( savebkmks() ) ); m_save_action->addTo( marks ); m_tidy_action = new QAction( tr( "Tidy" ), getmyicon( "bookmark_tidy" ), QString::null, 0, this, NULL); connect( m_tidy_action, SIGNAL( activated() ), this, SLOT( listBkmkFiles() ) ); marks->insertSeparator(); m_tidy_action->addTo( marks ); m_startBlock_action = new QAction( tr( "Start Block" ), geticon( "new" ), QString::null, 0, this, NULL); connect( m_startBlock_action, SIGNAL( activated() ), this, SLOT( editMark() ) ); marks->insertSeparator(); m_startBlock_action->addTo( marks ); m_endBlock_action = new QAction( tr( "Copy Block" ), geticon( "copy" ), QString::null, 0, this, NULL); connect( m_endBlock_action, SIGNAL( activated() ), this, SLOT( editCopy() ) ); m_endBlock_action->addTo( marks ); m_bkmkAvail = NULL; setToolBarsMovable(m_tbmove); addtoolbars(&config); + if (m_hidebars) + { +#if defined(USEQPE) + menubar->hide(); +#endif + if (fileBar != NULL) fileBar->hide(); + if (viewBar != NULL) viewBar->hide(); + if (navBar != NULL) navBar->hide(); + if (markBar != NULL) markBar->hide(); + mb->hide(); + } + pbar = new QProgressBar(this); pbar->hide(); searchBar = new QFloatBar( "Search", this, QMainWindow::Top, TRUE ); searchBar->setHorizontalStretchable( TRUE ); connect(searchBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() )); searchEdit = new QLineEdit( searchBar, "searchEdit" ); // QFont f("unifont", 16 /*, QFont::Bold*/); // searchEdit->setFont( f ); searchBar->setStretchableWidget( searchEdit ); #ifdef __ISEARCH connect( searchEdit, SIGNAL( textChanged( const QString & ) ), this, SLOT( search( const QString& ) ) ); #else connect( searchEdit, SIGNAL( returnPressed( ) ), this, SLOT( search( ) ) ); #endif QAction*a = new QAction( tr( "Find Next" ), geticon( "next" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findNext() ) ); a->addTo( searchBar ); a = new QAction( tr( "Close Find" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); a->addTo( searchBar ); searchBar->hide(); regBar = new QFloatBar( "Autogen", this, QMainWindow::Top, TRUE ); connect(regBar, SIGNAL( OnHide() ), this, SLOT( restoreFocus() )); regBar->setHorizontalStretchable( TRUE ); regEdit = new QLineEdit( regBar, "regEdit" ); // regEdit->setFont( f ); regBar->setStretchableWidget( regEdit ); connect( regEdit, SIGNAL( returnPressed( ) ), this, SLOT( do_regaction() ) ); a = new QAction( tr( "Do Reg" ), geticon( "enter" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( do_regaction() ) ); a->addTo( regBar ); a = new QAction( tr( "Close Edit" ), geticon( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( regClose() ) ); a->addTo( regBar ); regBar->hide(); m_fontBar = new QToolBar( "Autogen", this, QMainWindow::Top, TRUE ); m_fontBar->setHorizontalStretchable( TRUE ); // qDebug("Font selector"); m_fontSelector = new QComboBox(false, m_fontBar); m_fontBar->setStretchableWidget( m_fontSelector ); { QFontDatabase f; QStringList flist = f.families(); bool realfont = false; for (QStringList::Iterator nm = flist.begin(); nm != flist.end(); nm++) { if (reader->m_fontname == *nm) { realfont = true; } if ((*nm).contains(FIXEDFONT,false)) reader->m_fontControl.hasCourier(true, *nm); } if (!realfont) reader->m_fontname = flist[0]; } // delete the FontDatabase!!! connect( m_fontSelector, SIGNAL( activated(const QString& ) ), this, SLOT( do_setfont(const QString&) ) ); connect( m_fontSelector, SIGNAL( activated(int ) ), this, SLOT( do_setencoding(int) ) ); m_fontBar->hide(); m_fontVisible = false; #ifdef USEMSGS connect(qApp, SIGNAL( appMessage(const QCString&, const QByteArray& ) ), this, SLOT( msgHandler(const QCString&, const QByteArray&) ) ); #endif // qDebug("Initing"); m_layout->addWidget(editorStack); if (m_qtscroll != 0) { /* m_scrollbar = new QToolBar( "Autogen", this, (m_localscrollbar) ? QMainWindow::Left : QMainWindow::Right, TRUE ); m_scrollbar->setVerticalStretchable( TRUE ); */ scrollbar = m_scrollbar = new QScrollBar(QScrollBar::Vertical, widge); m_layout->addWidget(scrollbar); scrollbar->setTracking(false); // connect(scrollbar, SIGNAL(sliderMoved(int)), this, SLOT(actionscroll(int)) ); // m_scrollbar->setStretchableWidget( scrollbar ); if (m_scrollishidden) { m_scrollbar->hide(); } else { m_scrollbar->show(); } setrotated(reader->m_rotated); } else { m_scrollbar = NULL; } setBackgroundBitmap(); m_inverse_action->setOn(reader->bInverse); reader->init(); // qDebug("Inited"); // m_buttonAction[m_spaceTarget]->setOn(true); // qDebug("fonting"); do_setfont(reader->m_fontname); // qDebug("fonted"); QFont progfont(reader->m_fontname, reader->m_fontControl.getsize(0)); m_prog->setFont( progfont ); if (m_statusishidden) m_prog->hide(); + showEditTools(); if (!reader->m_lastfile.isEmpty()) { // qDebug("doclnk"); // doc = new DocLnk(reader->m_lastfile); // qDebug("doclnk done"); if (pOpenlist != NULL) { /* int ind = 0; Bkmk* p = (*pOpenlist)[ind]; while (p != NULL && toQString(CFiledata(p->anno()).name()) != reader->m_lastfile) { p = (*pOpenlist)[++ind]; } */ Bkmk* p = NULL; for (CList<Bkmk>::iterator iter = pOpenlist->begin(); iter != pOpenlist->end(); iter++) { p = iter.pContent(); if (toQString(CFiledata(p->anno()).name()) == reader->m_lastfile) { break; } // qDebug("Item:%s", (const char*)toQString(CFiledata(p->anno()).name())); p = NULL; } if (p != NULL) { if (!openfrombkmk(p)) { showEditTools(); } } else { openFile( reader->m_lastfile ); } } else { if (!reader->m_lastfile.isEmpty()) { openFile( reader->m_lastfile ); } } } else { showEditTools(); } // qApp->processEvents(); if (m_scrollbar == NULL || m_scrollbar->isHidden()) { reader->m_scrollpos = m_localscroll; } else { reader->m_scrollpos = (m_qtscroll == 0) ? m_localscroll : 0; } - reader->bDoUpdates = true; - reader->update(); + // reader->bDoUpdates = true; + // reader->update(); config.setGroup("Version"); int major = config.readNumEntry("Major", 0); int bkmktype = config.readNumEntry("BkmkType", 0); char minor = config.readNumEntry("Minor", 0); - if (CheckVersion(major, bkmktype, minor)) + if (CheckVersion(major, bkmktype, minor, this)) { config.writeEntry("Major", major); config.writeEntry("BkmkType", bkmktype); config.writeEntry("Minor", (int)minor); } // qDebug("finished update"); if (kmap.isEmpty()) { QMessageBox::warning(this, PROGNAME, "You haven't mapped any keys yet!\n\nYou will be taken to the key\nmapping dialog.\nA few defaults are provided\nbut you can change then to\nsuit yourself.\n\nYou can change the key\nmapping at any time by\nselecting the Settings/Button\noption on the menu."); m_buttonprefs->mapkey(Qt::NoButton, Key_Up, cesPageUp); m_buttonprefs->mapkey(Qt::NoButton, Key_Down, cesPageDown); m_buttonprefs->mapkey(Qt::NoButton, Key_Right, cesZoomIn); m_buttonprefs->mapkey(Qt::NoButton, Key_Left, cesZoomOut); showbuttonprefs(); } } void QTReaderApp::addtoolbars(Config* config) { config->setGroup("Toolbar"); if (fileBar != NULL) { -#ifdef USEQPE +#if defined(USEQPE) if (fileBar != menubar) { fileBar->clear(); } else { m_preferences_action->removeFrom( filebar() ); m_open_action->removeFrom( filebar() ); m_close_action->removeFrom( filebar() ); m_info_action->removeFrom( filebar() ); m_touch_action->removeFrom( filebar() ); m_find_action->removeFrom( filebar() ); } #else fileBar->clear(); #endif } m_preferences_action->addTo( filebar() ); addfilebar(config, "Open", m_open_action); addfilebar(config, "Close", m_close_action); addfilebar(config, "Info", m_info_action); addfilebar(config, "Two/One Touch", m_touch_action); addfilebar(config, "Find", m_find_action); if (navBar != NULL) { -#ifdef USEQPE +#if defined(USEQPE) if ((navBar == fileBar) && (fileBar == menubar)) #else if (navBar == fileBar) #endif { m_scrollButton->removeFrom( navbar() ); m_start_action->removeFrom( navbar() ); m_end_action->removeFrom( navbar() ); m_jump_action->removeFrom( navbar() ); m_pageline_action->removeFrom( navbar() ); m_pageup_action->removeFrom( navbar() ); m_pagedn_action->removeFrom( navbar() ); m_back_action->removeFrom( navbar() ); m_home_action->removeFrom( navbar() ); m_forward_action->removeFrom( navbar() ); } else if (navBar != fileBar) { navBar->clear(); } } addnavbar(config, "Scroll", m_scrollButton); addnavbar(config, "Goto Start", m_start_action); addnavbar(config, "Goto End", m_end_action); addnavbar(config, "Jump", m_jump_action); addnavbar(config, "Page/Line Scroll", m_pageline_action); addnavbar(config, "Page Up", m_pageup_action); addnavbar(config, "Page Down", m_pagedn_action); addnavbar(config, "Back", m_back_action); addnavbar(config, "Home", m_home_action); addnavbar(config, "Forward", m_forward_action); if (viewBar != NULL) { -#ifdef USEQPE +#if defined(USEQPE) if ((viewBar == fileBar) && (fileBar == menubar)) #else if (viewBar == fileBar) #endif { m_actFullscreen->removeFrom( filebar() ); m_rotate_action->removeFrom( viewbar() ); m_inverse_action->removeFrom( viewbar() ); m_zoomin_action->removeFrom( viewbar() ); m_zoomout_action->removeFrom( viewbar() ); m_setfont_action->removeFrom( viewbar() ); m_setenc_action->removeFrom( viewbar() ); m_setmono_action->removeFrom( viewbar() ); } else if (viewBar != fileBar) { viewBar->clear(); } } addviewbar(config, "Fullscreen", m_actFullscreen); addviewbar(config, "Rotate", m_rotate_action); addviewbar(config, "Invert Action", m_inverse_action); addviewbar(config, "Zoom In", m_zoomin_action); addviewbar(config, "Zoom Out", m_zoomout_action); addviewbar(config, "Set Font", m_setfont_action); addviewbar(config, "Encoding Select", m_setenc_action); addviewbar(config, "Ideogram Mode", m_setmono_action); if (markBar != NULL) { -#ifdef USEQPE +#if defined(USEQPE) if ((markBar == fileBar) && (fileBar == menubar)) #else if (markBar == fileBar) #endif { m_mark_action->removeFrom( markbar() ); m_annotate_action->removeFrom( markbar()); m_goto_action->removeFrom( markbar() ); m_delete_action->removeFrom( markbar() ); m_autogen_action->removeFrom( markbar() ); m_clear_action->removeFrom( markbar() ); m_save_action->removeFrom( markbar() ); m_tidy_action->removeFrom( markbar() ); m_startBlock_action->removeFrom( markbar() ); m_endBlock_action->removeFrom( markbar() ); } else if (markBar != fileBar) { markBar->clear(); } } addmarkbar(config, "Mark", m_mark_action); addmarkbar(config, "Annotate", m_annotate_action); addmarkbar(config, "Goto", m_goto_action); addmarkbar(config, "Delete", m_delete_action); addmarkbar(config, "Autogen", m_autogen_action); addmarkbar(config, "Clear", m_clear_action); addmarkbar(config, "Save", m_save_action); addmarkbar(config, "Tidy", m_tidy_action); addmarkbar(config, "Start Block", m_startBlock_action); addmarkbar(config, "Copy Block", m_endBlock_action); if (checkbar(config, "Annotation indicator")) { if (m_bkmkAvail == NULL) { m_bkmkAvail = new QAction( tr( "Annotation" ), geticon( "find" ), QString::null, 0, this, 0 ); connect( m_bkmkAvail, SIGNAL( activated() ), this, SLOT( showAnnotation() ) ); m_bkmkAvail->setEnabled(false); } QLabel *spacer = new QLabel(markBar, ""); markbar()->setStretchableWidget(spacer); m_bkmkAvail->removeFrom( markbar() ); m_bkmkAvail->addTo( markbar() ); } else { if (m_bkmkAvail != NULL) { m_bkmkAvail->removeFrom( markbar() ); delete m_bkmkAvail; m_bkmkAvail = NULL; } } } bool QTReaderApp::checkbar(Config* _config, const QString& key) { return _config->readBoolEntry(key, false); } QToolBar* QTReaderApp::filebar() { if (fileBar == NULL) { switch (m_tbpol) { -#ifdef USEQPE +#if defined(USEQPE) case cesSingle: // qDebug("Setting filebar to menubar"); fileBar = menubar; break; #endif default: qDebug("Incorrect toolbar policy set"); case cesMenuTool: case cesMultiple: // qDebug("Creating new file bar"); fileBar = new QToolBar("File", this, m_tbposition); break; } // fileBar->setHorizontalStretchable( true ); } return fileBar; } QToolBar* QTReaderApp::viewbar() { if (viewBar == NULL) { switch (m_tbpol) { case cesMultiple: viewBar = new QToolBar("View", this, m_tbposition); break; default: qDebug("Incorrect toolbar policy set"); #ifdef USEQPE case cesSingle: #endif case cesMenuTool: viewBar = fileBar; break; } } return viewBar; } QToolBar* QTReaderApp::navbar() { if (navBar == NULL) { switch (m_tbpol) { case cesMultiple: // qDebug("Creating new nav bar"); navBar = new QToolBar("Navigation", this, m_tbposition); break; default: qDebug("Incorrect toolbar policy set"); #ifdef USEQPE case cesSingle: #endif case cesMenuTool: navBar = fileBar; // qDebug("Setting navbar to filebar"); break; } } return navBar; } QToolBar* QTReaderApp::markbar() { if (markBar == NULL) { switch (m_tbpol) { case cesMultiple: markBar = new QToolBar("Marks", this, m_tbposition); break; default: qDebug("Incorrect toolbar policy set"); #ifdef USEQPE case cesSingle: #endif case cesMenuTool: markBar = fileBar; break; } } return markBar; } void QTReaderApp::addfilebar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( filebar() ); } void QTReaderApp::addnavbar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( navbar() ); } void QTReaderApp::addmarkbar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( markbar() ); } void QTReaderApp::addviewbar(Config* _config, const QString& key, QAction* a) { if (_config->readBoolEntry(key, false)) a->addTo( viewbar() ); } void QTReaderApp::suspend() { reader->suspend(); } void QTReaderApp::msgHandler(const QCString& _msg, const QByteArray& _data) { #ifndef USEMSGS return; #else QString msg = QString::fromUtf8(_msg); qDebug("Received:%s", (const char*)msg); QDataStream stream( _data, IO_ReadOnly ); if ( msg == "suspend()" ) { qDebug("Suspending"); suspend(); qDebug("Suspendedb"); } return; /* QDataStream stream( _data, IO_ReadOnly ); if ( msg == "info(QString)" ) { QString info; stream >> info; QMessageBox::information(this, PROGNAME, info); } else if ( msg == "Update(int)" ) { int info; stream >> info; if (info) { reader->bDoUpdates = true; reader->refresh(); } else { reader->bDoUpdates = false; } } else if ( msg == "warn(QString)" ) { QString info; stream >> info; QMessageBox::warning(this, PROGNAME, info); } else if ( msg == "exit()" ) { m_dontSave = true; close(); } else if ( msg == "pageDown()" ) { reader->dopagedn(); } else if ( msg == "pageUp()" ) { reader->dopageup(); } else if ( msg == "lineDown()" ) { reader->lineDown(); } else if ( msg == "lineUp()" ) { reader->lineUp(); } else if ( msg == "showText()" ) { showEditTools(); } else if ( msg == "home()" ) { reader->goHome(); } else if ( msg == "back()" ) { reader->goBack(); } else if ( msg == "forward()" ) { reader->goForward(); } else if ( msg == "File/Open(QString)" ) { QString info; stream >> info; openFile( info ); } else if ( msg == "File/Info()" ) { showinfo(); } else if ( msg == "File/Action(QString)" ) { QString info; stream >> info; m_spaceTarget = ActNameToInt(info); } else if ( msg == "Navigation/Scroll(int)" ) { int info; stream >> info; autoScroll(info); } else if ( msg == "Navigation/GotoStart()" ) { gotoStart(); } else if ( msg == "Navigation/GotoEnd()" ) { gotoEnd(); } else if ( msg == "Navigation/Jump(int)" ) { int info; stream >> info; reader->locate(info); } else if ( msg == "Navigation/Page/LineScroll(int)" ) { int info; stream >> info; pagemode(info); } else if ( msg == "Navigation/SetOverlap(int)" ) { int info; stream >> info; reader->m_overlap = info; } else if ( msg == "Navigation/SetMargin(int)" ) { int info; stream >> info; do_margin(info); } else if ( msg == "File/SetDictionary(QString)" ) { QString info; stream >> info; do_settarget(info); } #ifdef _SCROLLPIPE else if ( msg == "File/SetScrollTarget(QString)" ) { QString info; stream >> info; reader->m_pipetarget = info; } #endif else if ( msg == "File/Two/OneTouch(int)" ) { int info; stream >> info; setTwoTouch(info); } else if ( msg == "Target/Annotation(int)" ) { int info; stream >> info; OnAnnotation(info); } else if ( msg == "Target/Dictionary(int)" ) { int info; stream >> info; OnDictionary(info); } else if ( msg == "Target/Clipboard(int)" ) { int info; stream >> info; OnClipboard(info); } else if ( msg == "File/Find(QString)" ) { QString info; stream >> info; QRegExp arg(info); size_t pos = reader->pagelocate(); size_t start = pos; CDrawBuffer test(&(reader->m_fontControl)); reader->getline(&test); while (arg.match(toQString(test.data())) == -1) { pos = reader->locate(); if (!reader->getline(&test)) { QMessageBox::information(this, PROGNAME, QString("Can't find\n")+info); pos = start; break; } } reader->locate(pos); } else if ( msg == "File/Fullscreen(int)" ) { int info; stream >> info; setfullscreen(info); } else if ( msg == "File/Continuous(int)" ) { int info; stream >> info; setcontinuous(info); } else if ( msg == "Markup(QString)" ) { QString info; stream >> info; if (info == "Auto") { autofmt(true); } if (info == "None") { autofmt(false); textfmt(false); striphtml(false); peanut(false); } if (info == "Text") { textfmt(true); } if (info == "HTML") { striphtml(true); } if (info == "Peanut/PML") { peanut(true); } } else if ( msg == "Layout/StripCR(int)" ) { int info; stream >> info; stripcr(info); } else if ( msg == "Layout/Dehyphen(int)" ) { int info; stream >> info; dehyphen(info); } else if ( msg == "Layout/Depluck(int)" ) { int info; stream >> info; depluck(info); } else if ( msg == "Layout/Dejpluck(int)" ) { int info; stream >> info; dejpluck(info); } else if ( msg == "Layout/SingleSpace(int)" ) { int info; stream >> info; onespace(info); } else if ( msg == "Layout/Repalm(int)" ) { int info; stream >> info; repalm(info); } else if ( msg == "Layout/Unindent(int)" ) { int info; stream >> info; unindent(info); } else if ( msg == "Layout/Re-paragraph(int)" ) { int info; stream >> info; repara(info); } else if ( msg == "Layout/DoubleSpace(int)" ) { int info; stream >> info; dblspce(info); } else if ( msg == "Layout/Indent(int)" ) { int info; stream >> info; reader->bindenter = info; reader->setfilter(reader->getfilter()); } else if ( msg == "Layout/Remap(int)" ) { int info; stream >> info; remap(info); } else if ( msg == "Layout/Embolden(int)" ) { int info; stream >> info; embolden(info); } else if ( msg == "Format/Ideogram/Word(int)" ) { int info; stream >> info; monospace(info); } else if ( msg == "Format/SetWidth(int)" ) { int info; stream >> info; reader->m_charpc = info; reader->setfont(); reader->refresh(); } else if ( msg == "Format/SetFont(QString,int)" ) { QString fontname; int size; stream >> fontname; stream >> size; setfontHelper(fontname, size); } else if ( msg == "Marks/Autogen(QString)" ) { QString info; stream >> info; do_autogen(info); } else if ( msg == "File/StartBlock()" ) { editMark(); } else if ( msg == "File/CopyBlock()" ) { editCopy(); } */ #endif } ActionTypes QTReaderApp::ActNameToInt(const QString& _enc) { for (int i = 0; i < MAX_ACTIONS; i++) { if (m_buttonAction[i]->text() == _enc) return (ActionTypes)i; } return cesAutoScroll; } void QTReaderApp::setinverted(bool sfs) { reader->setInverse(sfs); reader->setfilter(reader->getfilter()); reader->refresh(); } void QTReaderApp::setrotated(bool sfs) { reader->setrotated(sfs); if (sfs) { m_layout->setDirection( (m_qtscroll == 2) ? QBoxLayout::BottomToTop : QBoxLayout::TopToBottom ); if (m_scrollbar != NULL) { scrollbar->disconnect(); m_scrollbar->setOrientation(Qt::Horizontal); connect(scrollbar, SIGNAL(nextLine()), reader, SLOT(lineUp()) ); connect(scrollbar, SIGNAL(prevLine()), reader, SLOT(lineDown()) ); connect(scrollbar, SIGNAL(nextPage()), reader, SLOT(dopageup()) ); connect(scrollbar, SIGNAL(prevPage()), reader, SLOT(dopagedn()) ); connect(scrollbar, SIGNAL(sliderMoved(int)), this, SLOT(actionscroll(int)) ); } // reader->repaint(0, reader->m_left_border, reader->width(), reader->height()-2*reader->m_border); - reader->repaint(); } else { m_layout->setDirection( (m_qtscroll == 2) ? QBoxLayout::RightToLeft : QBoxLayout::LeftToRight ); if (m_scrollbar != NULL) { scrollbar->disconnect(); m_scrollbar->setOrientation(Qt::Vertical); connect(scrollbar, SIGNAL(nextLine()), reader, SLOT(lineDown()) ); connect(scrollbar, SIGNAL(prevLine()), reader, SLOT(lineUp()) ); connect(scrollbar, SIGNAL(nextPage()), reader, SLOT(dopagedn()) ); connect(scrollbar, SIGNAL(prevPage()), reader, SLOT(dopageup()) ); connect(scrollbar, SIGNAL(sliderMoved(int)), this, SLOT(actionscroll(int)) ); } // reader->repaint(reader->m_border, 0, reader->width()-2*reader->m_border, reader->height()); - reader->repaint(); } - // reader->update(); + reader->refresh(); } void QTReaderApp::setgrab(bool sfs) { #ifdef USEQPE m_grabkeyboard = sfs; if (m_grabkeyboard) { ((QPEApplication*)qApp)->grabKeyboard(); } else { ((QPEApplication*)qApp)->ungrabKeyboard(); } #endif } void QTReaderApp::setfullscreen(bool sfs) { reader->bDoUpdates = false; m_fullscreen = sfs; showEditTools(); // qApp->processEvents(); reader->bDoUpdates = true; reader->update(); } /* void QTReaderApp::buttonActionSelected(QAction* _a) { //// qDebug("es:%x : %s (%u)", _a, (const char *)(_a->text()), ActNameToInt(_a->text())); m_spaceTarget = ActNameToInt(_a->text()); } */ QTReaderApp::~QTReaderApp() { } void QTReaderApp::autoScroll(bool _b) { reader->setautoscroll(_b); setScrollState(reader->m_autoScroll); } void QTReaderApp::zoomin() { reader->zoomin(); QFont f(reader->m_fontname, reader->m_fontControl.getsize(0)); m_prog->setFont( f ); } void QTReaderApp::zoomout() { reader->zoomout(); QFont f(reader->m_fontname, reader->m_fontControl.getsize(0)); m_prog->setFont( f ); } void QTReaderApp::clearBkmkList() { delete pBkmklist; reader->pBkmklist = pBkmklist = NULL; m_fBkmksChanged = false; reader->refresh(true); } void QTReaderApp::fileClose() { CCloseDialog* cd = new CCloseDialog(reader->m_string, false, this); if (cd->exec()) { if (pOpenlist != NULL) { int ind = 0; Bkmk* p = (*pOpenlist)[ind]; while (p != NULL && toQString(CFiledata(p->anno()).name()) != reader->m_lastfile) { p = (*pOpenlist)[++ind]; } if (p != NULL) pOpenlist->erase(ind); if (cd->delFile()) { unlink((const char*)reader->m_lastfile); } if (cd->delMarks()) { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); d.remove(reader->m_string); #else /* USEQPE */ unlink((const char *)Global::applicationFileName(APPDIR,reader->m_string)); #endif /* USEQPE */ } if (cd->delConfig()) { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR "/configs"); d.remove(reader->m_string); #else /* USEQPE */ unlink((const char *)Global::applicationFileName(APPDIR "/configs",reader->m_string)); #endif /* USEQPE */ } } fileOpen2(); } delete cd; } void QTReaderApp::updatefileinfo() { if (reader->m_string.isEmpty()) return; if (reader->m_lastfile.isEmpty()) return; tchar* nm = fromQString(reader->m_string); tchar* fl = fromQString(reader->m_lastfile); // qDebug("Lastfile:%x", fl); bool notadded = true; if (pOpenlist == NULL) pOpenlist = new CList<Bkmk>; else { for (CList<Bkmk>::iterator iter = pOpenlist->begin(); iter != pOpenlist->end(); iter++) { if (ustrcmp(CFiledata(iter->anno()).name(), fl) == 0) { iter->value(reader->pagelocate()); unsigned short dlen; unsigned char* data; CFiledata fd(iter->anno()); reader->setSaveData(data, dlen, fd.content(), fd.length()); // qDebug("Filedata(1):%u, %u", fd.length(), dlen); // getstate(data, dlen); iter->setAnno(data, dlen); notadded = false; delete [] data; break; } } } // qDebug("Added?:%x", notadded); if (notadded) { struct stat fnstat; stat((const char *)reader->m_lastfile, &fnstat); CFiledata fd(fnstat.st_mtime, fl); unsigned short dlen; unsigned char* data; reader->setSaveData(data, dlen, fd.content(), fd.length()); pOpenlist->push_front(Bkmk(nm, data, dlen, reader->pagelocate())); // qDebug("Filedata(2):%u, %u", fd.length(), dlen); delete [] data; } delete [] nm; delete [] fl; } void QTReaderApp::fileOpen() { /* menu->hide(); fileBar->hide(); if (regVisible) regBar->hide(); if (searchVisible) searchBar->hide(); */ // qDebug("fileOpen"); // if (!reader->m_lastfile.isEmpty()) updatefileinfo(); fileOpen2(); } void QTReaderApp::fileOpen2() { if (pBkmklist != NULL) { if (m_fBkmksChanged) { if (QMessageBox::warning(this, PROGNAME, "Save bookmarks?", "Save", "Don't bother") == 0) savebkmks(); } delete pBkmklist; reader->pBkmklist = pBkmklist = NULL; m_fBkmksChanged = false; } reader->disableAutoscroll(); /* editorStack->raiseWidget( fileSelector ); fileSelector->reread(); */ bool usebrowser = true; if (pOpenlist != NULL) { m_nBkmkAction = cOpenFile; - if (listbkmk(pOpenlist, "Browse")) usebrowser = false; + if (listbkmk(pOpenlist, "Browse", true)) usebrowser = false; } if (usebrowser) { QString fn = usefilebrowser(); // qApp->processEvents(); if (!fn.isEmpty() && QFileInfo(fn).isFile()) { openFile(fn); } reader->setFocus(); } // reader->refresh(); // qDebug("HEIGHT:%d", reader->m_lastheight); } QString QTReaderApp::usefilebrowser() { #ifndef USEQPE QString s( QFileDialog::getOpenFileName( reader->m_lastfile, QString::null, this ) ); return s; #else QString fn; -#ifdef OPIE +#if defined(OPIE) && defined(OPIEFILEDIALOG) QMap<QString, QStringList> mimeTypes; QStringList etypes; etypes << "etext/*"; mimeTypes.insert( tr("eText"), etypes ); QStringList types; types << "text/*"; mimeTypes.insert( tr("Text"), types ); mimeTypes.insert( tr("All"), "*/*" ); fn = OFileDialog::getOpenFileName(OFileSelector::EXTENDED_ALL, QFileInfo(reader->m_lastfile).dirPath(true), QString::null, mimeTypes, 0, "OpieReader"); #else fileBrowser* fb = new fileBrowser(false, this,"OpieReader",!m_bFloatingDialog, 0, // WStyle_Customize | WStyle_NoBorderEx, "*", QFileInfo(reader->m_lastfile).dirPath(true)); if (fb->exec()) { fn = fb->getCurrentFile(); } // qDebug("Selected %s", (const char*)fn); delete fb; #endif showEditTools(); return fn; #endif } void QTReaderApp::showgraphic(QImage& pm) { m_graphicwin->setImage(pm); editorStack->raiseWidget( m_graphicwin ); hidetoolbars(); m_graphicwin->setFocus(); } void QTReaderApp::showbuttonprefs() { editorStack->raiseWidget( m_buttonprefs ); hidetoolbars(); m_buttonprefs->setFocus(); m_kmapchanged = true; } void QTReaderApp::showprefs() { CPrefs* prefwin = new CPrefs(reader->width(), !m_bFloatingDialog, this); // prefwin->Debounce(m_debounce); prefwin->bgtype(m_bgtype); prefwin->repalm(reader->brepalm); + prefwin->UnderlineLink(reader->bunderlineLink); prefwin->kern(reader->bkern); prefwin->hyphenate(reader->hyphenate); // prefwin->customhyphen(reader->buffdoc.getCustomHyphen()); prefwin->scrolltype(reader->m_scrolltype); prefwin->scrollstep(reader->m_scrollstep); prefwin->scrollcolor(m_scrollcolor); prefwin->minibarcol(m_scrollbarcolor); prefwin->foreground(m_foreground); prefwin->background(m_background); prefwin->twotouch(m_twoTouch); prefwin->propfontchange(m_propogatefontchange); prefwin->StripCR(reader->bstripcr); + prefwin->InlineTables(!reader->bNoInlineTables); prefwin->Dehyphen(reader->bdehyphen); prefwin->SingleSpace(reader->bonespace); prefwin->Unindent(reader->bunindent); prefwin->Reparagraph(reader->brepara); prefwin->DoubleSpace(reader->bdblspce); prefwin->Remap(reader->bremap); prefwin->Embolden(reader->bmakebold); prefwin->FullJustify(reader->bfulljust); // prefwin->Inverse(reader->bInverse); // prefwin->Negative(reader->bNegative); prefwin->FixGraphics(reader->m_fontControl.FixGraphics()); prefwin->ParaLead(reader->getextraspace()); prefwin->LineLead(reader->getlead()); prefwin->TopMargin(reader->m_abstopmargin); prefwin->BottomMargin(reader->m_absbottommargin); prefwin->LeftMargin(reader->m_absleft_border); prefwin->RightMargin(reader->m_absright_border); prefwin->Indent(reader->bindenter); if (reader->bautofmt) { prefwin->Markup(0); } else if (reader->btextfmt) { prefwin->Markup(2); } else if (reader->bstriphtml) { prefwin->Markup(3); } else if (reader->bpeanut) { prefwin->Markup(4); } else { prefwin->Markup(1); } prefwin->Depluck(reader->bdepluck); prefwin->Dejpluck(reader->bdejpluck); prefwin->Continuous(reader->m_continuousDocument); + prefwin->DoubleBuffer(reader->m_doubleBuffered); prefwin->dictApplication(m_targetapp); prefwin->dictMessage(m_targetmsg); /* prefwin->leftScroll(m_leftScroll); prefwin->rightScroll(m_rightScroll); prefwin->upScroll(m_upScroll); prefwin->downScroll(m_downScroll); */ prefwin->miscannotation(m_doAnnotation); prefwin->miscdictionary(m_doDictionary); prefwin->miscclipboard(m_doClipboard); + prefwin->miscoutput(m_doOutput); prefwin->SwapMouse(reader->m_swapmouse); prefwin->Font(reader->m_fontname); prefwin->gfxsize(reader->getBaseSize()); prefwin->pageoverlap(reader->m_overlap); prefwin->ideogram(reader->m_bMonoSpaced); prefwin->encoding(reader->m_encd); prefwin->ideogramwidth(reader->m_charpc); + prefwin->outcodec(reader->m_outputName); + if (prefwin->exec()) { // m_debounce = prefwin->Debounce(); reader->brepalm = prefwin->repalm(); + reader->bunderlineLink = prefwin->UnderlineLink(); + reader->bkern = prefwin->kern(); reader->hyphenate = prefwin->hyphenate(); // reader->buffdoc.setCustomHyphen(prefwin->customhyphen()); reader->m_scrolltype = prefwin->scrolltype(); reader->m_scrollstep = prefwin->scrollstep(); m_scrollcolor = prefwin->scrollcolor(); setscrollcolour(); m_scrollbarcolor = prefwin->minibarcol(); setscrollbarcolour(); m_foreground = prefwin->foreground(); reader->setForeground(getcolour(m_foreground)); m_background = prefwin->background(); reader->setBackground(getcolour(m_background)); m_twoTouch = prefwin->twotouch(); reader->setTwoTouch(m_twoTouch); m_touch_action->setOn(m_twoTouch); reader->bstripcr = prefwin->StripCR(); + reader->bNoInlineTables = !prefwin->InlineTables(); reader->bdehyphen = prefwin->Dehyphen(); reader->bonespace = prefwin->SingleSpace(); reader->bunindent = prefwin->Unindent(); reader->brepara = prefwin->Reparagraph(); reader->bdblspce = prefwin->DoubleSpace(); reader->bremap = prefwin->Remap(); reader->bmakebold = prefwin->Embolden(); reader->bfulljust = prefwin->FullJustify(); // if (reader->bInverse != prefwin->Inverse()) reader->setInverse(prefwin->Inverse()); // if (reader->bNegative != prefwin->Negative()) reader->setNegative(); reader->m_fontControl.FixGraphics(prefwin->FixGraphics()); reader->setextraspace(prefwin->ParaLead()); reader->setlead(prefwin->LineLead()); reader->m_abstopmargin = prefwin->TopMargin(); reader->m_absbottommargin = prefwin->BottomMargin(); reader->m_absleft_border = prefwin->LeftMargin(); reader->m_absright_border = prefwin->RightMargin(); reader->bindenter = prefwin->Indent(); reader->bautofmt = reader->btextfmt = reader->bstriphtml = reader->bpeanut = false; switch (prefwin->Markup()) { case 0: reader->bautofmt = true; break; case 1: break; case 2: reader->btextfmt = true; break; case 3: reader->bstriphtml = true; break; case 4: reader->bpeanut = true; break; default: qDebug("Format out of range"); } reader->bdepluck = prefwin->Depluck(); reader->bdejpluck = prefwin->Dejpluck(); reader->setContinuous(prefwin->Continuous()); + reader->setDoubleBuffer(prefwin->DoubleBuffer()); /* m_leftScroll = prefwin->leftScroll(); m_rightScroll = prefwin->rightScroll(); m_upScroll = prefwin->upScroll(); m_downScroll = prefwin->downScroll(); */ m_targetapp = prefwin->dictApplication(); m_targetmsg = prefwin->dictMessage(); m_doAnnotation = prefwin->miscannotation(); m_doDictionary = prefwin->miscdictionary(); m_doClipboard = prefwin->miscclipboard(); + m_doOutput = prefwin->miscoutput(); reader->m_swapmouse = prefwin->SwapMouse(); reader->setBaseSize(prefwin->gfxsize()); reader->m_overlap = prefwin->pageoverlap(); reader->m_bMonoSpaced = prefwin->ideogram(); m_setmono_action->setOn(reader->m_bMonoSpaced); reader->m_encd = prefwin->encoding(); reader->m_charpc = prefwin->ideogramwidth(); if ( reader->m_fontname != prefwin->Font() || m_propogatefontchange != prefwin->propfontchange()) { m_propogatefontchange = prefwin->propfontchange(); setfontHelper(prefwin->Font()); } if (m_bgtype != (bground)prefwin->bgtype()) { m_bgtype = (bground)prefwin->bgtype(); setBackgroundBitmap(); } + qDebug("OutCodec:%s", (const char*)prefwin->outcodec()); + if (reader->m_outputName != prefwin->outcodec()) + { + if (reader->m_output != NULL) + { + QMessageBox::warning(this, PROGNAME, "Change of output codec\nrequires a restart"); + } + reader->m_outputName = prefwin->outcodec(); + } delete prefwin; reader->setfilter(reader->getfilter()); reader->refresh(); } else { delete prefwin; } } void QTReaderApp::showtoolbarprefs() { #ifdef USEQPE CBarPrefs* prefwin = new CBarPrefs(APPDIR, !m_bFloatingDialog, this); #else QFileInfo fi; QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/%s\" directory", APPDIR ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } fi.setFile(d, INIFILE); CBarPrefs* prefwin = new CBarPrefs(fi.absFilePath(), !m_bFloatingDialog, this); #endif prefwin->tbpolicy(m_tbpolsave); prefwin->tbposition(m_tbposition-2); prefwin->tbmovable(m_tbmovesave); prefwin->floating(m_bFloatingDialog); prefwin->qtscroll(m_qtscroll); prefwin->localscroll(m_localscroll); if (prefwin->exec()) { m_bFloatingDialog = prefwin->floating(); if ( m_tbpolsave != (ToolbarPolicy)prefwin->tbpolicy() || m_tbposition != (ToolBarDock)(prefwin->tbposition()+2) || m_tbmovesave != prefwin->tbmovable() || m_qtscroll != prefwin->qtscroll() // || // m_localscrollbar != prefwin->scrollonleft() ) { QMessageBox::warning(this, PROGNAME, "Some changes won't take effect\nuntil the next time the\napplication is started"); } m_tbpolsave = (ToolbarPolicy)prefwin->tbpolicy(); m_tbposition = (ToolBarDock)(prefwin->tbposition()+2); m_tbmovesave = prefwin->tbmovable(); reader->m_scrollpos = m_localscroll = prefwin->localscroll(); if (m_qtscroll != prefwin->qtscroll()) { m_qtscroll = prefwin->qtscroll(); setrotated(reader->m_rotated); } if (m_scrollbar == NULL || m_scrollbar->isHidden()) { reader->m_scrollpos = m_localscroll; } else { reader->m_scrollpos = (m_qtscroll == 0) ? m_localscroll : 0; } bool isChanged = prefwin->isChanged(); delete prefwin; #ifdef USEQPE Config config( APPDIR ); #else QFileInfo fi; QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/%s\" directory", APPDIR ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } fi.setFile(d, INIFILE); Config config( fi.absFilePath() ); #endif if (isChanged) addtoolbars(&config); } else { delete prefwin; } } void QTReaderApp::showinfo() { unsigned long ds, fs, ts, pl, dl; if (reader->empty()) { QMessageBox::information(this, PROGNAME, "No file loaded", 1); } else { reader->sizes(fs,ts); ds = reader->buffdoc.endSection() - reader->buffdoc.startSection(); pl = reader->pagelocate(); dl = pl - reader->buffdoc.startSection(); m_infoWin->setFileSize(fs); m_infoWin->setTextSize(ts); + if (fs > UINT_MAX/100) + { + unsigned long t1 = (ts+50)/100; + m_infoWin->setRatio(100-(fs + (t1 >> 1))/t1); + } + else + { m_infoWin->setRatio(100-(100*fs + (ts >> 1))/ts); + } m_infoWin->setLocation(pl); + if (pl > UINT_MAX/100) + { + unsigned long t1 = (ts+50)/100; + m_infoWin->setRead((pl + (t1 >> 1))/t1); + } + else + { m_infoWin->setRead((100*pl + (ts >> 1))/ts); + } m_infoWin->setDocSize(ds); m_infoWin->setDocLocation(dl); + if (dl > UINT_MAX/100) + { + unsigned long d1 = (ds+50)/100; + m_infoWin->setDocRead((dl + (d1 >> 1))/d1); + } + else + { m_infoWin->setDocRead((100*dl + (ds >> 1))/ds); + } m_infoWin->setZoom(reader->m_fontControl.currentsize()*10); m_infoWin->setAbout(QString("\nApplication (c) Tim Wentford\n")+reader->about()); editorStack->raiseWidget( m_infoWin ); hidetoolbars(); m_infoWin->setFocus(); } } void QTReaderApp::addAnno(const QString& name, const QString& text, size_t posn, size_t posn2) { if (pBkmklist == NULL) reader->pBkmklist = pBkmklist = new CList<Bkmk>; #ifdef _UNICODE CBuffer buff(name.length()+1); int i; for (i = 0; i < name.length(); i++) { buff[i] = name[i].unicode(); } buff[i] = 0; CBuffer buff2(text.length()+1); for (i = 0; i < text.length(); i++) { buff2[i] = text[i].unicode(); } buff2[i] = 0; Bkmk b(buff.data(), buff2.data(), posn, posn2); QColor c = m_annoWin->getColor(); int red,green,blue; c.rgb(&red, &green, &blue); b.red(red); b.green(green); b.blue(blue); pBkmklist->push_front(b); #else pBkmklist->push_front(Bkmk((const tchar*)text,posn)); #endif m_fBkmksChanged = true; pBkmklist->sort(); } void QTReaderApp::addAnno(const QString& name, const QString& text) { if (m_annoIsEditing) { if (name.isEmpty()) { QMessageBox::information(this, PROGNAME, "Need a name for the bookmark\nPlease try again", 1); } else { addAnno(name, text, m_annoWin->getPosn(), m_annoWin->getPosn2()); } showEditTools(); } else { if (m_annoWin->edited()) { CBuffer buff(text.length()+1); int i; for (i = 0; i < text.length(); i++) { buff[i] = text[i].unicode(); } buff[i] = 0; m_fBkmksChanged = true; m_anno->setAnno(buff.data()); } QColor c = m_annoWin->getColor(); int red,green,blue; c.rgb(&red, &green, &blue); m_anno->red(red); m_anno->green(green); m_anno->blue(blue); bool found = findNextBookmark(m_anno->value()+1); if (found) { m_annoWin->setName(toQString(m_anno->name())); m_annoWin->setAnno(toQString(m_anno->anno())); m_annoWin->setColor(QColor(m_anno->red(), m_anno->green(), m_anno->blue())); } else { showEditTools(); } } } bool QTReaderApp::findNextBookmark(size_t start) { bool found = false; for (CList<Bkmk>::iterator iter = pBkmklist->begin(); iter != pBkmklist->end(); iter++) { if (iter->value() >= start) { if (iter->value() < reader->locate()) { found = true; m_anno = iter.pContent(); } break; } } return found; } void QTReaderApp::addanno() { if (reader->empty()) { QMessageBox::information(this, PROGNAME, "No file loaded", 1); } else { m_annoWin->setName(""); m_annoWin->setAnno(""); m_annoWin->setPosn(reader->pagelocate()); m_annoIsEditing = true; editorStack->raiseWidget( m_annoWin ); hidetoolbars(); #ifdef USEQPE Global::showInputMethod(); #endif m_annoWin->setFocus(); } } void QTReaderApp::infoClose() { m_debounce = m_buttonprefs->Debounce(); if (m_kmapchanged) { m_kmapchanged = false; #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); QFileInfo fi(d, ".keymap"); FILE* f = fopen((const char *)fi.absFilePath(), "w"); #else /* USEQPE */ FILE* f = fopen((const char *)Global::applicationFileName(APPDIR,".keymap"), "w"); #endif /* USEQPE */ if (f != NULL) { uint cnt = KEYMAPVERSION; fwrite(&cnt, sizeof(cnt), 1, f); cnt = kmap.count(); fwrite(&cnt, sizeof(cnt), 1, f); for (QMap<orKey,int>::Iterator i = kmap.begin(); i != kmap.end(); i++) { orKey key = i.key(); int data = i.data(); fwrite(&key, sizeof(key), 1, f); fwrite(&data, sizeof(data), 1, f); qDebug("Saved %s as %u", (const char*)key.text(), data); } fclose(f); } } showEditTools(); } /* void QTReaderApp::fileRevert() { clear(); fileOpen(); } void QTReaderApp::editCut() { #ifndef QT_NO_CLIPBOARD editor->cut(); #endif } */ void QTReaderApp::editMark() { m_savedpos = reader->pagelocate(); } void QTReaderApp::editCopy() { QClipboard* cb = QApplication::clipboard(); QString text; int ch; unsigned long currentpos = reader->pagelocate(); unsigned long endpos = reader->locate(); if (m_savedpos == 0xffffffff) { m_savedpos = currentpos; } reader->jumpto(m_savedpos); while (reader->explocate() < endpos && (ch = reader->getch()) != UEOF) { text += ch; } cb->setText(text); reader->locate(currentpos); m_savedpos = 0xffffffff; } void QTReaderApp::gotoStart() { reader->locate(reader->buffdoc.startSection()); } void QTReaderApp::gotoEnd() { reader->dopageup(reader->buffdoc.endSection()); } void QTReaderApp::pageup() { reader->NavUp(); } void QTReaderApp::pagedn() { reader->NavDown(); } void QTReaderApp::pagemode(bool _b) { reader->setpagemode(_b); } /* void QTReaderApp::setspacing() { m_nRegAction = cMonoSpace; char lcn[20]; sprintf(lcn, "%lu", reader->m_charpc); regEdit->setText(lcn); do_regedit(); } */ void QTReaderApp::settarget() { m_nRegAction = cSetTarget; QString text = ((m_targetapp.isEmpty()) ? QString("") : m_targetapp) + "/" + ((m_targetmsg.isEmpty()) ? QString("") : m_targetmsg); regEdit->setText(text); do_regedit(); } /* void QTReaderApp::do_mono(const QString& lcn) { bool ok; unsigned long ulcn = lcn.toULong(&ok); if (ok) { reader->m_charpc = ulcn; reader->setfont(); reader->refresh(); // reader->setmono(true); } else QMessageBox::information(this, PROGNAME, "Must be a number"); } */ /* void QTReaderApp::editPaste() { #ifndef QT_NO_CLIPBOARD editor->paste(); #endif } */ void QTReaderApp::editFind() { searchStart = reader->pagelocate(); #ifdef __ISEARCH searchStack = new QStack<searchrecord>; #endif #ifdef USEQPE Global::showInputMethod(); #endif searchBar->show(); searchVisible = TRUE; searchEdit->setFocus(); #ifdef __ISEARCH searchStack->push(new searchrecord("",reader->pagelocate())); #endif } void QTReaderApp::findNext() { // // qDebug("findNext called\n"); #ifdef __ISEARCH QString arg = searchEdit->text(); #else QRegExp arg = searchEdit->text(); #endif CDrawBuffer test(&(reader->m_fontControl)); size_t start = reader->pagelocate(); reader->jumpto(start); reader->getline(&test); dosearch(start, test, arg); } void QTReaderApp::findClose() { searchVisible = FALSE; searchEdit->setText(""); #ifdef USEQPE Global::hideInputMethod(); #endif searchBar->hide(); #ifdef __ISEARCH // searchStack = new QStack<searchrecord>; while (!searchStack->isEmpty()) { delete searchStack->pop(); } delete searchStack; #endif reader->setFocus(); } void QTReaderApp::regClose() { regVisible = FALSE; regEdit->setText(""); regBar->hide(); #ifdef USEQPE Global::hideInputMethod(); #endif reader->setFocus(); } #ifdef __ISEARCH bool QTReaderApp::dosearch(size_t start, CDrawBuffer& test, const QString& arg) #else bool QTReaderApp::dosearch(size_t start, CDrawBuffer& test, const QRegExp& arg) #endif { bool ret = true; unsigned long fs, ts; reader->sizes(fs,ts); size_t pos = reader->locate(); pbar->setGeometry(searchBar->x(),searchBar->y(),searchBar->width(), searchBar->height()); pbar->show(); pbar->raise(); pbar->reset(); int offset; int lastpc = (100*pos)/ts; pbar->setProgress(lastpc); // qApp->processEvents(); if (reader->buffdoc.getpara(test) >= 0) { reader->setFocus(); #ifdef __ISEARCH while (strstr(test.data(),(const tchar*)arg) == NULL) #else #ifdef _UNICODE while ((offset = arg.match(toQString(test.data()))) == -1) #else while (arg.match(test.data()) == -1) #endif #endif { pos = reader->locate(); int pc = (100*pos)/ts; if (pc != lastpc) { pbar->setProgress(pc); qApp->processEvents(); reader->setFocus(); lastpc = pc; } if (reader->buffdoc.getpara(test) < 0) { if (QMessageBox::warning(this, "Can't find", searchEdit->text(), 1, 2) == 2) pos = searchStart; else pos = start; findClose(); pbar->hide(); reader->locate(pos); return false; } } // qDebug("Found it at %u:%u", pos, offset); pbar->hide(); // qDebug("Hid"); reader->locate(pos+offset); // qDebug("Loacted"); // qDebug("page up"); ret = true; } else { if (QMessageBox::warning(this, "Can't find", searchEdit->text(), 1, 2) == 2) pos = searchStart; else pos = start; ret = false; findClose(); } return ret; } #ifdef __ISEARCH void QTReaderApp::search(const QString & arg) { searchrecord* ss = searchStack->top(); CBuffer test; size_t start = reader->pagelocate(); bool haspopped = false; while (arg.left(ss->s.length()) != ss->s) { haspopped = true; start = ss->pos; // reader->locate(start); searchStack->pop(); delete ss; } if (haspopped) reader->locate(start); /* if (arg.length() < ss->len) { start = ss->pos; reader->locate(start); searchStack->pop(); delete ss; } */ else { start = reader->pagelocate(); reader->jumpto(start); searchStack->push(new searchrecord(arg,start)); } dosearch(start, test, arg); } #else void QTReaderApp::search() { findNext(); } #endif -void QTReaderApp::openFile( const QString &f ) +void QTReaderApp::openFile( const QString &f, unsigned int loc ) { // qDebug("File:%s", (const char*)f); // openFile(DocLnk(f)); //} // //void QTReaderApp::openFile( const DocLnk &f ) //{ clear(); QFileInfo fm(f); if ( fm.exists() ) { // QMessageBox::information(0, "Progress", "Calling fileNew()"); #ifdef USEQPE if (fm.extension( FALSE ) == "desktop") { DocLnk d(f); QFileInfo fnew(d.file()); fm = fnew; if (!fm.exists()) return; } #endif clear(); - reader->setText(fm.baseName(), fm.absFilePath()); + reader->setText(fm.baseName(), fm.absFilePath(), loc); m_loadedconfig = readconfig(APPDIR "/configs", reader->m_string, false); qDebug("Showing tools"); showEditTools(); qDebug("Shown tools"); readbkmks(); qDebug("read markss"); m_savedpos = 0xffffffff; } else { QString msg = f; msg += "\nFile does not exist"; QMessageBox::information(this, PROGNAME, msg); reader->m_lastfile = QString::null; } } /* void QTReaderApp::resizeEvent(QResizeEvent* e) { if (m_fullscreen) { showNormal(); showFullScreen(); } } */ void QTReaderApp::handlekey(QKeyEvent* e) { // qDebug("Keypress event"); timeb now; ftime(&now); unsigned long etime = (1000*(now.time - m_lastkeytime.time) + now.millitm)-m_lastkeytime.millitm; if (etime < m_debounce) { return; } switch(e->key()) { case Key_Escape: -// qDebug("escape event"); + qDebug("escape event"); if (m_disableesckey) { m_disableesckey = false; } else { m_bcloseDisabled = true; if (m_fullscreen) { m_actFullscreen->setOn(false); e->accept(); } else { // qDebug("escape action"); doAction(e); } } break; /* case Key_Left: { if (reader->m_autoScroll) { reader->reduceScroll(); } else { doAction(e); } } break; case Key_Right: { if (reader->m_autoScroll) { reader->increaseScroll(); } else { doAction(e); } } break; case Key_Up: { if (reader->m_autoScroll) { reader->increaseScroll(); } else { doAction(e); } } break; case Key_Down: { if (reader->m_autoScroll) { reader->reduceScroll(); } else { doAction(e); } } break; */ default: { doAction(e); } /* QString msg("Key press was:"); QString key; msg += key.setNum(e->key()); QMessageBox::information(this, PROGNAME, msg); */ } ftime(&m_lastkeytime); } -#ifdef NEWFULLSCREEN -void QTReaderApp::enableFullscreen() -{ - setFixedSize(qApp->desktop()->size()); - showNormal(); - reparent(0, WStyle_Customize | WStyle_NoBorder, QPoint(0,0)); - showFullScreen(); -} - -void QTReaderApp::resizeEvent(QResizeEvent *) +#if defined(USEQPE) && defined(USENEWFULLSCREEN) +void QTReaderApp::focusInEvent(QFocusEvent *) { - if (m_fullscreen && (size() != qApp->desktop()->size())) + if (m_usenewfullscreen && m_fullscreen && (editorStack->visibleWidget() == reader)) { - enableFullscreen(); + m_usenewfullscreen = false; + reader->bDoUpdates = false; + showEditTools(); + reader->bDoUpdates = true; + reader->update(); + m_usenewfullscreen = true; } } -void QTReaderApp::focusInEvent(QFocusEvent*) +void QTReaderApp::resizeEvent(QResizeEvent *) { - if (m_fullscreen) + if (m_usenewfullscreen && m_fullscreen && (editorStack->visibleWidget() == reader)) { - enableFullscreen(); - raise(); + m_usenewfullscreen = false; + reader->bDoUpdates = false; + showEditTools(); + reader->bDoUpdates = true; + reader->update(); + m_usenewfullscreen = true; } } #endif void QTReaderApp::showEditTools() { // if ( !doc ) // close(); if (m_fullscreen) { -#ifdef USEQPE +#if defined(USEQPE) if (menubar != NULL) menubar->hide(); #endif if (fileBar != NULL) fileBar->hide(); if (viewBar != NULL) viewBar->hide(); if (navBar != NULL) navBar->hide(); if (markBar != NULL) markBar->hide(); if (m_prog != NULL) { // qDebug("Hiding status"); m_prog->hide(); } searchBar->hide(); regBar->hide(); #ifdef USEQPE Global::hideInputMethod(); #endif if (m_scrollbar != NULL) m_scrollbar->hide(); m_fontBar->hide(); // showNormal(); -#ifdef NEWFULLSCREEN - enableFullscreen(); -#else showFullScreen(); -#endif } else { // qDebug("him"); #ifdef USEQPE Global::hideInputMethod(); #endif // qDebug("eb"); if (m_scrollbar != NULL) { if (m_scrollishidden) { m_scrollbar->hide(); } else { m_scrollbar->show(); } } if (!m_hidebars) { -#ifdef USEQPE +#if defined(USEQPE) menubar->show(); #endif if (fileBar != NULL) fileBar->show(); if (viewBar != NULL) viewBar->show(); if (navBar != NULL) navBar->show(); if (markBar != NULL) markBar->show(); if (m_prog != NULL && !m_statusishidden) { // qDebug("Showing status"); m_prog->show(); // qDebug("Shown status"); } // qDebug("Showing mb"); mb->show(); } if ( searchVisible ) { #ifdef USEQPE Global::showInputMethod(); #endif searchBar->show(); } if ( regVisible ) { #ifdef USEQPE Global::showInputMethod(); #endif regBar->show(); } if (m_fontVisible) m_fontBar->show(); // qDebug("sn"); showNormal(); // qDebug("sm"); -#ifdef USEQPE +#if defined(USEQPE) && !defined(SIMPAD) showMaximized(); #endif // setCentralWidget(reader); } // qDebug("uc"); updateCaption(); // qDebug("rw"); editorStack->raiseWidget( reader ); // qDebug("sf"); reader->setFocus(); // qDebug("ref"); - reader->refresh(true); + //reader->refresh(true); // qDebug("done"); } /* void QTReaderApp::save() { if ( !doc ) return; if ( !editor->edited() ) return; QString rt = editor->text(); QString pt = rt; if ( doc->name().isEmpty() ) { unsigned ispace = pt.find( ' ' ); unsigned ienter = pt.find( '\n' ); int i = (ispace < ienter) ? ispace : ienter; QString docname; if ( i == -1 ) { if ( pt.isEmpty() ) docname = "Empty Text"; else docname = pt; } else { docname = pt.left( i ); } doc->setName(docname); } FileManager fm; fm.saveFile( *doc, rt ); } */ void QTReaderApp::clear() { // if (doc != 0) // { // QMessageBox::information(this, PROGNAME, "Deleting doc", 1); // delete doc; // QMessageBox::information(this, PROGNAME, "Deleted doc", 1); // doc = 0; // } reader->clear(); } void QTReaderApp::updateCaption() { // if ( !doc ) // setCaption( tr("QTReader") ); // else { // QString s = doc->name(); // if ( s.isEmpty() ) // s = tr( "Unnamed" ); setCaption( reader->m_string + " - " + tr(SHORTPROGNAME) ); // } } void QTReaderApp::setDocument(const QString& fileref) { //QMessageBox::information(0, "setDocument", fileref); openFile(fileref); // showEditTools(); } void QTReaderApp::closeEvent( QCloseEvent *e ) { // qDebug("Close event"); if (m_fullscreen) { m_fullscreen = false; showEditTools(); e->ignore(); } else if (editorStack->visibleWidget() == m_buttonprefs) { m_buttonprefs->mapkey(Qt::NoButton, Key_Escape); e->ignore(); } else if (m_dontSave) { e->accept(); } else { if (editorStack->visibleWidget() == reader) { if ((kmap.find(orKey(Qt::NoButton,Key_Escape,false)) != kmap.end()) && m_bcloseDisabled) { // qDebug("Close disabled"); m_bcloseDisabled = false; e->ignore(); } else { if (m_fontVisible) { m_fontBar->hide(); m_fontVisible = false; e->ignore(); return; } if (regVisible) { regBar->hide(); #ifdef USEQPE Global::hideInputMethod(); #endif regVisible = false; e->ignore(); return; } if (searchVisible) { searchBar->hide(); #ifdef USEQPE Global::hideInputMethod(); #endif searchVisible = false; e->ignore(); return; } if (m_fBkmksChanged && pBkmklist != NULL) { if (QMessageBox::warning(this, PROGNAME, "Save bookmarks?", "Save", "Don't bother") == 0) savebkmks(); delete pBkmklist; reader->pBkmklist = pBkmklist = NULL; m_fBkmksChanged = false; } updatefileinfo(); saveprefs(); e->accept(); } } else { showEditTools(); m_disableesckey = true; } } } void QTReaderApp::do_gotomark() { m_nBkmkAction = cGotoBkmk; if (!listbkmk(pBkmklist)) QMessageBox::information(this, PROGNAME, "No bookmarks in memory"); } void QTReaderApp::do_delmark() { m_nBkmkAction = cDelBkmk; if (!listbkmk(pBkmklist)) QMessageBox::information(this, PROGNAME, "No bookmarks in memory"); } -bool QTReaderApp::listbkmk(CList<Bkmk>* plist, const QString& _lab) +bool QTReaderApp::listbkmk(CList<Bkmk>* plist, const QString& _lab, bool presel) { bkmkselector->clear(); if (_lab.isEmpty()) bkmkselector->setText("Cancel"); else bkmkselector->setText(_lab); int cnt = 0; + int slt = -1; if (plist != NULL) { for (CList<Bkmk>::iterator i = plist->begin(); i != plist->end(); i++) { + if (presel) + { + Bkmk* p = i.pContent(); + if (toQString(CFiledata(p->anno()).name()) == reader->m_lastfile) + { + slt = cnt; + } + } #ifdef _UNICODE // qDebug("Item:%s", (const char*)toQString(i->name())); - bkmkselector->insertItem(toQString(i->name())); + bkmkselector->insertItem(toQString(i->name()), cnt++); #else - bkmkselector->insertItem(i->name()); + bkmkselector->insertItem(i->name(), cnt++); #endif - cnt++; + } } if (cnt > 0) { hidetoolbars(); editorStack->raiseWidget( bkmkselector ); + if (slt != -1) bkmkselector->setCurrentItem(slt); return true; } else return false; } void QTReaderApp::do_autogen() { m_nRegAction = cAutoGen; regEdit->setText(m_autogenstr); do_regedit(); } void QTReaderApp::do_regedit() { // fileBar->hide(); reader->bDoUpdates = false; // qDebug("Showing regbar"); regBar->show(); // qDebug("Showing kbd"); #ifdef USEQPE Global::showInputMethod(); #endif regVisible = true; regEdit->setFocus(); // qApp->processEvents(); reader->bDoUpdates = true; reader->update(); } bool QTReaderApp::openfrombkmk(Bkmk* bk) { QString fn = toQString( CFiledata(bk->anno()).name() ); // qDebug("fileinfo"); if (!fn.isEmpty() && QFileInfo(fn).isFile()) { // qDebug("Opening"); - openFile(fn); struct stat fnstat; - stat((const char *)reader->m_lastfile, &fnstat); + stat((const char *)fn, &fnstat); if (CFiledata(bk->anno()).date() != fnstat.st_mtime) { CFiledata fd(bk->anno()); fd.setdate(fnstat.st_mtime); bk->value(0); + reader->m_lastposn = 0; + openFile(fn); } else { unsigned short svlen = bk->filedatalen(); unsigned char* svdata = bk->filedata(); + openFile(fn, bk->value()); reader->putSaveData(svdata, svlen); // setstate(svdata, svlen); if (svlen != 0) { QMessageBox::warning(this, PROGNAME, "Not all file data used\nNew version?"); } // qDebug("updating"); // showEditTools(); - reader->locate(bk->value()); } return true; } else { return false; } } void QTReaderApp::gotobkmk(int ind) { qDebug("gbkmk"); showEditTools(); switch (m_nBkmkAction) { case cOpenFile: { // qApp->processEvents(); if (!openfrombkmk((*pOpenlist)[ind])) { pOpenlist->erase(ind); QMessageBox::information(this, PROGNAME, "Can't find file"); } } break; case cGotoBkmk: reader->buffdoc.saveposn(reader->m_lastfile, reader->pagelocate()); reader->locate((*pBkmklist)[ind]->value()); break; case cDelBkmk: //// qDebug("Deleting:%s\n",(*pBkmklist)[ind]->name()); pBkmklist->erase(ind); m_fBkmksChanged = true; reader->refresh(true); // pBkmklist->sort(); break; case cRmBkmkFile: { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); d.remove(bkmkselector->text(ind)); #else /* USEQPE */ unlink((const char *)Global::applicationFileName(APPDIR,bkmkselector->text(ind))); #endif /* USEQPE */ } break; case cLdConfig: readconfig(APPDIR "/configs", bkmkselector->text(ind), false); break; case cLdTheme: m_themename = bkmkselector->text(ind); readconfig(QString(APPDIR "/Themes/")+m_themename , "config", false); setBackgroundBitmap(); break; case cRmConfig: { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR "/configs"); d.remove(bkmkselector->text(ind)); #else /* USEQPE */ unlink((const char *)Global::applicationFileName(APPDIR "/configs",bkmkselector->text(ind))); #endif /* USEQPE */ } break; case cExportLinks: { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR "/urls"); QFileInfo fi(d, bkmkselector->text(ind)); if (fi.exists()) { QString outfile( QFileDialog::getSaveFileName( QString::null, QString::null, this ) ); if (!outfile.isEmpty()) { FILE* fout = fopen((const char *)outfile, "w"); if (fout != NULL) { FILE* fin = fopen((const char *)fi.absFilePath(), "r"); if (fin != NULL) { fprintf(fout, "<html><body>\n"); int ch = 0; while ((ch = fgetc(fin)) != EOF) { fputc(ch, fout); } fclose(fin); fprintf(fout, "</html></body>\n"); d.remove(bkmkselector->text(ind)); } fclose(fout); } else QMessageBox::information(this, PROGNAME, "Couldn't open output"); } } #else /* USEQPE */ FILE* fin = fopen((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind)), "r"); if (fin != NULL) { bool allok = false; -#ifdef OPIE +#if defined(OPIE) && defined(OPIEFILEDIALOG) QString outfile = OFileDialog::getSaveFileName(OFileSelector::EXTENDED_ALL, QString::null, QString::null, MimeTypes(), 0, "OpieReader"); if (!outfile.isEmpty()) { FILE* fout = fopen((const char *)outfile, "w"); if (fout != NULL) { fprintf(fout, "<html><body>\n"); int ch = 0; while ((ch = fgetc(fin)) != EOF) { fputc(ch, fout); } fprintf(fout, "</html></body>\n"); fclose(fout); allok = true; } else QMessageBox::information(this, PROGNAME, "Couldn't open output"); } fclose(fin); if (allok) unlink((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind))); #else fileBrowser* fb = new fileBrowser(true, this,"OpieReader",!m_bFloatingDialog, 0, "*", QString::null); if (fb->exec()) { QString outfile = fb->getCurrentFile(); FILE* fout = fopen((const char *)outfile, "w"); if (fout != NULL) { fprintf(fout, "<html><body>\n"); int ch = 0; while ((ch = fgetc(fin)) != EOF) { fputc(ch, fout); } fprintf(fout, "</html></body>\n"); fclose(fout); allok = true; } else QMessageBox::information(this, PROGNAME, "Couldn't open output"); } delete fb; fclose(fin); if (allok) unlink((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind))); #endif } else { QMessageBox::information(this, PROGNAME, "Couldn't open input"); } /* CFileSelector *f = new CFileSelector("text/html", this, NULL, !m_bFloatingDialog, TRUE, TRUE ); int ret = f->exec(); qDebug("Return:%d", ret); DocLnk* doc = f->getDoc(); if (doc != NULL) { FILE* fin = fopen((const char *)Global::applicationFileName(APPDIR "/urls",bkmkselector->text(ind)), "r"); QString rt; rt = "<html><body>\n"; int ch = 0; while ((ch = fgetc(fin)) != EOF) { rt += (char)ch; } fclose(fin); rt += "</html></body>\n"; if ( doc->name().isEmpty() ) { doc->setName(bkmkselector->text(ind)); } FileManager fm; fm.saveFile( *doc, rt ); qDebug("YES"); } else { qDebug("NO"); } delete f; */ #endif /* USEQPE */ } break; } } void QTReaderApp::cancelbkmk() { if (m_nBkmkAction == cOpenFile) { QString fn = usefilebrowser(); if (!fn.isEmpty() && QFileInfo(fn).isFile()) openFile(fn); } showEditTools(); } void QTReaderApp::reparastring() { m_nRegAction = cRepara; regEdit->setText(reader->m_reparastring); do_regedit(); } void QTReaderApp::do_reparastring(const QString& _lcn) { reader->m_reparastring = _lcn; if (reader->brepara) { reader->bDoUpdates = true; reader->setfilter(reader->getfilter()); } } void QTReaderApp::jump() { m_nRegAction = cJump; char lcn[20]; sprintf(lcn, "%lu", reader->pagelocate()); regEdit->setText(lcn); do_regedit(); } void QTReaderApp::do_jump(const QString& _lcn) { bool ok; QString lcn = _lcn.stripWhiteSpace(); unsigned long ulcn = lcn.toULong(&ok); if (!ok) { double pc = 0.0; #ifdef _WINDOWS if (lcn.at(lcn.length()-1) == '%') #else if (lcn[lcn.length()-1] == '%') #endif { lcn = lcn.left(lcn.length()-1); pc = lcn.toDouble(&ok); } else { pc = lcn.toDouble(&ok); } if (ok && 0 <= pc && pc <= 100) { ulcn = (pc*(reader->buffdoc.endSection()-reader->buffdoc.startSection()))/100 + reader->buffdoc.startSection(); } else { ok = false; } } if (ok) reader->locate(ulcn); else QMessageBox::information(this, PROGNAME, "Must be a number\nor a percentage"); } void QTReaderApp::do_regaction() { reader->bDoUpdates = false; regBar->hide(); #ifdef USEQPE Global::hideInputMethod(); #endif regVisible = false; switch(m_nRegAction) { case cAutoGen: do_autogen(regEdit->text()); break; case cAddBkmk: do_addbkmk(regEdit->text()); break; case cRepara: do_reparastring(regEdit->text()); break; case cJump: do_jump(regEdit->text()); break; /* case cMonoSpace: do_mono(regEdit->text()); break; */ case cSetTarget: do_settarget(regEdit->text()); break; #ifdef _SCROLLPIPE case cSetPipeTarget: do_setpipetarget(regEdit->text()); break; #endif case cSetConfigName: // qDebug("Saving config"); do_saveconfig(regEdit->text(), false); break; } // reader->restore(); // fileBar->show(); reader->setFocus(); // qApp->processEvents(); reader->bDoUpdates = true; reader->update(); } void QTReaderApp::do_settarget(const QString& _txt) { int ind = _txt.find('/'); if (ind == -1) { m_targetapp = ""; m_targetmsg = ""; QMessageBox::information(this, PROGNAME, "Format is\nappname/messagename"); } else { m_targetapp = _txt.left(ind); m_targetmsg = _txt.right(_txt.length()-ind-1); } } void QTReaderApp::chooseencoding() { m_fontSelector->clear(); m_fontSelector->insertItem("Ascii"); m_fontSelector->insertItem("UTF-8"); m_fontSelector->insertItem("UCS-2(BE)"); m_fontSelector->insertItem("USC-2(LE)"); m_fontSelector->insertItem("Palm"); for (unicodetable::iterator iter = unicodetable::begin(); iter != unicodetable::end(); iter++) { m_fontSelector->insertItem(iter->mime); } // delete the FontDatabase!!! m_fontSelector->setCurrentItem (reader->m_encd); m_fontAction = cChooseEncoding; m_fontBar->show(); m_fontVisible = true; } void QTReaderApp::setfont() { m_fontSelector->clear(); { QFontDatabase f; QStringList flist = f.families(); m_fontSelector->insertStringList(flist); } // delete the FontDatabase!!! for (int i = 1; i <= m_fontSelector->count(); i++) { if (m_fontSelector->text(i) == reader->m_fontname) { m_fontSelector->setCurrentItem(i); break; } } m_fontAction = cChooseFont; m_fontBar->show(); m_fontVisible = true; } void QTReaderApp::setfontHelper(const QString& lcn, int size) { if (size == 0) size = reader->m_fontControl.currentsize(); if (m_propogatefontchange) { QFont f(lcn, 10); bkmkselector->setFont( f ); regEdit->setFont( f ); searchEdit->setFont( f ); m_annoWin->setFont( f ); } reader->m_fontname = lcn; if (!reader->ChangeFont(size)) { reader->ChangeFont(size); } } void QTReaderApp::do_setencoding(int i) { qDebug("setencoding:%d", i); if (m_fontAction == cChooseEncoding) { reader->setencoding(i); } reader->refresh(); m_fontBar->hide(); m_fontVisible = false; // qDebug("showedit"); if (reader->isVisible()) showEditTools(); // qDebug("showeditdone"); } void QTReaderApp::do_setfont(const QString& lcn) { if (m_fontAction == cChooseFont) { setfontHelper(lcn); } reader->refresh(); m_fontBar->hide(); m_fontVisible = false; // qDebug("setfont"); //if (reader->isVisible()) showEditTools(); // qDebug("showeditdone"); } void QTReaderApp::do_autogen(const QString& regText) { unsigned long fs, ts; reader->sizes(fs,ts); // // qDebug("Reg:%s\n", (const tchar*)(regEdit->text())); m_autogenstr = regText; QRegExp re(regText); CBuffer buff; if (pBkmklist != NULL) delete pBkmklist; reader->pBkmklist = pBkmklist = new CList<Bkmk>; m_fBkmksChanged = true; pbar->setGeometry(regBar->x(),regBar->y(),regBar->width(), regBar->height()); pbar->show(); pbar->raise(); pbar->reset(); reader->update(); qApp->processEvents(); reader->setFocus(); reader->jumpto(0); int lastpc = 0; int i = 0; + unsigned int llcn = reader->locate(); while (i >= 0) { - unsigned int lcn = reader->locate(); + unsigned int lcn = llcn; int pc = (100*lcn)/ts; if (pc != lastpc) { pbar->setProgress(pc); qApp->processEvents(); if (reader->locate() != lcn) reader->jumpto(lcn); reader->setFocus(); lastpc = pc; } i = reader->buffdoc.getpara(buff); #ifdef _UNICODE if (re.match(toQString(buff.data())) != -1) #else if (re.match(buff.data()) != -1) #endif pBkmklist->push_back(Bkmk(buff.data(), NULL, lcn)); + /* + llcn = reader->locate(); + if ((i == 0) && (llcn+1 < ts)) + { + reader->jumpto(++llcn); + i = 1; + } + */ } pBkmklist->sort(); pbar->setProgress(100); qApp->processEvents(); pbar->hide(); reader->refresh(); } void QTReaderApp::saveprefs() { do_saveconfig( APPDIR, true ); savefilelist(); } /* void QTReaderApp::oldFile() { // qDebug("oldFile called"); reader->setText(true); // qDebug("settext called"); showEditTools(); // qDebug("showedit called"); } */ /* void info_cb(Fl_Widget* o, void* _data) { if (infowin == NULL) { infowin = new Fl_Window(160,240); filename = new Fl_Output(45,5,110,14,"Filename"); filesize = new Fl_Output(45,25,110,14,"Filesize"); textsize = new Fl_Output(45,45,110,14,"Textsize"); comprat = new CBar(45,65,110,14,"Ratio %"); posn = new Fl_Output(45,85,110,14,"Location"); frcn = new CBar(45,105,110,14,"% Read"); about = new Fl_Multiline_Output(5,125,150,90); about->value("TWReader - $Name$\n\nA file reader program for the Agenda\n\nReads text, PalmDoc and ppms format files"); Fl_Button *jump_accept = new Fl_Button(62,220,35,14,"Okay"); infowin->set_modal(); } if (((reader_ui *)_data)->g_filename[0] != '\0') { unsigned long fs,ts; tchar sz[20]; ((reader_ui *)_data)->input->sizes(fs,ts); unsigned long pl = ((reader_ui *)_data)->input->locate(); filename->value(((reader_ui *)_data)->g_filename); sprintf(sz,"%u",fs); filesize->value(sz); sprintf(sz,"%u",ts); textsize->value(sz); comprat->value(100-(100*fs + (ts >> 1))/ts); sprintf(sz,"%u",pl); posn->value(sz); frcn->value((100*pl + (ts >> 1))/ts); } infowin->show(); } */ void QTReaderApp::savebkmks() { if (pBkmklist != NULL) { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); QFileInfo fi(d, reader->m_string); BkmkFile bf((const char *)fi.absFilePath(), true, true); #else /* USEQPE */ BkmkFile bf((const char *)Global::applicationFileName(APPDIR,reader->m_string), true, true); #endif /* USEQPE */ bf.write(*pBkmklist); } m_fBkmksChanged = false; } void QTReaderApp::readfilelist() { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); QFileInfo fi(d, ".openfiles"); BkmkFile bf((const char *)fi.absFilePath(), false, false); #else /* USEQPE */ BkmkFile bf((const char *)Global::applicationFileName(APPDIR,".openfiles"), false, false); #endif /* USEQPE */ // qDebug("Reading open files"); pOpenlist = bf.readall(); // if (pOpenlist != NULL) qDebug("...with success"); // else qDebug("...without success!"); } void QTReaderApp::savefilelist() { if (pOpenlist != NULL) { #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); QFileInfo fi(d, ".openfiles"); BkmkFile bf((const char *)fi.absFilePath(), true, false); #else /* USEQPE */ BkmkFile bf((const char *)Global::applicationFileName(APPDIR,".openfiles"), true, false); #endif /* USEQPE */ // qDebug("Writing open files"); bf.write(*pOpenlist); } } void QTReaderApp::readbkmks() { if (pBkmklist != NULL) { delete pBkmklist; } struct stat fnstat; struct stat bkstat; #ifndef USEQPE QDir d = QDir::home(); // "/" d.cd(APPDIR); QFileInfo fi(d, reader->m_string); #endif /* ! USEQPE */ if ( stat((const char *)reader->m_lastfile, &fnstat) == 0 && #ifndef USEQPE stat((const char *)fi.absFilePath(), &bkstat) == 0 #else /* USEQPE */ stat((const char *)Global::applicationFileName(APPDIR,reader->m_string), &bkstat) == 0 #endif /* USEQPE */ ) { if (bkstat.st_mtime < fnstat.st_mtime) { #ifndef USEQPE unlink((const char *)fi.absFilePath()); #else /* USEQPE */ unlink((const char *)Global::applicationFileName(APPDIR,reader->m_string)); #endif /* USEQPE */ } } #ifndef USEQPE BkmkFile bf((const char *)fi.absFilePath(), false, true); #else /* USEQPE */ BkmkFile bf((const char *)Global::applicationFileName(APPDIR,reader->m_string), false, true); #endif /* USEQPE */ reader->pBkmklist = pBkmklist = bf.readall(); m_fBkmksChanged = bf.upgraded(); if (pBkmklist == NULL) { reader->pBkmklist = pBkmklist = reader->getbkmklist(); } if (pBkmklist != NULL) pBkmklist->sort(); } void QTReaderApp::addbkmk() { m_nRegAction = cAddBkmk; regEdit->setText(reader->firstword()); do_regedit(); } void QTReaderApp::do_addbkmk(const QString& text) { if (text.isEmpty()) { QMessageBox::information(this, PROGNAME, "Need a name for the bookmark\nSelect add again", 1); } else { if (pBkmklist == NULL) reader->pBkmklist = pBkmklist = new CList<Bkmk>; #ifdef _UNICODE CBuffer buff; int i = 0; for (i = 0; i < text.length(); i++) { buff[i] = text[i].unicode(); } buff[i] = 0; pBkmklist->push_front(Bkmk(buff.data(), NULL, reader->pagelocate())); #else pBkmklist->push_front(Bkmk((const tchar*)text, reader->pagelocate())); #endif m_fBkmksChanged = true; pBkmklist->sort(); reader->refresh(true); } } void QTReaderApp::UpdateStatus() { QString status; for (int i = 0; i < m_statusstring.length(); i++) { if (m_statusstring[i].unicode() == '%') { i++; if (i < m_statusstring.length()) { switch (m_statusstring[i].unicode()) { case 'F': { unsigned long fs,ts; reader->sizes(fs,ts); status += filesize(ts); } break; case 'f': { status += filesize(reader->pagelocate()); } break; case 'D': { status += filesize(reader->buffdoc.endSection()-reader->buffdoc.startSection()); } break; case 'd': { status += filesize(reader->pagelocate()-reader->buffdoc.startSection()); } break; case 'P': { unsigned long fs,ts; reader->sizes(fs,ts); status += percent(reader->pagelocate(),ts); } break; case 'p': { status += percent(reader->pagelocate()-reader->buffdoc.startSection(),reader->buffdoc.endSection()-reader->buffdoc.startSection()); } break; case 'z': { // qDebug("case d"); status += QString().setNum(reader->m_fontControl.currentsize()*10); } break; default: status += m_statusstring[i]; } } } else { status += m_statusstring[i]; } } m_prog->setText(status); } void QTReaderApp::OnRedraw() { if ((pBkmklist != NULL) && (m_bkmkAvail != NULL)) { bool found = findNextBookmark(reader->pagelocate()); m_bkmkAvail->setEnabled(found); } if (m_scrollbar != NULL) { //qDebug("OnRedraw:[%u, %u]", reader->buffdoc.startSection(), reader->buffdoc.endSection()); scrollbar->setRange(reader->buffdoc.startSection(), reader->buffdoc.endSection()-1); scrollbar->setPageStep(reader->locate()-reader->pagelocate()); scrollbar->setValue((reader->m_rotated) ? (reader->buffdoc.endSection() - reader->locate()+reader->buffdoc.startSection()) : reader->pagelocate()); } if (m_prog->isVisible()) { // qDebug("updating status"); UpdateStatus(); // qDebug("updated status"); } } void QTReaderApp::showAnnotation() { m_annoWin->setName(toQString(m_anno->name())); m_annoWin->setAnno(toQString(m_anno->anno())); m_annoWin->setColor(QColor(m_anno->red(), m_anno->green(), m_anno->blue())); m_annoIsEditing = false; #ifdef USEQPE Global::showInputMethod(); #endif editorStack->raiseWidget( m_annoWin ); hidetoolbars(); m_annoWin->setFocus(); } void QTReaderApp::OnWordSelected(const QString& wrd, size_t posn, size_t posn2, const QString& line) { //// qDebug("OnWordSelected(%u):%s", posn, (const char*)wrd); + if (m_doOutput && reader->checkoutput()) + { + reader->doOutput(wrd); + } if (m_doClipboard) { QClipboard* cb = QApplication::clipboard(); cb->setText(wrd); #ifdef USEQPE if (wrd.length() > 10) { Global::statusMessage(wrd.left(8) + ".."); } else { Global::statusMessage(wrd); } #endif } if (m_doAnnotation) { // addAnno(wrd, "Need to be able to edit this", posn); m_annoWin->setName(line); m_annoWin->setAnno(""); m_annoWin->setPosn(posn); m_annoWin->setPosn2(posn2); m_annoIsEditing = true; #ifdef USEQPE Global::showInputMethod(); #endif editorStack->raiseWidget( m_annoWin ); hidetoolbars(); } #ifdef USEQPE if (m_doDictionary) { if (!m_targetapp.isEmpty() && !m_targetmsg.isEmpty()) { QCopEnvelope e(("QPE/Application/"+m_targetapp).utf8(), (m_targetmsg+"(QString)").utf8()); e << wrd; } } #endif } void QTReaderApp::doAction(QKeyEvent* e) { QMap<orKey,int>::Iterator f = kmap.end(); if (reader->m_autoScroll) { f = kmap.find(orKey(e->state(), e->key(), true)); } if (f == kmap.end()) { f = kmap.find(orKey(e->state(), e->key(), false)); } if (f == kmap.end()) { qDebug("doaction (no action) : %d %d %d", e->key(), e->state(), f.data()); e->ignore(); } else { qDebug("doaction (some action) : %d %d %d", e->key(), e->state(), f.data()); ActionTypes a = (ActionTypes)f.data(); e->accept(); // qDebug("Accepted"); switch (a) { case cesGotoLink: { reader->gotoLink(); } break; case cesNextLink: { reader->getNextLink(); } break; case cesInvertColours: m_inverse_action->setOn(!reader->bInverse); break; case cesToggleBars: m_hidebars = !m_hidebars; if (m_hidebars) { -#ifdef USEQPE +#if defined(USEQPE) menubar->hide(); #endif if (fileBar != NULL) fileBar->hide(); if (viewBar != NULL) viewBar->hide(); if (navBar != NULL) navBar->hide(); if (markBar != NULL) markBar->hide(); mb->hide(); } else { -#ifdef USEQPE +#if defined(USEQPE) menubar->show(); #endif if (fileBar != NULL) fileBar->show(); if (viewBar != NULL) viewBar->show(); if (navBar != NULL) navBar->show(); if (markBar != NULL) markBar->show(); mb->show(); } break; case cesToggleScrollBar: if (m_scrollbar != NULL) { if (m_scrollbar->isHidden()) { m_scrollishidden = false; m_scrollbar->show(); reader->m_scrollpos = (m_qtscroll == 0) ? m_localscroll : 0; } else { m_scrollishidden = true; m_scrollbar->hide(); reader->m_scrollpos = m_localscroll; } } break; case cesToggleStatusBar: if (m_prog != NULL) { if (m_prog->isHidden()) { m_statusishidden = false; m_prog->show(); } else { m_statusishidden = true; m_prog->hide(); } } break; case cesOpenFile: { qDebug("Open file"); fileOpen(); } break; case cesAutoScroll: { reader->setautoscroll(!reader->m_autoScroll); setScrollState(reader->m_autoScroll); } break; case cesActionMark: { addbkmk(); } break; case cesFullScreen: { m_actFullscreen->setOn(!m_fullscreen); } break; case cesRotate: { m_rotate_action->setOn(!reader->m_rotated); } break; case cesActionAnno: { addanno(); } break; case cesZoomIn: zoomin(); break; case cesZoomOut: zoomout(); break; case cesBack: reader->goBack(); break; case cesForward: reader->goForward(); break; case cesHome: reader->goHome(); break; case cesPageUp: reader->dopageup(); /* ftime(&m_lastkeytime); m_fndelay = m_debounce; // { timeb now; ftime(&now); m_fndelay = (1000*(now.time - m_lastkeytime.time) + now.millitm)-m_lastkeytime.millitm+100; } */ break; case cesPageDown: reader->dopagedn(); /* ftime(&m_lastkeytime); m_fndelay = m_debounce; // if (m_debounce != 0) { timeb now; ftime(&now); m_fndelay = (1000*(now.time - m_lastkeytime.time) + now.millitm)-m_lastkeytime.millitm+10; } */ break; case cesLineUp: reader->lineUp(); break; case cesLineDown: reader->lineDown(); break; case cesStartDoc: gotoStart(); break; case cesEndDoc: gotoEnd(); break; case cesScrollMore: reader->increaseScroll(); break; case cesScrollLess: reader->reduceScroll(); break; default: qDebug("Unknown ActionType:%u", a); break; } } } void QTReaderApp::setTwoTouch(bool _b) { reader->setTwoTouch(_b); } void QTReaderApp::restoreFocus() { reader->setFocus(); } void QTReaderApp::SaveConfig() { m_nRegAction = cSetConfigName; regEdit->setText(reader->m_string); do_regedit(); } void QTReaderApp::do_saveconfig(const QString& _txt, bool full) { // qDebug("do_saveconfig:%s", (const char*)_txt); #ifdef USEQPE QString configname; Config::Domain dom; if (full) { configname = _txt; dom = Config::User; } else { configname = Global::applicationFileName(APPDIR "/configs", _txt); dom = Config::File; } Config config(configname, dom); config.setGroup( "View" ); #else QFileInfo fi; if (full) { // qDebug("full:%s", (const char*)_txt); QDir d = QDir::home(); // "/" if ( !d.cd(_txt) ) { // "/tmp" qWarning( "Cannot find the \"~/%s\" directory", (const char*)_txt ); d = QDir::home(); d.mkdir(_txt); d.cd(_txt); } fi.setFile(d, INIFILE); } else { QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } if ( !d.cd("configs") ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "/configs\" directory" ); d = QDir::home(); d.cd(APPDIR); d.mkdir("configs"); d.cd("configs"); } fi.setFile(d, _txt); } // qDebug("Path:%s", (const char*)fi.absFilePath()); Config config(fi.absFilePath()); #endif config.writeEntry( "StripCr", reader->bstripcr ); + config.writeEntry( "NoInlineTables", reader->bNoInlineTables ); config.writeEntry( "AutoFmt", reader->bautofmt ); config.writeEntry( "TextFmt", reader->btextfmt ); config.writeEntry( "StripHtml", reader->bstriphtml ); config.writeEntry( "Dehyphen", reader->bdehyphen ); config.writeEntry( "Depluck", reader->bdepluck ); config.writeEntry( "Dejpluck", reader->bdejpluck ); config.writeEntry( "OneSpace", reader->bonespace ); config.writeEntry( "Unindent", reader->bunindent ); config.writeEntry( "Repara", reader->brepara ); config.writeEntry( "ReparaString", reader->m_reparastring); config.writeEntry( "BackgroundType" , (int)m_bgtype ); config.writeEntry( "Theme", m_themename ); config.writeEntry( "DoubleSpace", reader->bdblspce ); config.writeEntry( "Indent", reader->bindenter ); config.writeEntry( "FontSize", (int)(reader->m_fontControl.currentsize()) ); config.writeEntry( "ScrollDelay", reader->m_delay); config.writeEntry( "ScrollStep", reader->m_scrollstep); config.writeEntry( "ScrollType", reader->m_scrolltype ); if (full) { config.writeEntry("Debounce", m_debounce); config.writeEntry("FloatDialogs", m_bFloatingDialog); reader->m_lastposn = reader->pagelocate(); config.writeEntry( "LastFile", reader->m_lastfile ); config.writeEntry( "LastPosn", (int)(reader->pagelocate()) ); + config.writeEntry( "OutputCodec", reader->m_outputName); } config.writeEntry( "PageMode", reader->m_bpagemode ); config.writeEntry( "MonoSpaced", reader->m_bMonoSpaced ); config.writeEntry( "SwapMouse", reader->m_swapmouse); config.writeEntry( "IsRotated", reader->m_rotated ); config.writeEntry("StatusContent", m_statusstring); config.writeEntry("StatusHidden", m_statusishidden); config.writeEntry( "Background", m_background ); config.writeEntry( "Foreground", m_foreground ); config.writeEntry( "ScrollColour", m_scrollcolor ); config.writeEntry( "ScrollBarColour", m_scrollbarcolor ); config.writeEntry( "Hyphenate", reader->hyphenate ); // config.writeEntry( "CustomHyphen", reader->buffdoc.getCustomHyphen() ); config.writeEntry( "Fontname", reader->m_fontname ); config.writeEntry( "Encoding", reader->m_encd ); config.writeEntry( "CharSpacing", reader->m_charpc ); config.writeEntry( "Overlap", (int)(reader->m_overlap) ); config.writeEntry( "Top Margin", (int)reader->m_abstopmargin ); config.writeEntry( "Bottom Margin", (int)reader->m_absbottommargin ); config.writeEntry( "Left Margin", (int)reader->m_absleft_border ); config.writeEntry( "Right Margin", (int)reader->m_absright_border ); config.writeEntry( "TargetApp", m_targetapp ); config.writeEntry( "TargetMsg", m_targetmsg ); #ifdef _SCROLLPIPE config.writeEntry( "PipeTarget", reader->m_pipetarget ); config.writeEntry( "PauseAfterPara", reader->m_pauseAfterEachPara ); #endif config.writeEntry( "TwoTouch", m_twoTouch ); config.writeEntry( "Annotation", m_doAnnotation); config.writeEntry( "Dictionary", m_doDictionary); config.writeEntry( "Clipboard", m_doClipboard); + config.writeEntry( "OutputTgt", m_doOutput); /* config.writeEntry( "SpaceTarget", m_spaceTarget); config.writeEntry( "EscapeTarget", m_escapeTarget); config.writeEntry( "ReturnTarget", m_returnTarget); config.writeEntry( "LeftTarget", m_leftTarget); config.writeEntry( "RightTarget", m_rightTarget); config.writeEntry( "UpTarget", m_upTarget); config.writeEntry( "DownTarget", m_downTarget); config.writeEntry("LeftScroll", m_leftScroll); config.writeEntry("RightScroll", m_rightScroll); config.writeEntry("UpScroll", m_upScroll); config.writeEntry("DownScroll", m_downScroll); */ config.writeEntry( "Repalm", reader->brepalm ); + config.writeEntry( "UnderlineLink", reader->bunderlineLink ); config.writeEntry( "HideScrollBar", m_scrollishidden ); + config.writeEntry( "HideToolBar", m_hidebars ); config.writeEntry( "Kern", reader->bkern ); config.writeEntry( "Remap", reader->bremap ); config.writeEntry( "Peanut", reader->bpeanut ); config.writeEntry( "MakeBold", reader->bmakebold ); config.writeEntry( "Continuous", reader->m_continuousDocument ); + config.writeEntry( "DoubleBuffer", reader->m_doubleBuffered); config.writeEntry( "FullJust", reader->bfulljust ); // config.writeEntry( "Negative", reader->bNegative ); config.writeEntry( "Inverse", reader->bInverse ); config.writeEntry( "FixGraphics", reader->m_fontControl.FixGraphics()); config.writeEntry( "ExtraSpace", reader->getextraspace() ); config.writeEntry( "ExtraLead", reader->getlead() ); config.writeEntry( "Basesize", (int)reader->getBaseSize()); config.writeEntry( "RequestorFontChange", m_propogatefontchange); #ifdef USEQPE config.writeEntry( "GrabKeyboard", m_grabkeyboard ); #endif if (full) { config.setGroup( "Toolbar" ); config.writeEntry("QTScrollBar", m_qtscroll); config.writeEntry("LocalScrollBar", m_localscroll); config.writeEntry("Movable", m_tbmovesave); config.writeEntry("Policy", m_tbpolsave); config.writeEntry("Position", m_tbposition); #ifndef USEQPE if (!isMaximized() && !isMinimized()) { config.setGroup( "Geometry" ); config.writeEntry( "x", x() ); config.writeEntry( "y", y() ); config.writeEntry( "width", width() ); config.writeEntry( "height", height() ); } #endif } } #ifdef _SCROLLPIPE void QTReaderApp::setpipetarget() { m_nRegAction = cSetPipeTarget; QString text = (reader->m_pipetarget.isEmpty()) ? QString("") : reader->m_pipetarget; regEdit->setText(text); do_regedit(); } void QTReaderApp::do_setpipetarget(const QString& _txt) { reader->m_pipetarget = _txt; } void QTReaderApp::setpause(bool sfs) { reader->m_pauseAfterEachPara = sfs; } #endif void QTReaderApp::monospace(bool _b) { reader->setmono(_b); } bool QTReaderApp::readconfig(const QString& dirname, const QString& _txt, bool full=false) { #ifdef USEQPE QString configname; Config::Domain dom; if (full) { configname = _txt; dom = Config::User; } else { configname = Global::applicationFileName(dirname, _txt); QFileInfo fm(configname); if ( !fm.exists() ) return false; dom = Config::File; } Config config(configname, dom); config.setGroup( "View" ); #else QString fullname; if (full) { fullname = QDir::homeDirPath() + "/" + _txt + "/" + INIFILE; } else { fullname = QDir::homeDirPath() + "/" + dirname + "/" + _txt; } if (!QFile::exists(fullname)) return false; Config config(fullname); #endif if (full) { config.setGroup("Toolbar"); m_tbmovesave = m_tbmove = config.readBoolEntry("Movable", m_tbmovesave); m_tbpolsave = m_tbpol = (ToolbarPolicy)config.readNumEntry("Policy", m_tbpolsave); m_tbposition = (ToolBarDock)config.readNumEntry("Position", m_tbposition); } config.setGroup( "View" ); m_bFloatingDialog = config.readBoolEntry("FloatDialogs", m_bFloatingDialog); reader->bstripcr = config.readBoolEntry( "StripCr", reader->bstripcr ); + reader->bNoInlineTables = config.readBoolEntry( "NoInlineTables", reader->bNoInlineTables ); reader->bfulljust = config.readBoolEntry( "FullJust", reader->bfulljust ); reader->bInverse = config.readBoolEntry( "Inverse", reader->bInverse ); // reader->bNegative = config.readBoolEntry( "Negative", false ); reader->m_fontControl.FixGraphics(config.readBoolEntry( "FixGraphics", reader->m_fontControl.FixGraphics() )); reader->setextraspace(config.readNumEntry( "ExtraSpace", reader->getextraspace() )); reader->setlead(config.readNumEntry( "ExtraLead", reader->getlead() )); reader->btextfmt = config.readBoolEntry( "TextFmt", reader->btextfmt ); reader->bautofmt = config.readBoolEntry( "AutoFmt", reader->bautofmt ); reader->bstriphtml = config.readBoolEntry( "StripHtml", reader->bstriphtml ); reader->bpeanut = config.readBoolEntry( "Peanut", reader->bpeanut ); reader->bdehyphen = config.readBoolEntry( "Dehyphen", reader->bdehyphen ); reader->bdepluck = config.readBoolEntry( "Depluck", reader->bdepluck ); reader->bdejpluck = config.readBoolEntry( "Dejpluck", reader->bdejpluck ); reader->bonespace = config.readBoolEntry( "OneSpace", reader->bonespace ); reader->bunindent = config.readBoolEntry( "Unindent", reader->bunindent ); reader->brepara = config.readBoolEntry( "Repara", reader->brepara ); reader->m_reparastring = config.readEntry( "ReparaString", reader->m_reparastring); m_bgtype = (bground)config.readNumEntry( "BackgroundType" , m_bgtype ); m_themename = config.readEntry("Theme", m_themename ); reader->bdblspce = config.readBoolEntry( "DoubleSpace", reader->bdblspce ); reader->bindenter = config.readNumEntry( "Indent", reader->bindenter ); reader->m_textsize = config.readNumEntry( "FontSize", reader->m_textsize ); reader->m_delay = config.readNumEntry( "ScrollDelay", reader->m_delay); reader->m_scrollstep = config.readNumEntry( "ScrollStep", reader->m_scrollstep); reader->m_scrolltype = config.readNumEntry( "ScrollType", reader->m_scrolltype); if (full) { reader->m_lastfile = config.readEntry( "LastFile", reader->m_lastfile ); reader->m_lastposn = config.readNumEntry( "LastPosn", reader->m_lastposn ); } reader->m_bpagemode = config.readBoolEntry( "PageMode", reader->m_bpagemode ); reader->m_bMonoSpaced = config.readBoolEntry( "MonoSpaced", reader->m_bMonoSpaced); reader->m_rotated = config.readBoolEntry( "IsRotated", reader->m_rotated ); m_statusstring = config.readEntry("StatusContent", m_statusstring); m_statusishidden = config.readBoolEntry("StatusHidden", m_statusishidden); m_background = config.readNumEntry( "Background", m_background ); reader->setBackground(getcolour(m_background)); m_foreground = config.readNumEntry( "Foreground", m_foreground ); reader->setForeground(getcolour(m_foreground)); m_scrollcolor = config.readNumEntry( "ScrollColour", m_scrollcolor); setscrollcolour(); m_scrollbarcolor = config.readNumEntry( "ScrollBarColour", m_scrollbarcolor); setscrollbarcolour(); reader->hyphenate = config.readBoolEntry( "Hyphenate", reader->hyphenate ); // reader->buffdoc.setCustomHyphen(config.readBoolEntry( "CustomHyphen", false )); reader->m_swapmouse = config.readBoolEntry( "SwapMouse", reader->m_swapmouse); reader->m_fontname = config.readEntry( "Fontname", reader->m_fontname ); reader->m_encd = config.readNumEntry( "Encoding", reader->m_encd ); reader->m_charpc = config.readNumEntry( "CharSpacing", reader->m_charpc ); reader->m_overlap = config.readNumEntry( "Overlap", reader->m_overlap ); reader->m_abstopmargin = config.readNumEntry( "Top Margin", reader->m_abstopmargin ); reader->m_absbottommargin = config.readNumEntry( "Bottom Margin", reader->m_absbottommargin ); reader->m_absleft_border = config.readNumEntry( "Left Margin", reader->m_absleft_border ); reader->m_absright_border = config.readNumEntry( "Right Margin", reader->m_absright_border ); m_scrollishidden = config.readBoolEntry( "HideScrollBar", m_scrollishidden ); + m_hidebars = config.readBoolEntry( "HideToolBar", m_hidebars ); reader->brepalm = config.readBoolEntry( "Repalm", reader->brepalm ); + reader->bunderlineLink = config.readBoolEntry( "UnderlineLink", reader->bunderlineLink ); reader->bkern = config.readBoolEntry( "Kern", reader->bkern ); reader->bremap = config.readBoolEntry( "Remap", reader->bremap ); reader->bmakebold = config.readBoolEntry( "MakeBold", reader->bmakebold ); reader->setContinuous(config.readBoolEntry( "Continuous", reader->m_continuousDocument )); + reader->setDoubleBuffer(config.readBoolEntry("DoubleBuffer", reader->m_doubleBuffered)); m_targetapp = config.readEntry( "TargetApp", m_targetapp ); m_targetmsg = config.readEntry( "TargetMsg", m_targetmsg ); #ifdef _SCROLLPIPE reader->m_pipetarget = config.readEntry( "PipeTarget", reader->m_pipetarget ); reader->m_pauseAfterEachPara = config.readBoolEntry( "PauseAfterPara", reader->m_pauseAfterEachPara ); #endif m_twoTouch = config.readBoolEntry( "TwoTouch", m_twoTouch); m_doAnnotation = config.readBoolEntry( "Annotation", m_doAnnotation); m_doDictionary = config.readBoolEntry( "Dictionary", m_doDictionary); m_doClipboard = config.readBoolEntry( "Clipboard", m_doClipboard); + m_doOutput = config.readBoolEntry( "OutputTgt", m_doOutput); #ifdef USEQPE m_grabkeyboard = config.readBoolEntry( "GrabKeyboard", m_grabkeyboard); #endif m_propogatefontchange = config.readBoolEntry( "RequestorFontChange", m_propogatefontchange); reader->setBaseSize(config.readNumEntry( "Basesize", reader->getBaseSize() )); reader->setTwoTouch(m_twoTouch); + reader->m_outputName = config.readEntry( "OutputCodec", reader->m_outputName); + m_touch_action->setOn(m_twoTouch); m_setmono_action->setOn(reader->m_bMonoSpaced); setfontHelper(reader->m_fontname); if (full) { addtoolbars(&config); } reader->setfilter(reader->getfilter()); reader->refresh(); return true; } bool QTReaderApp::PopulateConfig(const char* tgtdir, bool usedirs) { bkmkselector->clear(); bkmkselector->setText("Cancel"); #ifndef USEQPE int cnt = 0; QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } if ( !d.cd(tgtdir) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "/%s\" directory", tgtdir ); d = QDir::home(); d.mkdir(tgtdir); d.cd(tgtdir); } d.setFilter( ((usedirs) ? QDir::Dirs : QDir::Files) | QDir::NoSymLinks ); // d.setSorting( QDir::Size | QDir::Reversed ); const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); // create list iterator QFileInfo *fi; // pointer for traversing while ( (fi=it.current()) ) { // for each file... - bkmkselector->insertItem(fi->fileName()); - cnt++; + bkmkselector->insertItem(fi->fileName(), cnt++); //qDebug( "%10li %s", fi->size(), fi->fileName().data() ); ++it; // goto next list element } #else /* USEQPE */ int cnt = 0; DIR *d; char* finaldir; finaldir = new char[strlen(APPDIR)+1+strlen(tgtdir)+1]; strcpy(finaldir, APPDIR); strcat(finaldir, "/"); strcat(finaldir, tgtdir); d = opendir((const char *)Global::applicationFileName(finaldir,"")); while(1) { struct dirent* de; struct stat buf; de = readdir(d); if (de == NULL) break; if (lstat((const char *)Global::applicationFileName(finaldir,de->d_name),&buf) == 0 && ((usedirs && S_ISDIR(buf.st_mode)) || (!usedirs && S_ISREG(buf.st_mode)))) { - bkmkselector->insertItem(de->d_name); - cnt++; + bkmkselector->insertItem(de->d_name, cnt++); } } delete [] finaldir; closedir(d); #endif return (cnt > 0); } void QTReaderApp::LoadTheme() { if (PopulateConfig("Themes", true)) { editorStack->raiseWidget( bkmkselector ); hidetoolbars(); m_nBkmkAction = cLdTheme; } else QMessageBox::information(this, PROGNAME, "No config files"); } void QTReaderApp::LoadConfig() { if (PopulateConfig("configs")) { editorStack->raiseWidget( bkmkselector ); hidetoolbars(); m_nBkmkAction = cLdConfig; } else QMessageBox::information(this, PROGNAME, "No config files"); } void QTReaderApp::TidyConfig() { if (PopulateConfig("configs")) { editorStack->raiseWidget( bkmkselector ); hidetoolbars(); m_nBkmkAction = cRmConfig; } else QMessageBox::information(this, PROGNAME, "No config files"); } void QTReaderApp::ExportLinks() { if (PopulateConfig("urls")) { editorStack->raiseWidget( bkmkselector ); hidetoolbars(); m_nBkmkAction = cExportLinks; } else QMessageBox::information(this, PROGNAME, "No url files"); } void QTReaderApp::OnURLSelected(const QString& href, const size_t tgt) { #ifndef USEQPE qDebug("URL:%s", (const char*)href); int col = href.find(':'); if (col > 0) { QString type = href.left(col); qDebug("Type:%s", (const char*)type); } else { qDebug("No type"); } + QString msg = "External URL\n" + href; + QMessageBox::information(this, PROGNAME, msg); #else if (href.isEmpty()) { QMessageBox::information(this, PROGNAME, "No URL information supplied"); } else { CURLDialog* urld = new CURLDialog(href, false, this); urld->clipboard(m_url_clipboard); urld->localfile(m_url_localfile); urld->globalfile(m_url_globalfile); if (urld->exec()) { m_url_clipboard = urld->clipboard(); m_url_localfile = urld->localfile(); m_url_globalfile = urld->globalfile(); if (m_url_clipboard) { QClipboard* cb = QApplication::clipboard(); cb->setText(href); qDebug("<a href=\"%s\">%s</a>", (const char*)href, (const char*)href); } if (m_url_localfile) { writeUrl(reader->m_string, href); } if (m_url_globalfile) { writeUrl("GlobalURLFile", href); } } delete urld; } #endif } void QTReaderApp::writeUrl(const QString& file, const QString& href) { QString filename; #ifdef USEQPE filename = Global::applicationFileName(APPDIR "/urls", file); #else QFileInfo fi; QDir d = QDir::home(); // "/" if ( !d.cd(APPDIR) ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "\" directory" ); d = QDir::home(); d.mkdir(APPDIR); d.cd(APPDIR); } if ( !d.cd("urls") ) { // "/tmp" qWarning( "Cannot find the \"~/" APPDIR "/urls\" directory" ); d = QDir::home(); d.cd(APPDIR); d.mkdir("urls"); d.cd("urls"); } fi.setFile(d, file); filename = fi.absFilePath(); #endif FILE* fout = fopen(filename, "a"); if (fout != NULL) { fprintf(fout, "<p><a href=\"%s\">%s</a>\n", (const char*)href, (const char*)href); fclose(fout); } else { QMessageBox::warning(this, PROGNAME, "Problem with writing URL"); } } QColor QTReaderApp::getcolour(int _c) { QColor c = white; switch (_c) { case 0: c = white; break; case 1: c = black; break; case 2: c = darkGray; break; case 3: c = gray; break; case 4: c = lightGray; break; case 5: c = red; break; case 6: c = green; break; case 7: c = blue; break; case 8: c = cyan; break; case 9: c = magenta; break; case 10: c = yellow; break; case 11: c = darkRed; break; case 12: c = darkGreen; break; case 13: c = darkBlue; break; case 14: c = darkCyan; break; case 15: c = darkMagenta; break; case 16: c = darkYellow; break; default: c = lightGray; break; } return c; } void QTReaderApp::setscrollcolour() { /* QColor xc = getcolour(m_scrollcolor); int r,g,b; xc.rgb(&r,&g,&b); reader->m_scrollcolor.setRgb(255^r, 255^g, 255^b); */ reader->m_scrollcolor = getcolour(m_scrollcolor); } void QTReaderApp::setscrollbarcolour() { /* QColor xc = getcolour(m_scrollcolor); int r,g,b; xc.rgb(&r,&g,&b); reader->m_scrollcolor.setRgb(255^r, 255^g, 255^b); */ reader->m_scrollbarcolor = getcolour(m_scrollbarcolor); } void QTReaderApp::forceopen(const QString& filename) { /* QFileInfo fi(reader->m_lastfile); fi = QFileInfo(filename); QString flnm = fi.absFilePath(); */ - if (!filename.isEmpty()) + if (!filename.isEmpty() && QFileInfo(filename).exists()) { updatefileinfo(); if (pBkmklist != NULL) { if (m_fBkmksChanged) { savebkmks(); } delete pBkmklist; pBkmklist = NULL; m_fBkmksChanged = false; } reader->disableAutoscroll(); openFile(filename); reader->setFocus(); } + else + { + OnURLSelected(filename, 0); + } } void QTReaderApp::actionscroll(int v) { if (reader->m_rotated) { reader->dopageup(reader->buffdoc.startSection()+reader->buffdoc.endSection()-v); } else { /* if (reader->pagelocate() < v) { while (reader->pagelocate() < v) reader->lineDown(); } else */ reader->locate(v); } } void QTReaderApp::setBackgroundBitmap() { #ifdef USEQPE QString file = APPDIR "/Themes/"; file += m_themename; QString tgt = Global::applicationFileName(file,"background"); #else QString tgt(QDir::homeDirPath()); tgt += QString("/" APPDIR "/Themes/") + m_themename + "/background"; #endif qDebug("Trying to load %s", (const char *)tgt); QPixmap pm(tgt); reader->setBackgroundBitmap(pm, m_bgtype); } /* myChannel = new QCopChannel( "QPE/FooBar", this ); connect( myChannel, SIGNAL(received(const QCString &, const QByteArray &)), this, SLOT(fooBarMessage( const QCString &, const QByteArray &)) ); */ diff --git a/noncore/apps/opie-reader/QTReaderApp.h b/noncore/apps/opie-reader/QTReaderApp.h index ad47fc9..ab1b7ad 100644 --- a/noncore/apps/opie-reader/QTReaderApp.h +++ b/noncore/apps/opie-reader/QTReaderApp.h @@ -1,484 +1,485 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qt Palmtop Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef __QTREADERAPP_H #define __QTREADERAPP_H //#define _SCROLLPIPE //#define __ISEARCH //#define MAX_ENCODING 6 #define MAX_ACTIONS 5 #include <sys/timeb.h> #include <qmainwindow.h> #include "CExpander.h" #include "CEncoding.h" #include <qlist.h> //#include <qpe/filemanager.h> #include <qmap.h> #include <qlineedit.h> #include <qstack.h> #include <qlistbox.h> #ifdef USEQPE #include <qpe/qpeapplication.h> #endif #include "orkey.h" //#include "Queue.h" #include "BGType.h" class QBoxLayout; class QWidgetStack; class QToolButton; class QPopupMenu; class QToolBar; #ifdef USEQPE class QPEToolBar; class QPEMenuBar; #endif class QScrollBar; class CBkmkSelector; class QProgressBar; class QAction; class CAnnoEdit; class QFloatBar; class CDrawBuffer; class QTReader; class QImage; class Config; class CButtonPrefs; #ifdef USEQPE enum ToolbarPolicy { cesSingle = 0, cesMenuTool, cesMultiple }; #else enum ToolbarPolicy { cesMenuTool = 0, cesMultiple }; #endif enum regedit_type { cAutoGen, cAddBkmk, cJump, cMonoSpace, cSetTarget, #ifdef _SCROLLPIPE cSetPipeTarget, #endif cSetConfigName, cMargin, cExtraSpace, cExtraLead, cRepara }; enum bkmk_action { cOpenFile, cGotoBkmk, cDelBkmk, cRmBkmkFile, cLdConfig, cRmConfig, cExportLinks, cLdTheme }; enum fontselector_action { cChooseFont, cChooseEncoding }; #ifdef __ISEARCH struct searchrecord { QString s; size_t pos; searchrecord(const QString& _s, size_t _pos) : s(_s), pos(_pos) {} }; #endif class infowin; class GraphicWin; class QTReaderApp : public QMainWindow { Q_OBJECT QColor getcolour(int c); QMap<orKey, int> kmap; unsigned long m_savedpos; int m_debounce; bool m_kmapchanged; bground m_bgtype; timeb m_lastkeytime; QScrollBar* m_scrollbar; QScrollBar* scrollbar; int m_qtscroll, m_localscroll; bool m_hidebars, m_scrollishidden, m_statusishidden; QBoxLayout *m_layout; QLabel* m_prog; bool m_annoIsEditing; bool m_propogatefontchange, m_bFloatingDialog; bool m_url_clipboard, m_url_localfile, m_url_globalfile; CButtonPrefs* m_buttonprefs; fontselector_action m_fontAction; void doAction(QKeyEvent* e); public: QTReaderApp( QWidget *parent = 0, const char *name = 0, WFlags f = 0 ); ~QTReaderApp(); void hideEvent(QHideEvent*) { #ifdef USEQPE if (m_grabkeyboard) { ((QPEApplication*)qApp)->ungrabKeyboard(); } #endif suspend(); } #ifdef USEQPE void showEvent(QShowEvent*) { if (m_grabkeyboard) { ((QPEApplication*)qApp)->grabKeyboard(); } } #endif void suspend(); - void openFile( const QString & ); + void openFile( const QString &, unsigned int loc = 0 ); protected: void setfontHelper(const QString& lcn, int size = 0); QAction* m_bkmkAvail, *m_actFullscreen; CAnnoEdit* m_annoWin; Bkmk* m_anno; int m_scrollcolor, m_scrollbarcolor, m_background, m_foreground; // void resizeEvent(QResizeEvent* e); void closeEvent( QCloseEvent *e ); -#ifdef NEWFULLSCREEN +#if defined(USEQPE) && defined(USENEWFULLSCREEN) + bool m_usenewfullscreen; void resizeEvent(QResizeEvent *); void focusInEvent(QFocusEvent*); - void enableFullscreen(); #endif void readbkmks(); void do_mono(const QString&); void do_jump(const QString&); void do_reparastring(const QString&); void do_settarget(const QString&); #ifdef _SCROLLPIPE // void do_setpipetarget(const QString&); #endif void do_saveconfig(const QString&, bool); bool readconfig(const QString&, const QString&, bool); bool PopulateConfig(const char*, bool usedirs = false); ActionTypes ActNameToInt(const QString&); #ifdef USEQPE bool m_grabkeyboard; #endif bool m_doAnnotation; bool m_doDictionary; + bool m_doOutput; bool m_doClipboard; bool m_fullscreen; bool m_loadedconfig; public: void saveprefs(); public slots: void setBackgroundBitmap(); void UpdateStatus(); void setScrollState(bool _b); void handlekey(QKeyEvent* e); void forceopen(const QString& filename); void setDocument(const QString&); private slots: #ifdef _SCRIPT // void RunScript(); #endif void actionscroll(int v); void SaveConfig(); void LoadTheme(); void LoadConfig(); void TidyConfig(); void ExportLinks(); void zoomin(); void zoomout(); void chooseencoding(); void setfullscreen(bool sfs); void setrotated(bool sfs); void setinverted(bool sfs); void setgrab(bool sfs); // void setcontinuous(bool sfs); void setTwoTouch(bool _b); void restoreFocus(); void OnAnnotation(bool _b) { m_doAnnotation = _b; } void OnDictionary(bool _b) { m_doDictionary = _b; } void OnClipboard(bool _b) { m_doClipboard = _b; } void OnWordSelected(const QString&, size_t, size_t, const QString&); void OnURLSelected(const QString& href, const size_t tgt); void showgraphic(QImage&); void addAnno(const QString&, const QString&, size_t, size_t); void addAnno(const QString&, const QString&); void addanno(); void showAnnotation(); void do_setencoding(int i); void do_setfont(const QString&); // void buttonActionSelected(QAction*); void msgHandler(const QCString&, const QByteArray&); void monospace(bool); void jump(); void reparastring(); void settarget(); #ifdef _SCROLLPIPE // void setpipetarget(); // void setpause(bool); #endif // void setspacing(); void setfont(); void clearBkmkList(); void listBkmkFiles(); void editMark(); void autoScroll(bool); void addbkmk(); void savebkmks(); // void importFiles(); void showprefs(); void showtoolbarprefs(); void showbuttonprefs(); void infoClose(); // void oldFile(); void showinfo(); // void indentplus(); // void indentminus(); void fileOpen(); void fileClose(); void editCopy(); void editFind(); void gotoStart(); void gotoEnd(); void pageup(); void pagedn(); void findNext(); void findClose(); void regClose(); #ifdef __ISEARCH // void search( const QString& ); #else void search(); #endif void showEditTools(); // void stripcr(bool); // void setfulljust(bool); // void onespace(bool); // void repalm(bool); // void peanut(bool _b); // void remap(bool); // void embolden(bool); // void autofmt(bool); // void textfmt(bool); // void striphtml(bool); // void dehyphen(bool); // void depluck(bool); // void dejpluck(bool); // void unindent(bool); // void repara(bool); // void dblspce(bool); void pagemode(bool); // void gotobkmk(const QString& bm); void gotobkmk(int); void cancelbkmk(); void do_gotomark(); void do_delmark(); void do_autogen(); void do_regaction(); void OnRedraw(); private: void setscrollcolour(); void setscrollbarcolour(); void writeUrl(const QString& file, const QString& href); QAction *m_preferences_action, *m_open_action, *m_close_action; QAction *m_info_action, *m_touch_action, *m_find_action, *m_start_action; QAction *m_end_action, *m_jump_action, *m_pageline_action; QAction *m_pageup_action, *m_pagedn_action, *m_back_action; QAction *m_home_action, *m_forward_action, *m_zoomin_action; QAction *m_zoomout_action, *m_setfont_action, *m_mark_action; QAction *m_annotate_action, *m_goto_action, *m_delete_action; QAction *m_autogen_action, *m_clear_action, *m_save_action; QAction *m_tidy_action, *m_startBlock_action, *m_endBlock_action; QAction *m_setenc_action, *m_setmono_action, *m_saveconfig_action; QAction *m_loadconfig_action, *m_loadtheme_action, *m_toolbarprefs_action, *m_tidyconfig_action; QAction *m_exportlinks_action, *m_rotate_action, *m_buttonprefs_action, *m_inverse_action; QAction *m_repara_action; #ifdef USEQPE QAction *m_grab_action; #endif void addtoolbars(Config* config); ToolbarPolicy m_tbpol, m_tbpolsave; ToolBarDock m_tbposition; bool m_tbmove, m_tbmovesave; QToolBar* filebar(); QToolBar* viewbar(); QToolBar* navbar(); QToolBar* markbar(); void hidetoolbars(); void addfilebar(Config* _config, const QString& key, QAction* a); void addviewbar(Config* _config, const QString& key, QAction* a); void addnavbar(Config* _config, const QString& key, QAction* a); void addmarkbar(Config* _config, const QString& key, QAction* a); bool checkbar(Config* _config, const QString& key); #ifdef _SCRIPT void SaveScript(const char* sname); #endif /* void setstate(unsigned char* _sd, unsigned short _sdlen); void getstate(unsigned char*& data, unsigned short& len); */ void fileOpen2(); void readfilelist(); void savefilelist(); void updatefileinfo(); bool openfrombkmk(Bkmk*); QString m_targetapp, m_targetmsg, m_statusstring, m_themename; - bool listbkmk(CList<Bkmk>*, const QString& _lab = QString::null); + bool listbkmk(CList<Bkmk>*, const QString& _lab = QString::null, bool presel=false); QString usefilebrowser(); void do_regedit(); void colorChanged( const QColor &c ); void clear(); void updateCaption(); void do_autogen(const QString&); void do_addbkmk(const QString&); bool findNextBookmark(size_t start); private: QAction* m_scrollButton; QAction* m_buttonAction[MAX_ACTIONS]; CBkmkSelector* bkmkselector; // ActionTypes m_spaceTarget, m_escapeTarget, m_returnTarget, m_leftTarget, m_rightTarget, //m_upTarget, m_downTarget; //bool m_leftScroll, m_rightScroll, m_upScroll, m_downScroll; bool m_bcloseDisabled, m_disableesckey; size_t searchStart; #ifdef __ISEARCH QStack<searchrecord>* searchStack; bool dosearch(size_t start, CDrawBuffer& test, const QString& arg); #else bool dosearch(size_t start, CDrawBuffer& test, const QRegExp& arg); #endif QWidgetStack *editorStack; QTReader* reader; QComboBox* m_fontSelector; // QPEToolBar /* *menu,*/ *fileBar; -#ifdef USEQPE +#if defined(USEQPE) QToolBar *menubar; #endif QToolBar *fileBar, *navBar, *viewBar, *markBar; -#ifdef USEQPE +#if defined(USEQPE) QPEMenuBar *mb; #else QMenuBar *mb; #endif QFloatBar *searchBar, *regBar/*, *m_fontBar*/; QToolBar /* *searchBar, *regBar,*/ *m_fontBar; QLineEdit *searchEdit, *regEdit; bool searchVisible; bool regVisible; bool m_fontVisible, m_twoTouch; static unsigned long m_uid; long unsigned get_unique_id() { return m_uid++; } /* void resizeEvent( QResizeEvent * r) { // qDebug("resize:(%u,%u)", r->oldSize().width(), r->oldSize().height()); // qDebug("resize:(%u,%u)", r->size().width(), r->size().height()); // bgroup->move( width()-bgroup->width(), 0 ); } */ CList<Bkmk>* pBkmklist; CList<Bkmk>* pOpenlist; infowin* m_infoWin; GraphicWin* m_graphicwin; QProgressBar* pbar; bool m_fBkmksChanged; // int m_nRegAction; regedit_type m_nRegAction; bkmk_action m_nBkmkAction; QString m_autogenstr; bool m_dontSave; }; //const int cAutoGen = 0; //const int cAddBkmk = 1; //const int cDelBkmk = 2; //const int cGotoBkmk = 3; //const int cRmBkmkFile = 4; //const int cJump = 5; //const int cMonoSpace = 6; //const int cOverlap = 7; //const int cSetTarget = 8; //const int cOpenFile = 9; //const int cSetPipeTarget = 10; //const int cSetConfigName = 11; //const int cMargin = 12; //const int cExtraSpace = 14; //const int cExtraLead = 15; //const int cGfxSize = 16; //const int cChooseFont = 2; //const int cChooseEncoding = 1; #endif diff --git a/noncore/apps/opie-reader/Reb.cpp b/noncore/apps/opie-reader/Reb.cpp new file mode 100644 index 0000000..2e6c1fc --- a/dev/null +++ b/noncore/apps/opie-reader/Reb.cpp @@ -0,0 +1,789 @@ +#include <stdio.h> +#include <string.h> +#include <qimage.h> +#include "decompress.h" +#include "Reb.h" +#include "my_list.h" +#include "Bkmks.h" +#include "Model.h" +/* +#ifdef offsetof +#define OffsetOf(type, field) ((int) offsetof(type, field)) +#else +#define OffsetOf(type, field) ((int) ((char *) &((type *) 0)->field)) +#endif + +template<class T> +UInt32 binarychop(T* data, UInt32 n, T val) +{ + UInt32 jl = 0,jh = n-1,jm = (jl+jh)/2; + while (jh > jl+1) + { + if (data[jm] > val) + { + jh = jm; + } + else + { + jl = jm; + } + jm = (jl+jh)/2; + } + return jl; +} + +template<class T, class D> +UInt32 binarychop(D* data, UInt32 n, T val, UInt32 offset) +{ + UInt32 jl = 0,jh = n-1,jm = (jl+jh)/2; + while (jh > jl+1) + { + T* d = reinterpret_cast<T*>(reinterpret_cast<char*>(data+jm)+offset); + if (*d > val) + { + jh = jm; + } + else + { + jl = jm; + } + jm = (jl+jh)/2; + } + return jl; +} +*/ + +CReb::CReb() +: + fin(NULL), m_indexpages(NULL), m_pagedetails(NULL),tagoffset(0), + tags(NULL), paras(NULL), noparas(0), joins(NULL), nojoins(0) +{ +} + +CReb::~CReb() +{ + if (fin != NULL) fclose(fin); + if (m_indexpages != NULL) delete [] m_indexpages; + if (m_pagedetails != NULL) delete [] m_pagedetails; + if (tags != NULL) delete [] tags; + if (paras != NULL) delete [] paras; + if (joins != NULL) delete [] joins; +} + +unsigned int CReb::locate() +{ + return m_pagedetails[currentpage.pageno()].pagestart+currentpage.offset(); +} + +void CReb::locate(unsigned int n) +{ + /* + UInt32 cp = nopages-1; + for (int i = 0; i < nopages; ++i) + { + if (m_pagedetails[i].pagestart > n) + { + cp = i-1; + break; + } + } + qDebug("Requesting %u from page %u [%u]", n, cp, n - m_pagedetails[cp].pagestart); + */ + //UInt32 jl = binarychop<UInt32, Page_detail>(m_pagedetails, nopages, n, OffsetOf(Page_detail, pagestart)); + + UInt32 jl = 0,jh = nopages-1,jm = (jl+jh)/2; + while (jh > jl+1) + { + if (m_pagedetails[jm].pagestart > n) + { + jh = jm; + } + else + { + jl = jm; + } + jm = (jl+jh)/2; + } + + unsuspend(); + Page_detail rs = m_pagedetails[jl]; + UInt32 val = n - rs.pagestart; + if (jl != currentpage.pageno()) readindex(jl); + currentpage.setoffset(page2pos(jl), jl, ((rs.flags & 8) != 0), rs.len, val); + if (noparas > 0) + { + //jl = binarychop<int, ParaRef>(paras, noparas, val, OffsetOf(ParaRef, pos)); + + UInt32 jl = 0,jh = noparas-1,jm = (jl+jh)/2; + while (jh > jl+1) + { + if (paras[jm].pos > val) + { + jh = jm; + } + else + { + jl = jm; + } + jm = (jl+jh)/2; + } + + qDebug("TAGS:%s", (const char*)tags[paras[jl].tag]); + tagstring = tags[paras[jl].tag]+"<br>"; // Add br to set extra space to 0 + tagoffset = 0; + } + unsigned long current = locate(); + if (m_currentstart > current || current > m_currentend) + { + start2endSection(); + } + if (current != n) qDebug("ERROR:Ended up at %u", current); +} + +bool CReb::getFile(const QString& href, const QString& nm) +{ + qDebug("File:%s, Name:%s", (const char*)href, (const char*)nm); + QMap<QString, UInt32>::Iterator iter = m_index.find(href); + if (iter != m_index.end()) + { + qDebug("REB:BEFORE:%u", locate()); + startpage(iter.data()); + qDebug("REB:AFTER:%u", locate()); + return true; + } + else + { + return false; + } +} + +QImage* CReb::getPicture(const QString& ref) +{ + QMap<QString, UInt32>::Iterator iter = m_index.find(ref); + if (iter != m_index.end()) + { + unsuspend(); + Page_detail rs = m_pagedetails[iter.data()]; + char* imgbuffer = new char[rs.len]; + fseek(fin, page2pos(iter.data()), SEEK_SET); + fread(imgbuffer, rs.len, 1, fin); + QByteArray arr; + arr.assign((const char*)imgbuffer, rs.len); + QImage* qimage = new QImage(arr); + return qimage; + } + else + { + return NULL; + } +} + +CList<Bkmk>* CReb::getbkmklist() { return NULL; } + +void CReb::home() +{ + startpage(m_homepage); +} + +int CReb::OpenFile(const char *src) +{ + m_binary = false; + if (fin != NULL) fclose(fin); + fin = fopen(src, "r"); + if (fin == NULL) + { + return -1; + } + UInt32 type; + fseek(fin, 6, SEEK_SET); + fread(&type, 1, sizeof(type), fin); + qDebug("CREB:Okay %x", type); + + if (type == 0x4f56554e || type == 0x574d4954 || type == 0x576d6954) + { + struct stat _stat; + stat(src, &_stat); + file_length = _stat.st_size; + fread(&m_blocksize, 1, sizeof(m_blocksize), fin); + if (type == 0x574d4954 || type == 0x576d6954) + { + if (type == 0x576d6954) m_binary = true; + qDebug("Blocksize(1) %x", m_blocksize); + unsigned char ct = (m_blocksize >> 24) & 0xff; + qDebug("Compress type:%x", ct); + switch (ct) + { + case 0: + m_decompress = UnZip; + break; + case 3: + m_decompress = getdecompressor("PluckerDecompress3"); + break; + case 4: + m_decompress = getdecompressor("PluckerDecompress4"); + break; + } + if (m_decompress == NULL) return -1; + m_blocksize = 1024*(m_blocksize & 0xffffff); + } + else + { + m_blocksize = 4096; + m_decompress = UnZip; + } + qDebug("Blocksize %u", m_blocksize); + currentpage.init(fin, m_blocksize, m_decompress); + qDebug("Its a REB!!!!"); + fseek(fin, 0x18, SEEK_SET); + fread(&toc, 1, sizeof(toc), fin); + qDebug("Expect this to be 128 or 20:%x", toc); + fread(&type, 1, sizeof(type), fin); + qDebug("File length:%u", type); + fseek(fin, toc, SEEK_SET); + fread(&nopages, 1, sizeof(nopages), fin); + m_indexpages = new UInt32[nopages]; + m_pagedetails = new Page_detail[nopages]; + qDebug("There are %u pages", nopages); + UInt32 loc = 0; + UInt32 homeguess = nopages-1; + QString homeurl; + for (int i = 0; i < nopages; ++i) + { + char name[32]; + UInt32 len, pos, flags; + fread(name, 1, 32, fin); + fread(&len, 1, 4, fin); + fread(&pos, 1, 4, fin); + fread(&flags, 1, 4, fin); + //qDebug("Page %u (%s) is %u bytes at %u (%u) of type %u", i, name, len, pos, loc, flags); + m_index[name] = i; + m_pagedetails[i] = Page_detail(loc, len, flags); + + if (QString(name).find(".htm", 0, false) >= 0) + { + if (homeguess > i) homeguess = i; + if ((flags & 8) != 0) + { + UInt32 lastpos = ftell(fin); + loc += pagelength(i); + fseek(fin, lastpos, SEEK_SET); + } + else + { + loc += len; + } + } + if ((flags & 2) != 0) + { + UInt32 lastpos = ftell(fin); + RBPage* idx = new RBPage(); + idx->init(fin, m_blocksize, m_decompress); + idx->startpage(page2pos(i), i, ((flags & 8) != 0), len); + int c = 0; + while (c != EOF) + { + QString s(""); + while (1) + { + c = idx->getch(this); + if (c == 10 || c == EOF) break; + s += c; + } + if (s.left(5) == "BODY=") + { + homeurl = s.right(s.length()-5); + qDebug("Home:%s", (const char*)homeurl); + } + else + { + qDebug("Info:%s", (const char*)s); + } + } + delete idx; + fseek(fin, lastpos, SEEK_SET); + } + } + text_length = loc; + qDebug("Looking for homepage"); + if (homeurl.isEmpty()) + { + m_homepage = homeguess; + } + else + { + QMap<QString, UInt32>::Iterator iter = m_index.find(homeurl); + if (iter != m_index.end()) + { + m_homepage = iter.data(); + } + else + { + m_homepage = homeguess; + } + } + m_homepos = m_pagedetails[m_homepage].pagestart; + qDebug("Finding indices"); + for (QMap<QString, UInt32>::Iterator iter = m_index.begin(); iter != m_index.end(); ++iter) + { + QString href = iter.key(); + if (href.find(".htm", 0, false) >= 0) + { + QString hind = href.left(href.find(".htm", 0, false))+".hidx"; + //qDebug("Index is %s", (const char*)hind); + QMap<QString, UInt32>::Iterator iter2 = m_index.find(hind); + if (iter2 != m_index.end()) + { + m_indexpages[iter.data()] = iter2.data(); + } + } + } + qDebug("Going home"); + home(); + return 0; + } + else + { + char * tmp = (char*)(&type); + for (int i = 0; i < 4; ++i) qDebug("%d:%c", i, tmp[i]); + return -1; + } +} + +UInt32 CReb::page2pos(UInt32 page) +{ + fseek(fin, toc+40+44*page, SEEK_SET); + UInt32 pos; + fread(&pos, 1, 4, fin); + return pos; +} + +UInt32 CReb::pagelength(UInt32 pagenum) +{ + fseek(fin, toc+40+44*pagenum, SEEK_SET); + UInt32 pos; + fread(&pos, 1, 4, fin); + fseek(fin, pos+4, SEEK_SET); + UInt32 len; + fread(&len, 1, sizeof(len), fin); + return len; +} + +void CReb::readindex(UInt32 cp) +{ + if (joins != NULL) + { + delete [] joins; + joins = NULL; + } + if (tags != NULL) + { + delete [] tags; + tags = NULL; + } + if (paras != NULL) + { + delete [] paras; + paras = NULL; + } + noparas = 0; + nojoins = 0; + names.clear(); + + UInt32 rspage = m_indexpages[cp]; + if (rspage != 0) + { + Page_detail rs = m_pagedetails[rspage]; + int count = 0; + RBPage* idx = new RBPage(); + idx->init(fin, m_blocksize, m_decompress); + idx->startpage(page2pos(rspage), rspage, ((rs.flags & 8) != 0), rs.len); + int c = 0; + int phase = 0; + int i; + if (m_binary) + { + count = idx->getuint(this); + qDebug("tag count:%d", count); + tags = new QString[count]; + for (int i = 0; i < count; ++i) + { + QString s; + while (1) + { + c = idx->getch(this); + if (c == 0 || c == EOF) break; + s += c; + } + unsigned short val = idx->getuint(this); + if (val != 0xffff) + { + tags[i] = tags[val]+s; + } + else + { + tags[i] = s; + } + //qDebug("tags[%d](%d) = %s", i, val, (const char*)tags[i]); + } + noparas = idx->getint(this); + qDebug("Para count %d", noparas); + paras = new ParaRef[noparas]; + for (int i = 0; i < noparas; ++i) + { + paras[i] = ParaRef(idx->getint(this), idx->getuint(this)); + } + count = idx->getint(this); + qDebug("Name count %d", count); + for (int i = 0; i < count; ++i) + { + QString s; + while (1) + { + c = idx->getch(this); + if (c == 0 || c == EOF) break; + s += c; + } + int val = idx->getint(this); + names[s.mid(1,s.length()-2)] = val; + qDebug("names[%s] = %d", (const char*)s, val); + } + count = idx->getint(this); + qDebug("Join count %d", count); + if (count > 0) + { + nojoins = count+2; + joins = new UInt32[count+2]; + joins[0] = 0; + joins[count+1] = currentpage.length(); + for (int i = 1; i < count+1; ++i) + { + joins[i] = idx->getint(this); + } + } + } + else + { + while (c != EOF) + { + QString s(""); + while (1) + { + c = idx->getch(this); + if (c == 10 || c == EOF) break; + s += c; + } + //qDebug("%s", (const char*)s); + if (count > 0) + { + --count; + int sp = s.findRev(' '); + QString l = s.left(sp); + int val = s.right(s.length()-sp).toInt(); + switch (phase) + { + case 4: + //qDebug("Join %d is at offset %d", i, val); + joins[i++] = val; + break; + case 3: + //qDebug("Name %s is at offset %d", (const char*)l.mid(1,l.length()-2), val+m_pagedetails[cp].pagestart); + names[l.mid(1,l.length()-2)] = val; + break; + case 1: + //qDebug("%s:%d [%d]", (const char*)l, val, i); + if (val >= 0) + { + tags[i++] = tags[val]+l; + } + else + { + tags[i++] = l; + } + //qDebug("TAG:%s", (const char*)tags[i-1]); + break; + case 2: + paras[i++] = ParaRef(QString(l).toInt(), val); + //qDebug("Para:%u - %u (%s)", QString(l).toInt(), val, (const char*)s); + break; + default: + qDebug("%s:%d", (const char*)l, val); + break; + } + } + else + { + QString key = "[tags "; + if (s.left(key.length()) == key) + { + phase = 1; + i = 0; + count = s.mid(key.length(),s.length()-key.length()-1).toInt(); + qDebug("%s:%s:%d", (const char*)key, (const char*)s, count); + tags = new QString[count]; + } + key = "[paragraphs "; + if (s.left(key.length()) == key) + { + phase = 2; + i = 0; + count = s.mid(key.length(),s.length()-key.length()-1).toInt(); + qDebug("%s:%s:%d", (const char*)key, (const char*)s, count); + paras = new ParaRef[count]; + noparas = count; + } + key = "[names "; + if (s.left(key.length()) == key) + { + phase = 3; + count = s.mid(key.length(),s.length()-key.length()-1).toInt(); + qDebug("%s:%s:%d", (const char*)key, (const char*)s, count); + } + key = "[joins "; + if (s.left(key.length()) == key) + { + phase = 4; + count = s.mid(key.length(),s.length()-key.length()-1).toInt(); + qDebug("%s:%s:%d", (const char*)key, (const char*)s, count); + nojoins = count+2; + i = 1; + joins = new UInt32[count+2]; + joins[0] = 0; + joins[count+1] = currentpage.length(); + qDebug("%s:%s:%d", (const char*)key, (const char*)s, count); + } + qDebug("ZC:%s", (const char*)s); + } + } + } + // for (int i = 0; i < nojoins; ++i) qDebug("JOINS:%u %u", i, joins[i]); + delete idx; + } +} + +bool CReb::findanchor(const QString& _info) +{ + QMap<QString, int>::Iterator iter = names.find(_info); + if (iter != names.end()) + { + locate(iter.data()+m_pagedetails[currentpage.pageno()].pagestart); + return true; + } + return false; +} + +#ifdef USEQPE +void CReb::suspend() +{ + CExpander::suspend(fin); +} +void CReb::unsuspend() +{ + CExpander::unsuspend(fin); +} +#endif + +#ifndef __STATIC +extern "C" +{ + CExpander* newcodec() { return new CReb; } +} +#endif + +void CReb::startpage(UInt32 pgno) +{ + Page_detail rs = m_pagedetails[pgno]; + unsuspend(); + readindex(pgno); + currentpage.startpage(page2pos(pgno), pgno, ((rs.flags & 8) != 0), rs.len); +} + +void CReb::startpage(UInt32 _cp, bool _isCompressed, UInt32 _len) +{ + unsuspend(); + readindex(_cp); + currentpage.startpage(page2pos(_cp), _cp, _isCompressed, _len); +} + +void RBPage::initpage(UInt32 pos, size_t _cp, bool _isCompressed, UInt32 _len) +{ + filepos = pos; + m_pageno = _cp; + m_Compressed = _isCompressed; + m_pagelen = _len; + currentchunk = 0; + pageoffset = 0; + + if (chunklist != NULL) delete [] chunklist; + + fseek(fin, filepos, SEEK_SET); + if (m_Compressed) + { + fread(&nochunks, 1, sizeof(nochunks), fin); + fread(&m_pagelen, 1, sizeof(m_pagelen), fin); + chunklist = new UInt32[nochunks]; + fread(chunklist, nochunks, 4, fin); + } + else + { + chunklist = NULL; + nochunks = (_len+m_blocksize-1)/m_blocksize; + } + m_startoff = 0; + m_endoff = m_pagelen; + chunkpos = ftell(fin); + qDebug("Compressed:%u Expanded:%u", _len, m_pagelen); +} + +void RBPage::startpage(UInt32 pos, UInt32 _cp, bool _isCompressed, UInt32 _len) +{ + initpage(pos, _cp, _isCompressed, _len); + readchunk(); +} + +int CReb::getch() +{ + if (tagoffset < tagstring.length()) + return tagstring[tagoffset++].unicode(); + else + return currentpage.getch(this); +} + +int RBPage::getch(CReb* parent) +{ + if (chunkoffset >= chunklen) + { + if (++currentchunk >= nochunks) + { + --currentchunk; + return EOF; + } + pageoffset += chunklen; + parent->unsuspend(); + readchunk(); + } + if (offset() == m_endoff) return EOF; + return chunk[chunkoffset++]; +} + +unsigned short int RBPage::getuint(CReb* parent) +{ + unsigned short int ret = 0; + char *buffer = (char*)(&ret); + for (int i = 0; i < 2; ++i) + { + int ch = getch(parent); + if (ch == EOF) return 0; + buffer[i] = ch; + } + return ret; +} + +int RBPage::getint(CReb* parent) +{ + int ret = 0; + char *buffer = (char*)(&ret); + for (int i = 0; i < 4; ++i) + { + int ch = getch(parent); + if (ch == EOF) return 0; + buffer[i] = ch; + } + return ret; +} + +void RBPage::readchunk() +{ + if (m_Compressed) + { + chunkoffset = 0; + fseek(fin, chunkpos, SEEK_SET); + UInt8* inbuf = new UInt8[chunklist[currentchunk]]; + fread(inbuf, 1, chunklist[currentchunk], fin); + chunklen = (*m_decompress)(inbuf, chunklist[currentchunk], chunk, m_blocksize); + delete [] inbuf; + chunkpos = ftell(fin); + } + else + { + chunkoffset = 0; + chunklen = m_blocksize; + if (m_blocksize*(currentchunk+1) > m_pagelen) + { + chunklen = m_pagelen - currentchunk*m_blocksize; + } + fseek(fin, chunkpos, SEEK_SET); + chunklen = fread(chunk, 1, chunklen, fin); + chunkpos = ftell(fin); + } +} + +void RBPage::setoffset(UInt32 pos, size_t _cp, bool _isCompressed, UInt32 _len, UInt32 _offset) +{ + if (m_pageno != _cp) + { + initpage(pos, _cp, _isCompressed, _len); + } + else + { + if (m_Compressed) + { + chunkpos = filepos + sizeof(nochunks) + sizeof(m_pagelen) + 4*nochunks; + } + else + { + chunkpos = filepos; + } + } + + currentchunk = _offset/m_blocksize; + pageoffset = m_blocksize*currentchunk; + if (m_Compressed) + { + for (int i = 0; i < currentchunk; ++i) + { + chunkpos += chunklist[i]; + } + } + else + { + chunkpos += pageoffset; + } + readchunk(); + chunkoffset = _offset - pageoffset; +} + +void CReb::start2endSection() +{ + if (m_pagedetails != NULL) + { + if (nojoins > 0) + { + //UInt32 jl = binarychop<UInt32>(joins, nojoins, currentpage.offset()); + + UInt32 jl = 0,jh = nojoins-1,jm = (jl+jh)/2; + while (jh > jl+1) + { + if (joins[jm] > currentpage.offset()) + { + jh = jm; + } + else + { + jl = jm; + } + jm = (jl+jh)/2; + } + + currentpage.m_startoff = joins[jl]; + currentpage.m_endoff = joins[jl+1]-1; + //currentpage.m_endoff = joins[jh]-1; + } + m_currentstart = m_pagedetails[currentpage.pageno()].pagestart+currentpage.m_startoff; + m_currentend = m_pagedetails[currentpage.pageno()].pagestart+currentpage.m_endoff; + } + else + { + m_currentstart = m_currentend = 0; + } + qDebug("s2e:[%u, %u, %u]", m_currentstart, locate(), m_currentend); +} diff --git a/noncore/apps/opie-reader/Reb.h b/noncore/apps/opie-reader/Reb.h new file mode 100644 index 0000000..f268eb0 --- a/dev/null +++ b/noncore/apps/opie-reader/Reb.h @@ -0,0 +1,157 @@ +#ifndef __REB_H +#define __REB_H +#include <stdio.h> +#include <zlib.h> +#include <sys/stat.h> +#ifdef USEQPE +#include <qpe/global.h> +#endif +#include <qmap.h> + +#include "CExpander.h" +#include <zlib.h> + +#ifdef _WINDOWS +#include <winsock.h> +#endif + +#include "mytypes.h" + +/* +struct Reb_Segment +{ + UInt32 len, page, flags; + Reb_Segment(UInt32 _len = 0, UInt32 _page = 0, UInt32 _flags = 0) + : + len(_len), page(_page), flags(_flags) + {} +}; +*/ + +class CReb; + +class RBPage +{ + UInt32 filepos; + UInt32 pageoffset; + UInt32 nochunks, currentchunk, chunkpos, chunklen, chunkoffset; + UInt32 m_pagelen, m_blocksize; + bool m_Compressed; + void readchunk(); + UInt32* chunklist; + UInt8* chunk; + FILE* fin; + UInt32 m_pageno; + void initpage(UInt32 pos, size_t _cp, bool _isCompressed, UInt32 _len); + size_t (*m_decompress)(UInt8*, size_t, UInt8*, size_t); + public: + RBPage() : pageoffset(0), nochunks(0), currentchunk(0), chunkpos(0), chunkoffset(0), m_pagelen(0), m_Compressed(false), chunklist(NULL), chunk(NULL) {} + ~RBPage() + { + if (chunk != NULL) delete [] chunk; + if (chunklist != NULL) delete [] chunklist; + } + int getch(CReb*); + unsigned short int getuint(CReb*); + int getint(CReb*); + void startpage(UInt32, UInt32, bool, UInt32); + UInt32 pageno() { return m_pageno; } + UInt32 offset() { return pageoffset+chunkoffset; } + void setoffset(UInt32, size_t, bool, UInt32, UInt32); + void init(FILE* _f, UInt32 _bs, size_t (*_decompress)(UInt8*, size_t, UInt8*, size_t)) + { + fin = _f; + m_blocksize = _bs; + chunk = new UInt8[m_blocksize]; + m_decompress = _decompress; + } + UInt32 length() { return m_pagelen; } + UInt32 m_startoff, m_endoff; +}; + +struct Page_detail +{ + UInt32 pagestart, len, flags; + Page_detail(UInt32 _ps = 0, UInt32 _l = 0, UInt32 _f = 0) + : + pagestart(_ps), len(_l), flags(_f) + { + } +}; + +struct ParaRef +{ + int pos, tag; + ParaRef(int _pos = 0, int _tag = 0) : pos(_pos), tag(_tag) + { + //qDebug("New PARAREF:%d, %d", pos, tag); + } +}; + +class CReb : public CExpander +{ + //friend class RBPage; + size_t (*m_decompress)(UInt8*, size_t, UInt8*, size_t); + RBPage currentpage; + UInt32 nopages, m_homepage, m_blocksize; + + QMap<QString, UInt32> m_index; + + size_t file_length, text_length; + UInt32 toc; + FILE* fin; + void home(); + void startpage(UInt32); + void startpage(UInt32, bool, UInt32); + void readchunk(); + QString tagstring; + UInt32 tagoffset; + UInt32 pagelength(UInt32); + QImage* getPicture(const QString& ref); + UInt32 page2pos(UInt32); + //UInt32 m_pagelen; + UInt32* m_indexpages; + Page_detail* m_pagedetails; + // void UnZip(size_t bsize); + QMap<QString, int> names; + QString* tags; + ParaRef* paras; + UInt32* joins; + UInt32 nojoins; + UInt32 noparas; + bool m_binary; + void readindex(UInt32); +public: + bool findanchor(const QString& _info); + QString about() { return QString("REB codec (c) Tim Wentford"); } + bool getFile(const QString& href, const QString& nm); + void start2endSection(); + void sizes(unsigned long& _file, unsigned long& _text) + { + _file = file_length; + _text = text_length; + } + bool hasrandomaccess() { return true; } + virtual ~CReb(); + CReb(); + int OpenFile(const char *src); + int getch(); + unsigned int locate(); + void locate(unsigned int n); + CList<Bkmk>* getbkmklist(); + MarkupType PreferredMarkup() + { + return cCHM; + } +#ifdef USEQPE + void suspend(); + void unsuspend(); +#else + void suspend() {} + void unsuspend() {} +#endif +}; + +#endif + + diff --git a/noncore/apps/opie-reader/RebCodec/.cvsignore b/noncore/apps/opie-reader/RebCodec/.cvsignore new file mode 100644 index 0000000..1810ee0 --- a/dev/null +++ b/noncore/apps/opie-reader/RebCodec/.cvsignore @@ -0,0 +1,5 @@ +Makefile +config.in +moc_* +.moc +.obj diff --git a/noncore/apps/opie-reader/RebCodec/RebCodec.pro b/noncore/apps/opie-reader/RebCodec/RebCodec.pro new file mode 100644 index 0000000..2d6410a --- a/dev/null +++ b/noncore/apps/opie-reader/RebCodec/RebCodec.pro @@ -0,0 +1,21 @@ +DEFINES += OPIE USEQPE +VPATH = .. +TEMPLATE = lib +CONFIG = qt warn_on release dll +HEADERS = Reb.h + +SOURCES = Reb.cpp \ + decompress.cpp + + +INTERFACES = +DESTDIR = $(OPIEDIR)/plugins/reader/codecs +TARGET = Reb +LIBS += -L$(OPIEDIR)/lib -lreader_codec + + +INCLUDEPATH += $(OPIEDIR)/include +DEPENDPATH += $(OPIEDIR)/include + +include( $(OPIEDIR)/include.pro ) + diff --git a/noncore/apps/opie-reader/StyleConsts.h b/noncore/apps/opie-reader/StyleConsts.h index 8e23c6f..4b7ff4b 100644 --- a/noncore/apps/opie-reader/StyleConsts.h +++ b/noncore/apps/opie-reader/StyleConsts.h @@ -1,222 +1,232 @@ #ifndef __STYLECONSTS_H #define __STYLECONSTS_H typedef unsigned short StyleType; #ifdef _WINDOWS #include <string.h> #endif #include <string.h> #include <stdlib.h> #include <qglobal.h> class QImage; struct GraphicLink { QImage* graphic; bool isLink; unsigned long link; GraphicLink(QImage* p, bool isLnk, unsigned long tgt) : graphic(p), isLink(isLnk), link(tgt) {} ~GraphicLink(); }; struct pmstore { unsigned int count; bool m_isScaleable; GraphicLink* graphic; pmstore(bool _canScale, QImage* p, bool isLnk, unsigned long tgt) : count(1), m_isScaleable(_canScale) { graphic = new GraphicLink(p, isLnk, tgt); } ~pmstore(); }; enum EalignmentType { m_AlignLeft, m_AlignRight, m_AlignCentre, - m_AlignJustify + m_AlignJustify, + m_AlignNone }; class CBasicStyle { friend class CStyle; bool m_bold, m_italic; + unsigned long m_table; int m_fontsize; EalignmentType m_align; unsigned char red, green, blue; unsigned char bred, bgreen, bblue; unsigned char pred, pgreen, pblue; unsigned long data; unsigned long offset; bool isLink; // bool isVisited; bool m_underline; bool m_strikethru; bool m_monospaced; unsigned char m_leftmargin, m_rightmargin; signed char m_extraspace; signed char m_voffset; CBasicStyle() { unset(); + m_table = 0xffffffff; } bool operator!=(const CBasicStyle& rhs) { return (memcmp(this, &rhs, sizeof(CBasicStyle)) != 0); } void unset() { m_bold = false; m_italic = false; m_fontsize = 0; m_align = m_AlignLeft; red = green = blue = 0; bred = bgreen = bblue = 255; pred = pgreen = pblue = 255; data = 0; offset = 0; isLink = false; // isVisited = false; m_underline = false; m_strikethru = false; m_leftmargin = 0; m_rightmargin = 0; m_monospaced = false; m_extraspace = 0; m_voffset = 0; } }; class CStyle { CBasicStyle sty; pmstore* graphic; public: signed char getVOffset() { return sty.m_voffset; } void setVOffset(signed char sp) { sty.m_voffset = sp; } signed char getExtraSpace() { return sty.m_extraspace; } void setExtraSpace(signed char sp) { sty.m_extraspace = sp; } bool getPictureLink() { return (graphic != NULL && graphic->graphic->isLink); } unsigned long getPictureLinkData() { return graphic->graphic->link; } void setLeftMargin(unsigned char m) { sty.m_leftmargin = m; } unsigned char getLeftMargin() { return sty.m_leftmargin; } void setRightMargin(unsigned char m) { sty.m_rightmargin = m; } unsigned char getRightMargin() { return sty.m_rightmargin; } unsigned char Red() { return sty.red; } unsigned char Green() { return sty.green; } unsigned char Blue() { return sty.blue; } void setColour(unsigned char r, unsigned char g, unsigned char b) { sty.red = r; sty.green = g; sty.blue = b; } unsigned char bRed() { return sty.bred; } unsigned char bGreen() { return sty.bgreen; } unsigned char bBlue() { return sty.bblue; } unsigned char pRed() { return sty.pred; } unsigned char pGreen() { return sty.pgreen; } unsigned char pBlue() { return sty.pblue; } void setPaper(unsigned char r, unsigned char g, unsigned char b) { sty.pred = r; sty.pgreen = g; sty.pblue = b; } void setBackground(unsigned char r, unsigned char g, unsigned char b) { sty.bred = r; sty.bgreen = g; sty.bblue = b; } CStyle() : graphic(NULL) {} ~CStyle(); // CStyle(CStyle&); CStyle(const CStyle&); CStyle& operator=(const CStyle&); void unset(); + bool isTable() const { return (sty.m_table != 0xffffffff); } + void setTable(unsigned long _b) { sty.m_table = _b; } + unsigned long getTable() { return sty.m_table; } bool isPicture() const { return (graphic != NULL); } bool canScale() const { return graphic->m_isScaleable; } void clearPicture(); void setPicture(bool canScale, QImage* _g, bool il=false, unsigned long tgt=0); QImage* getPicture() { QImage* pm = ((graphic != NULL) ? graphic->graphic->graphic : NULL); return pm; } void setUnderline() { sty.m_underline = true; } void unsetUnderline() { sty.m_underline = false; } bool isUnderline() { return sty.m_underline; } void setStrikethru() { sty.m_strikethru = true; } void unsetStrikethru() { sty.m_strikethru = false; } bool isStrikethru() { return sty.m_strikethru; } void setBold() { sty.m_bold = true; } void unsetBold() { sty.m_bold = false; } bool isBold() { return sty.m_bold; } void setItalic() { sty.m_italic = true; } void unsetItalic() { sty.m_italic = false; } bool isItalic() { return sty.m_italic; } void setMono() { sty.m_monospaced = true; } void unsetMono() { sty.m_monospaced = false; } bool isMono() { return sty.m_monospaced; } void setLeftJustify() { sty.m_align = m_AlignLeft; } void setRightJustify() { sty.m_align = m_AlignRight; } void setCentreJustify() { sty.m_align = m_AlignCentre; } void setFullJustify() { sty.m_align = m_AlignJustify; } + void setNoJustify() + { + sty.m_align = m_AlignNone; + } StyleType getJustify() { return sty.m_align; } void setFontSize(int _fs) { sty.m_fontsize = _fs; } int getFontSize() const { return sty.m_fontsize; } bool operator!=(const CStyle& rhs) { return ( (sty != rhs.sty) || (graphic != rhs.graphic) ); } void setLink(bool _l) { sty.isLink = _l; } bool getLink() { return sty.isLink; } // void setVisited(bool _l) { sty.isVisited = _l; } // bool getVisited() { return sty.isVisited; } void setData(unsigned long _d) { sty.data = _d; } unsigned long getData() { return sty.data; } void setOffset(unsigned long _d) { sty.offset = _d; } unsigned long getOffset() { return sty.offset; } void invert(); }; #endif diff --git a/noncore/apps/opie-reader/SubAlloc.h b/noncore/apps/opie-reader/SubAlloc.h new file mode 100644 index 0000000..ded2b73 --- a/dev/null +++ b/noncore/apps/opie-reader/SubAlloc.h @@ -0,0 +1,201 @@ +/****************************************************************************
+ * This file is part of PPMd project *
+ * Written and distributed to public domain by Dmitry Shkarin 1997, *
+ * 1999-2001 *
+ * Contents: memory allocation routines *
+ ****************************************************************************/
+
+enum { UNIT_SIZE=12, N1=4, N2=4, N3=4, N4=(128+3-1*N1-2*N2-3*N3)/4,
+ N_INDEXES=N1+N2+N3+N4 };
+
+#pragma pack(1)
+struct BLK_NODE {
+ DWORD Stamp;
+ BLK_NODE* next;
+ BOOL avail() const { return (next != NULL); }
+ void link(BLK_NODE* p) { p->next=next; next=p; }
+ void unlink() { next=next->next; }
+ void* remove() {
+ BLK_NODE* p=next; unlink();
+ Stamp--; return p;
+ }
+ inline void insert(void* pv,int NU);
+} BList[N_INDEXES];
+struct MEM_BLK: public BLK_NODE { DWORD NU; } _PACK_ATTR;
+#pragma pack()
+
+static BYTE Indx2Units[N_INDEXES], Units2Indx[128]; // constants
+static DWORD GlueCount, SubAllocatorSize=0;
+static BYTE* HeapStart, * pText, * UnitsStart, * LoUnit, * HiUnit;
+
+inline void PrefetchData(void* Addr)
+{
+#if defined(_USE_PREFETCHING)
+ BYTE PrefetchByte = *(volatile BYTE*) Addr;
+#endif /* defined(_USE_PREFETCHING) */
+}
+inline void BLK_NODE::insert(void* pv,int NU) {
+ MEM_BLK* p=(MEM_BLK*) pv; link(p);
+ p->Stamp=~0UL; p->NU=NU;
+ Stamp++;
+}
+inline UINT U2B(UINT NU) { return 8*NU+4*NU; }
+inline void SplitBlock(void* pv,UINT OldIndx,UINT NewIndx)
+{
+ UINT i, k, UDiff=Indx2Units[OldIndx]-Indx2Units[NewIndx];
+ BYTE* p=((BYTE*) pv)+U2B(Indx2Units[NewIndx]);
+ if (Indx2Units[i=Units2Indx[UDiff-1]] != UDiff) {
+ k=Indx2Units[--i]; BList[i].insert(p,k);
+ p += U2B(k); UDiff -= k;
+ }
+ BList[Units2Indx[UDiff-1]].insert(p,UDiff);
+}
+DWORD _STDCALL GetUsedMemory()
+{
+ DWORD i, RetVal=SubAllocatorSize-(HiUnit-LoUnit)-(UnitsStart-pText);
+ for (i=0;i < N_INDEXES;i++)
+ RetVal -= UNIT_SIZE*Indx2Units[i]*BList[i].Stamp;
+ return RetVal;
+}
+void _STDCALL StopSubAllocator() {
+ if ( SubAllocatorSize ) {
+ SubAllocatorSize=0; delete[] HeapStart;
+ }
+}
+BOOL _STDCALL StartSubAllocator(UINT SASize)
+{
+ DWORD t=SASize << 19U;
+ if (SubAllocatorSize == t) return TRUE;
+ StopSubAllocator();
+ if ((HeapStart=new BYTE[t]) == NULL) return FALSE;
+ SubAllocatorSize=t; return TRUE;
+}
+static inline void InitSubAllocator()
+{
+ memset(BList,0,sizeof(BList));
+ HiUnit=(pText=HeapStart)+SubAllocatorSize;
+ UINT Diff=UNIT_SIZE*(SubAllocatorSize/8/UNIT_SIZE*7);
+ LoUnit=UnitsStart=HiUnit-Diff; GlueCount=0;
+}
+static void GlueFreeBlocks()
+{
+ UINT i, k, sz;
+ MEM_BLK s0, * p, * p0, * p1;
+ if (LoUnit != HiUnit) *LoUnit=0;
+ for (i=0, (p0=&s0)->next=NULL;i < N_INDEXES;i++)
+ while ( BList[i].avail() ) {
+ p=(MEM_BLK*) BList[i].remove();
+ if ( !p->NU ) continue;
+ while ((p1=p+p->NU)->Stamp == ~0UL) {
+ p->NU += p1->NU; p1->NU=0;
+ }
+ p0->link(p); p0=p;
+ }
+ while ( s0.avail() ) {
+ p=(MEM_BLK*) s0.remove(); sz=p->NU;
+ if ( !sz ) continue;
+ for ( ;sz > 128;sz -= 128, p += 128)
+ BList[N_INDEXES-1].insert(p,128);
+ if (Indx2Units[i=Units2Indx[sz-1]] != sz) {
+ k=sz-Indx2Units[--i]; BList[k-1].insert(p+(sz-k),k);
+ }
+ BList[i].insert(p,Indx2Units[i]);
+ }
+ GlueCount=1 << 13;
+}
+static void* _STDCALL AllocUnitsRare(UINT indx)
+{
+ UINT i=indx;
+ if ( !GlueCount ) {
+ GlueFreeBlocks();
+ if ( BList[i].avail() ) return BList[i].remove();
+ }
+ do {
+ if (++i == N_INDEXES) {
+ GlueCount--; i=U2B(Indx2Units[indx]);
+ return (UnitsStart-pText > i)?(UnitsStart -= i):(NULL);
+ }
+ } while ( !BList[i].avail() );
+ void* RetVal=BList[i].remove(); SplitBlock(RetVal,i,indx);
+ return RetVal;
+}
+inline void* AllocUnits(UINT NU)
+{
+ UINT indx=Units2Indx[NU-1];
+ if ( BList[indx].avail() ) return BList[indx].remove();
+ void* RetVal=LoUnit; LoUnit += U2B(Indx2Units[indx]);
+ if (LoUnit <= HiUnit) return RetVal;
+ LoUnit -= U2B(Indx2Units[indx]); return AllocUnitsRare(indx);
+}
+inline void* AllocContext()
+{
+ if (HiUnit != LoUnit) return (HiUnit -= UNIT_SIZE);
+ else if ( BList->avail() ) return BList->remove();
+ else return AllocUnitsRare(0);
+}
+inline void UnitsCpy(void* Dest,void* Src,UINT NU)
+{
+ DWORD* p1=(DWORD*) Dest, * p2=(DWORD*) Src;
+ do {
+ p1[0]=p2[0]; p1[1]=p2[1];
+ p1[2]=p2[2];
+ p1 += 3; p2 += 3;
+ } while ( --NU );
+}
+inline void* ExpandUnits(void* OldPtr,UINT OldNU)
+{
+ UINT i0=Units2Indx[OldNU-1], i1=Units2Indx[OldNU-1+1];
+ if (i0 == i1) return OldPtr;
+ void* ptr=AllocUnits(OldNU+1);
+ if ( ptr ) {
+ UnitsCpy(ptr,OldPtr,OldNU); BList[i0].insert(OldPtr,OldNU);
+ }
+ return ptr;
+}
+inline void* ShrinkUnits(void* OldPtr,UINT OldNU,UINT NewNU)
+{
+ UINT i0=Units2Indx[OldNU-1], i1=Units2Indx[NewNU-1];
+ if (i0 == i1) return OldPtr;
+ if ( BList[i1].avail() ) {
+ void* ptr=BList[i1].remove(); UnitsCpy(ptr,OldPtr,NewNU);
+ BList[i0].insert(OldPtr,Indx2Units[i0]);
+ return ptr;
+ } else {
+ SplitBlock(OldPtr,i0,i1); return OldPtr;
+ }
+}
+inline void FreeUnits(void* ptr,UINT NU) {
+ UINT indx=Units2Indx[NU-1];
+ BList[indx].insert(ptr,Indx2Units[indx]);
+}
+inline void SpecialFreeUnit(void* ptr)
+{
+ if ((BYTE*) ptr != UnitsStart) BList->insert(ptr,1);
+ else { *(DWORD*) ptr=~0UL; UnitsStart += UNIT_SIZE; }
+}
+inline void* MoveUnitsUp(void* OldPtr,UINT NU)
+{
+ UINT indx=Units2Indx[NU-1];
+ if ((BYTE*) OldPtr > UnitsStart+16*1024 || (BLK_NODE*) OldPtr > BList[indx].next)
+ return OldPtr;
+ void* ptr=BList[indx].remove();
+ UnitsCpy(ptr,OldPtr,NU); NU=Indx2Units[indx];
+ if ((BYTE*) OldPtr != UnitsStart) BList[indx].insert(OldPtr,NU);
+ else UnitsStart += U2B(NU);
+ return ptr;
+}
+static inline void ExpandTextArea()
+{
+ BLK_NODE* p;
+ UINT Count[N_INDEXES]; memset(Count,0,sizeof(Count));
+ while ((p=(BLK_NODE*) UnitsStart)->Stamp == ~0UL) {
+ MEM_BLK* pm=(MEM_BLK*) p; UnitsStart=(BYTE*) (pm+pm->NU);
+ Count[Units2Indx[pm->NU-1]]++; pm->Stamp=0;
+ }
+ for (UINT i=0;i < N_INDEXES;i++)
+ for (p=BList+i;Count[i] != 0;p=p->next)
+ while ( !p->next->Stamp ) {
+ p->unlink(); BList[i].Stamp--;
+ if ( !--Count[i] ) break;
+ }
+}
diff --git a/noncore/apps/opie-reader/TableDialog.cpp b/noncore/apps/opie-reader/TableDialog.cpp new file mode 100644 index 0000000..b67d534 --- a/dev/null +++ b/noncore/apps/opie-reader/TableDialog.cpp @@ -0,0 +1,17 @@ +#include "TableDialog.h" + +CTableDialog::CTableDialog(const QFont& f, const QString& tabtext, bool fs, QWidget* parent, const char* name) : QDialog(parent, name, true) +{ + setCaption("Table View"); + QVBoxLayout *tmp = new QVBoxLayout(this); + QTextView* qtv = new QTextView(this); + qtv->setFont(f); + tmp->addWidget(qtv); + qtv->setText(tabtext); + if (fs) showMaximized(); + else if (parent != NULL) + { + resize(parent->size()); + move(parent->pos()); + } +} diff --git a/noncore/apps/opie-reader/TableDialog.h b/noncore/apps/opie-reader/TableDialog.h new file mode 100644 index 0000000..2257a81 --- a/dev/null +++ b/noncore/apps/opie-reader/TableDialog.h @@ -0,0 +1,34 @@ +#ifndef __TABLEDIALOG_H +#define __TABLEDIALOG_H + +#include <qdialog.h> +#include <qtextview.h> +#include <qlayout.h> + +class CTableDialog : public QDialog +{ +Q_OBJECT +#ifndef USEQPE + void keyPressEvent(QKeyEvent* e) + { + switch (e->key()) + { + case Key_Escape: + e->accept(); + reject(); + break; + case Key_Space: + case Key_Return: + e->accept(); + accept(); + break; + default: + QWidget::keyPressEvent(e); + } + } +#endif + public: + CTableDialog(const QFont& f, const QString& tabtext, bool fs = true, QWidget* parent = 0, const char* name = 0); + ~CTableDialog() {} +}; +#endif // CPREFS_H diff --git a/noncore/apps/opie-reader/ToolbarPrefs.h b/noncore/apps/opie-reader/ToolbarPrefs.h index 0bdae6b..9df8940 100644 --- a/noncore/apps/opie-reader/ToolbarPrefs.h +++ b/noncore/apps/opie-reader/ToolbarPrefs.h @@ -1,267 +1,266 @@ /**************************************************************************** ** Form interface generated from reading ui file 'Prefs.ui' ** ** Created: Tue Feb 11 23:53:32 2003 ** by: The User Interface Compiler (uic) ** ** WARNING! All changes made in this file will be lost! ****************************************************************************/ #ifndef CTOOLBARPREFS_H #define CTOOLBARPREFS_H + #include <qvariant.h> #include <qwidget.h> #include <qtabdialog.h> #include <qtabwidget.h> #include <qspinbox.h> #include <qcheckbox.h> #include <qcombobox.h> #include <qlineedit.h> #ifdef USEQPE #include <qpe/menubutton.h> #include <qpe/config.h> #else #include "preferences.h" #endif -//#ifdef OPIE #define USECOMBO -//#endif class QVBoxLayout; class QHBoxLayout; class QGridLayout; //class QCheckBox; class QLabel; //class QSpinBox; /* class CBarPrefs1 : public QWidget { Q_OBJECT Config& config; QCheckBox *open, *close, *info, *twotouch,*find,*scroll,*navigation,*page,*startend,*jump,*pageline; bool m_isChanged; private slots: void isChanged(int _v) { m_isChanged = true; } public: CBarPrefs1( Config&, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CBarPrefs1(); void saveall(); bool isChanged() { return m_isChanged; } }; */ class CFileBarPrefs : public QWidget { Q_OBJECT Config& config; QCheckBox *open, *close, *info, *twotouch, *find, *scroll; bool m_isChanged; private slots: void isChanged(int _v) { m_isChanged = true; } public: CFileBarPrefs( Config&, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CFileBarPrefs(); void saveall(); bool isChanged() { return m_isChanged; } }; class CNavBarPrefs : public QWidget { Q_OBJECT Config& config; QCheckBox *scroll, *navback, *navhome, *navforward; QCheckBox *pageup, *pagedown, *gotostart, *gotoend, *jump, *pageline; bool m_isChanged; private slots: void isChanged(int _v) { m_isChanged = true; } public: CNavBarPrefs( Config&, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CNavBarPrefs(); void saveall(); bool isChanged() { return m_isChanged; } }; /* class CBarPrefs2 : public QWidget { Q_OBJECT Config& config; QCheckBox *fullscreen, *zoom, *setfont, *mark, *annotate, *go_to, *Delete, *autogen, *clear, *save, *tidy, *block, *indannotate, *encoding, *ideogram; bool m_isChanged; private slots: void isChanged(int _v) { m_isChanged = true; } public: CBarPrefs2( Config&, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CBarPrefs2(); void saveall(); bool isChanged() { return m_isChanged; } }; */ class CViewBarPrefs : public QWidget { Q_OBJECT Config& config; QCheckBox *fullscreen, *rotate, *zoomin, *zoomout, *setfont, *encoding, *ideogram, *invert; bool m_isChanged; private slots: void isChanged(int _v) { m_isChanged = true; } public: CViewBarPrefs( Config&, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CViewBarPrefs(); void saveall(); bool isChanged() { return m_isChanged; } }; class CMarkBarPrefs : public QWidget { Q_OBJECT Config& config; QCheckBox *mark, *annotate, *go_to, *Delete, *autogen, *clear, *save, *tidy, *startblock, *copyblock; bool m_isChanged; private slots: void isChanged(int _v) { m_isChanged = true; } public: CMarkBarPrefs( Config&, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CMarkBarPrefs(); void saveall(); bool isChanged() { return m_isChanged; } }; class CIndBarPrefs : public QWidget { Q_OBJECT Config& config; QCheckBox *indannotate; bool m_isChanged; private slots: void isChanged(int _v) { m_isChanged = true; } public: CIndBarPrefs( Config&, QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CIndBarPrefs(); void saveall(); bool isChanged() { return m_isChanged; } }; class CMiscBarPrefs : public QWidget { public: CMiscBarPrefs( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 ); ~CMiscBarPrefs(); #ifdef USECOMBO QComboBox *tbpolicy, *tbposition, *qtscroll, *localscroll; #else MenuButton *tbpolicy, *tbposition, *qtscroll, *localscroll; #endif QCheckBox *tbmovable, *floating; }; class CBarPrefs : public QDialog { Q_OBJECT ; CMiscBarPrefs* misc; CFileBarPrefs* filebar; CNavBarPrefs* navbar; CViewBarPrefs* viewbar; CMarkBarPrefs* markbar; CIndBarPrefs* indbar; Config config; void keyPressEvent(QKeyEvent* e) { switch (e->key()) { case Key_Escape: e->accept(); reject(); break; case Key_Space: case Key_Return: e->accept(); accept(); break; default: QWidget::keyPressEvent(e); } } public: CBarPrefs(const QString& appdir, bool fs = true, QWidget* parent = 0, const char* name = 0); ~CBarPrefs() { if (result()) { if (navbar->isChanged()) navbar->saveall(); if (filebar->isChanged()) filebar->saveall(); if (viewbar->isChanged()) viewbar->saveall(); if (markbar->isChanged()) markbar->saveall(); if (indbar->isChanged()) indbar->saveall(); } } bool isChanged() { return ( filebar->isChanged() || navbar->isChanged() || viewbar->isChanged() || markbar->isChanged() || indbar->isChanged() ); } bool floating() { return misc->floating->isChecked(); } void floating(bool v) { misc->floating->setChecked(v); } int tbpolicy() { return misc->tbpolicy->currentItem(); } int qtscroll() { return misc->qtscroll->currentItem(); } int localscroll() { return misc->localscroll->currentItem(); } #ifdef USECOMBO void tbpolicy(int v) { misc->tbpolicy->setCurrentItem(v); } void qtscroll(int v) { misc->qtscroll->setCurrentItem(v); } void localscroll(int v) { misc->localscroll->setCurrentItem(v); } #else void tbpolicy(int v) { misc->tbpolicy->select(v); } void qtscroll(int v) { misc->qtscroll->select(v); } void localscroll(int v) { misc->localscroll->select(v); } #endif bool tbmovable() { return misc->tbmovable->isChecked(); } void tbmovable(bool v) { misc->tbmovable->setChecked(v); } int tbposition() { return misc->tbposition->currentItem(); } #ifdef USECOMBO void tbposition(int v) { misc->tbposition->setCurrentItem(v); } #else void tbposition(int v) { misc->tbposition->select(v); } #endif }; #endif // CPREFS_H diff --git a/noncore/apps/opie-reader/ZText.h b/noncore/apps/opie-reader/ZText.h index 199c7da..40b0f0a 100644 --- a/noncore/apps/opie-reader/ZText.h +++ b/noncore/apps/opie-reader/ZText.h @@ -1,115 +1,124 @@ #ifndef __Text_h #define __Text_h #include <stdio.h> #include <zlib.h> #include <sys/stat.h> +#ifdef USEQPE +#include <qpe/global.h> +#endif + #include "CExpander.h" class Text: public CExpander { gzFile file; unsigned long fsize; public: void suspend() { #ifdef USEQPE if (!bSuspended) { bSuspended = true; suspos = gztell(file); gzclose(file); file = NULL; sustime = time(NULL); } #endif } void unsuspend() { #ifdef USEQPE if (bSuspended) { bSuspended = false; if (sustime != ((time_t)-1)) { int delay = time(NULL) - sustime; - if (delay < 10) sleep(10-delay); + if (delay < 10) + { + Global::statusMessage("Stalling"); + sleep(10-delay); + } } file = gzopen(fname, "rb"); for (int i = 0; file == NULL && i < 5; i++) { + Global::statusMessage("Stalling"); sleep(5); file = gzopen(fname, "rb"); } if (file == NULL) { QMessageBox::warning(NULL, PROGNAME, "Couldn't reopen file"); exit(0); } suspos = gzseek(file, suspos, SEEK_SET); } #endif } Text() : file(NULL) {}; virtual ~Text() { if (file != NULL) { #ifdef USEQPE unsuspend(); #endif gzclose(file); } } int OpenFile(const char *src) { if (file != NULL) gzclose(file); struct stat _stat; stat(src,&_stat); fsize = _stat.st_size; return ((file = gzopen(src,"rb")) == NULL); } int getch() { #ifdef USEQPE unsuspend(); #endif return gzgetc(file); } unsigned int locate() { #ifdef USEQPE unsuspend(); #endif return gztell(file); } void locate(unsigned int n) { #ifdef USEQPE unsuspend(); #endif gzseek(file,n,SEEK_SET); } bool hasrandomaccess() { return true; } void sizes(unsigned long& _file, unsigned long& _text) { _text = _file = fsize; FILE* f = fopen(fname, "rb"); if (f != NULL) { unsigned char mn[2]; fread(mn, 1, 2, f); if ((mn[0] == 31) && (mn[1] == 139)) { int tmp = sizeof(_text); fseek(f,-tmp,SEEK_END); fread(&_text, sizeof(_text), 1, f); } fclose(f); } } MarkupType PreferredMarkup() { return cTEXT; } QString about() { return QString("Text/gzipped text codec (c) Tim Wentford"); } }; #endif diff --git a/noncore/apps/opie-reader/arith.h b/noncore/apps/opie-reader/arith.h index 19ca646..59b2ea9 100644 --- a/noncore/apps/opie-reader/arith.h +++ b/noncore/apps/opie-reader/arith.h @@ -1,43 +1,41 @@ /*
* Encodage & décodage arithmétique
*/
#ifndef ARITH_H
#define ARITH_H
#include "utypes.h"
#include <stdio.h>
+class ppm_expander;
+
class PPM_ReadBuf
{
FILE *my_file_in;
+ ppm_expander* parent;
public:
- PPM_ReadBuf(FILE* f) : my_file_in(f) {}
- UINT readbuf(UCHAR *buf,UINT len)
- {
- UINT len1;
- len1=fread(buf,1,len,my_file_in);
- return len1;
- }
+ PPM_ReadBuf(FILE* f, ppm_expander* _parent) : my_file_in(f), parent(_parent) {}
+ UINT readbuf(UCHAR *buf,UINT len);
};
class ArithClass
{
UCHAR *ainbuf;
UCHAR *apinbuf,*aendinbuf;
UINT ainbufsize;
USHORT avalue,alow,ahigh;
PPM_ReadBuf* areadbuf;
UCHAR abitcnt;
USHORT abitbuf;
public:
void Arith_DecodeInit(PPM_ReadBuf* readbuf,UCHAR *buf,UINT bufsize);
UINT Arith_DecodeVal(UINT size);
void Arith_Decode(UINT min,UINT max,UINT size);
void Arith_DecodeEnd(void);
};
#endif
diff --git a/noncore/apps/opie-reader/arrierego.cpp b/noncore/apps/opie-reader/arrierego.cpp new file mode 100644 index 0000000..be2a3fa --- a/dev/null +++ b/noncore/apps/opie-reader/arrierego.cpp @@ -0,0 +1,188 @@ +#ifdef USENEF +#include <qimage.h> +#include "arrierego.h" + +struct CArriere_dataRecord +{ + UInt16 uid; + UInt16 nParagraphs; + UInt32 size; + UInt8 type; + UInt8 reserved; +}; + +int CArriere::HeaderSize() +{ + return 10; +} + +void CArriere::GetHeader(UInt16& uid, UInt16& nParagraphs, UInt32& size, UInt8& type, UInt8& reserved) +{ + CArriere_dataRecord thishdr; + unsuspend(); + fread(&thishdr, 1, HeaderSize(), fin); + uid = ntohs(thishdr.uid); + nParagraphs = ntohs(thishdr.nParagraphs); + size = ntohl(thishdr.size); + type = thishdr.type; + reserved = thishdr.reserved; + // qDebug("UID:%u Paras:%u Size:%u Type:%u Reserved:%u", uid, nParagraphs, size, (unsigned int)type, (unsigned int)reserved); +// for (int i = 0; i < sizeof(thishdr); i++) +// printf("%d %x\n", i, (int)(((char *)(&thishdr))[i])); +} + +bool CArriere::CorrectDecoder() +{ + char * type = (char*)(&(head.type)); + for (int i = 0; i < 8; ++i) qDebug("%c", type[i]); + return (memcmp(&head.type, "ArriereG", 8) == 0); +} + +int CArriere::bgetch() +{ + int ch = EOF; + if (bufferpos >= buffercontent) + { + if (bufferrec >= ntohs(head.recordList.numRecords) - 1) + { + return EOF; + } + if (isEndOfSection(bufferrec)) + { + return EOF; + } + if (!expand(bufferrec+1)) + { + return EOF; + } + mystyle.unset(); + if (m_ParaOffsets[m_nextParaIndex] == 0) + { + while (m_ParaOffsets[m_nextParaIndex+1] == 0) + { + m_nextParaIndex++; + } + } + mystyle.setExtraSpace((m_ParaAttrs[m_nextParaIndex]&7)*2); + } + if (bufferpos == m_nextPara) + { + while (bufferpos == m_nextPara) + { + m_nextParaIndex++; + if (m_nextParaIndex == m_nParas) + { + m_nextPara = -1; + } + else + { + m_nextPara += m_ParaOffsets[m_nextParaIndex]; + } + } + mystyle.unset(); + mystyle.setExtraSpace((m_ParaAttrs[m_nextParaIndex]&7)*2); + if (m_lastBreak == locate()) + { + currentpos++; + ch = expandedtextbuffer[bufferpos++]; + } + else + { + ch = 10; + } + } + else + { + currentpos++; + ch = expandedtextbuffer[bufferpos++]; + } + return ch; +} + +tchar CArriere::getch(bool fast) +{ + mystyle.clearPicture(); + return getch_base(fast); +} + +/* +void CArriere::setlink(QString& fn, const QString& wrd) +{ + fn = wrd; +} +*/ + +QImage* CArriere::imagefromdata(UInt8* imgbuffer, UInt32 imgsize) +{ + QByteArray arr; + arr.assign((const char*)imgbuffer, imgsize); + + QImage* qimage = new QImage(arr); + + return qimage; +} + +void CArriere::start2endSection() +{ + m_currentstart = NEFstartSection(); + m_currentend = NEFendSection(); +} + +unsigned long CArriere::NEFstartSection() +{ +//inefficient - Should calc start/end of section on entry to section? + UInt16 thishdr_uid, thishdr_nParagraphs; + UInt32 thishdr_size; + UInt8 thishdr_type, thishdr_reserved; + unsigned long textlength = currentpos-bufferpos; + for (UInt16 recptr = bufferrec-1; recptr >= 1; recptr--) + { + gotorecordnumber(recptr); + //qDebug("recptr:%u", recptr); + GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); + if (thishdr_type < 2) + { + if ((thishdr_reserved && continuation_bit) == 0) break; + textlength -= thishdr_size; + //qDebug("Textlength:%u, reserved:%u, recptr:%u", textlength, thishdr_reserved, recptr); + } + } + return textlength; +} + +unsigned long CArriere::NEFendSection() +{ +//inefficient - Should calc start/end of section on entry to section? + unsigned long textlength = currentpos-bufferpos+buffercontent; + gotorecordnumber(bufferrec); + UInt16 thishdr_uid, thishdr_nParagraphs; + UInt32 thishdr_size; + UInt8 thishdr_type, thishdr_reserved; + GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); + if ((thishdr_reserved && continuation_bit) != 0) + { + for (UInt16 recptr = bufferrec+1; recptr < ntohs(head.recordList.numRecords); recptr++) + { + gotorecordnumber(recptr); + UInt16 thishdr_uid, thishdr_nParagraphs; + UInt32 thishdr_size; + UInt8 thishdr_type, thishdr_reserved; + GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); + // qDebug("recptr %u bufferrec %u type %u m_reserved %u", recptr, bufferrec, typ + if (thishdr_type < 2) + { + textlength += thishdr_size; + if ((thishdr_reserved && continuation_bit) == 0) break; + } + } + } + return textlength; +} + +#ifndef __STATIC +extern "C" +{ + CExpander* newcodec() { return new CArriere; } +} +#endif +#endif diff --git a/noncore/apps/opie-reader/arrierego.h b/noncore/apps/opie-reader/arrierego.h new file mode 100644 index 0000000..5d6e2d0 --- a/dev/null +++ b/noncore/apps/opie-reader/arrierego.h @@ -0,0 +1,37 @@ +#if (!defined(__ARRIEREGO_H)) && defined(USENEF) +#define __ARRIEREGO_H +#include "plucker_base.h" + +#ifdef LOCALPICTURES +class QScrollView; +class QWidget; +#endif + +class CArriere : public CPlucker_base +{ +protected: + bool isEndOfSection(int thisrec) + { + return !m_bufferisreserved; + } + unsigned long NEFstartSection(); + unsigned long NEFendSection(); + void setbuffersize() + { + compressedbuffersize = buffersize = 64*1024; + } + void GetHeader(UInt16&, UInt16&, UInt32&, UInt8&, UInt8&); + int HeaderSize(); + int bgetch(); + tchar getch(bool); + + bool CorrectDecoder(); +// void setlink(QString&, const QString&); + QImage* imagefromdata(UInt8*, UInt32); + unsigned char m_reserved; +public: + void start2endSection(); + QString about() { return CPlucker_base::about()+QString("\nArriereGo codec (c) Tim Wentford"); } +}; + +#endif diff --git a/noncore/apps/opie-reader/cbkmkselector.h b/noncore/apps/opie-reader/cbkmkselector.h index 42951e5..ec0c6e8 100644 --- a/noncore/apps/opie-reader/cbkmkselector.h +++ b/noncore/apps/opie-reader/cbkmkselector.h @@ -1,43 +1,89 @@ #include <qwidget.h> #include <qlistbox.h> #include <qpushbutton.h> #include <qlayout.h> +class CBkmkSelectorItem : public QListBoxText +{ + int m_ref; + public: + CBkmkSelectorItem(const QString& _t, int ref) : QListBoxText(_t), m_ref(ref) + { + } + int reference() { return m_ref; } +}; + class CBkmkSelector : public QWidget { Q_OBJECT QListBox* bkmkselector; QPushButton* exitButton; - + /* + void keyPressEvent ( QKeyEvent * e ) + { + if ((e->key() == Key_Return) || (e->key() == Key_Space)) + { + emit selected(reinterpret_cast<CBkmkSelectorItem*>(bkmkselector->item(bkmkselector->currentItem()))->reference()); + e->accept(); + } + else + { + e->ignore(); + } + } + */ signals: void selected(int i); void cancelled(); private slots: - void slotSelected(QListBoxItem* t) { emit selected(bkmkselector->index(t)); } - void slotSelected(int t) { emit selected(t); } + void slotSelected(QListBoxItem* t) + { + if (t != NULL) + { + emit selected(reinterpret_cast<CBkmkSelectorItem*>(t)->reference()); + } + } +//void slotSelected(int t) { emit selected(t); } void slotCancel() { emit cancelled(); } + void slotSort() + { + bkmkselector->sort(); +#ifdef USEQPE + setCurrentItem(bkmkselector->currentItem()); +#endif + } public: CBkmkSelector( QWidget *parent=0, const char *name=0, WFlags f = 0) : QWidget(parent, name, f) { // QFont f("unifont", 16); // setFont( f ); QVBoxLayout* grid = new QVBoxLayout(this); - bkmkselector = new QListBox(this, "Bookmarks"); - exitButton = new QPushButton("Cancel", this); - connect(bkmkselector, SIGNAL( selected(int) ), this, SLOT( slotSelected(int) ) ); + QHBoxLayout* hgrid = new QHBoxLayout(); + bkmkselector = new QListBox(this, tr("Bookmarks")); + QPushButton* _sort = new QPushButton(tr("Sort"), this); + connect(_sort, SIGNAL(clicked()), this, SLOT( slotSort() ) ); + exitButton = new QPushButton(tr("Cancel"), this); + // connect(bkmkselector, SIGNAL( selected(int) ), this, SLOT( slotSelected(int) ) ); connect(bkmkselector, SIGNAL( clicked(QListBoxItem*) ), this, SLOT( slotSelected(QListBoxItem*) ) ); + connect(bkmkselector, SIGNAL( returnPressed(QListBoxItem*) ), this, SLOT( slotSelected(QListBoxItem*) ) ); connect(exitButton, SIGNAL( clicked() ), this, SLOT( slotCancel() ) ); grid->addWidget(bkmkselector,1); - grid->addWidget(exitButton); + grid->addLayout(hgrid); + hgrid->addWidget(_sort); + hgrid->addWidget(exitButton); } void clear() { bkmkselector->clear(); } - void insertItem(const QString& item) { bkmkselector->insertItem(item); } + void insertItem(const QString& _item, int ref) + { + CBkmkSelectorItem* item = new CBkmkSelectorItem(_item, ref); + bkmkselector->insertItem(item); + } QString text(int index) const { return bkmkselector->text(index); } void setText(const QString& _l) { exitButton->setText(_l); } + void setCurrentItem(int _i) { bkmkselector->setCurrentItem(_i); } }; - diff --git a/noncore/apps/opie-reader/config.in b/noncore/apps/opie-reader/config.in index 9f80a93..04ff2f1 100644 --- a/noncore/apps/opie-reader/config.in +++ b/noncore/apps/opie-reader/config.in @@ -1,4 +1,8 @@ config OPIE-READER boolean "opie-reader (E-Text reader)" default "y" depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE && LIBOPIE2UI + + source noncore/apps/opie-reader/FliteDyn/config.in + source noncore/apps/opie-reader/FliteDyn16/config.in + diff --git a/noncore/apps/opie-reader/decompress.cpp b/noncore/apps/opie-reader/decompress.cpp new file mode 100644 index 0000000..9bfec49 --- a/dev/null +++ b/noncore/apps/opie-reader/decompress.cpp @@ -0,0 +1,95 @@ +#include <string.h> +#include "decompress.h" +#include <zlib.h> +#include <stdlib.h> + +size_t UnZip(UInt8* compressedbuffer, size_t reclen, UInt8* tgtbuffer, size_t bsize) +{ + z_stream zstream; + memset(&zstream,sizeof(zstream),0); + zstream.next_in = compressedbuffer; + zstream.next_out = tgtbuffer; + zstream.avail_out = bsize; + zstream.avail_in = reclen; + + int keylen = 0; + + zstream.zalloc = Z_NULL; + zstream.zfree = Z_NULL; + zstream.opaque = Z_NULL; + + // printf("Initialising\n"); + + inflateInit(&zstream); + int err = 0; + do { + if ( zstream.avail_in == 0 && 0 < keylen ) { + zstream.next_in = compressedbuffer + keylen; + zstream.avail_in = reclen - keylen; + keylen = 0; + } + zstream.next_out = tgtbuffer; + zstream.avail_out = bsize; + + err = inflate( &zstream, Z_SYNC_FLUSH ); + + // //qDebug("err:%d - %u", err, zstream.avail_in); + + } while ( err == Z_OK ); + + inflateEnd(&zstream); + return zstream.total_out; +} + +#if defined(__STATIC) && defined(USENEF) +#include "Model.h" +size_t (*getdecompressor(char* _s))(UInt8*, size_t, UInt8*, size_t) +{ + if (strcmp(_s, "PluckerDecompress3") == 0) + { + return PluckerDecompress3; + } + if (strcmp(_s, "PluckerDecompress4") == 0) + { + return PluckerDecompress4; + } + if (strcmp(_s, "RebDecompress") == 0) + { + return RebDecompress; + } + return NULL; +} +#else + +#include "qfileinfo.h" + +#include <dlfcn.h> + +size_t (*getdecompressor(char* _s))(UInt8*, size_t, UInt8*, size_t) +{ +#ifdef USEQPE +#ifdef OPIE + QString codecpath(getenv("OPIEDIR")); +#else + QString codecpath(getenv("QTDIR")); +#endif + codecpath += "/plugins/reader/support/libpluckerdecompress.so"; +#else + QString codecpath(getenv("READERDIR")); + codecpath += "/support/libpluckerdecompress.so"; +#endif + qDebug("Codec:%s", (const char*)codecpath); + if (QFile::exists(codecpath)) + { + qDebug("Codec:%s", (const char*)codecpath); + void* handle = dlopen(codecpath, RTLD_LAZY); + if (handle == 0) + { + qDebug("Can't find codec:%s", dlerror()); + return NULL; + } + return (size_t (*)(UInt8*, size_t, UInt8*, size_t))dlsym(handle, _s); + } + return NULL; +} +#endif diff --git a/noncore/apps/opie-reader/decompress.h b/noncore/apps/opie-reader/decompress.h new file mode 100644 index 0000000..400685f --- a/dev/null +++ b/noncore/apps/opie-reader/decompress.h @@ -0,0 +1,5 @@ +#include "mytypes.h" + +size_t UnZip(UInt8* compressedbuffer,size_t reclen,UInt8* tgtbuffer,size_t bsize); + +size_t (*getdecompressor(char* _s))(UInt8*, size_t, UInt8*, size_t); diff --git a/noncore/apps/opie-reader/ebookcodec.h b/noncore/apps/opie-reader/ebookcodec.h index f6e2daf..4229fb9 100644 --- a/noncore/apps/opie-reader/ebookcodec.h +++ b/noncore/apps/opie-reader/ebookcodec.h @@ -1,118 +1,131 @@ #include "CExpander.h" #include <qfileinfo.h> #include <qdir.h> #ifdef USEQPE #include <qpe/global.h> #endif -#include "util.h" - #ifndef __STATIC #include <dlfcn.h> class ebookcodec : public CExpander_Interface { CExpander *codec; void *handle; int status; public: + QString getTableAsHtml(unsigned long loc) { return codec->getTableAsHtml(loc); } QString about() { return QString("Plug-in ebook codec interface (c) Tim Wentford\n")+codec->about(); } ebookcodec(const QString& _s) : codec(NULL), handle(NULL), status(0) { - QString codecpath(QTReaderUtil::getPluginPath()); +#ifdef USEQPE +#ifdef OPIE + QString codecpath(getenv("OPIEDIR")); +#else + QString codecpath(getenv("QTDIR")); +#endif + codecpath += "/plugins/reader/codecs/"; +#else + QString codecpath(getenv("READERDIR")); + codecpath += "/codecs/"; +#endif codecpath += _s; if (QFile::exists(codecpath)) { qDebug("Codec:%s", (const char*)codecpath); handle = dlopen(codecpath, RTLD_LAZY); if (handle == 0) { /* QString wrn(dlerror()); QString fmt; while (wrn.length() > 10) { fmt += wrn.left(10); fmt += '\n'; wrn = wrn.right(wrn.length()-10); } fmt += wrn; QMessageBox::warning(NULL, PROGNAME, fmt); */ qDebug("Can't find codec:%s", dlerror()); status = -10; return; } CExpander* (*newcodec)(); newcodec = (CExpander* (*)())dlsym(handle, "newcodec"); if (newcodec == NULL) { qDebug("Can't find newcodec"); status = -20; return; } codec = (*newcodec)(); } else { qDebug("Can't find codec"); } if (codec == NULL) { qDebug("Can't do newcodec"); status = -30; return; } } virtual ~ebookcodec() { if (codec != NULL) delete codec; if (handle != NULL) dlclose(handle); } size_t getHome() { return codec->getHome(); } #ifdef USEQPE void suspend() { codec->suspend(); } void unsuspend() { codec->unsuspend(); } void suspend(FILE*& fin) { codec->suspend(fin); } void unsuspend(FILE*& fin) { codec->unsuspend(fin); } #endif unsigned int locate() { return codec->locate(); } void locate(unsigned int n) { codec->locate(n); } bool hasrandomaccess() { return codec->hasrandomaccess(); } void sizes(unsigned long& file, unsigned long& text) { codec->sizes(file, text); //qDebug("Codec sizes:(%u, %u)", file, text); } CList<Bkmk>* getbkmklist() { return codec->getbkmklist(); } void getch(tchar& ch, CStyle& sty, unsigned long& pos) { codec->getch(ch, sty, pos); } int getch() { return codec->getch(); } linkType hyperlink(unsigned int n, unsigned int noff, QString& wrd, QString& nm) { return codec->hyperlink(n, noff, wrd, nm); } MarkupType PreferredMarkup() { return codec->PreferredMarkup(); } void saveposn(size_t posn) { codec->saveposn(posn); } void writeposn(size_t posn) { codec->writeposn(posn); } linkType forward(size_t& loc) { return codec->forward(loc); } linkType back(size_t& loc) { return codec->back(loc); } bool hasnavigation() { return codec->hasnavigation(); } void start2endSection() { codec->start2endSection(); } QImage* getPicture(unsigned long tgt) { return codec->getPicture(tgt); } void setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen) { return codec->setSaveData(data, len, src, srclen); } void putSaveData(unsigned char*& src, unsigned short& srclen) { codec->putSaveData(src, srclen); } void setContinuous(bool _b) { codec->setContinuous(_b); } void setwidth(int w) { codec->setwidth(w); } unsigned long startSection() { return codec->startSection(); } unsigned long endSection() { return codec->endSection(); } int openfile(const char *src) { //qDebug("ebook openfile:%s", src); return (status != 0) ? status : codec->openfile(src); } int getwidth() { return codec->getwidth(); } QImage* getPicture(const QString& href) { return codec->getPicture(href); } - bool getFile(const QString& href) { return codec->getFile(href); } + bool getFile(const QString& href, const QString& nm) { return codec->getFile(href, nm); } + bool findanchor(const QString& nm) + { + return codec->findanchor(nm); + } }; #endif diff --git a/noncore/apps/opie-reader/fileBrowser.cpp b/noncore/apps/opie-reader/fileBrowser.cpp index 2291c85..c8c371a 100644 --- a/noncore/apps/opie-reader/fileBrowser.cpp +++ b/noncore/apps/opie-reader/fileBrowser.cpp @@ -1,288 +1,288 @@ /**************************************************************************** Derived from a file browser which was ** copyright 2001 ljp ljp@llornkcor.com Extensive modification by Tim Wentford to allow it to work in rotated mode ****************************************************************************/ #include "fileBrowser.h" #include "QtrListView.h" #include <qlineedit.h> #include <qpushbutton.h> #include <qfile.h> #include <qmessagebox.h> #ifndef _WINDOWS #include <unistd.h> #endif #include <qlayout.h> #ifdef _WINDOWS #include <direct.h> #endif fileBrowser::fileBrowser( bool allownew, QWidget* parent, const char* name, bool modal, WFlags fl , const QString filter, const QString iPath ) : QDialog( parent, name, true, fl/* | WStyle_Customize | WStyle_Tool*/), filterspec(QDir::All) { // showMaximized(); if ( !name ) setName( "fileBrowser" ); setCaption(tr( "Browse for file" ) ); filterStr=filter; buttonOk = new QPushButton( this, "buttonOk" ); // buttonOk->setFixedSize( 25, 25 ); buttonOk->setAutoDefault( false ); buttonOk->setText( tr( "/" ) ); buttonShowHidden = new QPushButton( this, "buttonShowHidden" ); // buttonShowHidden->setFixedSize( 50, 25 ); buttonShowHidden->setText( tr( "Hidden" ) ); buttonShowHidden->setAutoDefault( false ); buttonShowHidden->setToggleButton( true ); buttonShowHidden->setOn( false ); dirLabel = new QLabel(this, "DirLabel"); dirLabel->setAlignment(AlignLeft | AlignVCenter | ExpandTabs | WordBreak); dirLabel->setText(currentDir.canonicalPath()); ListView = new QtrListView( this, "ListView" ); ListView->addColumn( tr( "Name" ) ); ListView->setSorting( 2, FALSE); ListView->addColumn( tr( "Size" ) ); ListView->setSelectionMode(QListView::Single); ListView->setAllColumnsShowFocus( TRUE ); - ListView->setColumnWidthMode(0, QListView::Manual); + ListView->setColumnWidthMode(0, ((modal) ? QListView::Manual : QListView::Maximum)); ListView->setColumnWidthMode(1, QListView::Manual); // signals and slots connections connect( buttonShowHidden, SIGNAL( toggled(bool) ), this, SLOT( setHidden(bool) ) ); connect( buttonOk, SIGNAL( clicked() ), this, SLOT( OnRoot() ) ); connect( ListView, SIGNAL(doubleClicked( QListViewItem*)), SLOT(listDoubleClicked(QListViewItem *)) ); connect( ListView, SIGNAL(clicked( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); connect( ListView, SIGNAL(OnOKButton( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); connect( ListView, SIGNAL(OnCentreButton( QListViewItem*)), SLOT(listClicked(QListViewItem *)) ); connect( ListView, SIGNAL(OnCancelButton()), SLOT(OnCancel()) ); QVBoxLayout* grid = new QVBoxLayout(this); grid->addWidget(dirLabel); QHBoxLayout* hgrid = new QHBoxLayout(grid); QPushButton* bt = new QPushButton( this ); bt->setText( tr( "SD" ) ); connect( bt, SIGNAL( clicked() ), this, SLOT( onSD() ) ); hgrid->addWidget(bt); bt = new QPushButton( this ); bt->setText( tr( "CF" ) ); connect( bt, SIGNAL( clicked() ), this, SLOT( onCF() ) ); hgrid->addWidget(bt); bt = new QPushButton( this ); bt->setText( tr( "Home" ) ); connect( bt, SIGNAL( clicked() ), this, SLOT( onHome() ) ); hgrid->addWidget(bt); hgrid->addWidget(buttonOk); hgrid->addWidget(buttonShowHidden); grid->addWidget(ListView,1); if (allownew) { m_filename = new QLineEdit(this); grid->addWidget(m_filename); connect( m_filename, SIGNAL( returnPressed() ), this, SLOT( onReturn() )); } else { m_filename = NULL; } if (QFileInfo(iPath).exists()) { currentDir.setPath(iPath); #ifdef _WINDOWS _chdir(iPath.latin1()); #else chdir(iPath.latin1()); #endif } else { currentDir.setPath(QDir::currentDirPath()); chdir(QDir::currentDirPath().latin1()); } populateList(); if (modal) showMaximized(); } void fileBrowser::resizeEvent(QResizeEvent* e) { ListView->setColumnWidth(1,(ListView->width())/4); ListView->setColumnWidth(0,ListView->width()-20-ListView->columnWidth(1)); } fileBrowser::~fileBrowser() { } void fileBrowser::populateList() { ListView->clear(); ////qDebug(currentDir.canonicalPath()); // currentDir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks ); currentDir.setFilter( filterspec ); currentDir.setSorting(/* QDir::Size*/ /*| QDir::Reversed | */QDir::DirsFirst); currentDir.setMatchAllDirs(TRUE); currentDir.setNameFilter(filterStr); // currentDir.setNameFilter("*.txt;*.etx"); QString fileL, fileS; const QFileInfoList *list = currentDir.entryInfoList(); QFileInfoListIterator it(*list); QFileInfo *fi; while ( (fi=it.current()) ) { if (fi->fileName() != ".") { fileS.sprintf( "%10li", fi->size() ); fileL.sprintf( "%s",fi->fileName().data() ); if( fi->isDir() ) { fileL+="/"; } else { //// qDebug("Not a dir: "+currentDir.canonicalPath()+fileL); } new QListViewItem( ListView,fileL,fileS ); } ++it; } ListView->setSorting( 2, FALSE); dirLabel->setText("Current Directory:\n"+currentDir.canonicalPath()); ListView->setFocus(); } void fileBrowser::upDir() { //// qDebug(currentDir.canonicalPath()); } void fileBrowser::listClicked(QListViewItem *selectedItem) { if (selectedItem == NULL) return; QString strItem=selectedItem->text(0); //// qDebug("%s", (const char*)strItem); QString strSize=selectedItem->text(1); strSize.stripWhiteSpace(); bool ok; QFileInfo fi(strItem); while (fi.isSymLink()) fi.setFile(fi.readLink()); if (fi.isDir()) { strItem=QDir::cleanDirPath(currentDir.canonicalPath()+"/"+strItem); if(QDir(strItem).exists()) { currentDir.cd(strItem, TRUE); populateList(); } } else { QListViewItem *selectedItem = ListView->selectedItem(); if (selectedItem == NULL) { filename = ""; } else { filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+selectedItem->text(0)); } OnOK(); } chdir(strItem.latin1()); // } // you may want to switch these 2 functions. I like single clicks void fileBrowser::listDoubleClicked(QListViewItem *selectedItem) { } QString fileBrowser::getCurrentFile() { return filename; } void fileBrowser::OnOK() { accept(); } void fileBrowser::OnRoot() { setdir("/"); } void fileBrowser::OnCancel() { reject(); } void fileBrowser::setHidden(bool _hidden) { if (_hidden) filterspec = QDir::All | QDir::Hidden; else filterspec = QDir::All; populateList(); } void fileBrowser::onReturn() { QListViewItem *selectedItem = ListView->selectedItem(); if (selectedItem == NULL) { filename = m_filename->text(); } else { filename = QDir::cleanDirPath(currentDir.canonicalPath()+"/"+m_filename->text()); } OnOK(); } void fileBrowser::onCF() { setdir("/mnt/cf"); } void fileBrowser::onSD() { setdir("/mnt/card"); } void fileBrowser::onHome() { setdir(QDir::homeDirPath()); } void fileBrowser::setdir(const QString& s) { currentDir.cd(s, TRUE); populateList(); chdir(s); } diff --git a/noncore/apps/opie-reader/flitecmd.cpp b/noncore/apps/opie-reader/flitecmd.cpp new file mode 100644 index 0000000..bb7e303 --- a/dev/null +++ b/noncore/apps/opie-reader/flitecmd.cpp @@ -0,0 +1,43 @@ +#include <unistd.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <errno.h> +#include "flitecmd.h" + +void CFliteCmd::output(const QString& txt) +{ + pid_t pid; + if ((pid = fork()) <0) + { + qDebug("No memory"); + } + else if (pid == 0) + { + execlp("flite", "flite", "-t", (const char*)txt, NULL); + _exit(127); + qDebug("Can't find flite"); + } + else + { + int status; + while (waitpid(pid, &status, 0) < 0) + { + if (errno != EINTR) + { + qDebug("Error from flite"); + break; + } + } + qDebug("flite status:%d", status); + } +} + +QString CFliteCmd::about() +{ + return QString("FliteCmd output codec (c) Tim Wentford\n"); +} + +extern "C" +{ + COutput* newcodec() { return new CFliteCmd; } +} diff --git a/noncore/apps/opie-reader/flitecmd.h b/noncore/apps/opie-reader/flitecmd.h new file mode 100644 index 0000000..10f9710 --- a/dev/null +++ b/noncore/apps/opie-reader/flitecmd.h @@ -0,0 +1,10 @@ +#include "outputcodec.h" + +class CFliteCmd : public COutput +{ + public: + CFliteCmd() {} + ~CFliteCmd() {} + QString about(); + void output(const QString& _o); +}; diff --git a/noncore/apps/opie-reader/flitedyn.cpp b/noncore/apps/opie-reader/flitedyn.cpp new file mode 100644 index 0000000..c268cd4 --- a/dev/null +++ b/noncore/apps/opie-reader/flitedyn.cpp @@ -0,0 +1,29 @@ +#include "flitedyn.h" + +cst_voice *CFliteDyn::m_voice = NULL; + +CFliteDyn::CFliteDyn() +{ + if (m_voice == NULL) + { + qDebug("Constucting flite"); + flite_init(); + m_voice = register_cmu_us_kal(); + } +} + +QString CFliteDyn::about() +{ + return QString("FliteDyn output codec (c) Tim Wentford\n"); +} + +void CFliteDyn::output(const QString& _o) +{ + float tm = flite_text_to_speech((const char*)_o, m_voice, "play"); + qDebug("Produced %g seconds of speech", tm); +} + +extern "C" +{ + COutput* newcodec() { return new CFliteDyn; } +} diff --git a/noncore/apps/opie-reader/flitedyn.h b/noncore/apps/opie-reader/flitedyn.h new file mode 100644 index 0000000..4455048 --- a/dev/null +++ b/noncore/apps/opie-reader/flitedyn.h @@ -0,0 +1,16 @@ +#include "outputcodec.h" +extern "C" +{ +#include <flite.h> + cst_voice *register_cmu_us_kal(); +} + +class CFliteDyn : public COutput +{ + static cst_voice *m_voice; + public: + CFliteDyn(); + ~CFliteDyn() {} + QString about(); + void output(const QString& _o); +}; diff --git a/noncore/apps/opie-reader/iSilo.cpp b/noncore/apps/opie-reader/iSilo.cpp index 5f14b96..1f727fe 100644 --- a/noncore/apps/opie-reader/iSilo.cpp +++ b/noncore/apps/opie-reader/iSilo.cpp @@ -1,638 +1,639 @@ #include "iSilo.h" #ifdef _WINDOWS
#include <winsock.h>
#endif
u_int8_t *rodata = (u_int8_t *) "\x10\x11\x12\x00\x08\x07\x09\x06\x0a\x05\x0b\x04\x0c\x03\x0d\x02\x0e\x01\x0f"; u_int16_t *rsize_min = (u_int16_t *) "\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08\x00\x09\x00\x0a\x00\x0b\x00\x0d" "\x00\x0f\x00\x11\x00\x13\x00\x17\x00\x1b\x00\x1f\x00\x23\x00\x2b\x00\x33\x00" "\x3b\x00\x43\x00\x53\x00\x63\x00\x73\x00\x83\x00\xa3\x00\xc3\x00\xe3\x00\x02" "\x01"; u_int8_t *rsize_delta = (u_int8_t *) "\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x02\x02\x02\x02\x03\x03\x03" "\x03\x04\x04\x04\x04\x05\x05\x05\x05\x00"; u_int16_t *rpos_min = (u_int16_t *) "\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x07\x00\x09\x00\x0d\x00\x11\x00\x19" "\x00\x21\x00\x31\x00\x41\x00\x61\x00\x81\x00\xc1\x00\x01\x01\x81\x01\x01\x02" "\x01\x03\x01\x04\x01\x06\x01\x08\x01\x0c\x01\x10\x01\x18\x01\x20\x01\x30\x01" "\x40\x01\x60"; u_int8_t *rpos_delta = (u_int8_t *) "\x00\x00\x00\x00\x01\x01\x02\x02\x03\x03\x04\x04\x05\x05\x06\x06\x07\x07" "\x08\x08\x09\x09\x0a\x0a\x0b\x0b\x0c\x0c\x0d\x0d"; void iSilo::init_tables(void) { int i; u_int16_t j; return; for (i = 0; i < 3; i++) rodata[i] = 0x10 + i; rodata[3] = 0; for (i = 4; i < 19; i = i + 2) rodata[i] = 8 + (i-4)/2; for (i = 5; i < 19; i = i + 2) rodata[i] = 7 - (i-5)/2; memset(rsize_delta, 0, 29); for (i = 4; i < 29; i++) { rsize_delta[i] = (i - 4) >> 2; } memset(rpos_delta, 0, 30); for (i = 2; i < 30; i++) { rpos_delta[i] = (i - 2) >> 1; } j = 3; for (i = 0; i < 29; i++) { rsize_min[i] = j; j += 1 << rsize_delta[i]; } j = 1; for (i = 0; i < 30; i++) { rpos_min[i] = j; j += 1 << rpos_delta[i]; } } /* read num bits from the file descriptor */ int iSilo::code2tree(struct s_huffman *h) { struct s_tree *t, *tmp; u_int32_t i; int j, b; t = new s_tree(); h->tree = t; if (t == NULL) return -1; memset(t, 0, sizeof(struct s_tree)); t->value = (u_int32_t)-1; for (i = 0; i < h->num; i++) { tmp = t; for (j = 0; j < h->size[i]; j++) { b = (h->code[i] >> j) & 1; if (tmp->branch[b] == NULL) { tmp->branch[b] =new s_tree(); if (tmp->branch[b] == NULL) return(-1); memset(tmp->branch[b], 0, sizeof(struct s_tree)); tmp->value = (u_int32_t)-1; } tmp = tmp->branch[b]; } if (h->size[i] > 0) tmp->value = i; } return (0); } u_int32_t iSilo::swap_bits(u_int32_t n, int num) { n = ((n >> 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa); n = ((n >> 2) & 0x33333333) | ((n << 2) & 0xcccccccc); n = ((n >> 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0); n = ((n >> 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00); n = ((n >> 16) & 0x0000ffff) | ((n << 16) & 0xffff0000); n >>= (32 - num); return(n); } u_int32_t *iSilo::huffman_get(struct s_huffman *h) { int b; struct s_tree *t = h->tree; while (t->value == -1) { b = get_bits(1); if (t->branch[b] == NULL) { return(NULL); } t = t->branch[b]; } return (&t->value); } int iSilo::size2code(struct s_huffman *h) { u_int8_t i, sk, max = 0; u_int16_t sc, c; u_int32_t j, k, l; int skip; for (l = 0; l < h->num; l++) { if (h->size[l] > max) max = h->size[l]; } for (i = 1; i <= max; i++) { sc = 0; c = 0; for (j = 0; j < h->num; j++) { if (h->size[j] == i) { do { skip = 0; for (k = 0; k < h->num; k++) { sk = h->size[k]; if ((sk < i) && (sk != 0) && !((h->code[k] ^ c) & ((1 << sk)-1))) { if ((c + 1) == (1 << i)) { return -1; } sc += 1 << (i-sk); c = swap_bits(sc, i); skip = 1; break; } } } while (skip); h->code[j] = c; sc++; c = swap_bits(sc, i); } } } return(0); } struct s_huffman *iSilo::huffman_create(u_int32_t num) { struct s_huffman *h; h = new s_huffman(); h->tree = new s_tree(); memset(h->tree, 0, sizeof(struct s_tree)); h->tree->value = (u_int32_t)-1; h->num = num; h->code = new u_int16_t[num]; h->size = new u_int8_t[num]; memset(h->size, 0, num); memset(h->code, 0, num*2); return (h); } void iSilo::kill_tree(struct s_tree *tree) { if (tree == NULL) { return; } kill_tree(tree->branch[0]); kill_tree(tree->branch[1]); delete tree; } void iSilo::kill_huffman(struct s_huffman *h) { if (h == NULL) { return; } kill_tree(h->tree); delete h->code; delete h->size; delete h; } int iSilo::read_size(struct s_huffman *prev, struct s_huffman *h) { u_int32_t *j; u_int32_t i, n; int s_ok = 0, ls = 0; for (i = 0;i < h->num;) { j = huffman_get(prev); if (j == NULL) return(-1); switch(*j) { case HM_MEDIUM: n = get_swapped(3) + 3; /* n bytes of 0 */ memset(h->size + i, 0, n); i += n; break; case HM_LONG: n = get_swapped(7) + 11; /* n bytes of 0 */ memset(h->size + i, 0, n); i += n; break; case HM_SHORT: if (!s_ok) { return(-1); } n = get_swapped(2) + 3; /* n+1 bytes of ls */ memset(h->size + i, ls, n); i += n; break; default: h->size[i] = *j; ls = *j; i++; break; } if ((*j == HM_LONG) || (*j == HM_MEDIUM)) { s_ok = 0; } else { s_ok = 1; } } return(0); } void iSilo::mymemcpy(u_int8_t *dst, u_int8_t *src, u_int32_t num) { u_int32_t i; for (i = 0; i < num; i++) { dst[i] = src[i]; } } /* return size or -1 for error */ int iSilo::read_tree(struct s_huffman *prev, struct s_huffman *curr) { if (read_size(prev, curr) == -1) return(-1); if (size2code(curr) == -1) return(-1); if (code2tree(curr) == -1) return(-1); return(0); } bool iSilo::reset_trees() { get_bits(0); /* flush buffer */ /* This is a Table record so we reload the tables */ kill_huffman(lz); kill_huffman(text); kill_huffman(master); master = huffman_create(19); text = huffman_create(get_swapped(5) + 257); lz = huffman_create(get_swapped(5) + 1); int rdmax = get_swapped(4) + 4; for (int i = 0; i < rdmax; i++) { master->size[rodata[i]] = get_swapped(3); } if (size2code(master) == -1) { qDebug("size2code(master) error: size-table is incompatible"); return false; } code2tree(master); if (read_tree(master, text) == -1) { qDebug("read_tree() failed (format incorrect?)"); return false; } if (read_tree(master, lz) == -1) { qDebug("read_tree() failed (format incorrect?)"); return false;; } return true; } u_int32_t iSilo::get_bits(int num) { int i, r; u_int32_t result = 0; if (num == 0) { pos = 0; return(0); } for (i = 0; i < num; i++) { if (pos == 0) { + unsuspend(); r = fread(buf, sizeof(u_int32_t), 256, fin); if (r <= 0) { qDebug("ERROR: Unexpected end of file"); exit(-1); /* FIXME */ } pos = 32*256; } pos--; result <<= 1; result |= (ntohl(buf[255 - (pos/32)]) >> (31-(pos % 32))) & 1; } return(result); } u_int32_t iSilo::get_swapped(int num) { return(swap_bits(get_bits(num),num)); } int iSilo::read_text() { u_int32_t *j; u_int32_t k, l, bp, idx; for (bp = 0; bp < buffer_size;) { j = huffman_get(text); if (j == NULL) return(-1); if (*j == 256) { break; } if (*j >= 257) { idx = *j - 257; k = rsize_min[idx]; if (rsize_delta[idx] != 0) { k += get_swapped(rsize_delta[idx]); } j = huffman_get(lz); if (j == NULL) return(-1); l = rpos_min[*j]; if (rpos_delta[*j] != 0) { l += get_swapped(rpos_delta[*j]); } if (k <= l) { memcpy(buffer + bp, buffer + bp - l, k); } else { mymemcpy(buffer + bp, buffer + bp - l, k); } bp += k; } else { buffer[bp] = *j; bp++; } } return(bp); } u_int32_t iSilo::getreccode() { u_int32_t offset, rec_code; gotorecordnumber(cur_rec); if (fread(&rec_code, sizeof(rec_code), 1, fin) != 1) { qDebug("short read"); return 0xff; } return rec_code; } bool iSilo::process_record() { u_int32_t rec_code = getreccode(); if (((rec_code & 0xFF) == 0) && (cur_rec != 0)) { return false; } else { /* process text */ if ((cur_rec % 9) == 1) { bsize = 0; if (!reset_trees()) return false; cur_rec++; rec_code = getreccode(); if (((rec_code & 0xFF) == 0) && (cur_rec != 0)) { return false; } } if (cur_rec != 0) { /* This is a Data record so we decode text using the table */ get_bits(0); bsize = read_text(); } /* end of text processing */ } return true; } iSilo::~iSilo() { kill_huffman(master); kill_huffman(lz); kill_huffman(text); if (attr != NULL) { delete [] attr; attr = NULL; } } int iSilo::getch() { if (filepos >= textsize) { // qDebug("File end at record %u", cur_rec); return EOF; } if (current_pos >= bsize) { cur_rec++; if (!process_record()) return EOF; current_pos = 0; } filepos++; while (attr != NULL && filepos > attr[current_attr].offset) { mystyle.unset(); u_int16_t a = attr[current_attr].value; // qDebug("Handling attr:%x at pos:%u", a, filepos); if ((a & 0x1) != 0) { mystyle.setBold(); } if ((a & 0xe) != 0) { qDebug("Unknown attribute:%x (%x)", a & 0xe, a); } if ((a & 0x10) != 0) { mystyle.setCentreJustify(); } else if ((a & 0x20) != 0) { mystyle.setRightJustify(); } else { mystyle.setLeftJustify(); } if ((a & 0x40) != 0) { qDebug("Unknown attribute:%x (%x)", a & 0x40, a); } if ((a & 0x80) != 0) { mystyle.setLeftMargin(10); mystyle.setRightMargin(10); } switch (a & 0xf00) { case 0x300: mystyle.setFontSize(0); break; case 0xd00: mystyle.setFontSize(1); break; case 0xe00: mystyle.setFontSize(2); break; case 0xf00: mystyle.setFontSize(3); break; default: mystyle.setFontSize(0); qDebug("Not sure of font size:%x (%x)", a & 0xf00, a); break; } if ((a & 0x1000) != 0) { mystyle.setMono(); } if ((a & 0x2000) != 0) { mystyle.setItalic(); } if ((a & 0x4000) != 0) { qDebug("Unknown attribute:%x (%x)", a & 0x4000, a); } if ((a & 0x8000) != 0) { mystyle.setUnderline(); } current_attr++; if (current_attr >= attr_num) { attr_rec++; read_attr(); } } return buffer[current_pos++]; } void iSilo::getch(tchar& ch, CStyle& sty, unsigned long& pos) { pos = filepos; ch = getch(); sty = mystyle; } int iSilo::OpenFile(const char* src) { struct stat _stat; stat(src,&_stat); filesize = _stat.st_size; pos = 0; cur_rec = 0; buffer_size = 4096; current_pos = 0; bsize = 0; filepos = 0; if (!Cpdb::openpdbfile(src)) { return -1; } if (head.creator != 0x6F476F54 // 'ToGo' || head.type != 0x6F476F54) // 'ToGo') { return -1; } qDebug("There is %u records in this PDB file", ntohs(head.recordList.numRecords)); init_tables(); gotorecordnumber(0); fread(buffer,1,12,fin); fread(&textsize, sizeof(textsize), 1, fin); textsize = ntohl(textsize); fread(buffer,1,4,fin); fread(&attr_start,sizeof(attr_start),1,fin); attr_start = ntohs(attr_start); fread(buffer,1,2,fin); fread(&attr_end,sizeof(attr_end),1,fin); attr_end = ntohs(attr_end); attr_rec = attr_start; attr = NULL; pos_hi = 0xffff; last_pos = 0xffff; last_value = 0xffff; read_attr(); return 0; } void iSilo::read_attr() { // qDebug("read_attr:<%u, %u, %u>", attr_rec, attr_start, attr_end); current_attr = 0; if (attr != NULL) { delete [] attr; attr = NULL; } if (attr_rec >= attr_start && attr_rec < attr_end) { gotorecordnumber(attr_rec); fread(buffer, 1, 4, fin); fread(&attr_num, sizeof(attr_num), 1, fin); attr_num = ntohs(attr_num)+1; attr = new s_attrib[attr_num]; for (int j = 0; j < attr_num; j++) { fread(&attr[j].offset, 2, 1, fin); attr[j].offset = htons(attr[j].offset); }
#ifdef _WINDOWS for (j = 0; j < attr_num; j++)
#else
for (int j = 0; j < attr_num; j++)
#endif
{ fread(&attr[j].value, 2, 1, fin); if (attr[j].offset < last_pos) { pos_hi++; } if ((attr[j].offset == last_pos) && (attr[j].value == last_value)) { pos_hi++; } last_pos = attr[j].offset; attr[j].offset |= ((u_int32_t)pos_hi) << 16; last_value = attr[j].value; } current_attr = 0; // last_value = attr[attr_num-1].value; // qDebug("Next attr:%u (%u)", attr[current_attr].offset, filepos); // qDebug("Next attr:%x (%x)", attr[current_attr].offset, filepos); } } void iSilo::locate(unsigned int n) { // qDebug("Locating %u", n); if (n >= textsize) n = 0; pos = 0; buffer_size = 4096; current_pos = 0; bsize = 0; /* Brute force cur_rec = 0; filepos = 0; */ // Fast filepos = n - n % (8*buffer_size); cur_rec = 9*(n/(8*buffer_size)); // End of fast pos_hi = 0xffff; last_pos = 0xffff; last_value = 0xffff; attr_rec = attr_start; read_attr(); // While loop added for fast locate while (attr != NULL && attr[attr_num-1].offset < filepos) { attr_rec++; read_attr(); } while (filepos < n) { getch(); } } /* if (!process_record()) return EOF; current_pos = 0; */ QString iSilo::about() { return QString("iSilo codec (c) Tim Wentford, based on code supplied by an anonymous donor"); } extern "C" { CExpander* newcodec() { return new iSilo; } } diff --git a/noncore/apps/opie-reader/linktype.h b/noncore/apps/opie-reader/linktype.h index 23c24ac..a23d345 100644 --- a/noncore/apps/opie-reader/linktype.h +++ b/noncore/apps/opie-reader/linktype.h @@ -1,7 +1,7 @@ #ifndef __LINKTYPE_H #define __LINKTYPE_H typedef unsigned int linkType; -const linkType eNone = 0, eLink = 1, ePicture = 2, eFile = 4; +const linkType eNone = 0, eLink = 1, ePicture = 2, eFile = 4, eTable = 8; #endif diff --git a/noncore/apps/opie-reader/main.cpp b/noncore/apps/opie-reader/main.cpp index af276da..2be6045 100644 --- a/noncore/apps/opie-reader/main.cpp +++ b/noncore/apps/opie-reader/main.cpp @@ -1,49 +1,50 @@ + #ifdef USEQPE #include <qpe/qpeapplication.h> #else #include <qapplication.h> #endif #include "QTReaderApp.h" #include "signal.h" #include "stdio.h" #include "time.h" #ifdef USEQPE QTReaderApp* app = NULL; void handler(int signum) { if (app != NULL) { app->suspend(); app->saveprefs(); } signal(signum, handler); } #endif int main( int argc, char ** argv ) { #ifdef USEQPE signal(SIGCONT, handler); QPEApplication a( argc, argv ); QTReaderApp m; a.showMainDocumentWidget( &m ); app = &m; #else QApplication a( argc, argv ); QTReaderApp m; a.setMainWidget( &m ); if (argc > 1) { m.setDocument(argv[1]); } #endif return a.exec(); } diff --git a/noncore/apps/opie-reader/mytypes.h b/noncore/apps/opie-reader/mytypes.h new file mode 100644 index 0000000..ea60db3 --- a/dev/null +++ b/noncore/apps/opie-reader/mytypes.h @@ -0,0 +1,8 @@ +#ifndef __MYTYPES_H__ +#define __MYTYPES_H__ +typedef unsigned char UInt8; +typedef unsigned short UInt16; +typedef signed short Int16; +typedef unsigned long UInt32; +#endif + diff --git a/noncore/apps/opie-reader/opie-reader.pro b/noncore/apps/opie-reader/opie-reader.pro index 170f7fa..47980e1 100644 --- a/noncore/apps/opie-reader/opie-reader.pro +++ b/noncore/apps/opie-reader/opie-reader.pro @@ -1,16 +1,24 @@ TEMPLATE = subdirs SUBDIRS = pluckerbaselib \ codeclib \ pdblib \ PluckerCodec \ AportisCodec \ CHM \ HTMLFilter \ WeaselCodec \ iSiloCodec \ ppmsCodec \ + FliteCmd \ + pluckerdecompress \ + ArriereCodec \ + RebCodec \ reader +# these are added only built if enabled in "make menuconfig" +# FliteDyn +# FliteDyn16 + include( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/opie-reader/outputcodec.h b/noncore/apps/opie-reader/outputcodec.h new file mode 100644 index 0000000..727575c --- a/dev/null +++ b/noncore/apps/opie-reader/outputcodec.h @@ -0,0 +1,84 @@ +#include <stdlib.h> +#include <qfileinfo.h> +#include <qdir.h> + +#ifdef USEQPE +#include <qpe/global.h> +#endif + +class COutput +{ + public: + virtual ~COutput() {} + virtual void output(const QString&) = 0; + virtual QString about() = 0; +}; + +#ifndef __STATIC +#include <dlfcn.h> +class outputcodec : public COutput +{ + COutput *codec; + void *handle; + int status; + public: + void output(const QString& q) { codec->output(q); } + QString about() + { + return QString("Plug-in output codec interface (c) Tim Wentford\n")+codec->about(); + } + outputcodec(const QString& _s) : codec(NULL), handle(NULL), status(-1) + { +#ifdef USEQPE +#ifdef OPIE + QString codecpath(getenv("OPIEDIR")); +#else + QString codecpath(getenv("QTDIR")); +#endif + codecpath += "/plugins/reader/outcodecs/lib"; +#else + QString codecpath(getenv("READERDIR")); + codecpath += "/outcodecs/lib"; +#endif + codecpath += _s; + codecpath += ".so"; + if (QFile::exists(codecpath)) + { + qDebug("Codec:%s", (const char*)codecpath); + handle = dlopen(codecpath, RTLD_LAZY); + if (handle == 0) + { + qDebug("Can't find codec:%s", dlerror()); + status = -10; + return; + } + COutput* (*newcodec)(); + newcodec = (COutput* (*)())dlsym(handle, "newcodec"); + if (newcodec == NULL) + { + qDebug("Can't find newcodec"); + status = -20; + return; + } + codec = (*newcodec)(); + status = 0; + } + else + { + qDebug("Can't find codec:%s", (const char*)codecpath); + } + if (codec == NULL) + { + qDebug("Can't do newcodec"); + status = -30; + return; + } + } + virtual ~outputcodec() + { + if (codec != NULL) delete codec; + if (handle != NULL) dlclose(handle); + } + int getStatus() { return status; } +}; +#endif diff --git a/noncore/apps/opie-reader/pdb.cpp b/noncore/apps/opie-reader/pdb.cpp index 6719af4..a13b33d 100644 --- a/noncore/apps/opie-reader/pdb.cpp +++ b/noncore/apps/opie-reader/pdb.cpp @@ -1,89 +1,90 @@ #include "pdb.h" #ifdef _WINDOWS #include <winsock2.h> #endif - #ifdef USEQPE void Cpdb::suspend() { CExpander::suspend(fin); } void Cpdb::unsuspend() { CExpander::unsuspend(fin); } #endif Cpdb::~Cpdb() { if (fin != NULL) { #ifdef USEQPE unsuspend(); #endif fclose(fin); } } size_t Cpdb::recordpos(int n) { UInt16 mxn = ntohs(head.recordList.numRecords); if (n >= mxn) { return file_length; } else { size_t dataoffset = sizeof(DatabaseHdrType) - sizeof(UInt16); dataoffset += /*dataoffset%4 + */ sizeof(RecordListType) * n; + unsuspend(); fseek(fin, dataoffset, SEEK_SET); RecordListType hdr; fread(&hdr, 1, sizeof(hdr), fin); return ntohl(hdr.nextRecordListID); } } size_t Cpdb::recordlength(int n) { return recordpos(n+1)-recordpos(n); } void Cpdb::gotorecordnumber(int n) { +unsuspend(); fseek(fin, recordpos(n), SEEK_SET); } bool Cpdb::openpdbfile(const char *src) { //qDebug("cpdb openfile:%s", src); // printf("In openfile\n"); // printf("closing fin:%x\n",fin); if (fin != NULL) fclose(fin); // printf("opening fin\n"); fin = fopen(src,"rb"); if (fin==0) { return false; } // just holds the first few chars of the file // char buf[0x100]; struct stat _stat; stat(src,&_stat); file_length = _stat.st_size; // fseek(fin,0,SEEK_END); // file_length = ftell(fin); fseek(fin,0,SEEK_SET); fread(&head, 1, sizeof(head), fin); - qDebug("Database name:%s", head.name); - qDebug("Total number of records:%u", ntohs(head.recordList.numRecords)); + //qDebug("Database name:%s", head.name); + //qDebug("Total number of records:%u", ntohs(head.recordList.numRecords)); return true; } diff --git a/noncore/apps/opie-reader/pdb.h b/noncore/apps/opie-reader/pdb.h index 7458919..a0abd1b 100644 --- a/noncore/apps/opie-reader/pdb.h +++ b/noncore/apps/opie-reader/pdb.h @@ -1,100 +1,101 @@ /* * This header file defines some structures and types normally found in the * Palm SDK. However, I don't want to require the presense of the SDK for a * small utility since most Palm owners won't have it. * * $Id$ * */ #ifndef __PDB_H__ #define __PDB_H__ #ifndef _WINDOWS #include <netinet/in.h> #endif #include <stdio.h> + #include "CExpander.h" /* Normal Palm typedefs */ -typedef unsigned char UInt8; -typedef unsigned short UInt16; -typedef signed short Int16; -typedef unsigned long UInt32; +#include "mytypes.h" typedef UInt32 LocalID; /* Max length of DB name */ #define dmDBNameLength 0x20 /************************************************************ * Structure of a Record entry *************************************************************/ typedef struct { LocalID localChunkID; // local chunkID of a record UInt8 attributes; // record attributes; UInt8 uniqueID[3]; // unique ID of record; should // not be 0 for a legal record. } RecordEntryType; /************************************************************ * Structure of a record list extension. This is used if all * the database record/resource entries of a database can't fit into * the database header. *************************************************************/ typedef struct { LocalID nextRecordListID; // local chunkID of next list UInt16 numRecords; // number of records in this list UInt16 firstEntry; // array of Record/Rsrc entries // starts here } RecordListType; /************************************************************ * Structure of a Database Header *************************************************************/ typedef struct { UInt8 name[dmDBNameLength]; // name of database UInt16 attributes; // database attributes UInt16 version; // version of database UInt32 creationDate; // creation date of database UInt32 modificationDate; // latest modification date UInt32 lastBackupDate; // latest backup date UInt32 modificationNumber; // modification number of database LocalID appInfoID; // application specific info LocalID sortInfoID; // app specific sorting info UInt32 type; // database type UInt32 creator; // database creator UInt32 uniqueIDSeed; // used to generate unique IDs. // Note that only the low order // 3 bytes of this is used (in // RecordEntryType.uniqueID). // We are keeping 4 bytes for // alignment purposes. RecordListType recordList; // first record list } DatabaseHdrType; class Cpdb : public CExpander { protected: size_t file_length; FILE* fin; size_t recordpos(int); size_t recordlength(int); void gotorecordnumber(int); DatabaseHdrType head; bool openpdbfile(const char* src); Cpdb() : fin(NULL) {} ~Cpdb(); #ifdef USEQPE void suspend(); void unsuspend(); +#else + void suspend() {} + void unsuspend() {} #endif public: virtual void sizes(unsigned long& _file, unsigned long& _text) = 0; }; #endif diff --git a/noncore/apps/opie-reader/plucker_base.cpp b/noncore/apps/opie-reader/plucker_base.cpp index d7d538f..51c7fa7 100644 --- a/noncore/apps/opie-reader/plucker_base.cpp +++ b/noncore/apps/opie-reader/plucker_base.cpp @@ -1,1408 +1,1528 @@ -#include "usenef.h" #include <stdio.h> #include <string.h> #include <qmessagebox.h> #include <qpixmap.h> #ifdef USEQPE #include <qpe/qcopenvelope_qws.h> #endif /* USEQPE */ #ifdef LOCALPICTURES #include <qscrollview.h> #endif #ifdef USEQPE #include <qpe/global.h> #endif /* USEQPE */ #include <qclipboard.h> #ifndef USEQPE #include <qapplication.h> #else /* USEQPE */ #include <qpe/qpeapplication.h> #endif /* USEQPE */ #include <qimage.h> #include "plucker_base.h" #include "Aportis.h" #include "hrule.h" -#include "util.h" +#include "decompress.h" const UInt8 CPlucker_base::continuation_bit = 1; CPlucker_base::CPlucker_base() : #ifdef LOCALPICTURES m_viewer(NULL), m_picture(NULL), #endif expandedtextbuffer(NULL), compressedtextbuffer(NULL), bufferrec(-1), m_offset(0) //, urls(NULL) { /*printf("constructing:%x\n",fin);*/ } void CPlucker_base::Expand(UInt32 reclen, UInt8 type, UInt8* buffer, UInt32 buffersize) { - if (type%2 == 0) +unsuspend(); + if ((type%2 == 0) && (type != 14)) { fread(buffer, reclen, sizeof(char), fin); } else { UInt8* readbuffer = NULL; if (reclen > compressedbuffersize) { readbuffer = new UInt8[reclen]; } else { readbuffer = compressedtextbuffer; } if (readbuffer != NULL) { fread(readbuffer, reclen, sizeof(char), fin); (*m_decompress)(readbuffer, reclen, buffer, buffersize); if (reclen > compressedbuffersize) { delete [] readbuffer; } } } } void CPlucker_base::sizes(unsigned long& _file, unsigned long& _text) { _file = file_length; if (textlength == 0) { for (int recptr = 1; recptr < ntohs(head.recordList.numRecords); recptr++) { gotorecordnumber(recptr); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_type < 2) textlength += thishdr_size; } } _text = textlength; //ntohl(hdr0.size); } char* CPlucker_base::geturl(UInt16 tgt) { char * pRet = NULL; gotorecordnumber(0); fread(&hdr0, 1, 6, fin); unsigned int nrecs = ntohs(hdr0.nRecords); //qDebug("Version %u, no. recs %u", ntohs(hdr0.version), nrecs); UInt16 urlid = 0; bool urlsfound = false; char* urls = NULL; size_t urlsize = 0; for (unsigned int i = 0; i < nrecs; i++) { UInt16 id, name; fread(&name, 1, sizeof(name), fin); fread(&id, 1, sizeof(id), fin); //qDebug("N:%d, I:%d", ntohs(name), ntohs(id)); if (ntohs(name) == 2) { urlsfound = true; urlid = id; //qDebug("Found url index:%d", ntohs(urlid)); } // //qDebug("%x", id); } if (urlsfound) { unsigned short recptr = finduid(ntohs(urlid)); if (recptr != 0) { gotorecordnumber(recptr); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); UInt16 urlctr = 0; while (1) { UInt16 tctr; fread(&tctr, 1, sizeof(tctr), fin); fread(&urlid, 1, sizeof(urlid), fin); tctr = ntohs(tctr); //qDebug("tgt:%u urlctr:%u tctr:%u", tgt, urlctr, tctr); if (tctr >= tgt) { break; } urlctr = tctr; } //qDebug("urls are in %d", ntohs(urlid)); recptr = finduid(ntohs(urlid)); if (recptr != 0) { UInt32 reclen = recordlength(recptr) - HeaderSize(); gotorecordnumber(recptr); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); //qDebug("Found urls:%x",thishdr_type); urlsize = thishdr_size; urls = new char[urlsize]; Expand(reclen, thishdr_type, (UInt8*)urls, urlsize); char* ptr = urls; int rn = urlctr+1; while (ptr - urls < urlsize) { if (rn == tgt) { //qDebug("URL:%s", ptr); int len = strlen(ptr)+1; pRet = new char[len]; memcpy(pRet, ptr, len); break; } ptr += strlen(ptr)+1; rn++; } delete [] urls; } } } else { pRet = NULL; } return pRet; } CPlucker_base::~CPlucker_base() { if (expandedtextbuffer != NULL) delete [] expandedtextbuffer; if (compressedtextbuffer != NULL) delete [] compressedtextbuffer; #ifdef LOCALPICTURES if (m_viewer != NULL) delete m_viewer; #endif } int CPlucker_base::getch() { return getch(false); } void CPlucker_base::getch(tchar& ch, CStyle& sty, unsigned long& pos) { pos = locate(); ch = getch(false); sty = mystyle; } unsigned int CPlucker_base::locate() { return currentpos; /* UInt16 thisrec = 1; unsigned long locpos = 0; gotorecordnumber(thisrec); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; while (thisrec < bufferrec) { GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_type < 2) locpos += thishdr_size; thisrec++; gotorecordnumber(thisrec); } return locpos+bufferpos; */ } void CPlucker_base::locate(unsigned int n) { // clock_t start = clock(); if (n >= currentpos-bufferpos && n < currentpos - bufferpos + buffercontent) { currentpos -= bufferpos; expand(bufferrec); while (currentpos < n && bufferpos < buffercontent) getch_base(true); return; } /* UInt32 textlength = currentpos - bufferpos; UInt16 recptr = bufferrec; if (n < textlength/2) { textlength = 0; UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size = buffercontent; UInt8 thishdr_type, thishdr_reserved; for (recptr = 1; recptr < ntohs(head.recordList.numRecords); recptr++) { gotorecordnumber(recptr); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_type < 2) { textlength += thishdr_size; if (textlength > n) { textlength -= thishdr_size; break; } } } } else if (n < textlength) { UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; while (n < textlength && recptr > 1) { recptr--; gotorecordnumber(recptr); //qDebug("recptr:%u", recptr); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_type < 2) { textlength -= thishdr_size; } } } else { UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size = buffercontent; UInt8 thishdr_type, thishdr_reserved; while (n > textlength + thishdr_size && recptr < ntohs(head.recordList.numRecords)-1) { textlength += thishdr_size; recptr++; gotorecordnumber(recptr); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (!(thishdr_type < 2)) { thishdr_size = 0; } } } */ UInt16 thisrec = 0; unsigned long locpos = 0; unsigned long bs = 0; UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; do { thisrec++; locpos += bs; gotorecordnumber(thisrec); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_type < 2) { bs = thishdr_size; } else { bs = 0; } - } while (locpos + bs <= n); + } while (locpos + bs < n); // qDebug("Time(2): %u", clock()-start); /* if (recptr != thisrec) { qDebug("Disaster:recptr:%u thisrec:%u", recptr, thisrec); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size = buffercontent; UInt8 thishdr_type, thishdr_reserved; for (recptr = 1; recptr < ntohs(head.recordList.numRecords); recptr++) { gotorecordnumber(recptr); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); // qDebug("UID:%u Paras:%u Size:%u Type:%u Reserved:%u", thishdr_uid, thishdr_nParagraphs, thishdr_size, (unsigned int)thishdr_type, (unsigned int)thishdr_reserved); } // QApplication::exit ( 100 ); } */ currentpos = locpos; expand(thisrec); while (currentpos < n && bufferpos < buffercontent) getch_base(true); /* // This is faster but the alignment attribute doesn't get set 8^( bufferpos = n-locpos; currentpos = n; while (bufferpos >= m_nextPara && m_nextPara >= 0) { UInt16 attr = m_ParaAttrs[m_nextParaIndex]; m_nextParaIndex++; if (m_nextParaIndex == m_nParas) { m_nextPara = -1; } else { m_nextPara += m_ParaOffsets[m_nextParaIndex]; } } */ } bool CPlucker_base::expand(int thisrec) { mystyle.unset(); if (bufferrec != thisrec) { size_t reclen = recordlength(thisrec); gotorecordnumber(thisrec); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; while (1) { GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); //qDebug("This (%d) type is %d, uid is %u", thisrec, thishdr_type, thishdr_uid); if (thishdr_type < 2) break; //qDebug("Skipping paragraph of type %d", thishdr_type); if (++thisrec >= ntohs(head.recordList.numRecords) - 1) return false; reclen = recordlength(thisrec); gotorecordnumber(thisrec); } m_nParas = thishdr_nParagraphs; m_bufferisreserved = (thishdr_reserved != 0); //qDebug("It has %u paragraphs and is %u bytes", thishdr_nParagraphs, thishdr_size); uid = thishdr_uid; // gotorecordnumber(thisrec); // fread(expandedtextbuffer,1,10,fin); for (int i = 0; i < m_nParas; i++) { UInt16 ubytes, attrs; fread(&ubytes, 1, sizeof(ubytes), fin); fread(&attrs, 1, sizeof(attrs), fin); m_ParaOffsets[i] = ntohs(ubytes); m_ParaAttrs[i] = ntohs(attrs); // //qDebug("Bytes %u, Attr %x", ntohs(ubytes), ntohs(attrs)); } reclen -= HeaderSize()+4*m_nParas; buffercontent = thishdr_size; if (thishdr_size > buffersize) { delete [] expandedtextbuffer; buffersize = thishdr_size; expandedtextbuffer = new UInt8[buffersize]; } Expand(reclen, thishdr_type, expandedtextbuffer, buffercontent); bufferrec = thisrec; } if (m_nParas > 0) { m_nextPara = m_ParaOffsets[0]; //qDebug("First offset = %u", m_nextPara); m_nextParaIndex = 0; } else { m_nextPara = -1; } bufferpos = 0; //qDebug("BC:%u, HS:%u", buffercontent, thishdr_size); return true; } - +/* void CPlucker_base::UnZip(UInt8* compressedbuffer, size_t reclen, UInt8* tgtbuffer, size_t bsize) { z_stream zstream; memset(&zstream,sizeof(zstream),0); zstream.next_in = compressedbuffer; zstream.next_out = tgtbuffer; zstream.avail_out = bsize; zstream.avail_in = reclen; int keylen = 0; zstream.zalloc = Z_NULL; zstream.zfree = Z_NULL; zstream.opaque = Z_NULL; // printf("Initialising\n"); inflateInit(&zstream); int err = 0; do { if ( zstream.avail_in == 0 && 0 < keylen ) { zstream.next_in = compressedbuffer + keylen; zstream.avail_in = reclen - keylen; keylen = 0; } zstream.next_out = tgtbuffer; zstream.avail_out = bsize; err = inflate( &zstream, Z_SYNC_FLUSH ); // //qDebug("err:%d - %u", err, zstream.avail_in); } while ( err == Z_OK ); inflateEnd(&zstream); } - -void CPlucker_base::UnDoc(UInt8* compressedbuffer, size_t reclen, UInt8* tgtbuffer, size_t bsize) +*/ +size_t CPlucker_base::UnDoc(UInt8* compressedbuffer, size_t reclen, UInt8* tgtbuffer, size_t bsize) { // UInt16 headerSize; UInt16 docSize; UInt16 i; UInt16 j; UInt16 k; UInt8 *inBuf = compressedbuffer; UInt8 *outBuf = tgtbuffer; // headerSize = sizeof( Header ) + record->paragraphs * sizeof( Paragraph ); docSize = reclen; j = 0; k = 0; while ( j < docSize ) { i = 0; while ( i < bsize && j < docSize ) { UInt16 c; c = (UInt16) inBuf[ j++ ]; if ( 0 < c && c < 9 ) { while ( 0 < c-- ) outBuf[ i++ ] = inBuf[ j++ ]; } else if ( c < 0x80 ) outBuf[ i++ ] = c; else if ( 0xc0 <= c ) { outBuf[ i++ ] = ' '; outBuf[ i++ ] = c ^ 0x80; } else { Int16 m; Int16 n; c <<= 8; c += inBuf[ j++ ]; m = ( c & 0x3fff ) >> COUNT_BITS; n = c & ( ( 1 << COUNT_BITS ) - 1 ); n += 2; do { outBuf[ i ] = outBuf[ i - m ]; i++; } while ( 0 < n-- ); } } k += bsize; } + return i; } void CPlucker_base::home() { currentpos = 0; expand(1); } CList<Bkmk>* CPlucker_base::getbkmklist() { /* UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; for (int i = 1; i < ntohs(head.recordList.numRecords); i++) { gotorecordnumber(i); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_type == 8) { UInt16 n; fread(&n, 1, sizeof(n), fin); n = ntohs(n); //qDebug("Found %u bookmarks", n); } //qDebug("Found:%d, %u", i , thishdr_type); } */ return NULL; } #include <qnamespace.h> QImage* CPlucker_base::expandimg(UInt16 tgt, bool border) { QImage* qimage = getimg(tgt); QImage* ret; if (qimage == NULL) return NULL; if (border) { QPixmap* image = new QPixmap(0,0); image->convertFromImage(*qimage); delete qimage; QPixmap* pret = new QPixmap(image->width()+4, image->height()+4); pret->fill(Qt::red); bitBlt(pret, 2, 2, image, 0, 0, -1, -1);//, Qt::RasterOp::CopyROP); delete image; ret = new QImage(pret->convertToImage()); } else { ret = qimage; } return ret; } #ifdef _BUFFERPICS #include <qmap.h> #endif QImage* CPlucker_base::getPicture(unsigned long tgt) { #ifdef _BUFFERPICS static QMap<unsigned long, QPixmap> pix; QMap<unsigned long, QPixmap>::Iterator t = pix.find(tgt); if (t == pix.end()) { pix[tgt] = *expandimg(tgt); return &pix[tgt]; } else return &(t.data()); #else return expandimg(tgt >> 16); #endif } #ifdef LOCALPICTURES #include <unistd.h> #include <qpe/global.h> void CPlucker_base::showimg(UInt16 tgt) { //qDebug("Crassssssh!"); QPixmap* qimage = expandimg(tgt); m_picture->setFixedSize(qimage->size()); m_picture->setBackgroundPixmap(*qimage); delete qimage; m_viewer->show(); /* char tmp[] = "uqtreader.XXXXXX"; QImage* qimage = getimg(tgt); QPixmap* image = new QPixmap(0,0); // //qDebug("New image"); image->convertFromImage(*qimage); delete qimage; char tmpfile[sizeof(tmp)+1]; strcpy(tmpfile,tmp); int f = mkstemp(tmpfile); close(f); //qDebug("TMPFILE:%s", tmpfile); if (image->save(tmpfile,"PNG")) { QCopEnvelope e("QPE/Application/showimg", "setDocument(QString)"); e << QString(tmpfile); } Global::statusMessage("Opening image"); sleep(5); delete image; unlink(tmpfile); */ } #endif unsigned short CPlucker_base::finduid(unsigned short urlid) { // //qDebug("Finding %u", urlid); unsigned short jmin = 1, jmax = ntohs(head.recordList.numRecords); unsigned short jmid = (jmin+jmax) >> 1; while (jmax - jmin > 1) { gotorecordnumber(jmid); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); unsigned short luid = thishdr_uid; // //qDebug("%u %u %u : %u", jmin, jmid, jmax, urlid); if (luid == urlid) { return jmid; } if (luid < urlid) { jmin = jmid; } else { jmax = jmid; } jmid = (jmin+jmax) >> 1; } gotorecordnumber(jmin); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); unsigned short luid = thishdr_uid; //qDebug("jmin at end:%u,%u", jmin, luid); if (luid == urlid) { return jmin; } gotorecordnumber(jmax); GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); luid = thishdr_uid; //qDebug("jmax at end:%u,%u", jmax, luid); if (luid == urlid) { return jmax; } //qDebug("Couldn't find %u", urlid); return 0; // Not found! } #include <qnamespace.h> void CPlucker_base::setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen) { unsigned short sz = 0; for (CList<unsigned long>::iterator it = visited.begin(); it != visited.end(); it++) { sz++; } size_t newlen = srclen+sizeof(sz)+sz*sizeof(unsigned long); unsigned char* newdata = new unsigned char[newlen]; unsigned char* pdata = newdata; memcpy(newdata, src, srclen); newdata += srclen; memcpy(newdata, &sz, sizeof(sz)); newdata += sizeof(sz); #ifdef _WINDOWS for (it = visited.begin(); it != visited.end(); it++) #else for (CList<unsigned long>::iterator it = visited.begin(); it != visited.end(); it++) #endif { unsigned long t = *it; // qDebug("[%u]", t); memcpy(newdata, &t, sizeof(t)); newdata += sizeof(t); } m_nav.setSaveData(data, len, pdata, newlen); delete [] pdata; } void CPlucker_base::putSaveData(unsigned char*& src, unsigned short& srclen) { unsigned short sz; if (srclen >= sizeof(sz)) { memcpy(&sz, src, sizeof(sz)); src += sizeof(sz); srclen -= sizeof(sz); } for (int i = 0; i < sz; i++) { unsigned long t; if (srclen >= sizeof(t)) { memcpy(&t, src, sizeof(t)); // qDebug("[%u]", t); visited.push_front(t); src += sizeof(t); srclen -= sizeof(t); } else { QMessageBox::warning(NULL, PROGNAME, "File data mismatch\nMight fix itself"); break; } } m_nav.putSaveData(src, srclen); } int CPlucker_base::OpenFile(const char *src) { qDebug("plucker openfile:%s", src); m_lastBreak = 0; if (!Cpdb::openpdbfile(src)) { return -1; } if (!CorrectDecoder()) return -1; gotorecordnumber(0); fread(&hdr0, 1, 6, fin); qDebug("Compression type:%u", ntohs(hdr0.version)); switch (ntohs(hdr0.version)) { case 2: m_decompress = UnZip; break; case 1: m_decompress = UnDoc; break; #ifdef USENEF case 3: m_decompress = getdecompressor("PluckerDecompress3"); break; case 4: m_decompress = getdecompressor("PluckerDecompress4"); break; #endif default: m_decompress = NULL; } if (m_decompress == NULL) return -1; setbuffersize(); compressedtextbuffer = new UInt8[compressedbuffersize]; expandedtextbuffer = new UInt8[buffersize]; unsigned int nrecs = ntohs(hdr0.nRecords); qDebug("Version %u, no. reserved recs %u", ntohs(hdr0.version), nrecs); textlength = ntohl(head.sortInfoID); qDebug("Textlength at startup:%u", textlength); UInt16 homerecid = 1; for (unsigned int i = 0; i < nrecs; i++) { UInt16 id, name; fread(&name, 1, sizeof(name), fin); fread(&id, 1, sizeof(id), fin); //qDebug("N:%d, I:%d", ntohs(name), ntohs(id)); if (ntohs(name) == 0) homerecid = ntohs(id); } textlength = 0; for (int recptr = 1; recptr < ntohs(head.recordList.numRecords); recptr++) { gotorecordnumber(recptr); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_uid == homerecid) { m_homepos = textlength; break; } if (thishdr_type < 2) textlength += thishdr_size; } qDebug("Found home"); textlength = 0; home(); qDebug("Gone home"); #ifdef LOCALPICTURES if (m_viewer == NULL) { m_viewer = new QScrollView(NULL); m_picture = new QWidget(m_viewer->viewport()); m_viewer->addChild(m_picture); } #endif return 0; } QImage* CPlucker_base::getimg(UInt16 tgt) { size_t reclen; UInt16 thisrec = finduid(tgt); qDebug("getimg:Found %u from uid:%u", thisrec, tgt); reclen = recordlength(thisrec); gotorecordnumber(thisrec); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (thishdr_type == 15) { char *buffer = new char[thishdr_size]; fread(buffer, thishdr_size, sizeof(char), fin); unsigned short tmp; memcpy(&tmp, buffer, sizeof(tmp)); unsigned short cols = ntohs(tmp); memcpy(&tmp, buffer+sizeof(tmp), sizeof(tmp)); unsigned short rows = ntohs(tmp); qDebug("Found a picture of type:%u [%u,%u]", thishdr_type, rows, cols); QImage*** images; images = new QImage**[rows]; #ifdef _WINDOWS int i; for (i = 0; i < rows; i++) #else for (int i = 0; i < rows; i++) #endif { images[i] = new QImage*[cols]; } int height = 0; int width = 0; #ifdef _WINDOWS for (i = 0; i < rows; i++) #else for (int i = 0; i < rows; i++) #endif { width = 0; for (int j = 0; j < cols; j++) { memcpy(&tmp, buffer+(i*cols+j+2)*sizeof(tmp), sizeof(tmp)); unsigned short uid = ntohs(tmp); images[i][j] = getimg(uid); width += images[i][j]->width(); } height += images[i][0]->height(); } delete [] buffer; QPixmap pm(width, height); int hoffset = 0; #ifdef _WINDOWS for (i = 0; i < rows; i++) #else for (int i = 0; i < rows; i++) #endif { int woffset = 0; int delht = images[i][0]->height(); for (int j = 0; j < cols; j++) { QPixmap pm2; pm2.convertFromImage(*(images[i][j])); delete images[i][j]; bitBlt(&pm, woffset, hoffset, &pm2, 0, 0, pm2.width(), pm2.height()); woffset += pm2.width(); } hoffset += delht; } #ifdef _WINDOWS for (i = 0; i < rows; i++) #else for (int i = 0; i < rows; i++) #endif { delete [] images[i]; } delete [] images; return new QImage(pm.convertToImage()); } else { qDebug("Found a picture of type:%u", thishdr_type); reclen -= HeaderSize(); UInt32 imgsize = thishdr_size; UInt8* imgbuffer = new UInt8[imgsize]; Expand(reclen, thishdr_type, imgbuffer, imgsize); return imagefromdata(imgbuffer, imgsize); } } linkType CPlucker_base::hyperlink(unsigned int n, unsigned int offset, QString& wrd, QString&) { visited.push_front(n); UInt16 tuid = (n >> 16); n &= 0xffff; char *turl = geturl(tuid); if (turl != NULL) { qDebug("URL in PB:%s", turl); wrd = turl; delete [] turl; } else { wrd.truncate(0); } qDebug("Hyper: UID:%u, Para:%u, Offset:%u", tuid, n, offset); UInt16 thisrec = 1; currentpos = 0; gotorecordnumber(thisrec); UInt16 thishdr_uid, thishdr_nParagraphs; UInt32 thishdr_size; UInt8 thishdr_type, thishdr_reserved; while (1) { GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); if (tuid == thishdr_uid) break; if (thishdr_type < 2) currentpos += thishdr_size; // //qDebug("hyper-cp:%u", currentpos); thisrec++; if (thisrec >= ntohs(head.recordList.numRecords)) { if (wrd.isEmpty()) { QMessageBox::information(NULL, QString(PROGNAME), QString("Couldn't find link") ); } else { #ifdef USEQPE if (wrd.length() > 10) { Global::statusMessage(wrd.left(8) + ".."); } else { Global::statusMessage(wrd); } #else #endif /* USEQPE */ //qDebug("Link:%s", (const char*)wrd); // setlink(fn, wrd); } return eNone; } gotorecordnumber(thisrec); } if (thishdr_type > 1) { if (thishdr_type == 4) { QMessageBox::information(NULL, QString(PROGNAME), QString("Mailto links\nnot yet supported (2)")); } else { if (thishdr_type > 3 && thishdr_type != 15) { QMessageBox::information(NULL, QString(PROGNAME), QString("External links\nnot yet supported (2)") ); return eNone; } else { #ifdef LOCALPICTURES showimg(tuid); #else return ePicture; #endif } } return eNone; } /* if (thishdr_type == 2 || thishdr_type == 3) { expandimg(thisrec); } */ else { expand(thisrec); unsigned int paraoffset = offset; // unsigned int noff = 0; if (n != 0) { if (n >= m_nParas) { QMessageBox::information(NULL, QString(PROGNAME), QString("Error in link\nPara # too big") ); return eNone; } unsigned int noff = 0; for (unsigned int i = 0; i < n; i++) noff += m_ParaOffsets[i]; paraoffset += noff; } if (paraoffset > thishdr_size) { QMessageBox::information(NULL, QString(PROGNAME), QString("Error in link\nOffset too big") ); return eNone; } while (bufferpos < paraoffset && bufferpos < buffercontent) getch_base(true); //qDebug("Hyper:<%u,%u,%u>", paraoffset, bufferpos, currentpos); /* // This is faster but the alignment doesn't get set mystyle.unset(); bufferpos = n; currentpos += n; while (bufferpos >= m_nextPara && m_nextPara >= 0) { UInt16 attr = m_ParaAttrs[m_nextParaIndex]; m_nextParaIndex++; if (m_nextParaIndex == m_nParas) { m_nextPara = -1; } else { m_nextPara += m_ParaOffsets[m_nextParaIndex]; } } */ } return eLink; } +QString CPlucker_base::getTableAsHtml(unsigned long tgt) +{ + qDebug("CPlucker_base::getTableAsHtml:%u", tgt); + size_t reclen; + UInt16 thisrec = finduid(tgt); + qDebug("getimg:Found %u from uid:%u", thisrec, tgt); + reclen = recordlength(thisrec); + gotorecordnumber(thisrec); + UInt16 thishdr_uid, thishdr_nParagraphs; + UInt32 thishdr_size; + UInt8 thishdr_type, thishdr_reserved; + GetHeader(thishdr_uid, thishdr_nParagraphs, thishdr_size, thishdr_type, thishdr_reserved); + qDebug("Found a table of type:%u", thishdr_type); + reclen -= HeaderSize(); + UInt32 imgsize = thishdr_size; + UInt8* imgbuffer = new UInt8[imgsize]; + Expand(reclen, thishdr_type, imgbuffer, imgsize); + + QString ret; + + UInt16 size, columns, rows; + UInt8 depth, border; + UInt32 borderColour, linkColour; + UInt8* dp(imgbuffer); + + memcpy(&size, dp, sizeof(size)); + size = ntohs(size); + dp += sizeof(size); + memcpy(&columns, dp, sizeof(columns)); + columns = ntohs(columns); + dp += sizeof(columns); + memcpy(&rows, dp, sizeof(rows)); + rows = ntohs(rows); + dp += sizeof(rows); + qDebug("Rows:%u Cols:%u", rows, columns); + + memcpy(&depth, dp, sizeof(depth)); + dp += sizeof(depth); + memcpy(&border, dp, sizeof(border)); + dp += sizeof(border); + + qDebug("Depth:%u, Border:%u", depth, border); + + memcpy(&borderColour, dp, sizeof(borderColour)); + dp += sizeof(borderColour); + memcpy(&linkColour, dp, sizeof(linkColour)); + dp += sizeof(linkColour); + + qDebug("Colours: border:%x, link:%x", borderColour, linkColour); + + if (border) + { + ret = "<table border>"; + } + else + { + ret = "<table>"; + } + bool firstrow = true; + bool firstcol = true; + while (dp < imgbuffer+imgsize) + { + UInt8 ch = *dp++; + if (ch == 0x00) + { + ch = *dp++; + if (ch == 0x90) + { + if (firstrow) + { + ret += "<tr>"; + firstrow = false; + firstcol = true; + } + else + { + ret += "</tr><tr>"; + } + } + else if (ch == 0x97) + { + if (firstcol) + { + ret += "<td"; + firstcol = false; + } + else + { + ret += "</td><td"; + } + UInt8 align; + UInt16 imgid; + UInt8 cols, rows; + UInt16 len; + memcpy(&align, dp, sizeof(align)); + dp += sizeof(align); + memcpy(&imgid, dp, sizeof(imgid)); + dp += sizeof(imgid); + imgid = ntohs(imgid); + memcpy(&cols, dp, sizeof(cols)); + dp += sizeof(cols); + memcpy(&rows, dp, sizeof(rows)); + dp += sizeof(rows); + memcpy(&len, dp, sizeof(len)); + dp += sizeof(len); + len = ntohs(len); + switch (align) + { + case 1: + ret += " align=right"; + break; + case 2: + ret += " align=center"; + break; + case 3: + ret += " align=justify"; + break; + case 0: + break; + default: + qDebug("Unknown table cell alignment:%u", align); + } + if (cols != 1) + { + QString num; + num.setNum(cols); + ret += " colspan="; + ret += num; + } + if (rows != 1) + { + QString num; + num.setNum(rows); + ret += " rowspan="; + ret += num; + } + ret += ">"; + } + else + { + dp += (ch & 7); + } + } + else + { + ret += QChar(ch); + } + } + + ret += "</td></tr></table>"; + delete [] imgbuffer; + return ret; +} tchar CPlucker_base::getch_base(bool fast) { + mystyle.setTable(0xffffffff); int ch = bgetch(); while (ch == 0) { ch = bgetch(); // //qDebug("Function:%x", ch); switch (ch) { case 0x38: // //qDebug("Break:%u", locate()); if (m_lastBreak == locate()) { ch = bgetch(); } else { ch = 10; } m_lastBreak = locate(); break; case 0x0a: case 0x0c: { unsigned long ln = 0; int skip = ch & 7; for (int i = 0; i < 2; i++) { int ch = bgetch(); ln = (ln << 8) + ch; // //qDebug("ch:%d, ln:%u", ch, ln); } if (skip == 2) { ln <<= 16; } else { for (int i = 0; i < 2; i++) { int ch = bgetch(); ln = (ln << 8) + ch; // //qDebug("ch:%d, ln:%u", ch, ln); } } // //qDebug("ln:%u", ln); mystyle.setLink(true); mystyle.setData(ln); // mystyle.setColour(255, 0, 0); bool hasseen = false; for (CList<unsigned long>::iterator it = visited.begin(); it != visited.end(); it++) { if (*it == ln) { hasseen = true; break; } } if (hasseen) { mystyle.setStrikethru(); } - else - { - mystyle.setUnderline(); - } mystyle.setOffset(m_offset); m_offset = 0; ch = bgetch(); } break; case 0x08: ch = bgetch(); // mystyle.setColour(0, 0, 0); mystyle.unsetUnderline(); mystyle.unsetStrikethru(); mystyle.setLink(false); mystyle.setData(0); break; case 0x40: mystyle.setItalic(); ch = bgetch(); break; case 0x48: mystyle.unsetItalic(); ch = bgetch(); break; case 0x11: { ch = bgetch(); // //qDebug("Font:%d",ch); mystyle.setVOffset(0); mystyle.unsetMono(); mystyle.unsetBold(); switch (ch) { case 0: mystyle.setFontSize(0); break; case 1: mystyle.setFontSize(3); mystyle.setBold(); break; case 2: mystyle.setFontSize(2); mystyle.setBold(); break; case 3: mystyle.setFontSize(1); mystyle.setBold(); break; case 4: mystyle.setFontSize(0); mystyle.setBold(); break; case 5: mystyle.setFontSize(0); mystyle.setBold(); break; case 6: mystyle.setFontSize(0); mystyle.setBold(); break; case 7: mystyle.setFontSize(0); mystyle.setBold(); break; case 8: // should be fixed width //qDebug("Trying fixed width"); mystyle.setFontSize(0); mystyle.setMono(); break; case 9: // mystyle.setFontSize(mystyle.getFontSize()); mystyle.setFontSize(-1); break; case 10: mystyle.setFontSize(-2); mystyle.setVOffset(1); break; case 11: mystyle.setFontSize(-2); mystyle.setVOffset(-1); break; default: qDebug("Unrecognised font"); break; } ch = bgetch(); } break; case 0x29: ch = bgetch(); switch (ch) { case 0: mystyle.setLeftJustify(); // //qDebug("left"); break; case 1: mystyle.setRightJustify(); // //qDebug("right"); break; case 2: mystyle.setCentreJustify(); // //qDebug("centre"); break; case 3: mystyle.setFullJustify(); // //qDebug("full"); break; } ch = bgetch(); break; case 0x53: { int r = bgetch(); int g = bgetch(); int b = bgetch(); mystyle.setColour(r,g,b); ch = bgetch(); } break; case 0x1a: case 0x5c: { bool hasalternate = (ch == 0x5c); UInt16 ir = bgetch(); ir = (ir << 8) + bgetch(); if (hasalternate) { //qDebug("Alternate image:%x", ir); UInt16 ir2 = bgetch(); ir2 = (ir2 << 8) + bgetch(); if (!fast) mystyle.setPicture(true, expandimg(ir2, true), true, ir << 16); #ifdef LOCALPICTURES UInt32 ln = ir; ln <<= 16; mystyle.setLink(true); mystyle.setData(ln); #endif } else { if (!fast) mystyle.setPicture(true, expandimg(ir)); } // if (mystyle.getLink()) qDebug("Picture link!"); ch = '#'; } // ch = bgetch(); break; case 0x33: { UInt8 h = bgetch(); UInt8 wc = bgetch(); UInt8 pc = bgetch(); UInt16 w = wc; // //qDebug("h,w,pc [%u, %u, %u]", h, w, pc); if (w == 0) { w = (m_scrWidth*(unsigned long)pc)/100; } if (w == 0) w = m_scrWidth; mystyle.setPicture(false, hRule(w,h,mystyle.Red(),mystyle.Green(),mystyle.Blue())); // if (mystyle.getLink()) //qDebug("hRule link!"); ch = '#'; } break; case 0x60: mystyle.setUnderline(); ch = bgetch(); break; case 0x68: mystyle.unsetUnderline(); ch = bgetch(); break; case 0x22: ch = bgetch(); mystyle.setLeftMargin(ch); // //qDebug("Left margin:%d", ch); ch = bgetch(); mystyle.setRightMargin(ch); // //qDebug("Right margin:%d", ch); ch = bgetch(); break; case 0x70: mystyle.setStrikethru(); ch = bgetch(); break; case 0x78: mystyle.unsetStrikethru(); ch = bgetch(); break; case 0x83: { int tlen = bgetch(); ch = bgetch(); ch <<= 8; ch |= (tchar)bgetch(); for (int i = 0; i < tlen; i++) bgetch(); //qDebug("Function 83"); } break; case 0x9a: { m_offset = 255*bgetch(); m_offset += bgetch(); qDebug("Found offset:%u", m_offset); ch = bgetch(); } break; + case 0x92: + { + ch = bgetch(); + ch <<= 8; + ch |= (tchar)bgetch(); + mystyle.setTable(ch); + ch = 0x16e5; + } + break; case 0x85: default: qDebug("Function:%x NOT IMPLEMENTED", ch); { int skip = ch & 7; for (int i = 0; i < skip; i++) { ch = bgetch(); //qDebug("Arg %d, %d", i, ch); } ch = bgetch(); } } } if (m_lastIsBreak && !mystyle.isMono()) { while (ch == ' ') { ch = getch(false); } } m_lastIsBreak = (ch == 10); return (ch == EOF) ? UEOF : ch; } -#if defined(__STATIC) && defined(USENEF) -#include "Model.h" -void (*CPlucker_base::getdecompressor(const QString& _s))(UInt8*, size_t, UInt8*, size_t) -{ - if (_s == "PluckerDecompress3") - { - return PluckerDecompress3; - } - if (_s == "PluckerDecompress4") - { - return PluckerDecompress4; - } - return NULL; -} -#else - -#include "qfileinfo.h" - -#include <dlfcn.h> - -void (*CPlucker_base::getdecompressor(const QString& _s))(UInt8*, size_t, UInt8*, size_t) -{ - QString codecpath(QTReaderUtil::getPluginPath("support")); - codecpath += "/libpluckerdecompress.so"; - qDebug("Codec:%s", (const char*)codecpath); - if (QFile::exists(codecpath)) - { - qDebug("Codec:%s", (const char*)codecpath); - void* handle = dlopen(codecpath, RTLD_LAZY); - if (handle == 0) - { - qDebug("Can't find codec:%s", dlerror()); - return NULL; - } - return (void (*)(UInt8*, size_t, UInt8*, size_t))dlsym(handle, _s); - } - return NULL; -} -#endif - QString CPlucker_base::about() { QString abt = "Plucker base codec (c) Tim Wentford"; if (m_decompress != UnDoc && m_decompress != UnZip) { - abt += "\nSpecial decompression (c) Tim Wentford"; + abt += "\nSpecial decompression (c) Tim Wentford (ppmd by Dmitry Shkarin"; } return abt; } diff --git a/noncore/apps/opie-reader/plucker_base.h b/noncore/apps/opie-reader/plucker_base.h index 8d74cc2..2b57986 100644 --- a/noncore/apps/opie-reader/plucker_base.h +++ b/noncore/apps/opie-reader/plucker_base.h @@ -1,115 +1,116 @@ #ifndef __PLUCKER_BASE_H #define __PLUCKER_BASE_H #include "CExpander.h" #include <zlib.h> #include "ztxt.h" #include "pdb.h" #include "CBuffer.h" #include "my_list.h" #include "Navigation.h" #include "hrule.h" struct CPlucker_record0 { UInt16 uid; UInt16 version; UInt16 nRecords; }; struct CPluckerbkmk { UInt32 offset; tchar title[MAX_BMRK_LENGTH]; }; #ifdef LOCALPICTURES class QScrollView; class QWidget; #endif class QString; class CPlucker_base : public Cpdb { protected: static const UInt8 continuation_bit; virtual void setbuffersize() = 0; virtual void GetHeader(UInt16&, UInt16&, UInt32&, UInt8&, UInt8&) = 0; virtual int HeaderSize() = 0; unsigned short finduid(unsigned short); char* geturl(UInt16); void Expand(UInt32, UInt8, UInt8*, UInt32); CList<unsigned long> visited; bool m_lastIsBreak; #ifdef LOCALPICTURES QScrollView* m_viewer; QWidget* m_picture; #endif size_t textlength, m_lastBreak, m_offset; UInt16 uid; int m_nextPara, m_nextParaIndex; CBufferFace<UInt16> m_ParaOffsets; CBufferFace<UInt16> m_ParaAttrs; UInt16 m_nParas; CStyle mystyle; // bool bInit; UInt32 buffersize; UInt32 compressedbuffersize; UInt32 buffercontent; UInt8* expandedtextbuffer; UInt8* compressedtextbuffer; // char* urls; // size_t urlsize; size_t bufferpos; int bufferrec; CPlucker_record0 hdr0; bool m_bufferisreserved; size_t currentpos; bool expand(int); - static void UnZip(UInt8*, size_t, UInt8*, size_t); - static void UnDoc(UInt8*, size_t, UInt8*, size_t); + //static void UnZip(UInt8*, size_t, UInt8*, size_t); + static size_t UnDoc(UInt8*, size_t, UInt8*, size_t); + + size_t (*m_decompress)(UInt8*, size_t, UInt8*, size_t); - void (*m_decompress)(UInt8*, size_t, UInt8*, size_t); - void (*getdecompressor(const QString& _s))(UInt8*, size_t, UInt8*, size_t); #ifdef LOCALPICTURES void showimg(UInt16 tgt); #endif QImage* getimg(UInt16 tgt); QImage* expandimg(UInt16 tgt, bool border=false); void home(); virtual int bgetch() = 0; CNavigation m_nav; public: QString about(); QImage* getPicture(unsigned long tgt); void sizes(unsigned long& _file, unsigned long& _text); bool hasrandomaccess() { return true; } virtual ~CPlucker_base(); CPlucker_base(); int OpenFile(const char *src); virtual tchar getch(bool) = 0; tchar getch_base(bool); int getch(); void getch(tchar&, CStyle&, unsigned long& pos); unsigned int locate(); void locate(unsigned int n); CList<Bkmk>* getbkmklist(); linkType hyperlink(unsigned int, unsigned int, QString&, QString&); MarkupType PreferredMarkup() { return cNONE; } void saveposn(size_t posn) { m_nav.saveposn(posn); } void writeposn(size_t posn) { m_nav.writeposn(posn); } linkType forward(size_t& loc) { return (m_nav.forward(loc)) ? eLink : eNone; } linkType back(size_t& loc) { return (m_nav.back(loc)) ? eLink : eNone; } bool hasnavigation() { return true; } void setSaveData(unsigned char*& data, unsigned short& len, unsigned char* src, unsigned short srclen); void putSaveData(unsigned char*& src, unsigned short& srclen); virtual bool CorrectDecoder() = 0; // virtual void setlink(QString&, const QString&) = 0; virtual QImage* imagefromdata(UInt8*, UInt32) = 0; + QString getTableAsHtml(unsigned long loc); }; #endif diff --git a/noncore/apps/opie-reader/pluckerbaselib/pluckerbaselib.pro b/noncore/apps/opie-reader/pluckerbaselib/pluckerbaselib.pro index a66dc44..0212d84 100644 --- a/noncore/apps/opie-reader/pluckerbaselib/pluckerbaselib.pro +++ b/noncore/apps/opie-reader/pluckerbaselib/pluckerbaselib.pro @@ -1,18 +1,19 @@ DEFINES += OPIE USEQPE VPATH = .. TEMPLATE = lib CONFIG = qt warn_on release dll HEADERS = pdb.h \ util.h -SOURCES = plucker_base.cpp +SOURCES = plucker_base.cpp \ + decompress.cpp INTERFACES = DESTDIR = $(OPIEDIR)/lib TARGET = reader_pluckerbase LIBS += -ldl INCLUDEPATH += $(OPIEDIR)/include DEPENDPATH += $(OPIEDIR)/include include( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/opie-reader/pluckerdecompress/.cvsignore b/noncore/apps/opie-reader/pluckerdecompress/.cvsignore new file mode 100644 index 0000000..1810ee0 --- a/dev/null +++ b/noncore/apps/opie-reader/pluckerdecompress/.cvsignore @@ -0,0 +1,5 @@ +Makefile +config.in +moc_* +.moc +.obj diff --git a/noncore/apps/opie-reader/pluckerdecompress/pluckerdecompress.pro b/noncore/apps/opie-reader/pluckerdecompress/pluckerdecompress.pro new file mode 100644 index 0000000..c1b7686 --- a/dev/null +++ b/noncore/apps/opie-reader/pluckerdecompress/pluckerdecompress.pro @@ -0,0 +1,17 @@ +DEFINES += OPIE USEQPE +VPATH = .. +TEMPLATE = lib +CONFIG = qt warn_on release dll +HEADERS = CSource.h Model.h Coder.h SubAlloc.h + +SOURCES = Model.cpp + + +INTERFACES = +DESTDIR = $(OPIEDIR)/plugins/reader/support +TARGET = pluckerdecompress + +INCLUDEPATH += $(OPIEDIR)/include +DEPENDPATH += $(OPIEDIR)/include + +include( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/opie-reader/ppm_expander.cpp b/noncore/apps/opie-reader/ppm_expander.cpp index 2a4318b..61ef90e 100644 --- a/noncore/apps/opie-reader/ppm_expander.cpp +++ b/noncore/apps/opie-reader/ppm_expander.cpp @@ -1,115 +1,124 @@ /* * Interface pour le programme de compression * (c) 1995 Fabrice Bellard */ #include <stdlib.h> //#include <unistd.h> #include <stdio.h> #include <string.h> #include <time.h> /*************************************************************************** * Interface avec les routines de compression */ #define METHOD_NB 2 /* nombre total de méthodes de compression */ #define METHOD_STORE 0 #define METHOD_PPM 1 #define DEFAULT_SUFFIX ".st" /* extension par défault */ /* signature en début de fichier */ #define STAT_MAGIC_SIZE 4 char stat_magic[STAT_MAGIC_SIZE]={'P','P','M','S'}; #include "ppm_expander.h" ppm_expander::~ppm_expander() { if (needppmend) ppm.PPM_End(); ppm.arith.Arith_DecodeEnd(); if (buf_in!=NULL) delete [] buf_in; if (buf_out!=NULL) delete [] buf_out; if (my_read_buf != NULL) delete my_read_buf; if (my_file_in != NULL) fclose(my_file_in); } int ppm_expander::OpenFile(const char* infile) { my_file_in=fopen(infile,"rb"); - my_read_buf = new PPM_ReadBuf(my_file_in); + my_read_buf = new PPM_ReadBuf(my_file_in, this); return home(); } void ppm_expander::sizes(unsigned long& file, unsigned long& text) { struct stat _stat; fstat(fileno(my_file_in),&_stat); file = _stat.st_size; text = numblocks*blocksize; } int ppm_expander::home() { fseek(my_file_in,0, SEEK_SET); unsigned char header[STAT_MAGIC_SIZE]; size_t len=fread(header,1,STAT_MAGIC_SIZE,my_file_in); if (strncmp((char*)header,stat_magic,STAT_MAGIC_SIZE)!=0) { return 1; } if (len!=(STAT_MAGIC_SIZE)) { return 1; } if (fread(&maxnode,sizeof(maxnode),1,my_file_in) != 1) return 1; if (fread(&blocksize,sizeof(blocksize),1,my_file_in) != 1) return 1; if (fread(&numblocks,sizeof(numblocks),1,my_file_in) != 1) return 1; //fprintf(stderr,"<%u,%u,%u>\n",maxnode,blocksize,numblocks); locate(0,0); outbytes = 0; return 0; } void ppm_expander::locate(unsigned int n) { locate(n/blocksize, n%blocksize); outbytes = n; } void ppm_expander::locate(unsigned short block, unsigned int n) { if (needppmend) { ppm.PPM_End(); needppmend = false; } size_t fpos; fseek(my_file_in,STAT_MAGIC_SIZE+sizeof(maxnode)+sizeof(blocksize)+sizeof(numblocks)+block*sizeof(fpos),SEEK_SET); fread(&fpos,sizeof(fpos),1,my_file_in); fseek(my_file_in,fpos,SEEK_SET); ppm.arith.Arith_DecodeInit(my_read_buf,buf_in,bufsize); int err=ppm.PPM_Init(maxnode); needppmend = true; curblock = block; for (int i = 0; i < n; i++) getch(); } int ppm_expander::getch() { if (curblock >= numblocks) return EOF; int c=ppm.PPM_Decode(); if (c == SYM_EOF) { if (++curblock >= numblocks) return EOF; locate(curblock,0); c = ppm.PPM_Decode(); } outbytes++; return (c==SYM_EOF) ? EOF : c; } +UINT PPM_ReadBuf::readbuf(UCHAR *buf,UINT len) + { + UINT len1; + parent->unsuspend(); + len1=fread(buf,1,len,my_file_in); + return len1; + } + + #ifndef __STATIC extern "C" { CExpander* newcodec() { return new ppm_expander; } } #endif diff --git a/noncore/apps/opie-reader/ppm_expander.h b/noncore/apps/opie-reader/ppm_expander.h index ccc89c2..c5f8a17 100644 --- a/noncore/apps/opie-reader/ppm_expander.h +++ b/noncore/apps/opie-reader/ppm_expander.h @@ -1,61 +1,64 @@ #ifndef __ppm_expander_h #define __ppm_expander_h #include "CExpander.h" #include <sys/stat.h> #include "utypes.h" #include "ppm.h" -#include "arith.h" +class PPM_ReadBuf; #define SYM_EOF 256 class ppm_expander : public CExpander { UCHAR *buf_in,*buf_out; unsigned int bufsize; unsigned int outbytes; unsigned long blocksize; unsigned short numblocks; unsigned short curblock; unsigned short maxnode; bool needppmend; int home(); FILE* my_file_in; PPM_ReadBuf* my_read_buf; ppm_worker ppm; public: QString about() { return QString("ppms Codec (c) Tim Wentford\nCompression code (c) Fabrice Bellard"); } #ifdef USEQPE void suspend() { CExpander::suspend(my_file_in); } void unsuspend() { CExpander::unsuspend(my_file_in); } +#else + void suspend() {} + void unsuspend() {} #endif ppm_expander() : needppmend(false), my_file_in(NULL), my_read_buf(NULL) { bufsize = 1024; buf_in = new UCHAR[bufsize]; buf_out = new UCHAR[bufsize]; outbytes = 0; } int OpenFile(const char* infile); int getch(); void locate(unsigned short block, unsigned int n); virtual ~ppm_expander(); unsigned int locate() { return outbytes; } void locate(unsigned int n); bool hasrandomaccess() { return (numblocks > 1); } void sizes(unsigned long& file, unsigned long& text); MarkupType PreferredMarkup() { return cTEXT; } }; #endif diff --git a/noncore/apps/opie-reader/preferences.cpp b/noncore/apps/opie-reader/preferences.cpp index 0f59a22..67960ed 100755 --- a/noncore/apps/opie-reader/preferences.cpp +++ b/noncore/apps/opie-reader/preferences.cpp @@ -1,104 +1,105 @@ + #ifndef USEQPE #include "preferences.h" #include <qfile.h> #include <qtextstream.h> Config::Config(const QString& _fn) : fname(_fn) { // qDebug("Config::Config:%s", (const char*)fname); QFile fl(fname); if (fl.open(IO_ReadOnly)) { QTextStream t(&fl); QString key, value; while (!t.eof()) { QString data = t.readLine(); int colon = data.find(':'); if (colon > 0) { QString key = data.left(colon); QString value = data.right(data.length()-colon-1); values[key] = value; } } fl.close(); } // read entries into values } Config::~Config() { // qDebug("Config::~Config:%s", (const char*)fname); QFile fl(fname); if (fl.open(IO_WriteOnly)) { QTextStream t(&fl); for (QMap<QString,QString>::Iterator iter = values.begin(); iter != values.end(); iter++) { t << iter.key() << ':' << iter.data() << '\n'; } fl.close(); } } QString Config::readEntry(const QString& key, const QString& deflt) { QMap<QString,QString>::Iterator iter = values.find(key); if (iter != values.end()) { return iter.data(); } else { return deflt; } } bool Config::readBoolEntry(const QString& key, const bool deflt) { bool ok; QMap<QString,QString>::Iterator iter = values.find(key); if (iter != values.end()) { int ret = iter.data().toInt(&ok); return ((ok) ? !!ret : deflt); } else { return deflt; } } int Config::readNumEntry(const QString& key, const int deflt) { bool ok; QMap<QString,QString>::Iterator iter = values.find(key); if (iter != values.end()) { int ret = iter.data().toInt(&ok); return ((ok) ? ret : deflt); } else { return deflt; } } void Config::writeEntry(const QString& key, const QString& value) { values[key] = value; } void Config::writeEntry(const QString& key, const bool value) { values[key] = (value) ? "1" : "0"; } void Config::writeEntry(const QString& key, const int value) { QString rhs; rhs.setNum(value); values[key] = rhs; } #endif diff --git a/noncore/apps/opie-reader/preferences.h b/noncore/apps/opie-reader/preferences.h index aeb2a84..39959d4 100644 --- a/noncore/apps/opie-reader/preferences.h +++ b/noncore/apps/opie-reader/preferences.h diff --git a/noncore/apps/opie-reader/reader.staticpro b/noncore/apps/opie-reader/reader.staticpro deleted file mode 100644 index 78ea8fb..0000000 --- a/noncore/apps/opie-reader/reader.staticpro +++ b/dev/null @@ -1,108 +0,0 @@ -TEMPLATE = app -CONFIG = qt warn_off debug -HEADERS = Aportis.h \ - Bkmks.h \ - BuffDoc.h \ - ButtonPrefs.h \ - CAnnoEdit.h \ - CBuffer.h \ - CDrawBuffer.h \ - CEncoding.h \ - CEncoding_tables.h \ - CExpander.h \ - CFilter.h \ - CloseDialog.h \ - Filedata.h \ - FixedFont.h \ - FontControl.h \ - GraphicWin.h \ - Markups.h \ - Navigation.h \ - Palm2QImage.h \ - Prefs.h \ - QFloatBar.h \ - QTReader.h \ - QTReaderApp.h \ - QtrListView.h \ - Queue.h \ - StyleConsts.h \ - ToolbarPrefs.h \ - URLDialog.h \ - ZText.h \ - arith.h \ - cbkmkselector.h \ - config.h \ - fileBrowser.h \ - infowin.h \ - linktype.h \ - my_list.h \ - names.h \ - QSTATICREADERINC/opie.h \ - pdb.h \ - plucker_base.h \ - plucker.h \ - ppm.h \ - ppm_expander.h \ - preferences.h \ - QSTATICREADERINC/static.h \ - usenef.h \ - QSTATICREADERINC/useqpe.h \ - ustring.h \ - utypes.h \ - version.h \ - ztxt.h - -SOURCES = Aportis.cpp \ - Bkmks.cpp \ - BuffDoc.cpp \ - ButtonPrefs.cpp \ - CAnnoEdit.cpp \ - CBuffer.cpp \ - CDrawBuffer.cpp \ - CEncoding.cpp \ - CEncoding_tables.cpp \ - CExpander.cpp \ - CFilter.cpp \ - CHM.cpp \ - CRegExp.cpp \ - CloseDialog.cpp \ - FontControl.cpp \ - GraphicWin.cpp \ - Navigation.cpp \ - Palm2QImage.cpp \ - Prefs.cpp \ - QTReader.cpp \ - QTReaderApp.cpp \ - QtrListView.cpp \ - StyleConsts.cpp \ - ToolbarPrefs.cpp \ - URLDialog.cpp \ - arith_d.cpp \ - chm_lib.c \ - fileBrowser.cpp \ - hrule.cpp \ - infowin.cpp \ - iSilo.cpp \ - lzx.c \ - main.cpp \ - orkey.cpp \ - pdb.cpp \ - plucker.cpp \ - plucker_base.cpp \ - ppm.cpp \ - ppm_expander.cpp \ - preferences.cpp \ - striphtml.cpp \ - util.cpp \ - version.cpp \ - ztxt.cpp - -INTERFACES = -DESTDIR = QSTATICREADEROBJS -INCLUDEPATH += QSTATICREADERINC -DEPENDPATH += QSTATICREADERINC -OBJECTS_DIR = QSTATICREADEROBJS -MOC_DIR = QSTATICREADERMOCS -TARGET = uqtreader -#LIBS += -lqpe - diff --git a/noncore/apps/opie-reader/reader.staticzpro b/noncore/apps/opie-reader/reader.staticzpro deleted file mode 100644 index 861eb88..0000000 --- a/noncore/apps/opie-reader/reader.staticzpro +++ b/dev/null @@ -1,108 +0,0 @@ -TEMPLATE = app -CONFIG = qt warn_on release -HEADERS = Aportis.h \ - Bkmks.h \ - BuffDoc.h \ - ButtonPrefs.h \ - CAnnoEdit.h \ - CBuffer.h \ - CDrawBuffer.h \ - CEncoding.h \ - CEncoding_tables.h \ - CExpander.h \ - CFilter.h \ - CloseDialog.h \ - Filedata.h \ - FixedFont.h \ - FontControl.h \ - GraphicWin.h \ - Markups.h \ - Navigation.h \ - Palm2QImage.h \ - Prefs.h \ - QFloatBar.h \ - QTReader.h \ - QTReaderApp.h \ - QtrListView.h \ - Queue.h \ - StateData.h \ - StyleConsts.h \ - ToolbarPrefs.h \ - URLDialog.h \ - ZText.h \ - arith.h \ - cbkmkselector.h \ - config.h \ - fileBrowser.h \ - infowin.h \ - linktype.h \ - my_list.h \ - names.h \ - ZSTATICREADERINC/opie.h \ - pdb.h \ - plucker_base.h \ - plucker.h \ - ppm.h \ - ppm_expander.h \ - preferences.h \ - ZSTATICREADERINC/static.h \ - usenef.h \ - ZSTATICREADERINC/useqpe.h \ - ustring.h \ - utypes.h \ - version.h \ - ztxt.h - -SOURCES = Aportis.cpp \ - Bkmks.cpp \ - BuffDoc.cpp \ - ButtonPrefs.cpp \ - CAnnoEdit.cpp \ - CBuffer.cpp \ - CDrawBuffer.cpp \ - CEncoding.cpp \ - CEncoding_tables.cpp \ - CExpander.cpp \ - CFilter.cpp \ - CHM.cpp \ - CRegExp.cpp \ - CloseDialog.cpp \ - FontControl.cpp \ - GraphicWin.cpp \ - Navigation.cpp \ - Palm2QImage.cpp \ - Prefs.cpp \ - QTReader.cpp \ - QTReaderApp.cpp \ - QtrListView.cpp \ - StyleConsts.cpp \ - ToolbarPrefs.cpp \ - URLDialog.cpp \ - arith_d.cpp \ - chm_lib.c \ - fileBrowser.cpp \ - hrule.cpp \ - infowin.cpp \ - iSilo.cpp \ - lzx.c \ - main.cpp \ - orkey.cpp \ - pdb.cpp \ - plucker.cpp \ - plucker_base.cpp \ - ppm.cpp \ - ppm_expander.cpp \ - striphtml.cpp \ - util.cpp \ - version.cpp \ - ztxt.cpp - -INTERFACES = -DESTDIR = ZSTATICREADEROBJS -INCLUDEPATH += ZSTATICREADERINC -DEPENDPATH += ZSTATICREADERINC -OBJECTS_DIR = ZSTATICREADEROBJS -MOC_DIR = ZSTATICREADERMOCS -TARGET = uqtreader -LIBS += -lqpe - diff --git a/noncore/apps/opie-reader/reader/reader.pro b/noncore/apps/opie-reader/reader/reader.pro index 6349ea7..dc6a5dd 100644 --- a/noncore/apps/opie-reader/reader/reader.pro +++ b/noncore/apps/opie-reader/reader/reader.pro @@ -1,87 +1,88 @@ DEFINES += OPIE USEQPE VPATH = .. TEMPLATE = app CONFIG = qt warn_on release HEADERS = Aportis.h \ Bkmks.h \ BuffDoc.h \ ButtonPrefs.h \ CAnnoEdit.h \ CBuffer.h \ CDrawBuffer.h \ CEncoding.h \ CEncoding_tables.h \ CExpander.h \ CFilter.h \ CloseDialog.h \ Filedata.h \ FixedFont.h \ FontControl.h \ GraphicWin.h \ Markups.h \ Navigation.h \ Palm2QImage.h \ Prefs.h \ PPMd.h \ PPMdType.h \ QFloatBar.h \ QTReader.h \ QTReaderApp.h \ QtrListView.h \ Queue.h \ StyleConsts.h \ + TableDialog.h \ ToolbarPrefs.h \ URLDialog.h \ ZText.h \ arith.h \ cbkmkselector.h \ config.h \ fileBrowser.h \ infowin.h \ linktype.h \ my_list.h \ names.h \ pdb.h \ plucker.h \ plucker_base.h \ ppm.h \ ppm_expander.h \ - usenef.h \ ustring.h \ util.h \ utypes.h \ version.h \ ztxt.h SOURCES = BuffDoc.cpp \ ButtonPrefs.cpp \ CAnnoEdit.cpp \ CDrawBuffer.cpp \ CEncoding.cpp \ CEncoding_tables.cpp \ CFilter.cpp \ CRegExp.cpp \ CloseDialog.cpp \ FontControl.cpp \ GraphicWin.cpp \ Prefs.cpp \ QTReader.cpp \ QTReaderApp.cpp \ QtrListView.cpp \ + TableDialog.cpp \ ToolbarPrefs.cpp \ URLDialog.cpp \ fileBrowser.cpp \ infowin.cpp \ main.cpp \ orkey.cpp \ util.cpp \ version.cpp INTERFACES = DESTDIR = $(OPIEDIR)/bin INCLUDEPATH += $(OPIEDIR)/include DEPENDPATH += $(OPIEDIR)/include TARGET = opie-reader LIBS += -lopiecore2 -lopieui2 -lqpe -lreader_codec include( $(OPIEDIR)/include.pro ) diff --git a/noncore/apps/opie-reader/setn.sh b/noncore/apps/opie-reader/setn.sh deleted file mode 100644 index ad9409f..0000000 --- a/noncore/apps/opie-reader/setn.sh +++ b/dev/null @@ -1,27 +0,0 @@ -red='\e[0;31m' -RED='\e[1;31m' -blue='\e[0;34m' -BLUE='\e[1;34m' -cyan='\e[0;36m' -CYAN='\e[1;36m' -NC='\e[0m' # No Color - -if test -z $OLDPATH; then - export OLDPATH=$PATH -fi - -if test -z $OLD_LD_LIBRARY_PATH; then - export OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH -fi - -#export QPEDIR=/opt/Qtopia -export QTDIR=/home/tim/nevyos/qt-embedded-free-3.1.1 -export PATH=$QTDIR/bin:$OLDPATH -export TMAKEPATH=/opt/Qtopia/tmake/lib/qws/linux-generic-g++ -export LD_LIBRARY_PATH=$QTDIR/lib:$OLD_LD_LIBRARY_PATH - -#PS1="[${cyan}\T$NC][${RED}Laptop${NC}]\W> " -#PS1="[${RED}NevyOS${NC}]\W> " -PS1="[NevyOS]\W> " - -echo -e \\n${RED}NevyOS${NC} environment configured\\n diff --git a/noncore/apps/opie-reader/seto.sh b/noncore/apps/opie-reader/seto.sh deleted file mode 100644 index c1d1dd1..0000000 --- a/noncore/apps/opie-reader/seto.sh +++ b/dev/null @@ -1,25 +0,0 @@ -red='\e[0;31m' -RED='\e[1;31m' -blue='\e[0;34m' -BLUE='\e[1;34m' -cyan='\e[0;36m' -CYAN='\e[1;36m' -NC='\e[0m' # No Color - -if test -z $OLDPATH; then - export OLDPATH=$PATH -fi - -if test -z $OLD_LD_LIBRARY_PATH; then - export OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH -fi - -export QPEDIR=/opt/Qtopia/opie -export QTDIR=/opt/Qtopia/opie -export PATH=$QTDIR/bin:/usr/local/arm/3.3/bin:$OLDPATH -export TMAKEPATH=/opt/Qtopia/tmake/lib/qws/linux-opie-g++ -#export LD_LIBRARY_PATH=$QTDIR/lib:$OLD_LD_LIBRARY_PATH - -PS1="[Opie]\W> " - -echo -e \\n${RED}Opie${NC} environment configured\\n diff --git a/noncore/apps/opie-reader/setqt.sh b/noncore/apps/opie-reader/setqt.sh deleted file mode 100644 index 1b7e7b7..0000000 --- a/noncore/apps/opie-reader/setqt.sh +++ b/dev/null @@ -1,30 +0,0 @@ -red='\e[0;31m' -RED='\e[1;31m' -blue='\e[0;34m' -BLUE='\e[1;34m' -cyan='\e[0;36m' -CYAN='\e[1;36m' -NC='\e[0m' # No Color - -if test -z $OLDPATH; then - export OLDPATH=$PATH -fi - -if test -z $OLD_LD_LIBRARY_PATH; then - export OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH -fi - -#export QPEDIR=/opt/Qtopia -export QTDIR=/usr/lib/qt3 -export PATH=$QTDIR/bin:$OLDPATH -#export TMAKEPATH=/opt/Qtopia/tmake/lib/qws/linux-generic-g++ - -export READERDIR=/home/tim/uqtreader -export LD_LIBRARY_PATH=$READERDIR/lib:$OLD_LD_LIBRARY_PATH - - -#PS1="[${cyan}\T$NC][${RED}Laptop${NC}]\W> " -#PS1="[${RED}NevyOS${NC}]\W> " -PS1="[QT]\W> " - -echo -e \\n${RED}QT${NC} environment configured\\n diff --git a/noncore/apps/opie-reader/setws.sh b/noncore/apps/opie-reader/setws.sh deleted file mode 100644 index 61aeccb..0000000 --- a/noncore/apps/opie-reader/setws.sh +++ b/dev/null @@ -1,27 +0,0 @@ -red='\e[0;31m' -RED='\e[1;31m' -blue='\e[0;34m' -BLUE='\e[1;34m' -cyan='\e[0;36m' -CYAN='\e[1;36m' -NC='\e[0m' # No Color - -if test -z $OLDPATH; then - export OLDPATH=$PATH -fi - -if test -z $OLD_LD_LIBRARY_PATH; then - export OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH -fi - -export QPEDIR=/opt/Qtopia -export QTDIR=/opt/Qtopia -export PATH=$QTDIR/bin:$OLDPATH -export TMAKEPATH=/opt/Qtopia/tmake/lib/qws/linux-generic-g++ -export LD_LIBRARY_PATH=$QTDIR/lib:$OLD_LD_LIBRARY_PATH - -#PS1="[${cyan}\T$NC][${RED}Laptop${NC}]\W> " -#PS1="[${RED}Laptop${NC}]\W> " -PS1="[Laptop]\W> " - -echo -e \\n${RED}Laptop${NC} environment configured\\n diff --git a/noncore/apps/opie-reader/setz.sh b/noncore/apps/opie-reader/setz.sh deleted file mode 100644 index e2fa4cd..0000000 --- a/noncore/apps/opie-reader/setz.sh +++ b/dev/null @@ -1,25 +0,0 @@ -red='\e[0;31m' -RED='\e[1;31m' -blue='\e[0;34m' -BLUE='\e[1;34m' -cyan='\e[0;36m' -CYAN='\e[1;36m' -NC='\e[0m' # No Color - -if test -z $OLDPATH; then - export OLDPATH=$PATH -fi - -if test -z $OLD_LD_LIBRARY_PATH; then - export OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH -fi - -export QPEDIR=/opt/Qtopia/sharp -export QTDIR=/opt/Qtopia/sharp -export PATH=$QTDIR/bin:/usr/local/arm/bin:$OLDPATH -export TMAKEPATH=/opt/Qtopia/tmake/lib/qws/linux-sharp-g++ -export LD_LIBRARY_PATH=$QTDIR/lib:$OLD_LD_LIBRARY_PATH - -PS1="[Zaurus]\W> " - -echo -e \\n${RED}Zaurus${NC} environment configured\\n diff --git a/noncore/apps/opie-reader/striphtml.cpp b/noncore/apps/opie-reader/striphtml.cpp index e86402b..c434dbb 100644 --- a/noncore/apps/opie-reader/striphtml.cpp +++ b/noncore/apps/opie-reader/striphtml.cpp @@ -1,1248 +1,1414 @@ #include <qmap.h> #include <qfileinfo.h> #include <qtextstream.h> #include <qdir.h> #ifdef USEQPE #include <qpe/global.h> #endif #include "CDrawBuffer.h" #include "striphtml.h" #include "hrule.h" -#include "util.h" #include <qregexp.h> #include <qimage.h> #include <qpixmap.h> //#include <qprogressdialog.h> //#include <qapplication.h> static unsigned char h2i(unsigned char c) { unsigned char ret = 0; if ('0' <= c && c <= '9') { ret = c - '0'; } else if ('a' <= c && c <= 'f') { ret = c - 'a' + 10; } return ret; } static void parse_color(const QString& attr, unsigned char& r, unsigned char& g, unsigned char& b) { r = g = b = 0; if (attr.length() >= 7 && attr[0] == '#') { r = h2i(attr[1].unicode()); r = 16*r + h2i(attr[2].unicode()); g = h2i(attr[3].unicode()); g = 16*g + h2i(attr[4].unicode()); b = h2i(attr[5].unicode()); b = 16*b + h2i(attr[6].unicode()); } else if (attr == "red") { r = 255; } else if (attr == "green") { g = 255; } else if (attr == "blue") { b = 255; } else if (attr == "white") { r = g = b = 255; } else if (attr == "black") { r = g = b = 0; } else { qDebug("Don't understand colour \"%s\"", (const char*)attr); } } CNavigation_base<htmlmark> striphtml::m_nav; void striphtml::skipblock(const QString& _ent) { tchar ch = '>'; CStyle dummy; QString ent; unsigned long pos; do { while (ch != '<' && ch != UEOF) { mygetch(ch, dummy, pos); } ch = skip_ws(); ent = getname(ch, " >").lower(); qDebug("Skipblock:%s", (const char*)ent); } while (ent != _ent && ch != UEOF); } -void striphtml::locate(unsigned int n) +void striphtml::reset() { m_inblock = false; text_q = ""; + q = ""; + tablenesteddepth = 0; forcecentre = false; ignorespace = false; + indent = 0; while (!stylestack.isEmpty()) stylestack.pop(); currentstyle.unset(); +} + +void striphtml::locate(unsigned int n) +{ qDebug("striphtml:locating:%u", n); + reset(); parent->locate(n); } int striphtml::getpara(CBuffer& buff, unsigned long& startpos) { tchar ch; CStyle sty; unsigned long pos; int i = 0; parent->getch(ch, sty, startpos); pos = startpos; while (1) { if (ch == 10 && !isPre) { ch = ' '; } if (ch == UEOF) { // qDebug("EOF:%d:%u", i, pos); buff[i] = 0; if (i == 0) { i = -1; } return i; } else if (ch == '<') { tchar ch2 = skip_ws(); QString ent = getname(ch2, " >"); ent = ent.lower(); // qDebug("ent:%s", (const char*)ent); if (ent == "a") { buff[i++] = '<'; buff[i++] = 'a'; buff[i++] = ch2; // buff[i] = 0; qDebug("ANCHOR:%s", (const char*)toQString(buff.data())); } else if (ent == "/a") { buff[i++] = '<'; buff[i++] = '/'; buff[i++] = 'a'; buff[i++] = ch2; // buff[i] = 0; qDebug("/ANCHOR:%s", (const char*)toQString(buff.data())); } else if (ent == "div") { // buff[i] = 0; qDebug("DIV:%s", (const char*)toQString(buff.data())); if (i == 0) { buff[i++] = '<'; buff[i++] = 'd'; buff[i++] = 'i'; buff[i++] = 'v'; buff[i++] = ' '; buff[i++] = ch2; while (ch2 != '>' && ch2 != UEOF && i < 2048) { parent->getch(ch2, sty, pos); buff[i++] = ch2; } } else { locate(pos); } buff[i++] = 0; // qDebug("DIV:%s", (const char*)toQString(buff.data())); return i; } else if (ent == "p" || (ent[0] == 'h' && ent.length() == 2 && QString("123456789").find(ent[1]) != -1)) { buff[i++] = 0; while (ch2 != '>' && ch2 != UEOF) { parent->getch(ch2, sty, pos); } return i; } else { while (ch2 != '>' && ch2 != UEOF) { parent->getch(ch2, sty, pos); } } } else { buff[i++] = ch; } parent->getch(ch, sty, pos); } } QString striphtml::dehtml(const QString& _info) { QString info; for (int i = 0; i < _info.length(); i++) { tchar ch = _info[i]; if (ch == '%') { ch = 0; for (int j = 0; j < 2; j++) { ch <<= 4; tchar ch1 = _info[++i]; if ('0' <= ch1 && ch1 <= '9') { ch += ch1 - '0'; } else if ('a' <= ch1 && ch1 <= 'f') { ch += ch1 - 'a' + 10; } else if ('A' <= ch1 && ch1 <= 'F') { ch += ch1 - 'A' + 10; } } } info += ch; } return info; } bool striphtml::findanchor(const QString& _info) { // QProgressDialog dlg("Finding link...", QString::null, 0, NULL, "progress", true); // QProgressBar dlg(0); + if (parent->findanchor(_info)) + { + reset(); + return true; + } + qDebug("Using html find"); + parent->locate(parent->startSection()); #if defined(USEQPE) || defined(_WINDOWS) QString info; for (int i = 0; i < _info.length(); i++) { tchar ch = _info[i]; if (QString(".^$[]*+?").find(ch) != -1) { info += '\\'; } info += ch; } #else QString info = QRegExp::escape(_info); #endif qDebug("Adjusted searchstring:%s", (const char*)info); QString sname("<[Aa][^>]*[ \t]+[Nn][Aa][Mm][Ee][ \t]*=[ \t]*\"?"); sname += info + "\"?[ \t>]"; QString sid("<[A-Za-z][^>]*[ \t]+[Ii][Dd][ \t]*=[ \t]*\"?"); sid += info+"\"?[ \t>]"; #ifdef USEQPE QRegExp name(sname); QRegExp id(sid); #else QRegExp name(sname+"|"+sid); #endif bool ret = true; locate(0); unsigned long pos = 0; unsigned long startpos = 0; int offset; CBuffer test; qDebug("striphtml::findanchor"); // dlg.show(); if (getpara(test, pos) >= 0) { while (1) { // qApp->processEvents(); if ((offset = name.match(toQString(test.data()))) != -1) break; #ifdef USEQPE if ((offset = id.match(toQString(test.data()))) != -1) break; #endif if (getpara(test, pos) < 0) { locate(startpos); qDebug("Not found"); return false; } } locate(pos); qDebug("Found"); ret = true; } else { locate(startpos); qDebug("Not found"); ret = false; } return ret; } -striphtml::striphtml(const QString& _s) : entmap(NULL), isPre(false), currentid(0), lastch(0), currentfile(_s), indent(0), forcecentre(false), m_inblock(false), m_bchm(false), ignorespace(false) +striphtml::striphtml(const QString& _s) : entmap(NULL), isPre(false), currentid(0), lastch(0), currentfile(_s), indent(0), forcecentre(false), m_inblock(false), m_bchm(false), ignorespace(false), tablenesteddepth(0) { href2filepos = new QMap<QString, unsigned long>; id2href = new QMap<unsigned long, QString>; } striphtml::~striphtml() { if (entmap != NULL) delete entmap; delete href2filepos; delete id2href; } void striphtml::initentmap() { entmap = new QMap<QString, tchar>; - QString fname(QTReaderUtil::getPluginPath("data")); +#ifdef USEQPE +#ifdef OPIE + QString fname(getenv("OPIEDIR")); +#else + QString fname(getenv("QTDIR")); +#endif + fname += "/plugins/reader/data"; +#else + QString fname(getenv("READERDIR")); + fname += "/data"; +#endif QFileInfo fi; fi.setFile(fname, "HTMLentities"); if (fi.exists()) { fname = fi.absFilePath(); QFile fl(fname); if (fl.open(IO_ReadOnly)) { QTextStream t(&fl); QString key, value; while (!t.eof()) { QString data = t.readLine(); int colon = data.find(':'); if (colon > 0) { QString key = data.left(colon); QString value = data.right(data.length()-colon-1); bool ok; int ret = value.toInt(&ok); if (ok) { (*entmap)[key] = ret; } } } fl.close(); } } } unsigned short striphtml::skip_ws() { tchar ch; CStyle sty; unsigned long dummy; do { mygetch(ch, sty, dummy); } while (ch < 33 && ch != UEOF); return ch; } unsigned short striphtml::skip_ws_end() { unsigned long dummy; return skip_ws_end(dummy); } unsigned short striphtml::skip_ws_end(unsigned long& pos) { tchar ch; CStyle sty; do { mygetch(ch, sty, pos); } while (ch != '>' && ch != UEOF); return ch; } QString striphtml::getname(tchar& ch, const QString& nd) { QString nm = ""; // nm += ch; CStyle sty; unsigned long dummy; while (1) { // if ( QChar(ch).isLetterOrNumber() ) if (ch != UEOF && nd.find(ch, 0, false) == -1 && nm.length() < 2048) { nm += ch; } else { break; } mygetch(ch, sty, dummy); } return nm; } QString striphtml::getattr(tchar& ch) { QString ref; CStyle sty; unsigned long pos; if (ch == ' ') ch = skip_ws(); if (ch == '=') { ch = skip_ws(); if (ch == '"') { mygetch(ch, sty, pos); ref = getname(ch, "\""); ch = skip_ws(); } + else if (ch == '\'') + { + mygetch(ch, sty, pos); + ref = getname(ch, "\'"); + ch = skip_ws(); + } else { ref = getname(ch, " >"); if (ch == ' ') ch = skip_ws(); } } return ref; } linkType striphtml::hyperlink(unsigned int n, unsigned int, QString& w, QString& nm) { #if defined(USEQPE) || defined(_WINDOWS) QMap<unsigned long, QString>::Iterator hrefit = id2href->find(n); #else QMap<unsigned long, QString>::iterator hrefit = id2href->find(n); #endif if (hrefit == id2href->end()) { return eNone; } QString href = *hrefit; #if defined(USEQPE) || defined(_WINDOWS) QMap<QString, unsigned long>::Iterator fpit = href2filepos->find(href); #else QMap<QString, unsigned long>::iterator fpit = href2filepos->find(href); #endif if (fpit == href2filepos->end()) { if (href == "history.back()") { QString fc = currentfile; unsigned long loc; htmlmark m(fc, loc); linkType ret = (m_nav.back(m)) ? eFile : eNone; if (fc == m.filename()) { if ((ret & eFile) != 0) { locate(m.posn()); return eLink; } } return eNone; } qDebug("Searching for %s", (const char*)href); QString file, name; int colon = href.find('#'); if (colon >= 0) { file = dehtml(href.left(colon)); name = dehtml(href.right(href.length()-colon-1)); } else { file = dehtml(href); } qDebug("File:%s", (const char*)file); qDebug("Name:%s", (const char*)name); if (file.isEmpty()) { + if (parent->findanchor(name)) + { + reset(); + return eLink; + } fpit = href2filepos->find(name); if (fpit != href2filepos->end()) { locate(*fpit); return eLink; } else { // nm = QString("<a[^>]*name[ \t]*=[ \t]*\"") + name + "\""; qDebug("Do a search for:%s", (const char*)name); - parent->locate(0); findanchor(name); return eLink; } } else // if (href.find('#') == -1) { if (m_bchm) { - w = "/"+file; + w = file; nm = name; return eFile; } else { QFileInfo f(currentfile); QFileInfo f1(f.dir(true), file); if (f1.exists()) { w = f1.absFilePath(); nm = name; } else { w = file; } return (f1.exists() ? eFile : eNone); } } return eNone; } locate(*fpit); // parent->locate((*href2filepos)[(*id2href)[n]]); return eLink; } /* unsigned short striphtml::parse_m() { tchar ch; CStyle sty; unsigned long dummy; mygetch(ch, sty, dummy); if (ch == 'm' || ch == 'M') { ch = skip_ws_end(); if (ch == '>') { return 0; } } return ch; } */ void striphtml::mygetch(tchar& ch, CStyle& sty, unsigned long& pos) { if (!text_q.isEmpty() && !m_inblock) { ch = text_q[0].unicode(); text_q = text_q.right(text_q.length()-1); } else { parent->getch(ch, sty, pos); if (ch == '<') { m_inblock = true; } if (ch == '>') { m_inblock = false; } } if (ch == 10 && !isPre) { +#ifdef REMOVE_LF_BEFORE_ENDTAG + parent->getch(ch, sty, pos); + if (ch == '<') + { + parent->getch(ch, sty, pos); + if (ch == '/') + { + ch = '<'; + text_q += '/'; + } + else + { + text_q += '<'; + text_q += ch; + ch = ' '; + } + } + else + { + text_q += ch; + ch = ' '; + } +#else ch = ' '; +#endif } } void striphtml::parse_paragraph(CStyle& currentstyle, tchar& ch, unsigned long pos) { /* int count = 0; for (CList<CStyle>::iterator iter = stylestack.begin(); iter != stylestack.end(); ++iter) { count++; } qDebug("Currently have %u styles", count); */ if (stylestack.isEmpty()) { currentstyle.unset(); } else { - qDebug("Using stack style"); currentstyle = stylestack.first(); } if (forcecentre) { currentstyle.setCentreJustify(); } if (ch == ' ') ch = skip_ws(); while (ch != '>' && ch != UEOF) { QString ent = getname(ch, " =>").lower(); QString attr = getattr(ch).lower(); //qDebug("(Paragraph)Entity:%s Attr:%s", (const char*)ent, (const char*)attr); if (ent == "align") { if (attr == "center") { currentstyle.setCentreJustify(); } if (attr == "right") { currentstyle.setRightJustify(); } + if (attr == "justify") + { + currentstyle.setFullJustify(); + } } if (ent == "id") { (*href2filepos)[attr] = pos; } if (ent == "bgcolor") { qDebug("Got paper colour:%s", (const char*)attr); unsigned char r,g,b; parse_color(attr, r, g, b); currentstyle.setPaper(r, g, b); } if (ent == "color") { qDebug("Got foreground colour:%s", (const char*)attr); unsigned char r,g,b; parse_color(attr, r, g, b); currentstyle.setColour(r, g, b); } if (ch == ' ') ch = skip_ws(); } ch = 10; } void striphtml::getch(tchar& ch, CStyle& sty, unsigned long& pos) { currentstyle.clearPicture(); if (!q.isEmpty()) { ch = q[0].unicode(); if (ch == '-') { tchar w = q[1].unicode(); tchar h = q[2].unicode(); unsigned char r = q[3].unicode(); unsigned char g = q[4].unicode(); unsigned char b = q[5].unicode(); ch = '#'; //qDebug("html:hrule<%u, %u>", w, h); currentstyle.setPicture(false, hRule(w,h,r,g,b)); q = q.right(q.length()-6); } else { q = q.right(q.length()-1); } sty = currentstyle; + lastch = ch; return; } do { unsigned long npos; CStyle dummy; mygetch(ch, dummy, pos); - // if (ch == 10 && !isPre) ch = ' '; while (ch == '<' && ch != UEOF) { ch = skip_ws(); - QString ent = getname(ch, " >").lower(); // qDebug("Entity:%s", (const char*)ent); if (ent == "a"/* || ent == "reference"*/) { if (ch == ' ') ch = skip_ws(); bool fileposfound = false; bool ishref = false; unsigned int filepos = 0; QString ref, name; while (ch != '>' && ch != UEOF) { QString ent = getname(ch, " =>").lower(); QString attr = getattr(ch); - qDebug("<A>Entity:%s Attr:%s", (const char*)ent, (const char*)attr); + //qDebug("<A>Entity:%s Attr:%s", (const char*)ent, (const char*)attr); if (ent == "name") { name = attr; } if (ent == "onclick") { int st = attr.find('\''); int nd = attr.findRev('\''); ref = attr.mid(st+1, nd-st-1); ishref = true; qDebug("Onclick:%s", (const char*)ref); } if (ent == "href") { ishref = true; ref = attr; } if (ent == "filepos") { filepos = attr.toUInt(&fileposfound); if (ref.isEmpty()) { ishref = true; ref = attr; } } if (ent == "title") { text_q = attr + "</a><p>"; } - qDebug("<a %s=%s>", (const char*)ent, (const char*)ref); + //qDebug("<a %s=%s>", (const char*)ent, (const char*)ref); } if (ishref) { currentstyle.setColour(0,0,255); currentstyle.setLink(true); currentstyle.setData(currentid); if (!text_q.isEmpty()) { currentstyle.setBold(); currentstyle.setCentreJustify(); } (*id2href)[currentid] = ref; currentid++; if (fileposfound) { (*href2filepos)[ref] = filepos; } } if (!name.isEmpty()) { (*href2filepos)[name] = pos; } } else if (ent == "p") { parse_paragraph(currentstyle, ch, pos); currentstyle.setExtraSpace(3); continue; } else if (ent == "div") { parse_paragraph(currentstyle, ch, pos); stylestack.push_front(currentstyle); + currentstyle.setExtraSpace(16); //indent = 0; continue; } else if (ent == "sup") { currentstyle.setVOffset(-1); } else if (ent == "sup") { currentstyle.setVOffset(1); } else if (ent == "/sup" || ent == "/sub") { currentstyle.setVOffset(0); } else if (ent == "span") { if (ch == ' ') ch = skip_ws(); while (ch != '>' && ch != UEOF) { QString ent = getname(ch, " =>").lower(); QString attr = getattr(ch).lower(); if (ent == "bgcolor") { qDebug("Got background colour:%s", (const char*)attr); unsigned char r,g,b; parse_color(attr, r, g, b); currentstyle.setBackground(r, g, b); } if (ent == "color") { qDebug("Got foreground colour:%s", (const char*)attr); unsigned char r,g,b; parse_color(attr, r, g, b); currentstyle.setColour(r, g, b); } } stylestack.push_front(currentstyle); } else if (ent == "/span") { if (ch != '>') ch = skip_ws_end(); currentstyle.setBackground(255, 255, 255); currentstyle.setColour(0, 0, 0); if (!stylestack.isEmpty()) { stylestack.pop(); } } else if (ent == "pre") { isPre = true; + currentstyle.setNoJustify(); currentstyle.setMono(); } else if (ent == "tt") { currentstyle.setMono(); } else if (ent == "b" || ent == "strong") { currentstyle.setBold(); } else if (ent == "u") { currentstyle.setUnderline(); } else if (ent == "/u") { currentstyle.unsetUnderline(); } else if (ent == "blockquote") { if (ch != '>') ch = skip_ws_end(); ch = 10; + currentstyle.setExtraSpace(0); currentstyle.setLeftMargin(30); currentstyle.setRightMargin(30); continue; } else if (ent == "br" || ent == "br/") { if (ch != '>') ch = skip_ws_end(); ch = 10; + currentstyle.setExtraSpace(0); + lastch = 0; continue; } else if (ent == "mbp:pagebreak") { /* if (ch != '>') ch = skip_ws_end(pos); q += 10; q += QChar(UEOF); ch = 10; continue; */ ch = 6; // currentstyle.setTop(); continue; } else if (ent == "center") { //forcecentre = true; qDebug("setting centre"); currentstyle.setCentreJustify(); ch = 10; continue; } else if (ent == "/center") { qDebug("unsetting centre"); forcecentre = false; } else if (ent == "li") { if (ch != '>') ch = skip_ws_end(); + lastch = 0; ch = 10; if (m_listtype[indent % m_cmaxdepth] == 1) { q.setNum(m_ctr[indent % m_cmaxdepth]++); } else { q += QChar(8226); } q += ' '; currentstyle.setLeftMargin(6*indent); qDebug("Setting indent:%d", indent); continue; } else if (ent == "ul") { indent++; m_listtype[indent % m_cmaxdepth] = 0; } else if (ent == "/ul") { indent--; } else if (ent == "ol") { indent++; m_listtype[indent % m_cmaxdepth] = 1; m_ctr[indent % m_cmaxdepth] = 1; } else if (ent == "/ol") { indent--; } else if (ent == "i") { currentstyle.setItalic(); } else if (ent == "em") { currentstyle.setItalic(); } else if (ent == "small") { currentstyle.setFontSize(-2); } else if (ent == "/small") { currentstyle.setFontSize(0); } else if (ent == "big") { currentstyle.setFontSize(2); } else if (ent == "/big") { currentstyle.setFontSize(0); } + else if (ent[0] == '/' && ent[1] == 'h' && ent.length() == 3 && QString("123456789").find(ent[2]) != -1) + { + parse_paragraph(currentstyle, ch, pos); + currentstyle.setExtraSpace(3); + continue; + } else if (ent[0] == 'h' && ent.length() == 2 && QString("123456789").find(ent[1]) != -1) { indent = 0; if (ent[1] == '1') { parse_paragraph(currentstyle, ch, pos); currentstyle.setFontSize(3); currentstyle.setExtraSpace(8); currentstyle.setBold(); // currentstyle.setExtraSpace(10); - continue; } else if (ent[1] == '2') { parse_paragraph(currentstyle, ch, pos); currentstyle.setFontSize(2); currentstyle.setExtraSpace(6); currentstyle.setBold(); // currentstyle.setExtraSpace(10); - continue; } else if (ent[1] == '3') { parse_paragraph(currentstyle, ch, pos); currentstyle.setFontSize(1); currentstyle.setExtraSpace(4); currentstyle.setBold(); // currentstyle.setExtraSpace(10); - continue; } else { parse_paragraph(currentstyle, ch, pos); currentstyle.setExtraSpace(4); currentstyle.setBold(); // currentstyle.setExtraSpace(10); - continue; } + ch = 10; + continue; } else if (ent == "/a") { currentstyle.setColour(0,0,0); currentstyle.setLink(false); } else if (ent == "/pre") { currentstyle.unsetMono(); isPre = false; } else if (ent == "/tt") { currentstyle.unsetMono(); } else if (ent == "/b" || ent == "/strong") { currentstyle.unsetBold(); } else if (ent == "/i") { currentstyle.unsetItalic(); } else if (ent == "/em") { currentstyle.unsetItalic(); } else if (ent == "/div") { currentstyle.unset(); if (ch != '>') ch = skip_ws_end(); ch = 10; if (!stylestack.isEmpty()) { stylestack.pop(); } continue; } else if (ent == "tr") { if (ch != '>') ch = skip_ws_end(); ch = 10; q += '-'; q += QChar(parent->getwidth()); q += 2; q += '\0'; q += '\0'; q += '\0'; continue; } else if (ent == "td") { if (ch != '>') ch = skip_ws_end(); ignorespace = false; } else if (ent == "/td") { ignorespace = true; // parse_paragraph(currentstyle, ch, pos); //stylestack.push_front(currentstyle); if (ch != '>') ch = skip_ws_end(); // ch = '|'; //continue; ch = 10; q += '-'; q += QChar(parent->getwidth()); q += 1; q += '\0'; q += '\0'; q += '\0'; continue; } /* else if (ent == "/td") { currentstyle.unset(); if (ch != '>') ch = skip_ws_end(); if (!stylestack.isEmpty()) { stylestack.pop(); } // ch = 10; continue; } */ else if (ent[0] == '/' && ent.length() == 3 && ent[1] == 'h' && QString("123456789").find(ent[2]) != -1) { currentstyle.unset(); if (ch != '>') ch = skip_ws_end(); - ch = 10; - continue; + //ch = 10; + //continue; } - - - else if (ent == "table" || ent == "/table") { currentstyle.unset(); ignorespace = (ent == "table"); + if (ent == "table") + { + if (tablenesteddepth++ == 0) currentstyle.setTable(pos); + } + else + { + if (--tablenesteddepth <= 0) + { + tablenesteddepth = 0; + currentstyle.setTable(0xffffffff); + } + } if (ch == ' ') ch = skip_ws(); while (ch != '>' && ch != UEOF) { QString ent = getname(ch, " =>").lower(); QString attr = getattr(ch); qDebug("<table>Entity:%s Attr:%s", (const char*)ent, (const char*)attr); } if (ch != '>') ch = skip_ws_end(); + currentstyle.setLeftMargin(6*tablenesteddepth); + + + lastch = 0; // Anything but 10 ch = 10; q += '-'; q += QChar(parent->getwidth()); - q += 2; + q += 3; q += '\0'; q += '\0'; q += '\0'; continue; } else if (ent == "hr") { + //bool isPageBreak = false; if (ch == ' ') ch = skip_ws(); - // if (stylestack.isEmpty()) - // { - currentstyle.unset(); - // } - /* - else - { - qDebug("Using stack style"); - currentstyle = stylestack.first(); - } - */ unsigned char red = 0, green = 0, blue = 0; while (ch != '>' && ch != UEOF) { QString ent = getname(ch, " =>").lower(); QString attr = getattr(ch); if (ent == "color") { parse_color(attr, red, green, blue); } + /* + if (ent == "size") + { + if (attr == "0") + { + isPageBreak = true; + } + } + */ qDebug("<hr>Entity:%s Attr:%s", (const char*)ent, (const char*)attr); } if (ch != '>') ch = skip_ws_end(); + /* + if (isPageBreak) + { + ch = UEOF; + } + else + { + */ + // if (stylestack.isEmpty()) + // { + currentstyle.unset(); + // } + /* + else + { + qDebug("Using stack style"); + currentstyle = stylestack.first(); + } + */ + lastch = 0; //Anything but 10 or ' ' ch = 10; q += '-'; q += QChar(parent->getwidth()); q += 3; q += red; q += green; q += blue; + continue; } else if (ent == "img") { if (ch == ' ') ch = skip_ws(); while (ch != '>' && ch != UEOF) { QString ent = getname(ch, " =>").lower(); QString attr = getattr(ch); qDebug("<img>Entity:%s Attr:%s", (const char*)ent, (const char*)attr); if (ent == "src") { + /* if (m_bchm) { QImage* img = parent->getPicture(attr); if (img != NULL) { currentstyle.setPicture(true, img); } } + */ + + + QImage* img = parent->getPicture(attr); + if (img != NULL) + { + currentstyle.setPicture(true, img); + } else { QFileInfo f(currentfile); QFileInfo f1(f.dir(true), attr); QPixmap pm; if (pm.load(f1.absFilePath())) { QImage* img = new QImage(pm.convertToImage()); currentstyle.setPicture(true, img); } } } if (ent == "recindex") { bool ok; unsigned int picindex = attr.toUInt(&ok); qDebug("Looking for image at %u", picindex); QImage* img = parent->getPicture(picindex); if (img != NULL) { currentstyle.setPicture(true, img); } else { qDebug("No image found"); } } } if (ch != '>') ch = skip_ws_end(); ch = '#'; break; } else if (ent.left(2) == "dc") { QString nd("/"); skipblock(nd+ent); } else if (ent == "metadata") { // skipblock("/metadata"); } + else if (ent == "title") + { + skipblock("/title"); + } + else if (ent == "head") + { + skipblock("/head"); + } /* else if (ent == "metadata") { currentstyle.setFontSize(-2); } else if (ent == "/metadata") { currentstyle.unset(); ch = 10; continue; } */ else { if (ent[0] != '/') qDebug("Not handling:%s", (const char*)ent); } if (ch != '>') ch = skip_ws_end(); + if (ent[0] == '/') + mygetch(ch, dummy, pos); + else mygetch(ch, dummy, npos); } if (ch == '&') { mygetch(ch, dummy, npos); if (ch == '#') { int id = 0; mygetch(ch, dummy, npos); while (ch != ';' && ch != UEOF) { id = 10*id+ch-'0'; mygetch(ch, dummy, npos); } ch = id; } else { QString en; en += ch; mygetch(ch, dummy, npos); while (ch != ';' && ch != UEOF) { en += ch; mygetch(ch, dummy, npos); } if (entmap == NULL) initentmap(); #if defined(USEQPE) || defined(_WINDOWS) QMap<QString, tchar>::Iterator it = entmap->find(en); #else QMap<QString, tchar>::iterator it = entmap->find(en); #endif if (it != entmap->end()) { ch = *it; } else { ch = '.'; } } } // sty = (dummy == ucFontBase) ? currentstyle : dummy; + if (lastch == 10 && ch == 10 && sty.getExtraSpace() > currentstyle.getExtraSpace()) + { + currentstyle.setExtraSpace(sty.getExtraSpace()); + } sty = currentstyle; } - while (!isPre && (lastch == ' ' || lastch == 10 || ignorespace) && ch == ' '); + while (!isPre && (((lastch == ' ' || lastch == 10 || ignorespace) && ch == ' ') || ((ch == 10) && (lastch == 10)))); // lastch = ch; lastch = ch; return; } +QString striphtml::getTableAsHtml(unsigned long loc) +{ + qDebug("striphtml::getTableAsHtml"); + QString ret; + tchar ch(0); + CStyle sty; + unsigned long pos; + locate(loc); + int endpos(0); + QString endmarker("</table>"); + QString startmarker("<table"); + int startpos(0); + int depth(0); + while (ch != UEOF) + { + parent->getch(ch, sty, pos); + QChar qc(ch); + ret += qc; + if (qc.lower() == endmarker[endpos]) + { + if ((++endpos >= endmarker.length()) && (--depth <= 0)) break; + } + else + { + endpos = 0; + } + if (qc.lower() == startmarker[startpos]) + { + if (++startpos >= startmarker.length()) ++depth; + } + else + { + startpos = 0; + } + } + return ret; +} + + extern "C" { CFilter* newfilter(const QString& s) { return new striphtml(s); } } diff --git a/noncore/apps/opie-reader/striphtml.h b/noncore/apps/opie-reader/striphtml.h index 42e2b7e..b1f7c0a 100644 --- a/noncore/apps/opie-reader/striphtml.h +++ b/noncore/apps/opie-reader/striphtml.h @@ -1,93 +1,96 @@ #ifndef __STRIPHTML_H #define __STRIPHTML_H #include "CFilter.h" #include "Navigation.h" #include "CBuffer.h" #include "CExpander.h" #include "my_list.h" class striphtml : public CFilter { + void reset(); bool ignorespace; bool m_bchm; + int tablenesteddepth; CList<CStyle> stylestack; static CNavigation_base<htmlmark> m_nav; QMap<QString, tchar>* entmap; CStyle currentstyle; bool isPre; unsigned short skip_ws(); unsigned short skip_ws_end(); unsigned short skip_ws_end(unsigned long&); unsigned short parse_m(); QMap<QString, unsigned long>* href2filepos; QMap<unsigned long, QString>* id2href; unsigned long currentid; tchar lastch; QString currentfile; QString q; bool forcecentre, m_inblock; QString text_q; int indent; int m_listtype[m_cmaxdepth]; int m_ctr[m_cmaxdepth]; void mygetch(tchar& ch, CStyle& sty, unsigned long& pos); void initentmap(); QString getname(tchar& ch, const QString& nd); void skipblock(const QString&); QString getattr(tchar&); QString dehtml(const QString& _info); void parse_paragraph(CStyle& currentstyle, tchar& ch, unsigned long); int getpara(CBuffer&, unsigned long&); public: QString about() { return QString("HTML filter (c) Tim Wentford\n")+parent->about(); } striphtml(const QString&); ~striphtml(); void getch(tchar& ch, CStyle& sty, unsigned long& pos); virtual linkType hyperlink(unsigned int n, unsigned int noff, QString& w, QString& nm); bool findanchor(const QString&); void saveposn(const QString& f, size_t posn) { m_nav.saveposn(htmlmark(f, posn)); } void writeposn(const QString& f, size_t posn) { m_nav.writeposn(htmlmark(f, posn)); } linkType forward(QString& f, size_t& loc) { htmlmark m(f, loc); linkType ret = (m_nav.forward(m)) ? eFile : eNone; if (f == m.filename()) { if (ret == eFile) { ret = eLink; } } else { f = m.filename(); } loc = m.posn(); return ret; } linkType back(QString& f, size_t& loc) { htmlmark m(f, loc); linkType ret = (m_nav.back(m)) ? eFile : eNone; if (f == m.filename()) { if (ret == eFile) { ret = eLink; } } else { f = m.filename(); } loc = m.posn(); return ret; } bool hasnavigation() { return true; } virtual void locate(unsigned int n); void setchm(bool _b) { m_bchm = _b; } + QString getTableAsHtml(unsigned long loc); }; #endif diff --git a/noncore/apps/opie-reader/update-gcc3.sh b/noncore/apps/opie-reader/update-gcc3.sh deleted file mode 100755 index f604e42..0000000 --- a/noncore/apps/opie-reader/update-gcc3.sh +++ b/dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -touch infowin.cpp -for f in *lib.omak; do make -f $f; done -for f in *.omak; do make -f $f; done -for f in *.omak; do make -f $f; done -cp /home/tim/codecreader/opie-reader.desktop $QTDIR/apps/Applications/ -cp /home/tim/codecreader/pics/* $QTDIR/pics/opie-reader/ -cp /home/tim/codecreader/opie-pics/* $QTDIR/pics/opie-reader/ -cp HTMLentities $QTDIR/plugins/reader/data/ -rm $QTDIR/help/html/*reader*.html -cp /home/tim/codecreader/help/*.html $QTDIR/help/html/ -rm $QTDIR/help/html/*reader*.html -cp /home/tim/codecreader/help/*.html $QTDIR/help/html/ -rm -f $QTDIR/lib/libreader*.so -rm -f $QTDIR/lib/libreader*.so.1 -for f in $QTDIR/lib/libreader*.1.0.0 ; do mv -f $f $QTDIR/lib/`basename $f .1.0.0`.1 ; done -rm -f $QTDIR/lib/libreader*.so.1.* - -/home/tim/bin/zstrip.sh $QTDIR/bin/reader -for f in $QTDIR/lib/libreader* ; do /home/tim/bin/zstrip.sh $f; done - -for SUBDIR in codecs support filters -do - CDIR=$QTDIR/plugins/reader/$SUBDIR - rm -f $CDIR/*.so - for f in $CDIR/*.1.0.0 ; do mv -f $f $CDIR/`basename $f .1.0.0` ; done - rm -f $CDIR/*.so.* - for f in $CDIR/*.so ; do /home/tim/bin/zstrip.sh $f ; done -done -rm -f opie-reader-gcc3_*.ipk -rm -f full/opie-reader-gcc3_*.ipk -rm -f partial/opie-reader-gcc3_*.ipk -mkipks opie-reader-gcc3.control -cp opie-reader-gcc3_*.ipk full/ -for f in opie-reader-gcc3_*.ipk - do - cp $f full/`basename $f _arm.ipk`-`date +%y%m%d`_arm.ipk -done -rm $QTDIR/plugins/reader/support/libpluckerdecompress.so -rm $QTDIR/plugins/reader/codecs/libArriereGo.so -rm $QTDIR/plugins/reader/codecs/libNEF.so -mkipks opie-reader-gcc3.control -cp opie-reader-gcc3_*.ipk partial/ -for f in opie-reader-gcc3_*.ipk - do - cp $f partial/`basename $f _arm.ipk`-`date +%y%m%d`_arm.ipk -done diff --git a/noncore/apps/opie-reader/update-opie.sh b/noncore/apps/opie-reader/update-opie.sh deleted file mode 100755 index 261ef46..0000000 --- a/noncore/apps/opie-reader/update-opie.sh +++ b/dev/null @@ -1,45 +0,0 @@ -#!/bin/bash -touch infowin.cpp -for f in *lib.zmak; do make -f $f; done -for f in *.zmak; do make -f $f; done -for f in *.zmak; do make -f $f; done -cp /home/tim/codecreader/pics/* $QTDIR/pics/opie-reader/ -cp /home/tim/codecreader/opie-pics/* $QTDIR/pics/opie-reader/ -cp HTMLentities $QTDIR/plugins/reader/data/ -rm $QTDIR/help/html/*reader*.html -cp /home/tim/codecreader/help/*.html $QTDIR/help/html/ -rm -f $QTDIR/lib/libreader*.so -rm -f $QTDIR/lib/libreader*.so.1 -for f in $QTDIR/lib/libreader*.1.0.0 ; do mv -f $f $QTDIR/lib/`basename $f .1.0.0`.1 ; done -rm -f $QTDIR/lib/libreader*.so.1.* - -/home/tim/bin/zstrip.sh $QTDIR/bin/uqtreader -rm -f $QTDIR/bin/reader -mv $QTDIR/bin/uqtreader $QTDIR/bin/reader -for f in $QTDIR/lib/libreader* ; do /home/tim/bin/zstrip.sh $f; done -for SUBDIR in codecs support filters -do - CDIR=$QTDIR/plugins/reader/$SUBDIR - rm -f $CDIR/*.so - for f in $CDIR/*.1.0.0 ; do mv -f $f $CDIR/`basename $f .1.0.0` ; done - rm -f $CDIR/*.so.* - for f in $CDIR/*.so ; do zstrip.sh $f ; done -done -rm -f opie-reader-opie_*.ipk -rm -f full/opie-reader-opie_*.ipk -rm -f partial/opie-reader-opie_*.ipk -mkipks opie-reader-opie.control -cp opie-reader-opie_*.ipk full/ -for f in opie-reader-opie_*.ipk - do - cp $f full/`basename $f _arm.ipk`-`date +%y%m%d`_arm.ipk -done -rm $QTDIR/plugins/reader/support/libpluckerdecompress.so -rm $QTDIR/plugins/reader/codecs/libArriereGo.so -rm $QTDIR/plugins/reader/codecs/libNEF.so -mkipks opie-reader-opie.control -cp opie-reader-opie_*.ipk partial/ -for f in opie-reader-opie_*.ipk - do - cp $f partial/`basename $f _arm.ipk`-`date +%y%m%d`_arm.ipk -done diff --git a/noncore/apps/opie-reader/update.sh b/noncore/apps/opie-reader/update.sh deleted file mode 100755 index 61b8a5e..0000000 --- a/noncore/apps/opie-reader/update.sh +++ b/dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -touch infowin.cpp -for f in *lib.zmak; do make -f $f; done -for f in *.zmak; do make -f $f; done -for f in *.zmak; do make -f $f; done -cp /home/tim/codecreader/uqtreader*.desktop /opt/Qtopia/apps/Applications/ -cp /home/tim/codecreader/pics/* /opt/Qtopia/pics/opie-reader/ -cp /home/tim/codecreader/uqtreader*.desktop $QTDIR/apps/Applications/ -cp /home/tim/codecreader/opie-reader.desktop $QTDIR/apps/Applications/ -cp /home/tim/codecreader/pics/* $QTDIR/pics/opie-reader/ -cp HTMLentities $QTDIR/plugins/reader/data/ -rm $QTDIR/help/html/*reader*.html -cp /home/tim/codecreader/help/*.html $QTDIR/help/html/ -rm -f $QTDIR/lib/libreader*.so -rm -f $QTDIR/lib/libreader*.so.1 -for f in $QTDIR/lib/libreader*.1.0.0 ; do mv -f $f $QTDIR/lib/`basename $f .1.0.0`.1 ; done -rm -f $QTDIR/lib/libreader*.so.1.* - -/home/tim/bin/zstrip.sh $QTDIR/bin/uqtreader -for f in $QTDIR/lib/libreader* ; do /home/tim/bin/zstrip.sh $f; done - -for SUBDIR in codecs support filters -do - CDIR=$QTDIR/plugins/reader/$SUBDIR - rm -f $CDIR/*.so - for f in $CDIR/*.1.0.0 ; do mv -f $f $CDIR/`basename $f .1.0.0` ; done - rm -f $CDIR/*.so.* - for f in $CDIR/*.so ; do /home/tim/bin/zstrip.sh $f ; done -done -rm -f opie-reader_*.ipk -rm -f full/opie-reader_*.ipk -rm -f partial/opie-reader_*.ipk -mkipks opie-reader.control -cp opie-reader_*.ipk full/ -for f in opie-reader_*.ipk - do - cp $f full/`basename $f _arm.ipk`-`date +%y%m%d`_arm.ipk -done -rm $QTDIR/plugins/reader/support/libpluckerdecompress.so -rm $QTDIR/plugins/reader/codecs/libArriereGo.so -rm $QTDIR/plugins/reader/codecs/libNEF.so -mkipks opie-reader.control -cp opie-reader_*.ipk partial/ -for f in opie-reader_*.ipk - do - cp $f partial/`basename $f _arm.ipk`-`date +%y%m%d`_arm.ipk -done diff --git a/noncore/apps/opie-reader/usenef.h b/noncore/apps/opie-reader/usenef.h deleted file mode 100644 index 57898cb..0000000 --- a/noncore/apps/opie-reader/usenef.h +++ b/dev/null @@ -1,6 +0,0 @@ -#ifndef __USENEF_H -#define __USENEF_H - -//#define USENEF - -#endif diff --git a/noncore/apps/opie-reader/util.cpp b/noncore/apps/opie-reader/util.cpp index a736f8b..2ca1cc8 100644 --- a/noncore/apps/opie-reader/util.cpp +++ b/noncore/apps/opie-reader/util.cpp @@ -1,36 +1,45 @@ #include "util.h" +#include <limits.h> QString filesize(unsigned long l) { char units[] = { 'K', 'M', 'G' }; int iu = 0; while (l > 999 && iu < sizeof(units)) { l = (l+512)/1024; iu++; } QString ret = QString::number(l); if (iu != 0) { ret += QChar(units[iu-1]); } return ret; } QString percent(unsigned long pos, unsigned long len) { unsigned long permil = 0; if (len != 0) { + if (pos > UINT_MAX/1000) + { + unsigned long l1 = (len+500)/1000; + permil = (pos+l1/2)/l1; + } + else + { permil = (1000*pos+len/2)/len; } + } unsigned long percen = permil/10; unsigned long frac = permil - 10*percen; return QString::number(percen) + "." + QString::number(frac); } QString fmt(unsigned long pos, unsigned long len) { QString ret = filesize(pos) + "/" + filesize(len) + " : " + percent(pos,len) +"%"; return ret; } diff --git a/noncore/apps/opie-reader/util.h b/noncore/apps/opie-reader/util.h index f831ead..3964b5e 100644 --- a/noncore/apps/opie-reader/util.h +++ b/noncore/apps/opie-reader/util.h @@ -1,57 +1,9 @@ #ifndef __UTIL_H #define __UTIL_H #include <qstring.h> -#include <qdir.h> -#include <stdlib.h> QString filesize(unsigned long l); QString percent(unsigned long pos, unsigned long len); QString fmt(unsigned long pos, unsigned long len); - -/** - * class with utility inline function(s) - * (in contrast to global functions they become available by just - * including util.h) - */ -class QTReaderUtil -{ - public: - - /** - * searches for a specific direcory inside OpieReader installation - * - * @param subdir name of sub directory inside installation directory which is needed - * @return full path name including that sub directory - * - * search order is (on all platforms): - * - OPIEDIR - * - QTDIR - * - READERDIR - */ - static QString getPluginPath( const char *subdir = "codecs/" ) - { - QString dirname; - dirname = getenv("OPIEDIR"); - dirname += "/plugins/reader/"; - dirname += subdir; - if (QDir(dirname).exists()) - return dirname; - - dirname = getenv("QTDIR"); - dirname += "/plugins/reader/"; - dirname += subdir; - if (QDir(dirname).exists()) - return dirname; - - dirname = getenv("READERDIR"); - dirname += "/"; - dirname += subdir; - if (QDir(dirname).exists()) - return dirname; - - return ""; - } -}; - #endif diff --git a/noncore/apps/opie-reader/version.cpp b/noncore/apps/opie-reader/version.cpp index 9d92abe..aafb3d8 100644 --- a/noncore/apps/opie-reader/version.cpp +++ b/noncore/apps/opie-reader/version.cpp @@ -1,29 +1,62 @@ #include "version.h" #include "names.h" #include <qmessagebox.h> -bool CheckVersion(int& major, int& bkmktype, char& minor) +#include <qmultilineedit.h> +#include <qlayout.h> +#include <qtextview.h> +class versionbox : public QDialog +{ +public: + versionbox(const QString& txt, QWidget* parent = NULL) : QDialog(parent, NULL, true) + { + setCaption(tr( "New Features" )); + QVBoxLayout* v = new QVBoxLayout(this); + /* + QMultiLineEdit* box = new QMultiLineEdit(this); + v->addWidget(box); + box->setReadOnly(true); + box->setWordWrap(QMultiLineEdit::WidgetWidth); + box->setText(txt); + */ + QTextView* box = new QTextView(this); + v->addWidget(box); + box->setText(txt); +#ifdef USEQPE + showMaximized(); +#endif + } +}; + +bool CheckVersion(int& major, int& bkmktype, char& minor, QWidget* pnt) { if ( (major != MAJOR) || (bkmktype != BKMKTYPE) || (minor != MINOR) ) { major = MAJOR; bkmktype = BKMKTYPE; minor = MINOR; - - QMessageBox::warning(NULL, PROGNAME, - "New Features in this version\n\n\n" - "Relative margin settings\n" - "Cyrillic hyphenation"); + versionbox v( + "<h2>New Features</h2>" + "<h3>Support for custom version of rbmake</h3>" + "<h3>Mini scrollbar now acts more like a QT scrollbar.</h3>" + "<p>The handle can be dragged to jump to a \"random\" location and tapping to either side of the handle does page up/down</p>" + "<p>Line up/down is done by tapping in the margins to either end of the scroll bar (left/right margins for a horizontal scrollbar, top/bottom for a vertical scrollbar).</p>" + "<p>The toolbar now stays hidden if you hide it.</p>" + "<p>Better support for tables. Tapping on a table brings up a table viewer. The inline display of the linearised table can be toggled using the Inline Table option" + , + pnt + ); + v.exec(); return true; } else { return false; } } diff --git a/noncore/apps/opie-reader/version.h b/noncore/apps/opie-reader/version.h index dcf0692..486d152 100644 --- a/noncore/apps/opie-reader/version.h +++ b/noncore/apps/opie-reader/version.h @@ -1,9 +1,9 @@ #ifndef __VERSION_H #define __VERSION_H #define MAJOR 0 #define BKMKTYPE 7 -#define MINOR 'g' +#define MINOR 'i' #define RELEASE_TYPE "beta" #endif diff --git a/noncore/apps/opie-reader/ztxt.cpp b/noncore/apps/opie-reader/ztxt.cpp index 35db05e..e04eaa0 100644 --- a/noncore/apps/opie-reader/ztxt.cpp +++ b/noncore/apps/opie-reader/ztxt.cpp @@ -1,173 +1,176 @@ #include <stdio.h> #include <string.h> #include "ztxt.h" #include "my_list.h" #include "Bkmks.h" ztxt::ztxt() : bInit(false), expandedtextbuffer(NULL), compressedtextbuffer(NULL) { /*printf("constructing:%x\n",fin);*/ } int ztxt::OpenFile(const char *src) { if (!Cpdb::openpdbfile(src)) { return -1; } //printf("Okay %u\n", 4); if (head.type != ZTXT_ID) return -1; gotorecordnumber(0); fread(&hdr0, 1, sizeof(hdr0), fin); //printf("Okay %u\n", 5); buffersize = ntohl(hdr0.size); compressedtextbuffer = new UInt8[buffersize]; expandedtextbuffer = new UInt8[buffersize]; //printf("Okay %u\n", 6); home(); //printf("Okay %u\n", 7); // printf("Returning 0\n"); return 0; } int ztxt::getch() { if (bufferpos >= buffercontent) { size_t reclen = recordlength(++bufferrec); if (reclen == 0) return -1; gotorecordnumber(bufferrec); fread(compressedtextbuffer, reclen, sizeof(char), fin); zstream.next_in = compressedtextbuffer; zstream.next_out = expandedtextbuffer; zstream.avail_out = buffersize; zstream.avail_in = reclen; int ret = inflate(&zstream, Z_SYNC_FLUSH); buffercontent = buffersize - zstream.avail_out; bufferpos = 0; } currentpos++; return expandedtextbuffer[bufferpos++]; } unsigned int ztxt::locate() { return currentpos; } void ztxt::locate(unsigned int n) { if (hasrandomaccess()) { + unsuspend(); bufferrec = n / ntohs(hdr0.recordSize) + 1; if (bufferrec == 1) { inflateEnd(&zstream); } size_t reclen = recordlength(bufferrec); if (reclen == 0) return; gotorecordnumber(bufferrec); fread(compressedtextbuffer, reclen, sizeof(char), fin); zstream.next_in = compressedtextbuffer; zstream.next_out = expandedtextbuffer; zstream.avail_out = buffersize; zstream.avail_in = reclen; if (bufferrec == 1) { zstream.zalloc = Z_NULL; zstream.zfree = Z_NULL; zstream.opaque = Z_NULL; inflateInit(&zstream); } int ret = inflate(&zstream, Z_SYNC_FLUSH); buffercontent = buffersize - zstream.avail_out; bufferpos = 0; currentpos = n - n % ntohs(hdr0.recordSize); while (currentpos < n) getch(); } else { home(); while (currentpos < n && getch() != EOF); } } void ztxt::home() { +unsuspend(); if (bInit) { inflateEnd(&zstream); } bInit = true; size_t reclen = recordlength(1); gotorecordnumber(1); fread(compressedtextbuffer, reclen, sizeof(char), fin); zstream.next_in = compressedtextbuffer; zstream.next_out = expandedtextbuffer; zstream.avail_out = buffersize; zstream.avail_in = reclen; zstream.zalloc = Z_NULL; zstream.zfree = Z_NULL; zstream.opaque = Z_NULL; // printf("Initialising\n"); inflateInit(&zstream); int ret = inflate(&zstream, Z_SYNC_FLUSH); // printf("Inflate : %d\n", ret); bufferpos = 0; bufferrec = 1; currentpos = 0; buffercontent = buffersize - zstream.avail_out; // printf("buffercontent:%u\n", buffercontent); } CList<Bkmk>* ztxt::getbkmklist() { UInt16 recno = ntohs(hdr0.bookmarkRecord); // printf("Bookmarks - record %d contains %d\n", recno, ntohs(hdr0.numBookmarks)); if (recno == 0) return NULL; CList<Bkmk>* t = new CList<Bkmk>; + unsuspend(); size_t cur = ftell(fin); gotorecordnumber(recno); for (int i = 0; i < ntohs(hdr0.numBookmarks); i++) { zTXTbkmk bkmk; if (fread(&bkmk, sizeof(bkmk), 1, fin) != 1) break; // printf("Bookmark number:%d:%.20s\n", i, bkmk.title); tchar title[MAX_BMRK_LENGTH]; for (int j = 0; j < MAX_BMRK_LENGTH; j++) { title[j] = bkmk.title[j]; } t->push_back(Bkmk(title, NULL, ntohl(bkmk.offset))); } fseek(fin, cur, SEEK_SET); return t; } #ifndef __STATIC extern "C" { CExpander* newcodec() { return new ztxt; } } #endif |