code
stringlengths
1
2.06M
language
stringclasses
1 value
// Copyright (c) 2013 Oliver Lau <ola@ct.de>, Heise Zeitschriften Verlag // All rights reserved. #include "qlitchapplication.h" #include <QtCore/QDebug> QlitchApplication::QlitchApplication(int &argc, char *argv[]) : QApplication(argc, argv) { setOrganizationName(Company); setOrganizationDomain(Company); setApplicationName(Name); setApplicationVersion(VersionNoDebug); } QlitchApplication::~QlitchApplication() { /* ... */ } const QString QlitchApplication::Company = "c't"; const QString QlitchApplication::Name = "Qlitch"; const QString QlitchApplication::Url = "http://qlitch.googlecode.com/"; const QString QlitchApplication::Author = "Oliver Lau"; const QString QlitchApplication::AuthorMail = "ola@ct.de"; const QString QlitchApplication::VersionNoDebug = "1.0.2"; const QString QlitchApplication::MinorVersion = ""; #ifdef QT_NO_DEBUG const QString QlitchApplication::Version = QlitchApplication::VersionNoDebug + QlitchApplication::MinorVersion; #else const QString QlitchApplication::Version = QlitchApplication::VersionNoDebug + QlitchApplication::MinorVersion + " [DEBUG]"; #endif #if defined(_M_X64) || defined(_WIN64) || defined(__x86_64__) const QString QlitchApplication::Platform = "x64"; #else const QString QlitchApplication::Platform = "x86"; #endif
C++
// Copyright (c) 2013 Oliver Lau <ola@ct.de>, Heise Zeitschriften Verlag // All rights reserved. #include "qlitchapplication.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include "imagewidget.h" #include "random/rnd.h" #include <QtCore/QDebug> #include <QtGlobal> #include <QFileDialog> #include <QBuffer> #include <QTime> #include <QMessageBox> #include <QSettings> #include <QApplication> #include <QClipboard> #include <QKeyEvent> #include <QMimeData> class MainWindowPrivate { public: explicit MainWindowPrivate(void) : algorithm(ALGORITHM_XOR) , imageWidget(new ImageWidget) , flipBit(0) { /* ... */ } ~MainWindowPrivate() { delete imageWidget; } Algorithm algorithm; ImageWidget *imageWidget; QImage image; QString imageFilename; unsigned int flipBit; int prevQuality; int prevSeed; int prevPercentage; int prevIterations; }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , d_ptr(new MainWindowPrivate) { ui->setupUi(this); setWindowTitle(tr("%1 %2 (%3)").arg(QlitchApplication::Name).arg(QlitchApplication::Version).arg(QlitchApplication::Platform)); ui->verticalLayout->addWidget(d_ptr->imageWidget); QObject::connect(ui->actionOpenImage, SIGNAL(triggered()), SLOT(openImage())); QObject::connect(ui->actionSaveImageAs, SIGNAL(triggered()), SLOT(saveImageAs())); QObject::connect(ui->actionExit, SIGNAL(triggered()), SLOT(close())); QObject::connect(ui->actionAbout, SIGNAL(triggered()), SLOT(about())); QObject::connect(ui->actionAboutQt, SIGNAL(triggered()), SLOT(aboutQt())); QObject::connect(ui->actionCopyImageToClipboard, SIGNAL(triggered()), SLOT(copyToClipboard())); QObject::connect(ui->actionPasteImageFromClipboard, SIGNAL(triggered()), SLOT(pasteFromClipboard())); QObject::connect(ui->actionFixedSeed, SIGNAL(toggled(bool)), ui->seedSlider, SLOT(setEnabled(bool))); QObject::connect(ui->actionFixedSeed, SIGNAL(triggered()), SLOT(updateImageWidget())); QObject::connect(ui->qualitySlider, SIGNAL(valueChanged(int)), SLOT(updateImageWidget())); QObject::connect(ui->percentageSlider, SIGNAL(valueChanged(int)), SLOT(updateImageWidget())); QObject::connect(ui->iterationsSlider, SIGNAL(valueChanged(int)), SLOT(updateImageWidget())); QObject::connect(ui->seedSlider, SIGNAL(valueChanged(int)), SLOT(updateImageWidget())); QObject::connect(d_ptr->imageWidget, SIGNAL(imageDropped(QImage)), SLOT(setImage(QImage))); QObject::connect(d_ptr->imageWidget, SIGNAL(refresh()), SLOT(updateImageWidget())); QObject::connect(d_ptr->imageWidget, SIGNAL(positionChanged(int,int)), SLOT(positionChanged(int,int))); QObject::connect(ui->actionShowInlineHelp, SIGNAL(toggled(bool)), d_ptr->imageWidget, SLOT(showHelp(bool))); QObject::connect(ui->actionSingleBitMode, SIGNAL(toggled(bool)), SLOT(singleBitModeChanged(bool))); ui->actionOne->setData(ALGORITHM_ONE); QObject::connect(ui->actionOne, SIGNAL(triggered()), SLOT(setAlgorithm())); ui->actionZero->setData(ALGORITHM_ZERO); QObject::connect(ui->actionZero, SIGNAL(triggered()), SLOT(setAlgorithm())); ui->actionXOR->setData(ALGORITHM_XOR); QObject::connect(ui->actionXOR, SIGNAL(triggered()), SLOT(setAlgorithm())); RAND::initialize(); restoreSettings(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::restoreSettings(void) { Q_D(MainWindow); static const QString DEFAULT_IMAGE = ":/images/default.jpg"; QSettings settings(QlitchApplication::Company, QlitchApplication::Name); restoreGeometry(settings.value("MainWindow/geometry").toByteArray()); setAlgorithm((Algorithm)settings.value("Options/algorithm", ALGORITHM_ONE).toInt()); d->imageFilename = settings.value("Options/recentImageFilename", DEFAULT_IMAGE).toString(); if (!openImage(d->imageFilename)) openImage(DEFAULT_IMAGE); ui->percentageSlider->setValue(settings.value("Options/percentage", 70).toInt()); ui->iterationsSlider->setValue(settings.value("Options/iterations", 2).toInt()); ui->seedSlider->setValue(settings.value("Options/seed", 1).toInt()); ui->qualitySlider->setValue(settings.value("Options/quality", 50).toInt()); ui->actionPreventFF->setChecked(settings.value("Options/preventFF", true).toBool()); ui->seedSlider->setEnabled(ui->actionPreventFF->isChecked()); ui->actionLeaveFFUntouched->setChecked(settings.value("Options/dontTouchFF", true).toBool()); ui->actionSingleBitMode->setChecked(settings.value("Options/singleBitMode", false).toBool()); singleBitModeChanged(ui->actionSingleBitMode->isChecked()); ui->actionShowInlineHelp->setChecked(settings.value("Options/showInlineHelp", true).toBool()); ui->actionFixedSeed->setChecked(settings.value("Options/fixedSeed", false).toBool()); } void MainWindow::saveSettings(void) { Q_D(MainWindow); QSettings settings(QlitchApplication::Company, QlitchApplication::Name); settings.setValue("MainWindow/geometry", saveGeometry()); settings.setValue("Options/algorithm", d->algorithm); settings.setValue("Options/recentImageFilename", d->imageFilename); settings.setValue("Options/percentage", d->prevPercentage); settings.setValue("Options/iterations", d->prevIterations); settings.setValue("Options/quality", d->prevQuality); settings.setValue("Options/seed", d->prevSeed); settings.setValue("Options/singleBitMode", ui->actionSingleBitMode->isChecked()); settings.setValue("Options/preventFF", ui->actionPreventFF->isChecked()); settings.setValue("Options/dontTouchFF", ui->actionLeaveFFUntouched->isChecked()); settings.setValue("Options/showInlineHelp", ui->actionShowInlineHelp->isChecked()); settings.setValue("Options/fixedSeed", ui->actionFixedSeed->isChecked()); } void MainWindow::closeEvent(QCloseEvent *) { saveSettings(); } void MainWindow::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_Space: updateImageWidget(); break; default: e->ignore(); return; } e->accept(); } void MainWindow::updateImageWidget(void) { Q_D(MainWindow); if (d->image.isNull()) return; if (ui->actionFixedSeed->isChecked()) rng.seed(ui->seedSlider->value()); QByteArray raw; QBuffer buffer(&raw); buffer.open(QIODevice::WriteOnly); d->image.save(&buffer, "JPG", ui->qualitySlider->value()); // skip JPEG header (quantization tables, Huffmann tables ...) int headerSize = 0; for (int i = 0; i < raw.size() - 1; ++i) { if (quint8(raw.at(i)) == 0xFFu && quint8(raw.at(i + 1)) == 0xDAu) { headerSize = i + 2; break; } } const int firstPos = headerSize + (raw.size() - headerSize) * (ui->percentageSlider->value() - ui->percentageSlider->minimum()) / (ui->percentageSlider->maximum() - ui->percentageSlider->minimum()); quint8 newByte = 0; if (ui->actionSingleBitMode->isChecked()) { const quint8 oldByte = quint8(raw.at(firstPos)); const quint8 bit = 1 << (d->flipBit++ % 8); switch (d->algorithm) { default: // fall-through case ALGORITHM_XOR: newByte = oldByte ^ bit; break; case ALGORITHM_ONE: newByte = oldByte | bit; break; case ALGORITHM_ZERO: newByte = oldByte & ~bit; break; } raw[firstPos] = ((newByte == 0xFFu) && ui->actionPreventFF->isChecked())? oldByte : newByte; } else { const int N = ui->iterationsSlider->value(); for (int i = 0; i < N; ++i) { const int pos = RAND::rnd(firstPos, raw.size() - 3); const quint8 oldByte = quint8(raw.at(pos)); if (ui->actionLeaveFFUntouched->isChecked() && oldByte == 0xFFu) continue; const quint8 bit = 1 << (RAND::rnd() % 8); switch (d->algorithm) { default: // fall-through case ALGORITHM_XOR: newByte = oldByte ^ bit; break; case ALGORITHM_ONE: newByte = oldByte | bit; break; case ALGORITHM_ZERO: newByte = oldByte & ~bit; break; } raw[pos] = ((newByte == 0xFFu) && ui->actionPreventFF->isChecked())? oldByte : newByte; } } ui->statusBar->showMessage(tr("Resulting image size: %1 bytes").arg(raw.size()), 3000); buffer.close(); bool ok = d->imageWidget->setRaw(raw); if (ok) { d->prevIterations = ui->iterationsSlider->value(); d->prevPercentage = ui->percentageSlider->value(); d->prevQuality = ui->qualitySlider->value(); d->prevSeed = ui->seedSlider->value(); } } void MainWindow::positionChanged(int bPos, int maxPos) { qreal relPos = (qreal)bPos / maxPos; int v = int(ui->percentageSlider->minimum() + relPos * (ui->percentageSlider->maximum() - ui->percentageSlider->minimum())); ui->percentageSlider->setValue(v); } void MainWindow::singleBitModeChanged(bool enabled) { ui->iterationsSlider->setEnabled(!enabled); } void MainWindow::setAlgorithm(Algorithm a) { Q_D(MainWindow); QAction *action = reinterpret_cast<QAction*>(sender()); d->algorithm = (action != NULL)? (Algorithm)action->data().toInt() : a; ui->actionZero->setChecked(false); ui->actionOne->setChecked(false); ui->actionXOR->setChecked(false); switch (d->algorithm) { case ALGORITHM_ONE: ui->actionOne->setChecked(true); break; case ALGORITHM_ZERO: ui->actionZero->setChecked(true); break; case ALGORITHM_XOR: ui->actionXOR->setChecked(true); break; case ALGORITHM_NONE: // fall-through default: break; } ui->statusBar->showMessage(tr("Algorithm: %1").arg(d->algorithm), 1000); updateImageWidget(); } void MainWindow::copyToClipboard(void) { Q_D(MainWindow); QApplication::clipboard()->setImage(d->imageWidget->image(), QClipboard::Clipboard); ui->statusBar->showMessage(tr("Image copied to clipboard."), 5000); } void MainWindow::pasteFromClipboard(void) { if (QApplication::clipboard()->mimeData()->hasImage()) { const QPixmap &pix = QApplication::clipboard()->pixmap(QClipboard::Clipboard); if (!pix.isNull()) setImage(pix.toImage()); } } void MainWindow::setImage(const QImage &img) { Q_D(MainWindow); d->image = img; updateImageWidget(); } bool MainWindow::openImage(const QString &filename) { Q_D(MainWindow); d->image.load(filename); if (d->image.isNull()) return false; updateImageWidget(); return true; } void MainWindow::openImage(void) { Q_D(MainWindow); const QString &imgFileName = QFileDialog::getOpenFileName(this, tr("Open image ...")); if (imgFileName.isEmpty()) return; d->imageFilename = imgFileName; openImage(d->imageFilename); } void MainWindow::saveImageAs(void) { Q_D(MainWindow); const QString &imgFileName = QFileDialog::getSaveFileName(this, tr("Save image as ...")); if (imgFileName.isEmpty()) return; d->imageWidget->image().save(imgFileName); } void MainWindow::about(void) { QMessageBox::about(this, tr("About %1 %2%3 (%4)").arg(QlitchApplication::Name).arg(QlitchApplication::VersionNoDebug).arg(QlitchApplication::MinorVersion).arg(QlitchApplication::Platform), tr("<p><b>%1</b> produces a JPG glitch effect in images.\n" "See <a href=\"%2\" title=\"%1 project homepage\">%2</a> for more info.</p>" "<p>Copyright &copy; 2013 %3 &lt;%4&gt;, Heise Zeitschriften Verlag.</p>" "<p>This program is free software: you can redistribute it and/or modify " "it under the terms of the GNU General Public License as published by " "the Free Software Foundation, either version 3 of the License, or " "(at your option) any later version.</p>" "<p>This program is distributed in the hope that it will be useful, " "but WITHOUT ANY WARRANTY; without even the implied warranty of " "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " "GNU General Public License for more details.</p>" "You should have received a copy of the GNU General Public License " "along with this program. " "If not, see <a href=\"http://www.gnu.org/licenses/gpl-3.0\">http://www.gnu.org/licenses</a>.</p>") .arg(QlitchApplication::Name).arg(QlitchApplication::Url).arg(QlitchApplication::Author).arg(QlitchApplication::AuthorMail)); } void MainWindow::aboutQt(void) { QMessageBox::aboutQt(this); }
C++
/// glitch - Produce glitch effect in a JPG file. /// /// Copyright (c) 2013 Oliver Lau <oliver@von-und-fuer-lau.de>. /// All rights reserved. #ifndef WIN32 #define TEXT() #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #endif #ifdef WIN32 #include <Windows.h> #endif #include <cmath> #include <cstdlib> #include <cstdio> #include <ctime> #include <climits> #include <getopt.h> enum _long_options { SELECT_HELP, SELECT_PERCENT, SELECT_IN, SELECT_OUT, SELECT_ITERATIONS, SELECT_QUIET, SELECT_VERBOSE, SELECT_ALGORITHM, SELECT_AMOUNT }; enum ALGORITHMS { ALGORITHM_0, ALGORITHM_1, ALGORITHM_XOR }; static struct option long_options[] = { { "help", no_argument, 0, SELECT_HELP }, { "percent", required_argument, 0, SELECT_PERCENT }, { "iterations", required_argument, 0, SELECT_ITERATIONS }, { "algorithm", required_argument, 0, SELECT_ALGORITHM }, { "amount", required_argument, 0, SELECT_AMOUNT }, { "in", required_argument, 0, SELECT_IN }, { "out", required_argument, 0, SELECT_OUT }, { "quiet", no_argument, 0, SELECT_QUIET }, { "verbose", no_argument, 0, SELECT_VERBOSE }, { 0, 0, 0, 0 } }; static int verbose = 0; static int iterations = 10; static int amount = 1; static bool quiet = false; static char *infile = "original.jpg"; static char *outfile = "glitched.jpg"; static double percent = 10; static ALGORITHMS algorithm = ALGORITHM_1; static unsigned int BUFFSIZE = 1024; template <typename T> inline T MIN(T x, T y) { return (x > y) ? y : x; } template <typename T> inline T MAX(T x, T y) { return (x < y) ? y : x; } static inline bool fuzzyEqual(double x, double y) { return fabs(x - y) <= (0.000000000001 * MIN(fabs(x), fabs(y))); } double random(double x, double y) { if (fuzzyEqual(x, y)) return x; double hi = MAX(x, y), lo = MIN(x, y); #ifdef WIN32 UINT rn; rand_s(&rn); return lo + ((hi - lo) * rn / (UINT_MAX + 1.0)); #else return lo + ((hi - lo) * rand() / (RAND_MAX + 1.0)); #endif } void disclaimer() { printf("glitch - Produce glitch effect in a JPG file.\n" "Copyright (c) 2013 Oliver Lau <ola@ct.de>, Heise Zeitschriften Verlag.\n" "All rights reserved.\n\n"); } void usage() { printf("Usage: glitch [--in %s] [--out %s] [--iterations|-i %d] [--amount %d] [--percent|-p %lf] [--algorithm|-a ONE|NULL|XOR|]\n\r", infile, outfile, iterations, amount, percent); } #ifdef WIN32 void glitch(void) { srand(GetTickCount()); BOOL rc = CopyFile(infile, outfile, FALSE); if (rc == 0) { fprintf(stderr, TEXT("Copying failed, last error: %d\n"), GetLastError()); exit(1); } HANDLE hFile = CreateFile(outfile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { fprintf(stderr, TEXT("hFile is NULL\n")); fprintf(stderr, TEXT("Target file is %s\n"), outfile); exit(4); } DWORD dwFileSize = GetFileSize(hFile, NULL); SYSTEM_INFO SysInfo; GetSystemInfo(&SysInfo); DWORD dwSysGran = SysInfo.dwAllocationGranularity; DWORD dwFirstPos = (DWORD)(1e-2 * dwFileSize * percent); HANDLE hMapFile = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL); if (hMapFile == NULL) { fprintf(stderr, TEXT("hMapFile is NULL, last error: %d\n"), GetLastError() ); exit(2); } if (verbose > 0) printf("randomly glitching in between %lu and %lu\n", dwFirstPos, dwFileSize); for (int i = 0; i < iterations; ++i) { DWORD dwPos = (DWORD)random(dwFirstPos, dwFileSize); DWORD dwFileMapStart = (dwPos / dwSysGran) * dwSysGran; LPVOID lpMapAddress = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, dwFileMapStart, 0); if (lpMapAddress == NULL) { fprintf(stderr, TEXT("lpMapAddress is NULL, last error: %d\n"), GetLastError()); exit(3); } BYTE *b = reinterpret_cast<BYTE*>(lpMapAddress) + dwPos % dwSysGran; BYTE oldByte = *b; BYTE newByte = oldByte; UINT rn = 0; for (int j = 0; j < amount; ++j) { rand_s(&rn); int bit = rn % 8; switch (algorithm) { default: // fall-through case ALGORITHM_XOR: newByte ^= (1 << bit); break; case ALGORITHM_0: newByte |= (1 << bit); break; case ALGORITHM_1: newByte &= ~(1 << bit); break; } if (verbose > 0) printf("glitching @%11lu[%d]: %02xh->%02xh\n", dwPos, bit, (UINT)oldByte, (UINT)newByte); } *b = newByte; UnmapViewOfFile(lpMapAddress); } CloseHandle(hMapFile); CloseHandle(hFile); } #else void glitch(void) { FILE *in = fopen(infile, "rb"); fseek(in, 0L, SEEK_END); long sz = ftell(in); fseek(in, 0L, SEEK_SET); unsigned char *buf = (unsigned char*) malloc(sz); size_t bytesread = fread(buf, 1, sz, in); fclose(in); FILE *out = fopen(outfile, "wb+"); struct timeval tv; gettimeofday(&tv, 0); long int n = (tv.tv_sec ^ tv.tv_usec) ^ getpid(); srand(n); long firstPos = (long)(1e-2 * sz * percent); printf("in between %lu and %lu\n\r", firstPos, sz); for (int i = 0; i < iterations; ++i) { const long pos = (long) random(firstPos, sz); const int bit = rand() % 8; const unsigned char oldByte = buf[pos]; unsigned char newByte = oldByte; switch (algorithm) { default: // fall-through case ALGORITHM_XOR: newByte ^= (1 << bit); break; case ALGORITHM_OR: newByte |= (1 << bit); break; } buf[pos] = newByte; printf("glitching at position %ld:%d (%02xh->%02xh)\n", pos, bit, (unsigned int) oldByte, (unsigned int) newByte); } fwrite(buf, 1, sz, out); fclose(out); free(buf); } #endif int main(int argc, char *argv[]) { for (;;) { int option_index = 0; int c = getopt_long(argc, argv, "i:p:h?vqa:", long_options, &option_index); if (c == -1) break; switch (c) { case SELECT_IN: infile = optarg; break; case SELECT_OUT: outfile = optarg; break; case 'i': case SELECT_ITERATIONS: iterations = atoi(optarg); break; case SELECT_AMOUNT: amount = atoi(optarg); break; case 'p': case SELECT_PERCENT: percent = atof(optarg); break; case 'a': case SELECT_ALGORITHM: if (strcmp(optarg, "XOR") == 0) algorithm = ALGORITHM_XOR; else if (strcmp(optarg, "NULL") == 0) algorithm = ALGORITHM_0; else if (strcmp(optarg, "ONE") == 0) algorithm = ALGORITHM_1; break; case 'h': /* fall-through */ case '?': /* fall-through */ case SELECT_HELP: usage(); return 0; break; case SELECT_VERBOSE: /* fall-through */ case 'v': ++verbose; break; case SELECT_QUIET: /* fall-through */ case 'q': quiet = true; break; default: usage(); exit(EXIT_FAILURE); break; } } if (!quiet) disclaimer(); if (infile == NULL || outfile == NULL) { usage(); return EXIT_FAILURE; } if (percent >= 100) { usage(); return EXIT_FAILURE; } if (amount < 1 || amount > 7) { usage(); return EXIT_FAILURE; } if (iterations < 1) { usage(); return EXIT_FAILURE; } if (verbose > 1) printf("%s -> %s\n", infile, outfile); glitch(); return EXIT_SUCCESS; }
C++
#include "examplefs.hh" ExampleFS* ExampleFS::_instance = NULL; #define RETURN_ERRNO(x) (x) == 0 ? 0 : -errno ExampleFS* ExampleFS::Instance() { if(_instance == NULL) { _instance = new ExampleFS(); } return _instance; } ExampleFS::ExampleFS() { } ExampleFS::~ExampleFS() { } void ExampleFS::AbsPath(char dest[PATH_MAX], const char *path) { strcpy(dest, _root); strncat(dest, path, PATH_MAX); //printf("translated path: %s to %s\n", path, dest); } void ExampleFS::setRootDir(const char *path) { printf("setting FS root to: %s\n", path); _root = path; } int ExampleFS::Getattr(const char *path, struct stat *statbuf) { char fullPath[PATH_MAX]; AbsPath(fullPath, path); printf("getattr(%s)\n", fullPath); return RETURN_ERRNO(lstat(fullPath, statbuf)); } int ExampleFS::Readlink(const char *path, char *link, size_t size) { printf("readlink(path=%s, link=%s, size=%d)\n", path, link, (int)size); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(readlink(fullPath, link, size)); } int ExampleFS::Mknod(const char *path, mode_t mode, dev_t dev) { printf("mknod(path=%s, mode=%d)\n", path, mode); char fullPath[PATH_MAX]; AbsPath(fullPath, path); //handles creating FIFOs, regular files, etc... return RETURN_ERRNO(mknod(fullPath, mode, dev)); } int ExampleFS::Mkdir(const char *path, mode_t mode) { printf("**mkdir(path=%s, mode=%d)\n", path, (int)mode); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(mkdir(fullPath, mode)); } int ExampleFS::Unlink(const char *path) { printf("unlink(path=%s\n)", path); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(unlink(fullPath)); } int ExampleFS::Rmdir(const char *path) { printf("rmkdir(path=%s\n)", path); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(rmdir(fullPath)); } int ExampleFS::Symlink(const char *path, const char *link) { printf("symlink(path=%s, link=%s)\n", path, link); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(symlink(fullPath, link)); } int ExampleFS::Rename(const char *path, const char *newpath) { printf("rename(path=%s, newPath=%s)\n", path, newpath); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(rename(fullPath, newpath)); } int ExampleFS::Link(const char *path, const char *newpath) { printf("link(path=%s, newPath=%s)\n", path, newpath); char fullPath[PATH_MAX]; char fullNewPath[PATH_MAX]; AbsPath(fullPath, path); AbsPath(fullNewPath, newpath); return RETURN_ERRNO(link(fullPath, fullNewPath)); } int ExampleFS::Chmod(const char *path, mode_t mode) { printf("chmod(path=%s, mode=%d)\n", path, mode); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(chmod(fullPath, mode)); } int ExampleFS::Chown(const char *path, uid_t uid, gid_t gid) { printf("chown(path=%s, uid=%d, gid=%d)\n", path, (int)uid, (int)gid); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(chown(fullPath, uid, gid)); } int ExampleFS::Truncate(const char *path, off_t newSize) { printf("truncate(path=%s, newSize=%d\n", path, (int)newSize); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(truncate(fullPath, newSize)); } int ExampleFS::Utime(const char *path, struct utimbuf *ubuf) { printf("utime(path=%s)\n", path); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(utime(fullPath, ubuf)); } int ExampleFS::Open(const char *path, struct fuse_file_info *fileInfo) { printf("open(path=%s)\n", path); char fullPath[PATH_MAX]; AbsPath(fullPath, path); fileInfo->fh = open(fullPath, fileInfo->flags); return 0; } int ExampleFS::Read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { printf("read(path=%s, size=%d, offset=%d)\n", path, (int)size, (int)offset); return RETURN_ERRNO(pread(fileInfo->fh, buf, size, offset)); } int ExampleFS::Write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { printf("write(path=%s, size=%d, offset=%d)\n", path, (int)size, (int)offset); return RETURN_ERRNO(pwrite(fileInfo->fh, buf, size, offset)); } int ExampleFS::Statfs(const char *path, struct statvfs *statInfo) { printf("statfs(path=%s)\n", path); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(statvfs(fullPath, statInfo)); } int ExampleFS::Flush(const char *path, struct fuse_file_info *fileInfo) { printf("flush(path=%s)\n", path); //noop because we don't maintain our own buffers return 0; } int ExampleFS::Release(const char *path, struct fuse_file_info *fileInfo) { printf("release(path=%s)\n", path); return 0; } int ExampleFS::Fsync(const char *path, int datasync, struct fuse_file_info *fi) { printf("fsync(path=%s, datasync=%d\n", path, datasync); if(datasync) { //sync data only return RETURN_ERRNO(fdatasync(fi->fh)); } else { //sync data + file metadata return RETURN_ERRNO(fsync(fi->fh)); } } int ExampleFS::Setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { printf("setxattr(path=%s, name=%s, value=%s, size=%d, flags=%d\n", path, name, value, (int)size, flags); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(lsetxattr(fullPath, name, value, size, flags)); } int ExampleFS::Getxattr(const char *path, const char *name, char *value, size_t size) { printf("getxattr(path=%s, name=%s, size=%d\n", path, name, (int)size); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(getxattr(fullPath, name, value, size)); } int ExampleFS::Listxattr(const char *path, char *list, size_t size) { printf("listxattr(path=%s, size=%d)\n", path, (int)size); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(llistxattr(fullPath, list, size)); } int ExampleFS::Removexattr(const char *path, const char *name) { printf("removexattry(path=%s, name=%s)\n", path, name); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(lremovexattr(fullPath, name)); } int ExampleFS::Opendir(const char *path, struct fuse_file_info *fileInfo) { printf("opendir(path=%s)\n", path); char fullPath[PATH_MAX]; AbsPath(fullPath, path); DIR *dir = opendir(fullPath); fileInfo->fh = (uint64_t)dir; return NULL == dir ? -errno : 0; } int ExampleFS::Readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo) { printf("readdir(path=%s, offset=%d)\n", path, (int)offset); DIR *dir = (DIR*)fileInfo->fh; struct dirent *de = readdir(dir); if(NULL == de) { return -errno; } else { do { if(filler(buf, de->d_name, NULL, 0) != 0) { return -ENOMEM; } } while(NULL != (de = readdir(dir))); } return 0; } int ExampleFS::Releasedir(const char *path, struct fuse_file_info *fileInfo) { printf("releasedir(path=%s)\n", path); closedir((DIR*)fileInfo->fh); return 0; } int ExampleFS::Fsyncdir(const char *path, int datasync, struct fuse_file_info *fileInfo) { return 0; } int ExampleFS::Init(struct fuse_conn_info *conn) { return 0; } int ExampleFS::Truncate(const char *path, off_t offset, struct fuse_file_info *fileInfo) { printf("truncate(path=%s, offset=%d)\n", path, (int)offset); char fullPath[PATH_MAX]; AbsPath(fullPath, path); return RETURN_ERRNO(ftruncate(fileInfo->fh, offset)); }
C++
#include "wrap.hh" #include "examplefs.hh" void set_rootdir(const char *path) { ExampleFS::Instance()->setRootDir(path); } int wrap_getattr(const char *path, struct stat *statbuf) { return ExampleFS::Instance()->Getattr(path, statbuf); } int wrap_readlink(const char *path, char *link, size_t size) { return ExampleFS::Instance()->Readlink(path, link, size); } int wrap_mknod(const char *path, mode_t mode, dev_t dev) { return ExampleFS::Instance()->Mknod(path, mode, dev); } int wrap_mkdir(const char *path, mode_t mode) { return ExampleFS::Instance()->Mkdir(path, mode); } int wrap_unlink(const char *path) { return ExampleFS::Instance()->Unlink(path); } int wrap_rmdir(const char *path) { return ExampleFS::Instance()->Rmdir(path); } int wrap_symlink(const char *path, const char *link) { return ExampleFS::Instance()->Symlink(path, link); } int wrap_rename(const char *path, const char *newpath) { return ExampleFS::Instance()->Rename(path, newpath); } int wrap_link(const char *path, const char *newpath) { return ExampleFS::Instance()->Link(path, newpath); } int wrap_chmod(const char *path, mode_t mode) { return ExampleFS::Instance()->Chmod(path, mode); } int wrap_chown(const char *path, uid_t uid, gid_t gid) { return ExampleFS::Instance()->Chown(path, uid, gid); } int wrap_truncate(const char *path, off_t newSize) { return ExampleFS::Instance()->Truncate(path, newSize); } int wrap_utime(const char *path, struct utimbuf *ubuf) { return ExampleFS::Instance()->Utime(path, ubuf); } int wrap_open(const char *path, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Open(path, fileInfo); } int wrap_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Read(path, buf, size, offset, fileInfo); } int wrap_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Write(path, buf, size, offset, fileInfo); } int wrap_statfs(const char *path, struct statvfs *statInfo) { return ExampleFS::Instance()->Statfs(path, statInfo); } int wrap_flush(const char *path, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Flush(path, fileInfo); } int wrap_release(const char *path, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Release(path, fileInfo); } int wrap_fsync(const char *path, int datasync, struct fuse_file_info *fi) { return ExampleFS::Instance()->Fsync(path, datasync, fi); } int wrap_setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { return ExampleFS::Instance()->Setxattr(path, name, value, size, flags); } int wrap_getxattr(const char *path, const char *name, char *value, size_t size) { return ExampleFS::Instance()->Getxattr(path, name, value, size); } int wrap_listxattr(const char *path, char *list, size_t size) { return ExampleFS::Instance()->Listxattr(path, list, size); } int wrap_removexattr(const char *path, const char *name) { return ExampleFS::Instance()->Removexattr(path, name); } int wrap_opendir(const char *path, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Opendir(path, fileInfo); } int wrap_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Readdir(path, buf, filler, offset, fileInfo); } int wrap_releasedir(const char *path, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Releasedir(path, fileInfo); } int wrap_fsyncdir(const char *path, int datasync, struct fuse_file_info *fileInfo) { return ExampleFS::Instance()->Fsyncdir(path, datasync, fileInfo); } int wrap_init(struct fuse_conn_info *conn) { return ExampleFS::Instance()->Init(conn); }
C++
#ifndef wrap_hh #define wrap_hh #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <fuse.h> #include <libgen.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/xattr.h> #ifdef __cplusplus extern "C" { #endif void set_rootdir(const char *path); int wrap_getattr(const char *path, struct stat *statbuf); int wrap_readlink(const char *path, char *link, size_t size); int wrap_mknod(const char *path, mode_t mode, dev_t dev); int wrap_mkdir(const char *path, mode_t mode); int wrap_unlink(const char *path); int wrap_rmdir(const char *path); int wrap_symlink(const char *path, const char *link); int wrap_rename(const char *path, const char *newpath); int wrap_link(const char *path, const char *newpath); int wrap_chmod(const char *path, mode_t mode); int wrap_chown(const char *path, uid_t uid, gid_t gid); int wrap_truncate(const char *path, off_t newSize); int wrap_utime(const char *path, struct utimbuf *ubuf); int wrap_open(const char *path, struct fuse_file_info *fileInfo); int wrap_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo); int wrap_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo); int wrap_statfs(const char *path, struct statvfs *statInfo); int wrap_flush(const char *path, struct fuse_file_info *fileInfo); int wrap_release(const char *path, struct fuse_file_info *fileInfo); int wrap_fsync(const char *path, int datasync, struct fuse_file_info *fi); int wrap_setxattr(const char *path, const char *name, const char *value, size_t size, int flags); int wrap_getxattr(const char *path, const char *name, char *value, size_t size); int wrap_listxattr(const char *path, char *list, size_t size); int wrap_removexattr(const char *path, const char *name); int wrap_opendir(const char *path, struct fuse_file_info *fileInfo); int wrap_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo); int wrap_releasedir(const char *path, struct fuse_file_info *fileInfo); int wrap_fsyncdir(const char *path, int datasync, struct fuse_file_info *fileInfo); int wrap_init(struct fuse_conn_info *conn); #ifdef __cplusplus } #endif #endif //wrap_hh
C++
#ifndef examples_hh #define examples_hh #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <fuse.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/xattr.h> class ExampleFS { private: const char *_root; static ExampleFS *_instance; void AbsPath(char dest[PATH_MAX], const char *path); public: static ExampleFS *Instance(); ExampleFS(); ~ExampleFS(); void setRootDir(const char *path); int Getattr(const char *path, struct stat *statbuf); int Readlink(const char *path, char *link, size_t size); int Mknod(const char *path, mode_t mode, dev_t dev); int Mkdir(const char *path, mode_t mode); int Unlink(const char *path); int Rmdir(const char *path); int Symlink(const char *path, const char *link); int Rename(const char *path, const char *newpath); int Link(const char *path, const char *newpath); int Chmod(const char *path, mode_t mode); int Chown(const char *path, uid_t uid, gid_t gid); int Truncate(const char *path, off_t newSize); int Utime(const char *path, struct utimbuf *ubuf); int Open(const char *path, struct fuse_file_info *fileInfo); int Read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo); int Write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo); int Statfs(const char *path, struct statvfs *statInfo); int Flush(const char *path, struct fuse_file_info *fileInfo); int Release(const char *path, struct fuse_file_info *fileInfo); int Fsync(const char *path, int datasync, struct fuse_file_info *fi); int Setxattr(const char *path, const char *name, const char *value, size_t size, int flags); int Getxattr(const char *path, const char *name, char *value, size_t size); int Listxattr(const char *path, char *list, size_t size); int Removexattr(const char *path, const char *name); int Opendir(const char *path, struct fuse_file_info *fileInfo); int Readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo); int Releasedir(const char *path, struct fuse_file_info *fileInfo); int Fsyncdir(const char *path, int datasync, struct fuse_file_info *fileInfo); int Init(struct fuse_conn_info *conn); int Truncate(const char *path, off_t offset, struct fuse_file_info *fileInfo); }; #endif //examples_hh
C++
class CFrameGrinder { public: CFrameGrinder(); ~CFrameGrinder(); void lookForTarget(); void compress(); cv::Mat m_frame; std::vector<uchar> m_outbuf; std::vector<int> m_params; std::string m_targetCoordinateText; protected: IplImage* m_gray; int m_thresh; CvMemStorage* m_storage; };
C++
#include <stdio.h> #include <opencv2/opencv.hpp> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" using namespace std; using namespace cv; #include "CFrameGrinder.h" CFrameGrinder::CFrameGrinder() { m_gray = NULL; m_thresh = 100; m_storage = NULL; } CFrameGrinder::~CFrameGrinder() { } void CFrameGrinder::lookForTarget() { try { // Work on a clone so the orignal image is not altered until the end cv::Mat tempImage = m_frame.clone(); /// Convert it to gray cvtColor(tempImage, tempImage, CV_BGR2GRAY); /// Reduce the noise so we find the larger shapes GaussianBlur(tempImage, tempImage, Size(9, 9), 2, 2); cv::threshold(tempImage, tempImage, 128, 255, CV_THRESH_BINARY); //Find the contours. Use the contourOutput Mat so the original image doesn't get overwritten std::vector<std::vector<cv::Point> > contours; cv::findContours(tempImage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); vector<vector<Point> >hull(contours.size()); for (int i = 0; i < contours.size(); i++) { convexHull(Mat(contours[i]), hull[i], false); } /// Draw hull results const Scalar color = cv::Scalar(255, 255, 255); for (int i = 0; i < contours.size(); i++) { drawContours(m_frame, hull, i, color, 1, 8, vector<Vec4i>(), 0, Point()); } } catch (...) { } } void CFrameGrinder::compress() { m_outbuf.clear(); m_params.clear(); m_params.push_back(CV_IMWRITE_JPEG_QUALITY); m_params.push_back(8); if (!cv::imencode(".jpg", m_frame, m_outbuf, m_params)) { printf("Failed to encode frame to JPG format\n"); } }
C++
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <string> #include <string.h> #include <stdio.h> using namespace std; #define SOCKET_ERROR -1 static char buf[256]; #include "CConnection.h" void dbgMsg_displayConnectionContext(const char* func, const char* msg, const CConnection& con); CConnection::CConnection() { } CConnection::~CConnection() { } void CConnection::init(int port, char* pName) { m_port = port; m_sock = -1; m_client = -1; m_state = CONNECTION_STATE_INIT; m_thread_handle = -1; strcpy(m_name, pName); } string CConnection::displayText() const { sprintf(buf, "%s Connection port: %d sock: %d client: %d state: %s", m_name, m_port, m_sock, m_client, connectionStateToText(m_state).c_str()); return buf; } string CConnection::connectionStateToText(CONNECTION_STATE eState) { string sRet; switch (eState) { case CONNECTION_STATE_RESET: sRet = "CONNECTION_STATE_RESET"; break; case CONNECTION_STATE_INIT: sRet = "CONNECTION_STATE_INIT"; break; case CONNECTION_STATE_BIND_OK: sRet = "CONNECTION_STATE_BIND_OK"; break; case CONNECTION_STATE_ACCEPT_OK: sRet = "CONNECTION_STATE_ACCEPT_OK"; break; default: sRet = "****"; break; } return sRet; } int CConnection::serverBind() { int tempSock = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in address; address.sin_addr.s_addr = INADDR_ANY; address.sin_family = AF_INET; address.sin_port = ::htons(m_port); if (::bind(tempSock, (struct sockaddr*) & address, sizeof (struct sockaddr_in)) == SOCKET_ERROR) { sprintf(buf, "error %d : couldn't bind ", errno); dbgMsg_displayConnectionContext(__FUNCTION__, buf, *this); close(tempSock); tempSock = -1; } else { if (::listen(tempSock, 10) == SOCKET_ERROR) { sprintf(buf, "error %d : couldn't listen ", errno); dbgMsg_displayConnectionContext(__FUNCTION__, buf, *this); close(tempSock); tempSock = -1; } return tempSock; } } int CConnection::acceptConnection() { // // Accept will block // unsigned int addrlen = sizeof (struct sockaddr); struct sockaddr_in address = {0}; int client = ::accept(m_sock, (struct sockaddr*) & address, &addrlen); if (client == SOCKET_ERROR) { sprintf(buf, "error %d : couldn't accept ", errno); dbgMsg_displayConnectionContext(__FUNCTION__, buf, *this); client = -1; } return client; } void CConnection::resetConnection() { dbgMsg_displayConnectionContext(__FUNCTION__, "Before reset connection - ", *this); if ((m_state == CONNECTION_STATE_BIND_OK) || (m_state == CONNECTION_STATE_ACCEPT_OK)) { m_state = CONNECTION_STATE_RESET; dbgMsg_displayConnectionContext(__FUNCTION__, "Resetting connection", *this); fflush(NULL); close(m_client); m_client = -1; close(m_sock); m_sock = -1; m_state = CONNECTION_STATE_INIT; } } void CConnection::tryToBind() { if (m_sock != -1) { close(m_sock); m_sock = -1; } m_sock = serverBind(); if (m_sock == -1) { m_state = CONNECTION_STATE_INIT; } else { m_state = CONNECTION_STATE_BIND_OK; dbgMsg_displayConnectionContext(__FUNCTION__, "Bind OK", *this); } } void CConnection::tryToAccept() { if (m_state == CONNECTION_STATE_BIND_OK) { dbgMsg_displayConnectionContext(__FUNCTION__, "Trying to accept", *this); int tempClient = acceptConnection(); if (tempClient == -1) { dbgMsg_displayConnectionContext(__FUNCTION__, "Accept failed", *this); } else { int browserBytes = 0; char browser_request[1024]; browserBytes = read(tempClient, browser_request, 1023); m_client = tempClient; calledOnceAfterAccept(); m_state = CONNECTION_STATE_ACCEPT_OK; dbgMsg_displayConnectionContext(__FUNCTION__, "Accept OK", *this); } } } int CConnection::writeClient(char* pBuf, unsigned int siz) { return write(m_client, pBuf, siz); }
C++
#include <stdio.h> #include <stdlib.h> #include <string> #include <string.h> #include <unistd.h> #include <errno.h> #include <signal.h> #include <pthread.h> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; #include "CConnection.h" #include "CFrameGrinder.h" char buf[256]; sighandler_t old_pipeHandler; sighandler_t old_ctrlcHandler; bool isShutdown = false; pthread_t browser_connect_thread; pthread_t text_connect_thread; CBrowserConnection browser; CConnection text; CFrameGrinder frameGrinder; void dbgInit() { FILE* fp = fopen("/home/ubuntu/dbg.log", "w"); if (fp != NULL) { fclose(fp); } } void dbgMsg(string msg) { FILE* fp = fopen("/home/ubuntu/dbg.log", "a"); if (fp != NULL) { int bytesWritten = fwrite(msg.c_str(), sizeof (char), msg.size(), fp); bytesWritten = fwrite("\n", sizeof (char), 1, fp); fflush(NULL); fclose(fp); } } void dbgMsg_displayConnectionContext(const char* func, const char* msg, const CConnection& con) { sprintf(buf, "%s() - %s - %s", func, msg, con.displayText().c_str()); dbgMsg(buf); } void* connect_thread(void* pVoid) { CConnection* pCtx = (CConnection*) pVoid; pCtx->resetConnection(); while (!isShutdown) { if (pCtx->m_state == CConnection::CONNECTION_STATE_INIT) { dbgMsg_displayConnectionContext(__FUNCTION__, "Before TryToBind() ", *pCtx); pCtx->tryToBind(); } if (pCtx->m_state == CConnection::CONNECTION_STATE_BIND_OK) { dbgMsg_displayConnectionContext(__FUNCTION__, "bind OK, try to accept ", *pCtx); CConnection::CONNECTION_STATE eTempBrowserState = CConnection::CONNECTION_STATE_INIT; pCtx->tryToAccept(); } usleep(2000 * 1000); } pthread_exit(NULL); } void sigPipeHandler(int sig_num) { browser.resetConnection(); text.resetConnection(); fflush(NULL); } void sigCtrlCHandler(int sig_num) { isShutdown = true; browser.resetConnection(); text.resetConnection(); fflush(NULL); } int main(int, char**) { char head[512]; cv::VideoCapture camera; const std::string videoStreamAddress = "http://root:root@192.168.1.16/axis-cgi/mjpg/video.cgi?.mjpg"; /* it may be an address of an mjpeg stream, e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */ dbgInit(); browser.init(7777, (char*) "browser"); text.init(5555, (char*) "text"); old_pipeHandler = signal(SIGPIPE, sigPipeHandler); if (old_pipeHandler == SIG_ERR) { printf("We have an error\n"); } old_ctrlcHandler = signal(SIGINT, sigCtrlCHandler); if (old_ctrlcHandler == SIG_ERR) { printf("We have an error\n"); } int iRet = pthread_create(&browser.m_thread_handle, NULL, connect_thread, &browser); if (iRet != 0) { printf("We have an error\n"); } iRet = pthread_create(&text.m_thread_handle, NULL, connect_thread, &text); if (iRet != 0) { printf("We have an error\n"); } //open the video stream and make sure it's opened if (!camera.open(videoStreamAddress)) { std::cout << "Error opening video stream or file" << std::endl; return -1; } if (camera.isOpened()) { dbgMsg_displayConnectionContext(__FUNCTION__, "Camera opened OK 1 ", browser); dbgMsg_displayConnectionContext(__FUNCTION__, "Camera opened OK 2 ", text); while (1) { camera >> frameGrinder.m_frame; if (!frameGrinder.m_frame.empty()) { frameGrinder.lookForTarget(); if (text.m_state == CConnection::CONNECTION_STATE_ACCEPT_OK) { text.writeClient((char*) frameGrinder.m_targetCoordinateText.c_str(), frameGrinder.m_targetCoordinateText.size()); fflush(NULL); } if (browser.m_state == CConnection::CONNECTION_STATE_ACCEPT_OK) { try { frameGrinder.compress(); sprintf(head, "\r\n--informs\r\nContent-Type: image/jpeg\r\nContent-Length: %d\r\n\r\n", frameGrinder.m_outbuf.size()); browser.writeClient(head, strlen(head)); fflush(NULL); browser.writeClient((char*) frameGrinder.m_outbuf.data(), frameGrinder.m_outbuf.size()); fflush(NULL); } catch (...) { try { dbgMsg("browser - exception"); } catch (...) { } } } } } } return 0; }
C++
class CConnection { public: typedef enum { CONNECTION_STATE_RESET, CONNECTION_STATE_INIT, CONNECTION_STATE_BIND_OK, CONNECTION_STATE_ACCEPT_OK, } CONNECTION_STATE; CConnection(); ~CConnection(); void init(int port, char* pName); string displayText() const; static string connectionStateToText(CONNECTION_STATE eState); int serverBind(); int acceptConnection(); void resetConnection(); void tryToBind(); void tryToAccept(); int writeClient(char* pBuf, unsigned int siz); virtual void calledOnceAfterAccept(void) { } int m_port; int m_sock; int m_client; CONNECTION_STATE m_state; pthread_t m_thread_handle; char m_name[32]; }; class CBrowserConnection : public CConnection { public: void calledOnceAfterAccept(void) { // Tell the browser that what follows is an mjpeg stream char head[512]; sprintf(head, "HTTP/1.0 200 OK\r\nServer: mjpeg-streamer\r\nContent-Type: multipart/x-mixed-replace;boundary=informs\r\n--informs\r\n"); writeClient(head, strlen(head)); fflush(NULL); } };
C++
// // main.cpp // 1-cs4310-firstproject // // Created by John Grange on 9/24/11. // Copyright 2011 SD Networks. All rights reserved. // #include <iostream> int main (int argc, const char * argv[]) { // insert code here... std::cout << "Hello, CS 4310 Class!!\n"; // this is a test comment return 0; }
C++
#include "lvdocview.h" #include "crtrace.h" #include "props.h" #include "cr3widget.h" #include "crqtutil.h" #include "qpainter.h" #include "settings.h" #include <QtGui/QResizeEvent> #include <QtGui/QScrollBar> #include <QtGui/QMenu> #include <QtGui/QStyleFactory> #include <QtGui/QStyle> #include <QtGui/QApplication> #include <QUrl> #include <QDir> #include <QFileInfo> #include <QDesktopServices> /// to hide non-qt implementation, place all crengine-related fields here class CR3View::DocViewData { friend class CR3View; lString16 _settingsFileName; lString16 _historyFileName; CRPropRef _props; }; static void replaceColor( char * str, lUInt32 color ) { // in line like "0 c #80000000", // replace value of color for ( int i=0; i<8; i++ ) { str[i+5] = toHexDigit((color>>28) & 0xF); color <<= 4; } } static LVRefVec<LVImageSource> getBatteryIcons( lUInt32 color ) { CRLog::debug("Making list of Battery icon bitmats"); lUInt32 cl1 = 0x00000000|(color&0xFFFFFF); lUInt32 cl2 = 0x40000000|(color&0xFFFFFF); lUInt32 cl3 = 0x80000000|(color&0xFFFFFF); lUInt32 cl4 = 0xF0000000|(color&0xFFFFFF); static char color1[] = "0 c #80000000"; static char color2[] = "X c #80000000"; static char color3[] = "o c #80AAAAAA"; static char color4[] = ". c #80FFFFFF"; #define BATTERY_HEADER \ "28 15 5 1", \ color1, \ color2, \ color3, \ color4, \ " c None", static const char * battery8[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0.XXXX.XXXX.XXXX.XXXX.0.", ".0000.XXXX.XXXX.XXXX.XXXX.0.", ".0..0.XXXX.XXXX.XXXX.XXXX.0.", ".0..0.XXXX.XXXX.XXXX.XXXX.0.", ".0..0.XXXX.XXXX.XXXX.XXXX.0.", ".0..0.XXXX.XXXX.XXXX.XXXX.0.", ".0..0.XXXX.XXXX.XXXX.XXXX.0.", ".0..0.XXXX.XXXX.XXXX.XXXX.0.", ".0..0.XXXX.XXXX.XXXX.XXXX.0.", ".0000.XXXX.XXXX.XXXX.XXXX.0.", "....0.XXXX.XXXX.XXXX.XXXX.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery7[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0.oooo.XXXX.XXXX.XXXX.0.", ".0000.oooo.XXXX.XXXX.XXXX.0.", ".0..0.oooo.XXXX.XXXX.XXXX.0.", ".0..0.oooo.XXXX.XXXX.XXXX.0.", ".0..0.oooo.XXXX.XXXX.XXXX.0.", ".0..0.oooo.XXXX.XXXX.XXXX.0.", ".0..0.oooo.XXXX.XXXX.XXXX.0.", ".0000.oooo.XXXX.XXXX.XXXX.0.", "....0.oooo.XXXX.XXXX.XXXX.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery6[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0......XXXX.XXXX.XXXX.0.", ".0000......XXXX.XXXX.XXXX.0.", ".0..0......XXXX.XXXX.XXXX.0.", ".0..0......XXXX.XXXX.XXXX.0.", ".0..0......XXXX.XXXX.XXXX.0.", ".0..0......XXXX.XXXX.XXXX.0.", ".0..0......XXXX.XXXX.XXXX.0.", ".0000......XXXX.XXXX.XXXX.0.", "....0......XXXX.XXXX.XXXX.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery5[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0......oooo.XXXX.XXXX.0.", ".0000......oooo.XXXX.XXXX.0.", ".0..0......oooo.XXXX.XXXX.0.", ".0..0......oooo.XXXX.XXXX.0.", ".0..0......oooo.XXXX.XXXX.0.", ".0..0......oooo.XXXX.XXXX.0.", ".0..0......oooo.XXXX.XXXX.0.", ".0000......oooo.XXXX.XXXX.0.", "....0......oooo.XXXX.XXXX.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery4[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0...........XXXX.XXXX.0.", ".0000...........XXXX.XXXX.0.", ".0..0...........XXXX.XXXX.0.", ".0..0...........XXXX.XXXX.0.", ".0..0...........XXXX.XXXX.0.", ".0..0...........XXXX.XXXX.0.", ".0..0...........XXXX.XXXX.0.", ".0000...........XXXX.XXXX.0.", "....0...........XXXX.XXXX.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery3[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0...........oooo.XXXX.0.", ".0000...........oooo.XXXX.0.", ".0..0...........oooo.XXXX.0.", ".0..0...........oooo.XXXX.0.", ".0..0...........oooo.XXXX.0.", ".0..0...........oooo.XXXX.0.", ".0..0...........oooo.XXXX.0.", ".0000...........oooo.XXXX.0.", "....0...........oooo.XXXX.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery2[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0................XXXX.0.", ".0000................XXXX.0.", ".0..0................XXXX.0.", ".0..0................XXXX.0.", ".0..0................XXXX.0.", ".0..0................XXXX.0.", ".0..0................XXXX.0.", ".0000................XXXX.0.", "....0................XXXX.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery1[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", " .0................oooo.0.", ".0000................oooo.0.", ".0..0................oooo.0.", ".0..0................oooo.0.", ".0..0................oooo.0.", ".0..0................oooo.0.", ".0..0................oooo.0.", ".0000................oooo.0.", " .0................oooo.0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery0[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", " .0.....................0.", ".0000.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0000.....................0.", "....0.....................0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; //#endif static const char * battery_charge[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0.....................0.", ".0000............XX.......0.", ".0..0...........XXXX......0.", ".0..0..XX......XXXXXX.....0.", ".0..0...XXX...XXXX..XX....0.", ".0..0....XXX..XXXX...XX...0.", ".0..0.....XXXXXXX.....XX..0.", ".0000.......XXXX..........0.", "....0........XX...........0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; static const char * battery_frame[] = { BATTERY_HEADER " .........................", " .00000000000000000000000.", " .0.....................0.", "....0.....................0.", ".0000.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0..0.....................0.", ".0000.....................0.", "....0.....................0.", " .0.....................0.", " .00000000000000000000000.", " .........................", }; const char * * icon_bpm[] = { battery_charge, battery0, battery1, battery2, battery3, battery4, battery5, battery6, battery7, battery8, battery_frame, NULL }; replaceColor( color1, cl1 ); replaceColor( color2, cl2 ); replaceColor( color3, cl3 ); replaceColor( color4, cl4 ); LVRefVec<LVImageSource> icons; for ( int i=0; icon_bpm[i]; i++ ) icons.add( LVCreateXPMImageSource( icon_bpm[i] ) ); return icons; } //DECL_DEF_CR_FONT_SIZES CR3View::CR3View( QWidget *parent) : QWidget( parent, Qt::WindowFlags() ), _scroll(NULL), _propsCallback(NULL) , _normalCursor(Qt::ArrowCursor), _linkCursor(Qt::PointingHandCursor) , _selCursor(Qt::IBeamCursor), _waitCursor(Qt::WaitCursor) , _selecting(false), _selected(false), _editMode(false), _lastBatteryState(CR_BATTERY_STATE_NO_BATTERY) { #if WORD_SELECTOR_ENABLED==1 _wordSelector = NULL; #endif _data = new DocViewData(); _data->_props = LVCreatePropsContainer(); _docview = new LVDocView(); _docview->setCallback(this); _selStart = ldomXPointer(); _selEnd = ldomXPointer(); _selText.clear(); ldomXPointerEx p1; ldomXPointerEx p2; _selRange.setStart(p1); _selRange.setEnd(p2); int cr_font_sizes[MAX_CR_FONT_SIZE - MIN_CR_FONT_SIZE + 1]; for(int i = 0; i < sizeof(cr_font_sizes)/sizeof(int); i++) cr_font_sizes[i] = MIN_CR_FONT_SIZE + i; LVArray<int> sizes(cr_font_sizes, sizeof(cr_font_sizes)/sizeof(int)); _docview->setFontSizes(sizes, false); _docview->setBatteryIcons( getBatteryIcons(0x000000) ); // _docview->setBatteryState(CR_BATTERY_STATE_NO_BATTERY); // don't show battery updateDefProps(); // setMouseTracking(true); setFocusPolicy(Qt::NoFocus); // setFocusPolicy(Qt::StrongFocus); } void CR3View::updateDefProps() { _data->_props->setIntDef(PROP_APP_START_ACTION, 0); _data->_props->setIntDef(PROP_FONT_SIZE, DEF_FONT_SIZE); _data->_props->setIntDef(PROP_STATUS_FONT_SIZE, DEF_HEADER_FONT_SIZE); _data->_props->setIntDef(PROP_LANDSCAPE_PAGES, 1); _data->_props->setIntDef(PROP_PAGE_VIEW_MODE, 1); _data->_props->setIntDef(PROP_FLOATING_PUNCTUATION, 0); _data->_props->setIntDef(PROP_SHOW_TIME, 1); _data->_props->setStringDef(PROP_FONT_GAMMA, "1.5"); } CR3View::~CR3View() { #if WORD_SELECTOR_ENABLED==1 if ( _wordSelector ) delete _wordSelector; #endif _docview->savePosition(); saveHistory( QString() ); saveSettings( QString() ); delete _docview; delete _data; } #if WORD_SELECTOR_ENABLED==1 void CR3View::startWordSelection() { if ( isWordSelection() ) endWordSelection(); _wordSelector = new LVPageWordSelector(_docview); update(); } QString CR3View::endWordSelection() { QString text; if ( isWordSelection() ) { ldomWordEx * word = _wordSelector->getSelectedWord(); if ( word ) text = cr2qt(word->getText()); delete _wordSelector; _wordSelector = NULL; _docview->clearSelection(); update(); } return text; } #endif void CR3View::setHyphDir(QString dirname) { HyphMan::initDictionaries(qt2cr(dirname)); _hyphDicts.clear(); for ( int i=0; i<HyphMan::getDictList()->length(); i++ ) { HyphDictionary * item = HyphMan::getDictList()->get( i ); QString fn = cr2qt( item->getFilename() ); _hyphDicts.append( fn ); } } const QStringList & CR3View::getHyphDicts() { return _hyphDicts; } LVTocItem * CR3View::getToc() { return _docview->getToc(); } /// go to position specified by xPointer string void CR3View::goToXPointer(QString xPointer) { ldomXPointer p = _docview->getDocument()->createXPointer(qt2cr(xPointer)); _docview->savePosToNavigationHistory(); doCommand( DCMD_GO_POS, p.toPoint().y ); } /// returns current page int CR3View::getCurPage() { return _docview->getCurPage(); } void CR3View::setDocumentText(QString text) { _docview->savePosition(); clearSelection(); _docview->createDefaultDocument( lString16(), qt2cr(text) ); } bool CR3View::loadLastDocument() { CRFileHist * hist = _docview->getHistory(); if ( !hist || hist->getRecords().length()<=0 ) return false; return loadDocument( cr2qt(hist->getRecords()[0]->getFilePathName()) ); } bool CR3View::loadDocument(QString fileName) { _docview->savePosition(); clearSelection(); bool res = _docview->LoadDocument( qt2cr(fileName).c_str() ); if ( res ) { _docview->swapToCache(); QByteArray utf8 = fileName.toUtf8(); CRLog::debug( "Trying to restore position for %s", utf8.constData() ); _docview->restorePosition(); } else _docview->createDefaultDocument( lString16(), qt2cr(tr("Error while opening document ") + fileName) ); update(); return res; } void CR3View::resizeEvent( QResizeEvent * event) { QSize sz = event->size(); _docview->Resize( sz.width(), sz.height() ); } int getBatteryState() { return CR_BATTERY_STATE_NO_BATTERY; } void CR3View::paintEvent( QPaintEvent * event) { QPainter painter(this); QRect rc = rect(); int newBatteryState = getBatteryState(); if (_lastBatteryState != newBatteryState) { _docview->setBatteryState( newBatteryState ); _lastBatteryState = newBatteryState; } LVDocImageRef ref = _docview->getPageImage(0); if ( ref.isNull() ) { return; } LVDrawBuf * buf = ref->getDrawBuf(); int dx = buf->GetWidth(); int dy = buf->GetHeight(); if ( buf->GetBitsPerPixel()==16 ) { QImage img(dx, dy, QImage::Format_RGB16 ); for ( int i=0; i<dy; i++ ) { unsigned char * dst = img.scanLine( i ); unsigned char * src = buf->GetScanLine(i); for ( int x=0; x<dx; x++ ) { *dst++ = *src++; *dst++ = *src++; } } painter.drawImage( rc, img ); } else if ( buf->GetBitsPerPixel()==32 ) { QImage img(dx, dy, QImage::Format_RGB32 ); for ( int i=0; i<dy; i++ ) { unsigned char * dst = img.scanLine( i ); unsigned char * src = buf->GetScanLine(i); for ( int x=0; x<dx; x++ ) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = 0xFF; src++; } } painter.drawImage( rc, img ); } if ( _editMode ) { // draw caret lvRect cursorRc; if ( _docview->getCursorRect( cursorRc, false ) ) { if ( cursorRc.left<0 ) cursorRc.left = 0; if ( cursorRc.top<0 ) cursorRc.top = 0; if ( cursorRc.right>dx ) cursorRc.right = dx; if ( cursorRc.bottom > dy ) cursorRc.bottom = dy; if ( !cursorRc.isEmpty() ) { painter.setPen(QColor(255,255,255)); painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination); painter.drawRect( cursorRc.left, cursorRc.top, cursorRc.width(), cursorRc.height() ); } } } } void CR3View::scrollTo( int value ) { int currPos = _docview->getScrollInfo()->pos; if ( currPos != value ) { doCommand( DCMD_GO_SCROLL_POS, value ); } } void CR3View::doCommand( int cmd, int param ) { _docview->doCommand( (LVDocCmd)cmd, param ); update(); } void CR3View::togglePageScrollView() { if(_editMode) return; doCommand( DCMD_TOGGLE_PAGE_SCROLL_VIEW, 1); refreshPropFromView( PROP_PAGE_VIEW_MODE); } void CR3View::setEditMode(bool flgEdit) { if ( _editMode == flgEdit ) return; if ( flgEdit && _data->_props->getIntDef( PROP_PAGE_VIEW_MODE, 0 ) ) togglePageScrollView(); _editMode = flgEdit; update(); } void CR3View::refreshPropFromView(const char * propName) { _data->_props->setString( propName, _docview->propsGetCurrent()->getStringDef(propName, "" )); } void CR3View::zoomFont(int param) { if(param>0) doCommand(DCMD_ZOOM_IN, 1); else doCommand(DCMD_ZOOM_OUT, 1); refreshPropFromView(PROP_FONT_SIZE); } void CR3View::zoomHeaderFont(int param) { int size = _data->_props->getIntDef(PROP_STATUS_FONT_SIZE, DEF_HEADER_FONT_SIZE); if(param>0) { size+=1; if(size>MAX_CR_HEADER_FONT_SIZE) return; } else { size-=1; if(size<MIN_CR_HEADER_FONT_SIZE) return; } PropsRef props = Props::create(); props->setInt(PROP_STATUS_FONT_SIZE, size); setOptions(props); } QScrollBar * CR3View::scrollBar() const { return _scroll; } void CR3View::setScrollBar( QScrollBar * scroll ) { _scroll = scroll; if ( _scroll!=NULL ) { QObject::connect(_scroll, SIGNAL(valueChanged(int)), this, SLOT(scrollTo(int))); } } /// load fb2.css file bool CR3View::loadCSS( QString fn ) { lString16 filename( qt2cr(fn) ); lString8 css; if ( LVLoadStylesheetFile( filename, css ) ) { if ( !css.empty() ) { QFileInfo f( fn ); CRLog::info( "Using style sheet from %s", fn.toUtf8().constData() ); _cssDir = f.absolutePath() + "/"; _docview->setStyleSheet( css ); return true; } } return false; } /// load settings from file bool CR3View::loadSettings( QString fn ) { lString16 filename(qt2cr(fn)); _data->_settingsFileName = filename; LVStreamRef stream = LVOpenFileStream( filename.c_str(), LVOM_READ ); bool res = false; if ( !stream.isNull() && _data->_props->loadFromStream( stream.get() ) ) { CRLog::error("Loading settings from file %s", fn.toUtf8().data() ); res = true; } else { CRLog::error("Cannot load settings from file %s", fn.toUtf8().data() ); } _docview->propsUpdateDefaults(_data->_props); updateDefProps(); CRPropRef r = _docview->propsApply(_data->_props); PropsRef unknownOptions = cr2qt(r); if (_propsCallback != NULL) _propsCallback->onPropsChange(unknownOptions); rowCount = _data->_props->getIntDef(PROP_WINDOW_ROW_COUNT, 10); return res; } /// toggle boolean property void CR3View::toggleProperty( const char * name ) { int state = _data->_props->getIntDef( name, 0 )!=0 ? 0 : 1; PropsRef props = Props::create(); props->setString(name, state?"1":"0"); setOptions(props); } /// set new option values void CR3View::propsApply(PropsRef props) { // CRPropRef changed = _data->_props ^ qt2cr(props); CRPropRef newProps = qt2cr(props); _docview->propsApply(newProps); update(); } PropsRef CR3View::setOptions(PropsRef props) { CRPropRef changed = _data->_props ^ qt2cr(props); _data->_props = changed | _data->_props; CRPropRef r = _docview->propsApply(changed); PropsRef unknownOptions = cr2qt(r); if(_propsCallback != NULL) _propsCallback->onPropsChange(unknownOptions); saveSettings(QString()); update(); return unknownOptions; } /// get current option values PropsRef CR3View::getOptions() { return Props::clone(cr2qt( _data->_props )); } /// save settings from file bool CR3View::saveSettings( QString fn ) { lString16 filename( qt2cr(fn) ); crtrace log; if ( filename.empty() ) filename = _data->_settingsFileName; if ( filename.empty() ) return false; _data->_settingsFileName = filename; log << "V3DocViewWin::saveSettings(" << filename << ")"; LVStreamRef stream = LVOpenFileStream( filename.c_str(), LVOM_WRITE ); if ( !stream ) { lString16 path16 = LVExtractPath( filename ); lString8 path = UnicodeToUtf8(path16); if ( !LVCreateDirectory( path16 ) ) { CRLog::error("Cannot create directory %s", path.c_str() ); } else { stream = LVOpenFileStream( filename.c_str(), LVOM_WRITE ); } } if ( stream.isNull() ) { lString8 fn = UnicodeToUtf8( filename ); CRLog::error("Cannot save settings to file %s", fn.c_str() ); return false; } return _data->_props->saveToStream( stream.get() ); } /// load history from file bool CR3View::loadHistory( QString fn ) { lString16 filename( qt2cr(fn) ); CRLog::trace("V3DocViewWin::loadHistory( %s )", UnicodeToUtf8(filename).c_str()); _data->_historyFileName = filename; LVStreamRef stream = LVOpenFileStream( filename.c_str(), LVOM_READ ); if ( stream.isNull() ) { return false; } if ( !_docview->getHistory()->loadFromStream( stream ) ) return false; return true; } /// save history to file bool CR3View::saveHistory( QString fn ) { lString16 filename( qt2cr(fn) ); crtrace log; if ( filename.empty() ) filename = _data->_historyFileName; if ( filename.empty() ) { CRLog::info("Cannot write history file - no file name specified"); return false; } //CRLog::debug("Exporting bookmarks to %s", UnicodeToUtf8(_bookmarkDir).c_str()); //_docview->exportBookmarks(_bookmarkDir); //use default filename lString16 bmdir = qt2cr(_bookmarkDir); LVAppendPathDelimiter( bmdir ); _docview->exportBookmarks( bmdir ); //use default filename _data->_historyFileName = filename; log << "V3DocViewWin::saveHistory(" << filename << ")"; LVStreamRef stream = LVOpenFileStream( filename.c_str(), LVOM_WRITE ); if ( !stream ) { lString16 path16 = LVExtractPath( filename ); lString8 path = UnicodeToUtf8(path16); if ( !LVCreateDirectory( path16 ) ) { CRLog::error("Cannot create directory %s", path.c_str() ); } else { stream = LVOpenFileStream( filename.c_str(), LVOM_WRITE ); } } if ( stream.isNull() ) { CRLog::error("Error while creating history file %s - position will be lost", UnicodeToUtf8(filename).c_str() ); return false; } return _docview->getHistory()->saveToStream( stream.get() ); } void CR3View::contextMenu( QPoint pos ) { } /// returns true if point is inside selected text bool CR3View::isPointInsideSelection( QPoint pos ) { if ( !_selected ) return false; lvPoint pt( pos.x(), pos.y() ); ldomXPointerEx p( _docview->getNodeByPoint( pt ) ); if ( p.isNull() ) return false; return _selRange.isInside( p ); } void CR3View::clearSelection() { if ( _selected ) { _docview->clearSelection(); update(); } _selecting = false; _selected = false; _selStart = ldomXPointer(); _selEnd = ldomXPointer(); _selText.clear(); ldomXPointerEx p1; ldomXPointerEx p2; _selRange.setStart(p1); _selRange.setEnd(p2); } void CR3View::startSelection( ldomXPointer p ) { clearSelection(); _selecting = true; _selStart = p; updateSelection( p ); } bool CR3View::endSelection( ldomXPointer p ) { if ( !_selecting ) return false; updateSelection( p ); if ( _selected ) { } _selecting = false; return _selected; } bool CR3View::updateSelection( ldomXPointer p ) { if ( !_selecting ) return false; _selEnd = p; ldomXRange r( _selStart, _selEnd ); if ( r.getStart().isNull() || r.getEnd().isNull() ) return false; r.sort(); if ( !_editMode ) { if ( !r.getStart().isVisibleWordStart() ) r.getStart().prevVisibleWordStart(); //lString16 start = r.getStart().toString(); if ( !r.getEnd().isVisibleWordEnd() ) r.getEnd().nextVisibleWordEnd(); } if ( r.isNull() ) return false; //lString16 end = r.getEnd().toString(); //CRLog::debug("Range: %s - %s", UnicodeToUtf8(start).c_str(), UnicodeToUtf8(end).c_str()); r.setFlags(1); _docview->selectRange( r ); _selText = cr2qt( r.getRangeText( '\n', 10000 ) ); _selected = true; _selRange = r; update(); return true; } /// Override to handle external links void CR3View::OnExternalLink( lString16 url, ldomNode * node ) { // TODO: add support of file links // only URL supported for now QUrl qturl( cr2qt(url) ); QDesktopServices::openUrl( qturl ); } /// create bookmark CRBookmark * CR3View::createBookmark() { CRBookmark * bm = NULL; if ( getSelectionText().length()>0 && !_selRange.isNull() ) { bm = getDocView()->saveRangeBookmark( _selRange, bmkt_comment, lString16() ); } else { bm = getDocView()->saveCurrentPageBookmark(lString16()); } return bm; } void CR3View::goToBookmark( CRBookmark * bm ) { ldomXPointer start = _docview->getDocument()->createXPointer( bm->getStartPos() ); ldomXPointer end = _docview->getDocument()->createXPointer( bm->getEndPos() ); if ( start.isNull() ) return; if ( end.isNull() ) end = start; // startSelection(start); // endSelection(end); goToXPointer( cr2qt(bm->getStartPos())); update(); } /// format detection finished void CR3View::OnLoadFileFormatDetected( doc_format_t fileFormat ) { QString filename = "fb2.css"; if ( _cssDir.length() > 0 ) { switch ( fileFormat ) { case doc_format_txt: filename = "txt.css"; break; case doc_format_rtf: filename = "rtf.css"; break; case doc_format_epub: filename = "epub.css"; break; case doc_format_html: filename = "htm.css"; break; case doc_format_doc: filename = "doc.css"; break; case doc_format_chm: filename = "chm.css"; break; default: // do nothing ; } CRLog::debug( "CSS file to load: %s", filename.toUtf8().constData() ); if ( QFileInfo( _cssDir + filename ).exists() ) { loadCSS( _cssDir + filename ); } else if ( QFileInfo( _cssDir + "fb2.css" ).exists() ) { loadCSS( _cssDir + "fb2.css" ); } } } /// on starting file loading void CR3View::OnLoadFileStart(lString16 filename) { } /// file load finished with error void CR3View::OnLoadFileError( lString16 message ) { } /// file loading is finished successfully - drawCoveTo() may be called there void CR3View::OnLoadFileEnd() { } /// document formatting started void CR3View::OnFormatStart() { } /// document formatting finished void CR3View::OnFormatEnd() { } /// set bookmarks dir void CR3View::setBookmarksDir( QString dirname ) { _bookmarkDir = dirname; } void CR3View::keyPressEvent(QKeyEvent * event) { #if 0 // testing sentence navigation/selection switch ( event->key() ) { case Qt::Key_Z: _docview->doCommand(DCMD_SELECT_FIRST_SENTENCE); update(); return; case Qt::Key_X: _docview->doCommand(DCMD_SELECT_NEXT_SENTENCE); update(); return; case Qt::Key_C: _docview->doCommand(DCMD_SELECT_PREV_SENTENCE); update(); return; } #endif #if WORD_SELECTOR_ENABLED==1 if (isWordSelection()) { MoveDirection dir = DIR_ANY; switch ( event->key() ) { case Qt::Key_Left: case Qt::Key_A: dir = DIR_LEFT; break; case Qt::Key_Right: case Qt::Key_D: dir = DIR_RIGHT; break; case Qt::Key_W: case Qt::Key_Up: dir = DIR_UP; break; case Qt::Key_S: case Qt::Key_Down: dir = DIR_DOWN; break; case Qt::Key_Q: case Qt::Key_Enter: case Qt::Key_Escape: { QString text = endWordSelection(); event->setAccepted(true); CRLog::debug("Word selected: %s", LCSTR(qt2cr(text))); } return; case Qt::Key_Backspace: _wordSelector->reducePattern(); update(); break; default: { int key = event->key(); if ( key>=Qt::Key_A && key<=Qt::Key_Z ) { QString text = event->text(); if ( text.length()==1 ) { _wordSelector->appendPattern(qt2cr(text)); update(); } } } event->setAccepted(true); return; } int dist = event->modifiers() & Qt::ShiftModifier ? 5 : 1; _wordSelector->moveBy(dir, dist); update(); event->setAccepted(true); } else { if ( event->key()==Qt::Key_F3 && (event->modifiers() & Qt::ShiftModifier) ) { startWordSelection(); event->setAccepted(true); return; } } #endif if ( !_editMode ) return; switch ( event->key() ) { case Qt::Key_Left: break; case Qt::Key_Right: case Qt::Key_Up: case Qt::Key_Down: case Qt::Key_Home: case Qt::Key_End: case Qt::Key_PageUp: case Qt::Key_PageDown: break; } } /// file progress indicator, called with values 0..100 void CR3View::OnLoadFileProgress( int percent ) { } /// format progress, called with values 0..100 void CR3View::OnFormatProgress( int percent ) { } /// first page is loaded from file an can be formatted for preview void CR3View::OnLoadFileFirstPagesReady() { #if 0 // disabled if ( !_data->_props->getBoolDef( PROP_PROGRESS_SHOW_FIRST_PAGE, 1 ) ) { CRLog::info( "OnLoadFileFirstPagesReady() - don't paint first page because " PROP_PROGRESS_SHOW_FIRST_PAGE " setting is 0" ); return; } CRLog::info( "OnLoadFileFirstPagesReady() - painting first page" ); _docview->setPageHeaderOverride(qt2cr(tr("Loading: please wait..."))); //update(); repaint(); CRLog::info( "OnLoadFileFirstPagesReady() - painting done" ); _docview->setPageHeaderOverride(lString16()); _docview->requestRender(); // TODO: remove debug sleep //sleep(5); #endif } // fau+ void CR3View::point_to_end(ldomXPointer& xp) { ldomNode * p = xp.getNode(); if(p->isText()) { lString16 text = p->getText(); xp.setOffset(text.length()); }; if(p->isElement()) { xp.setOffset(p->getChildCount()); } } void CR3View::point_to_begin(ldomXPointer& xp) { ldomNode * p = xp.getNode(); if(p->isText()) xp.setOffset(0); } void CR3View::startSelection() { clearSelection(); _selecting = true; ldomXPointerEx middle = _docview->getCurrentPageMiddleParagraph(); middle.prevVisibleText(); _selStart = middle; point_to_begin(_selStart); _selEnd = middle; point_to_end(_selEnd); updateSelection(); } void CR3View::updateSelection() { _docview->clearSelection(); ldomXRange selected(_selStart, _selEnd, 1); _docview->selectRange(selected); _selected = true; update(); _selRange = selected; } void CR3View::GoToPage(int pagenum) { _docview->goToPage(pagenum); update(); } int CR3View::getPageCount() { return _docview->getPageCount(); } bool CR3View::GetLastPathName(QString *lastpath) { LVPtrVector<CRFileHistRecord> & files = _docview->getHistory()->getRecords(); if (files.length()>0) { *lastpath = cr2qt(files[0]->getFilePathName()); return true; } return false; } void CR3View::Rotate(int param) { _docview->doCommand(DCMD_ROTATE_BY, param); refreshPropFromView(PROP_ROTATE_ANGLE); update(); } void CR3View::ChangeFont(int param) { QStringList faceList; crGetFontFaceList(faceList); QString fontname; if(param) { if(param<1 || param>faceList.count()) return; fontname = faceList.at(param-1); } else { int index = faceList.indexOf(cr2qt(_data->_props->getStringDef(PROP_FONT_FACE, "Verdana"))); if(index+2>faceList.count()) index= 0; else index+=1; fontname = faceList.at(index); } PropsRef props = Props::create(); props->setString(PROP_FONT_FACE, fontname); setOptions(props); } void CR3View::ChangeHeaderFont(int param) { QStringList faceList; crGetFontFaceList(faceList); QString fontname; if(param) { if(param<1 || param>faceList.count()) return; fontname = faceList.at(param-1); } else { int index = faceList.indexOf(cr2qt(_data->_props->getStringDef(PROP_STATUS_FONT_FACE, "Verdana"))); if(index+2>faceList.count()) index= 0; else index+=1; fontname = faceList.at(index); } PropsRef props = Props::create(); props->setString(PROP_STATUS_FONT_FACE, fontname); setOptions(props); } #define MIN_FONT_GAMMA 0.3 #define MAX_FONT_GAMMA 1.91 void CR3View::ChangeFontGamma(int param) { QString fontgamma = cr2qt(_data->_props->getStringDef(PROP_FONT_GAMMA, "1")); double value = fontgamma.toDouble(); if(param>0) { value+=0.1; if(value>MAX_FONT_GAMMA) return; } else { value-=0.1; if(value<MIN_FONT_GAMMA) return; } PropsRef props = Props::create(); props->setDouble(PROP_FONT_GAMMA, value); setOptions(props); } #define MIN_INTERLINE_SPACE 70 #define MAX_INTERLINE_SPACE 150 void CR3View::ChangeInterlineSpace(int param) { int prevValue = _data->_props->getIntDef(PROP_INTERLINE_SPACE, 100); if(param>0) { param=prevValue+5; if(param>MAX_INTERLINE_SPACE) return; } else { param=prevValue-5; if(param<MIN_INTERLINE_SPACE) return; } int newValue = GetArrayNextValue(cr_interline_spaces, sizeof(cr_interline_spaces)/sizeof(int), prevValue, param); PropsRef props = Props::create(); props->setDouble(PROP_INTERLINE_SPACE, newValue); setOptions(props); } //bool CR3View::kbIvent(QWSKeyEvent *pke) //{ // // word selection // if((pke->simpleData.is_press) && isWordSelection()) { // MoveDirection dir = DIR_ANY; // switch(pke->simpleData.keycode) // { // case Qt::Key_PageUp: // case Qt::Key_PageDown: // case Qt::Key_Return: // return true; // case Qt::Key_Escape: // { // QString text = endWordSelection(); // qDebug("selected word is: %s", LCSTR(qt2cr(text))); // return true; // } // case Qt::Key_Left: // dir = DIR_LEFT; // break; // case Qt::Key_Right: // dir = DIR_RIGHT; // break; // case Qt::Key_Up: // dir = DIR_UP; // break; // case Qt::Key_Down: // dir = DIR_DOWN; // break; // default: //// if ((pke->simpleData.keycode) >= Qt::Key_A && (pke->simpleData.keycode) <= Qt::Key_Z ) { //// QString text = event->text(); //// pke->simpleData.keycode //// if ( text.length()==1 ) { //// _wordSelector->appendPattern(qt2cr(text)); //// update(); //// return true; //// } //// } // return false; // } //// int dist = event->modifiers() & Qt::ShiftModifier ? 5 : 1; // int dist = 1; // _wordSelector->moveBy(dir, dist); // update(); // return true; // } // // cite selection? // if (pke->simpleData.is_press) { // switch(pke->simpleData.keycode) // { //// case Qt::Key_PageUp: //// case Qt::Key_PageDown: //// case Qt::Key_Return: //// return true; // } // } else { // switch (pke->simpleData.keycode) // { // case Qt::Key_Left: // case Qt::Key_Right: // case Qt::Key_Up: // case Qt::Key_Down: // return true; // } // } // qDebug("cr3view key event!"); // return false; //} int CR3View::GetArrayNextValue(int *array, int arraySize, int prevValue, int newValue) { if(prevValue<newValue) { for(int i=0; i<arraySize; i++) { if(array[i]>=newValue) { newValue=array[i]; break; } } } else { for(int i=arraySize-1; i>0; i--) { if(array[i]<=newValue) { newValue=array[i]; break; } }; } return newValue; }
C++
#include "recentdlg.h" #include "ui_recentdlg.h" #include <QDir> #include <QKeyEvent> RecentBooksDlg::RecentBooksDlg(QWidget *parent, CR3View * docView ) : QDialog(parent), m_ui(new Ui::RecentBooksDlg), m_docview(docView) { m_ui->setupUi(this); m_ui->tableWidget->setItemDelegate(new RecentBooksListDelegate()); addAction(m_ui->actionRemoveBook); addAction(m_ui->actionRemoveAll); QAction *actionSelect = m_ui->actionSelectBook; actionSelect->setShortcut(Qt::Key_Select); addAction(actionSelect); addAction(m_ui->actionNextPage); addAction(m_ui->actionPrevPage); m_ui->tableWidget->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); m_ui->tableWidget->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); int rc = m_docview->rowCount*2; int h = m_docview->height() -2 - (qApp->font().pointSize() + rc); m_ui->tableWidget->verticalHeader()->setResizeMode(QHeaderView::Custom); m_ui->tableWidget->verticalHeader()->setDefaultSectionSize(h/rc); h = h%rc; int t, b; if(h%2) { t = h/2; b = t + h%2; } else t = b = h/2; m_ui->verticalLayout->setContentsMargins(0, t, 0, b); // fill rows QFont fontBold = m_ui->tableWidget->font(); fontBold.setBold(true); QFont fontItalic = m_ui->tableWidget->font(); fontItalic.setItalic(true); QTableWidgetItem *str11Widget = new QTableWidgetItem(); str11Widget->setFlags(Qt::NoItemFlags); str11Widget->setFont(fontBold); str11Widget->setData(Qt::UserRole, QVariant(2)); QTableWidgetItem *str12Widget = new QTableWidgetItem(); str12Widget->setFont(fontItalic); str12Widget->setData(Qt::UserRole, QVariant(3)); QTableWidgetItem *str22Widget = new QTableWidgetItem(); str22Widget->setFont(fontItalic); str22Widget->setTextAlignment(Qt::AlignRight|Qt::AlignVCenter); str22Widget->setData(Qt::UserRole, QVariant(4)); rc = m_docview->rowCount; m_ui->tableWidget->setRowCount(rc*2); for(int i=0; i<rc*2; i+=2) { m_ui->tableWidget->setItem(i, 0, str11Widget->clone()); m_ui->tableWidget->setItem(i+1, 0, str12Widget->clone()); m_ui->tableWidget->setItem(i+1, 1, str22Widget->clone()); m_ui->tableWidget->setSpan(i, 0, 1, 2); } m_ui->tableWidget->installEventFilter(this); titleMask = windowTitle(); docView->getDocView()->savePosition(); // to move current file to top SetPageCount(); curPage=0; ShowPage(1); } void RecentBooksDlg::SetPageCount() { LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); int count = files.length() - (m_docview->getDocView()->isDocumentOpened() ? 1 : 0); int rc = m_docview->rowCount; pageCount = 1; if(count>rc) { pageCount = count/rc; if(count%rc) pageCount+=1; } } void RecentBooksDlg::ShowPage(int updown, int selectRow) { if(updown>0) { if(curPage+1>pageCount) return; curPage+=1; } else { if(curPage-1<=0) return; curPage-=1; } setWindowTitle(titleMask + " (" + QString::number(curPage) + "/" + QString::number(pageCount) + ")"); int rc = m_docview->rowCount; int firstItem = m_docview->getDocView()->isDocumentOpened() ? 1 : 0; int startPos = ((curPage-1)*rc)+firstItem; LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); for(int k=startPos, index=0; index<rc*2; ++k, index+=2) { if(k<files.length()) { CRFileHistRecord * book = files.get(k); lString16 title = book->getTitle(); lString16 author = book->getAuthor(); lString16 series = book->getSeries(); lString16 filename = book->getFileName(); if(title.empty()) title = filename; QString fileExt = cr2qt(filename); fileExt = fileExt.mid(fileExt.lastIndexOf(".")+1); int fileSize = book->getFileSize(); CRBookmark *bm = book->getLastPos(); int percent = bm->getPercent(); if(author.empty()) author = L"-"; if(title.empty()) title = L"-"; if(!series.empty()) series = L"(" + series + L")"; QTableWidgetItem *item = m_ui->tableWidget->item(index, 0); item->setText(cr2qt(title)); item = m_ui->tableWidget->item(index+1, 0); item->setText(cr2qt(author)+"\n"+cr2qt(series)); item = m_ui->tableWidget->item(index+1, 1); item->setText(crpercent(percent) + "\n" + fileExt+" / "+crFileSize(fileSize)); m_ui->tableWidget->showRow(index); m_ui->tableWidget->showRow(index+1); } else { m_ui->tableWidget->hideRow(index); m_ui->tableWidget->hideRow(index+1); } } // select first row if(m_ui->tableWidget->rowCount()>0) m_ui->tableWidget->selectRow(selectRow); } RecentBooksDlg::~RecentBooksDlg() { delete m_ui; } bool RecentBooksDlg::showDlg( QWidget * parent, CR3View * docView ) { RecentBooksDlg *dlg = new RecentBooksDlg(parent, docView); dlg->showMaximized(); return true; } void RecentBooksDlg::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } bool RecentBooksDlg::eventFilter(QObject *obj, QEvent *event) { if(event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); QString text; switch(keyEvent->key()) { case Qt::Key_Up: if(obj == m_ui->tableWidget) { QScrollBar * scrollBar = m_ui->tableWidget->verticalScrollBar(); int pageStrCount = scrollBar->pageStep(); int fullStrCount = scrollBar->maximum()-scrollBar->minimum()+pageStrCount; if(fullStrCount==pageStrCount) { pageCount = 1; //return; } if(pageStrCount==1) { scrollBar->setMaximum(fullStrCount*2); pageStrCount = scrollBar->pageStep(); } pageCount = ceil((double)fullStrCount/pageStrCount); if(((m_ui->tableWidget->currentRow()+1)/2 == 1) && (pageStrCount/2>1)){ } } break; return true; } } return false; } void RecentBooksDlg::openBook(int row) { int firstItem = m_docview->getDocView()->isDocumentOpened() ? 1 : 0; row+=firstItem; LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); if(row>files.length()) return; // go to file m_docview->loadDocument(cr2qt(files[row-1]->getFilePathName())); close(); } int RecentBooksDlg::getBookNum() { int cr = m_ui->tableWidget->currentRow(); if(cr<0) cr=0; if(cr==0) cr=1; else ++cr/=2; cr+=(curPage-1)*m_docview->rowCount; qDebug("%i", cr); return cr; } void RecentBooksDlg::on_actionSelectBook_triggered() { openBook(getBookNum()); } void RecentBooksDlg::removeFile(LVPtrVector<CRFileHistRecord> & files, int num) { QDir Dir0( cr2qt(files[num-1]->getFilePath()) ); // Удаляемый файл ещё существует if((Dir0.exists( cr2qt(files.get(num-1)->getFileName()) )) && (files.length() > 1)){ // Нужно чтобы в истории было больше одной книжки, чтобы можно было загрузить удяляемую запись а потом удалить m_docview->loadDocument(cr2qt(files[num-1]->getFilePathName())); // remove cache file QString filename = cr2qt(files.get(num-1)->getFileName()); filename = cr2qt(m_docview->getDocView()->getDocProps()->getStringDef(DOC_PROP_FILE_NAME)); // Уточняем CRC удаляемого файла lUInt32 crc = m_docview->getDocView()->getDocProps()->getIntDef(DOC_PROP_FILE_CRC32, 0); char s[16]; sprintf(s, ".%08x", (unsigned)crc); filename = filename+ QString(s); // Возвращаем активным первоначально просматриваемый документ (он сейчас первым в списке истории стоит) m_docview->loadDocument(cr2qt(files[1]->getFilePathName())); // // для отладки // trim file extension, need for archive files QDir Dir(qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/cache/"))); QStringList fileList = Dir.entryList(QStringList() << filename + "*.cr3", QDir::Files); if(fileList.count()) Dir.remove(fileList.at(0)); files.remove(1); } else { // Известно лишь название архива и если его название не совпадает с названием файла то кеш файл не будет удалён // remove cache file QString filename = cr2qt(files.get(num-1)->getFileName()); // trim file extension, need for archive files int pos = filename.lastIndexOf("."); if(pos != -1) filename.resize(pos); QDir Dir(qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/cache/"))); QStringList fileList = Dir.entryList(QStringList() << filename + "*.cr3", QDir::Files); if(fileList.count()) Dir.remove(fileList.at(0)); files.remove(num-1); } } void RecentBooksDlg::on_actionRemoveAll_triggered() { if(QMessageBox::question(this, tr("Remove all history items"), tr("Do you really want to remove all history records?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes) { int firstItem = m_docview->getDocView()->isDocumentOpened() ? 1 : 0; LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); for(int r=files.length(); r>=firstItem; r--) removeFile(files, r); close(); } } void RecentBooksDlg::on_actionRemoveBook_triggered() { int cr = m_ui->tableWidget->currentRow(); if(cr<0) cr=0; int firstItem = m_docview->getDocView()->isDocumentOpened() ? 1 : 0; LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); int row = getBookNum() + firstItem; if(row>files.length()) return; removeFile(files, row); SetPageCount(); if(curPage>pageCount) curPage-=1; curPage-=1; // select row cr = (row-firstItem)*2-1; if((cr+firstItem)/2 >= files.length()) cr = files.length()*2-3; if(cr<0) cr=1; ShowPage(1, cr); } void RecentBooksDlg::on_actionNextPage_triggered() { ShowPage(1); } void RecentBooksDlg::on_actionPrevPage_triggered() { ShowPage(-1); }
C++
#ifndef CR3WIDGET_H #define CR3WIDGET_H #include <qwidget.h> #include <QScrollBar> #include "crqtutil.h" #define MIN_CR_FONT_SIZE 14 #define MAX_CR_FONT_SIZE 72 #define MIN_CR_HEADER_FONT_SIZE 8 #define MAX_CR_HEADER_FONT_SIZE 28 #define DEF_HEADER_FONT_SIZE 22 #define DEF_FONT_SIZE 32 static int cr_interline_spaces[] = { 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150 }; static int def_margin[] = { 0, 1, 2, 3, 4, 5, 8, 10, 12, 14, 15, 16, 20, 25, 30 }; #define PROP_WINDOW_ROW_COUNT "window.row.count" class LVDocView; class LVTocItem; class CRBookmark; class PropsChangeCallback { public: virtual void onPropsChange( PropsRef props ) = 0; virtual ~PropsChangeCallback() { } }; #define WORD_SELECTOR_ENABLED 1 class CR3View : public QWidget, public LVDocViewCallback { Q_OBJECT Q_PROPERTY( QScrollBar* scrollBar READ scrollBar WRITE setScrollBar ) class DocViewData; #if WORD_SELECTOR_ENABLED==1 LVPageWordSelector * _wordSelector; // fau+ // protected: public: // fau- void startWordSelection(); QString endWordSelection(); bool isWordSelection() { return _wordSelector!=NULL; } int rowCount; #endif public: CR3View( QWidget *parent = 0 ); virtual ~CR3View(); bool loadDocument( QString fileName ); bool loadLastDocument(); void setDocumentText( QString text ); QScrollBar * scrollBar() const; /// get document's table of contents LVTocItem * getToc(); /// return LVDocView associated with widget LVDocView * getDocView() { return _docview; } /// go to position specified by xPointer string void goToXPointer(QString xPointer); /// returns current page int getCurPage(); /// load settings from file bool loadSettings( QString filename ); /// save settings from file bool saveSettings( QString filename ); /// load history from file bool loadHistory( QString filename ); /// save history to file bool saveHistory( QString filename ); void setHyphDir( QString dirname ); const QStringList & getHyphDicts(); /// load fb2.css file bool loadCSS( QString filename ); /// set bookmarks dir void setBookmarksDir( QString dirname ); /// set new option values PropsRef setOptions( PropsRef props ); /// get current option values PropsRef getOptions(); /// turns on/off Edit mode (forces Scroll view) void setEditMode( bool flgEdit ); /// returns true if edit mode is active bool getEditMode() { return _editMode; } // void saveWindowPos( QWidget * window, const char * prefix ); // void restoreWindowPos( QWidget * window, const char * prefix, bool allowExtraStates = false ); void setPropsChangeCallback ( PropsChangeCallback * propsCallback ) { _propsCallback = propsCallback; } /// toggle boolean property void toggleProperty( const char * name ); /// returns true if point is inside selected text bool isPointInsideSelection( QPoint pt ); /// returns selection text QString getSelectionText() { return _selText; } /// create bookmark CRBookmark * createBookmark(); /// go to bookmark and highlight it void goToBookmark( CRBookmark * bm ); /// rotate view, +1 = 90` clockwise, -1 = 90` counterclockwise // void rotate( int angle ); /// Override to handle external links virtual void OnExternalLink( lString16 url, ldomNode * node ); /// format detection finished virtual void OnLoadFileFormatDetected( doc_format_t fileFormat ); /// on starting file loading virtual void OnLoadFileStart( lString16 filename ); /// first page is loaded from file an can be formatted for preview virtual void OnLoadFileFirstPagesReady(); /// file load finiished with error virtual void OnLoadFileError( lString16 message ); /// file loading is finished successfully - drawCoveTo() may be called there virtual void OnLoadFileEnd(); /// document formatting started virtual void OnFormatStart(); /// document formatting finished virtual void OnFormatEnd(); /// file progress indicator, called with values 0..100 virtual void OnLoadFileProgress( int percent ); /// format progress, called with values 0..100 virtual void OnFormatProgress( int percent ); // fau+ virtual void doCommand( int cmd, int param = 0); void GoToPage(int pagenum); int getPageCount(); void startSelection(); void updateSelection(); void point_to_end(ldomXPointer& xp); void point_to_begin(ldomXPointer& xp); bool GetLastPathName(QString *lastpath); void Rotate(int param); void ChangeFont(int param); void ChangeHeaderFont(int param); void ChangeFontGamma(int param); void ChangeInterlineSpace(int param); void propsApply(PropsRef props); int GetArrayNextValue(int *array, int arraySize, int prevValue, int newValue); public slots: void contextMenu( QPoint pos ); void setScrollBar( QScrollBar * scroll ); /// on scroll void togglePageScrollView(); void scrollTo( int value ); // void historyBack(); // void historyForward(); void zoomFont(int param); void zoomHeaderFont(int param); signals: //void fileNameChanged( const QString & ); protected: virtual void keyPressEvent(QKeyEvent * event); virtual void paintEvent(QPaintEvent * event); virtual void resizeEvent(QResizeEvent * event); // virtual void wheelEvent ( QWheelEvent * event ); // virtual void updateScroll(); // virtual void doCommand( int cmd, int param = 0 ); // virtual void mouseMoveEvent ( QMouseEvent * event ); // virtual void mousePressEvent ( QMouseEvent * event ); // virtual void mouseReleaseEvent ( QMouseEvent * event ); virtual void refreshPropFromView( const char * propName ); private slots: private: void updateDefProps(); void clearSelection(); void startSelection( ldomXPointer p ); bool endSelection( ldomXPointer p ); bool updateSelection( ldomXPointer p ); DocViewData * _data; // to hide non-qt implementation LVDocView * _docview; QScrollBar * _scroll; PropsChangeCallback * _propsCallback; QStringList _hyphDicts; QCursor _normalCursor; QCursor _linkCursor; QCursor _selCursor; QCursor _waitCursor; bool _selecting; bool _selected; ldomXPointer _selStart; ldomXPointer _selEnd; QString _selText; ldomXRange _selRange; QString _cssDir; QString _bookmarkDir; bool _editMode; int _lastBatteryState; }; #endif // CR3WIDGET_H
C++
#ifndef TOCDLG_H #define TOCDLG_H #include <QMessageBox> #include <QDialog> #include <QModelIndex> #include <QStandardItemModel> #include <QTreeWidget> #include "lvdocview.h" #include "cr3widget.h" #include "crqtutil.h" namespace Ui { class TocDlg; } class CR3View; class TocDlg : public QDialog { Q_OBJECT Q_DISABLE_COPY(TocDlg) public: virtual ~TocDlg(); static bool showDlg(QWidget * parent, CR3View * docView); protected: explicit TocDlg(QWidget *parent, CR3View * docView); virtual void changeEvent(QEvent *e); bool eventFilter(QObject *obj, QEvent *event); void showEvent(QShowEvent *); private: Ui::TocDlg *m_ui; CR3View * m_docview; int fullStrCount; int pageStrCount; int pageCount; int curPage; int countItems; int countItemsTotal; QString titleMask; bool isPageUpdated; void fillOpts(); void updateTitle(); int getCurrentItemPosFromBegin(); int getCurrentItemPosFromBegin(LVTocItem * item_top,QTreeWidgetItem * LevelItem, int level); int getMaxItemPosFromBegin(LVTocItem * item_top,QTreeWidgetItem * LevelItem,int level); int getCurrentItemPage(); void setCurrentItemPage(); bool setCurrentItemFirstInPage(int page_num,LVTocItem * item_top,QTreeWidgetItem * LevelItem,int level); void moveUp(); void moveDown(); void moveUpPage(); void moveDownPage(); private slots: void on_actionGotoPage_triggered(); void on_actionNextPage_triggered(); void on_actionPrevPage_triggered(); void on_actionUpdatePage_triggered(); void on_treeWidget_activated(const QModelIndex &index); }; #endif // TOCDLG_H
C++
#include "openfiledlg.h" #include "ui_openfiledlg.h" #include <QDir> OpenFileDlg::OpenFileDlg(QWidget *parent, CR3View * docView): QDialog(parent), m_ui(new Ui::OpenFileDlg), m_docview(docView) { m_ui->setupUi(this); addAction(m_ui->actionGoToBegin); addAction(m_ui->actionNextPage); addAction(m_ui->actionPrevPage); addAction(m_ui->actionGoToFirstPage); addAction(m_ui->actionGoToLastPage); // code added 28.11.2011 addAction(m_ui->actionRemoveFile); QAction *actionSelect = m_ui->actionSelectFile; actionSelect->setShortcut(Qt::Key_Select); addAction(actionSelect); folder = QIcon(":/icons/folder_sans_32.png"); file = QIcon(":/icons/book_text_32.png"); arrowUp = QIcon(":/icons/arrow_full_up_32.png"); m_ui->FileList->setItemDelegate(new FileListDelegate()); QString lastPathName; QString lastName; if(!docView->GetLastPathName(&lastPathName)) #ifdef i386 CurrentDir = "/home/"; #else CurrentDir = "/mnt/us/documents/"; #endif else { int pos = lastPathName.lastIndexOf("/"); CurrentDir = lastPathName.mid(0, pos+1); lastName = lastPathName.mid(pos+1); } do { QDir Dir(CurrentDir); if(Dir.exists()) break; // trim last "/" CurrentDir.chop(1); int pos = CurrentDir.lastIndexOf("/"); CurrentDir = CurrentDir.mid(0, pos+1); lastName = ""; } while(true); FillFileList(); m_ui->FileList->setCurrentRow(0); // showing last opened page int rc = docView->rowCount*2; curPage=0; if(!lastName.isEmpty()) { int pos = curFileList.indexOf(lastName)+1; if(pos!=0 && pos>rc) { curPage = (pos/rc)-1; if(pos%rc) curPage+=1; } } ShowPage(1); // selecting last opened book if(!lastName.isEmpty()) { QList<QListWidgetItem*> searchlist = m_ui->FileList->findItems(lastName, Qt::MatchExactly); if(searchlist.count()) m_ui->FileList->setCurrentItem(searchlist.at(0)); } } bool OpenFileDlg::showDlg(QWidget * parent, CR3View * docView) { OpenFileDlg *dlg = new OpenFileDlg(parent, docView); dlg->showMaximized(); return true; } OpenFileDlg::~OpenFileDlg() { delete m_ui; } void OpenFileDlg::FillFileList() { if(titleMask.isEmpty()) titleMask = windowTitle(); curFileList.clear(); m_ui->FileList->clear(); QDir::Filters filters; #ifdef i386 if(CurrentDir=="/") filters = QDir::AllDirs|QDir::NoDotAndDotDot; #else if(CurrentDir=="/mnt/us/") filters = QDir::AllDirs|QDir::NoDotAndDotDot; #endif else filters = QDir::AllDirs|QDir::NoDot; QDir Dir(CurrentDir); curFileList=Dir.entryList(filters, QDir::Name); dirCount=curFileList.count(); QStringList Filter; Filter << "*.fb2" << "*.zip" << "*.epub" << "*.rtf" << "*.txt" \ << "*.html" << "*.htm" << "*.tcr" << "*.pdb" << "*.chm" << "*.mobi" << "*.doc" << "*.azw"; curFileList+= Dir.entryList(Filter, QDir::Files, QDir::Name); int count = curFileList.count(); pageCount = 1; int rc = m_docview->rowCount*2; if(count>rc) { pageCount = count/rc; if(count%rc) pageCount+=1; } } void OpenFileDlg::ShowPage(int updown) { if(updown>0) { if(curPage+1>pageCount) return; curPage+=1; } else { if(curPage-1<=0) return; curPage-=1; } m_ui->FileList->clear(); setWindowTitle(titleMask + " (" + QString::number(curPage) + "/" + QString::number(pageCount) + ")"); int rc = m_docview->rowCount*2; int h = (m_docview->height() -2 - (qApp->font().pointSize() + rc))/rc; QListWidgetItem *item = new QListWidgetItem(); item->setSizeHint(QSize(item->sizeHint().width(), h)); QListWidgetItem *pItem; int i=0; int startPos = ((curPage-1)*rc); if(startPos==0 && curFileList.at(0)=="..") { pItem = item->clone(); pItem->setText(".."); pItem->setIcon(arrowUp); m_ui->FileList->addItem(pItem); i++; startPos++; } for(int k=startPos; (k<curFileList.count()) && (i<rc); ++k, ++i) { if(k<dirCount) item->setIcon(folder); else item->setIcon(file); pItem = item->clone(); pItem->setText(curFileList[k]); m_ui->FileList->addItem(pItem); } m_ui->FileList->setCurrentRow(0); } // code added 28.11.2011 void OpenFileDlg::on_actionRemoveFile_triggered() { QListWidgetItem *item = m_ui->FileList->currentItem(); QString ItemText = item->text(); if(ItemText == "..") { return; } else { bool isFileRemoved = false; int current_row = m_ui->FileList->currentRow(); if (ItemText.length()==0) return; QString fileName = CurrentDir + ItemText; QFileInfo FileInfo(fileName); if(FileInfo.isDir()) { QDir::Filters filters; filters = QDir::AllDirs|QDir::NoDotAndDotDot; QDir Dir(fileName); QStringList curFileList1 = Dir.entryList(filters, QDir::Name); QStringList Filter; Filter << "*.fb2" << "*.zip" << "*.epub" << "*.rtf" << "*.txt" \ << "*.html" << "*.htm" << "*.tcr" << "*.pdb" << "*.chm" << "*.mobi" << "*.doc" << "*.azw" << "*.*"; curFileList1 += Dir.entryList(Filter, QDir::Files, QDir::Name); if(curFileList1.count()>0) { QMessageBox * mb = new QMessageBox( QMessageBox::Information, tr("Info"), tr("Directory ")+ItemText+tr(" is not empty."), QMessageBox::Close, this ); mb->setButtonText(QMessageBox::Close,tr("Close")); mb->exec(); } else { QMessageBox * mb = new QMessageBox(QMessageBox::Information,"","", QMessageBox::Yes | QMessageBox::No, this); mb->setButtonText(QMessageBox::No,tr("No")); mb->setButtonText(QMessageBox::Yes,tr("Yes")); if(mb->question(this, tr("Remove directory"), tr("Do you really want to remove directory ")+ItemText+"?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ) == QMessageBox::Yes) { QDir Dir_file(QDir::toNativeSeparators(CurrentDir)); isFileRemoved = Dir_file.rmdir(ItemText); } } } else { // Remove file dialog if(QMessageBox::question(this, tr("Remove file"), tr("Do you really want to remove file ")+ItemText+"?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ) == QMessageBox::Yes) { // Удаление из истории и файла кеша // // для отладки LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); int num=-1; QString filenamepath; // ищем в истории файл с таким путём и названием архива for(int i=0;i<files.length();i++) { filenamepath = cr2qt(files.get(i)->getFilePathName()); if(fileName == filenamepath) num = i; } // Найдена запись в истории, удаляем саму запись и нужный файл кеша if(num>-1){ // делаем активным найденный документ чтобы узнать его истинное название файла if(num>0) m_docview->loadDocument(cr2qt(files[num]->getFilePathName())); QString filename1 = cr2qt(files.get(num)->getFileName()); filename1 = cr2qt(m_docview->getDocView()->getDocProps()->getStringDef(DOC_PROP_FILE_NAME)); // Уточняем CRC удаляемого файла lUInt32 crc = m_docview->getDocView()->getDocProps()->getIntDef(DOC_PROP_FILE_CRC32, 0); char s[16]; sprintf(s, ".%08x", (unsigned)crc); filename1 = filename1+ QString(s); // делаем активным опять предыдущий документ if(files.length()>1) { m_docview->loadDocument(cr2qt(files[1]->getFilePathName())); } else { QMessageBox * mb = new QMessageBox( QMessageBox::Information, tr("Info"), tr("You can't remove last book that you are reading now. Please, choose other active book then try to remove file again."), QMessageBox::Close, this ); mb->setButtonText(QMessageBox::Close,tr("Close")); mb->exec(); return; } // trim file extension, need for archive files QDir Dir(qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/cache/"))); QStringList fileList1 = Dir.entryList(QStringList() << filename1 + "*.cr3", QDir::Files); if(fileList1.count()) Dir.remove(fileList1.at(0)); // Удаление записи истории if(files.length()>1) { files.remove(1); } } QDir Dir_file(QDir::toNativeSeparators(CurrentDir)); QStringList fileList = Dir_file.entryList(QStringList() << ItemText, QDir::Files); if(fileList.count()) isFileRemoved = Dir_file.remove(fileList.at(0)); } } if(isFileRemoved){ for(int k=0; k<curFileList.count(); ++k) { if(curFileList.at(k) == ItemText) { curFileList.removeAt(k); break; } } m_ui->FileList->clear(); setWindowTitle(titleMask + " (" + QString::number(curPage) + "/" + QString::number(pageCount) + ")"); int rc = m_docview->rowCount*2; int h = (m_docview->height() -2 - (qApp->font().pointSize() + rc))/rc; QListWidgetItem *item = new QListWidgetItem(); item->setSizeHint(QSize(item->sizeHint().width(), h)); QListWidgetItem *pItem; int i=0; int startPos = ((curPage-1)*rc); if(startPos==0 && curFileList.at(0)=="..") { pItem = item->clone(); pItem->setText(".."); pItem->setIcon(arrowUp); m_ui->FileList->addItem(pItem); i++; startPos++; } for(int k=startPos; (k<curFileList.count()) && (i<rc); ++k, ++i) { if(k<dirCount) item->setIcon(folder); else item->setIcon(file); pItem = item->clone(); pItem->setText(curFileList[k]); m_ui->FileList->addItem(pItem); } m_ui->FileList->setCurrentRow(0); int count = curFileList.count(); if(count>current_row) m_ui->FileList->setCurrentRow(current_row); else m_ui->FileList->setCurrentRow(current_row-1); } return; } } void OpenFileDlg::on_actionGoToBegin_triggered() { m_ui->FileList->setCurrentRow(0); } void OpenFileDlg::on_actionSelectFile_triggered() { QListWidgetItem *item = m_ui->FileList->currentItem(); QString ItemText = item->text(); if(ItemText == "..") { int i; for(i=CurrentDir.length()-1; i>1; i--) { if(CurrentDir[i-1] == QChar('/')) break; } QString prevDir = CurrentDir.mid(i); prevDir.resize(prevDir.count()-1); CurrentDir.resize(i); FillFileList(); // showing previous opened page int rc = m_docview->rowCount*2; curPage=0; if(!prevDir.isEmpty()) { int pos = curFileList.indexOf(prevDir)+1; if(pos!=0 && pos>rc) { curPage = (pos/rc)-1; if(pos%rc) curPage+=1; } } ShowPage(1); // selecting previous opened dir if(!prevDir.isEmpty()) { QList<QListWidgetItem*> searchlist = m_ui->FileList->findItems(prevDir, Qt::MatchExactly); if(searchlist.count()) m_ui->FileList->setCurrentItem(searchlist.at(0)); } } else { if (ItemText.length()==0) return; QString fileName = CurrentDir + ItemText; QFileInfo FileInfo(fileName); if(FileInfo.isDir()) { CurrentDir = fileName + QString("/"); FillFileList(); curPage=0; ShowPage(1); } else { // Удаление из истории и файла кеша LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); int num=-1; QString filenamepath; // ищем в истории файл с таким путём и названием архива for(int i=0;i<files.length();i++) { filenamepath = cr2qt(files.get(i)->getFilePathName()); if(fileName == filenamepath) num = i; } lvpos_t file_size1; // Проверка - не лежит ли в истории файл с таким же путём и названием if(fileName.length()>0){ // Найдена запись в истории, удаляем саму запись и нужный файл кеша if(num>-1){ file_size1 = files.get(num)->getFileSize(); // делаем активным найденный документ чтобы узнать его истинное название файла if(num>=0) { QString filename1; filename1 = cr2qt(files.get(num)->getFileName()); // Уточняем CRC удаляемого файла // делаем активным опять предыдущий документ // trim file extension, need for archive files int pos = filename1.lastIndexOf("."); if(pos != -1) filename1.resize(pos); // remove cache file QDir Dir(qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/cache/"))); QStringList fileList1 = Dir.entryList(QStringList() << filename1 + "*.cr3", QDir::Files); if(fileList1.count()) Dir.remove(fileList1.at(0)); fileList1 = Dir.entryList(QStringList() << filename1 + "*.cr3", QDir::Files); if(fileList1.count()) Dir.remove(fileList1.at(0)); // Удаление записи истории // Загружаем новую книгу m_docview->loadDocument(fileName); LVPtrVector<CRFileHistRecord> & files1 = m_docview->getDocView()->getHistory()->getRecords(); lvpos_t file_size2 = files.get(0)->getFileSize(); if(num>-1){ // Удаление записи истории if (file_size1 != file_size2) { QMessageBox * mb = new QMessageBox( QMessageBox::Information, tr("Info"), tr("Other File with such FilePath in history"), QMessageBox::Close, this ); mb->setButtonText(QMessageBox::Close,tr("Close")); mb->exec(); files1.remove(num+1); } } } // Удаление из истории // // ищем в истории файл с таким путём и названием архива // // Найдена запись в истории, удаляем саму запись } } // Загружаем новую книгу m_docview->loadDocument(fileName); // Зачем вообще нужен файл кеша? Все равно потом появится сам :-( close(); } } } void OpenFileDlg::on_actionNextPage_triggered() { ShowPage(1); } void OpenFileDlg::on_actionPrevPage_triggered() { ShowPage(-1); } void OpenFileDlg::on_actionGoToLastPage_triggered() { if(pageCount-1==0) return; curPage=pageCount-1; ShowPage(1); } void OpenFileDlg::on_actionGoToFirstPage_triggered() { if(curPage==1) return; curPage=0; ShowPage(1); }
C++
#ifndef OPENFILEDLG_H #define OPENFILEDLG_H // code added 28.11.2011 #include <QMessageBox> #include <QDialog> #include <QFileDialog> #include <QListWidgetItem> #include <QItemDelegate> #include <QPainter> #include <QProxyStyle> #include "lvstream.h" #include "cr3widget.h" #include "crqtutil.h" namespace Ui { class OpenFileDlg; } class CR3View; class FileListDelegate : public QItemDelegate { public: FileListDelegate(QObject *pobj = 0) : QItemDelegate(pobj) { } void drawDecoration(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QPixmap &pixmap) const { if(option.state & QStyle::State_Selected) { QPoint p = QStyle::alignedRect(option.direction, option.decorationAlignment, pixmap.size(), rect).topLeft(); painter->drawPixmap(p, pixmap); return; } QItemDelegate::drawDecoration(painter, option, rect, pixmap); } void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {; if(option.state & QStyle::State_Selected) { painter->save(); QVariant value; QStyleOptionViewItemV4 opt = setOptions(index, option); value = index.data(Qt::DisplayRole); QString text; if(value.isValid() && !value.isNull()) text = value.toString(); value = index.data(Qt::DecorationRole); QPixmap pixmap = qvariant_cast<QIcon>(value).pixmap(option.decorationSize, QIcon::Normal, QIcon::On); QRect decorationRect = QRect(QPoint(0, 0), pixmap.size()); QRect checkRect; QRect displayRect; doLayout(opt, &checkRect, &decorationRect, &displayRect, false); drawDecoration(painter, opt, decorationRect, pixmap); drawDisplay(painter, opt, displayRect, text); QPen pen(Qt::black, 2, Qt::SolidLine); painter->setPen(pen); painter->drawLine(displayRect.bottomLeft(), displayRect.bottomRight()); painter->restore(); return; } QItemDelegate::paint(painter, option, index); } }; class OpenFileDlg : public QDialog { Q_OBJECT Q_DISABLE_COPY(OpenFileDlg) public: explicit OpenFileDlg(QWidget *parent, CR3View * docView); virtual ~OpenFileDlg(); QString CurrentDir; static bool showDlg(QWidget *parent, CR3View * docView); private slots: void on_actionSelectFile_triggered(); void on_actionGoToBegin_triggered(); void on_actionNextPage_triggered(); void on_actionPrevPage_triggered(); void on_actionGoToLastPage_triggered(); void on_actionGoToFirstPage_triggered(); // code added 28.11.2011 void on_actionRemoveFile_triggered(); private: void FillFileList(); void ShowPage(int updown); Ui::OpenFileDlg *m_ui; CR3View * m_docview; QIcon folder, file, arrowUp; QStringList curFileList; int curPage, pageCount; QString titleMask; int dirCount; int rowCount; }; #endif // OPENFILEDLG_H
C++
#include "crqtutil.h" #include "props.h" #include <QStringList> #include <QWidget> #include <QPoint> lString16 qt2cr(QString str) { return lString16( str.toUtf8().constData() ); } QString cr2qt(lString16 str) { lString8 s8 = UnicodeToUtf8(str); return QString::fromUtf8( s8.c_str(), s8.length() ); } class CRPropsImpl : public Props { CRPropRef _ref; public: CRPropRef getRef() { return _ref; } CRPropsImpl(CRPropRef ref) : _ref( ref ) { } virtual int count() { return _ref->getCount(); } virtual const char * name( int index ) { return _ref->getName( index ); } virtual QString value( int index ) { return cr2qt(_ref->getValue( index )); } virtual bool hasProperty( const char * propName ) const { return _ref->hasProperty(propName); } virtual bool getString( const char * prop, QString & result ) { lString16 value; if ( !_ref->getString(prop, value) ) return false; result = cr2qt( value ); return true; } virtual QString getStringDef( const char * prop, const char * defValue ) { return cr2qt( _ref->getStringDef(prop, defValue) ); } virtual void setString( const char * prop, const QString & value ) { _ref->setString( prop, qt2cr(value) ); } virtual bool getInt( const char * prop, int & result ) { return _ref->getInt(prop, result); } virtual void setInt( const char * prop, int value ) { _ref->setInt( prop, value ); } virtual int getIntDef( const char * prop, int defValue ) { return _ref->getIntDef(prop, defValue); } // fau+ virtual double getDoubleDef(const char * prop, const char * defValue) { QString s = cr2qt(_ref->getStringDef(prop, defValue)); return s.toDouble(); } virtual void setDouble(const char * prop, const double value) { _ref->setString(prop, qt2cr(QString::number(value))); } // fau- virtual void setHex( const char * propName, int value ) { _ref->setHex( propName, value ); } virtual CRPropRef & accessor() { return _ref; } virtual ~CRPropsImpl() { } }; PropsRef cr2qt( CRPropRef & ref ) { return QSharedPointer<Props>( new CRPropsImpl(ref) ); } const CRPropRef & qt2cr( PropsRef & ref ) { return ref->accessor(); } PropsRef Props::create() { return QSharedPointer<Props>( new CRPropsImpl(LVCreatePropsContainer()) ); } PropsRef Props::clone( PropsRef v ) { return QSharedPointer<Props>( new CRPropsImpl(LVClonePropsContainer( ((CRPropsImpl*)v.data())->getRef() )) ); } /// returns common items from props1 not containing in props2 PropsRef operator - ( PropsRef props1, PropsRef props2 ) { return QSharedPointer<Props>( new CRPropsImpl(((CRPropsImpl*)props1.data())->getRef() - ((CRPropsImpl*)props2.data())->getRef())); } /// returns common items containing in props1 or props2 PropsRef operator | ( PropsRef props1, PropsRef props2 ) { return QSharedPointer<Props>( new CRPropsImpl(((CRPropsImpl*)props1.data())->getRef() | ((CRPropsImpl*)props2.data())->getRef())); } /// returns common items of props1 and props2 PropsRef operator & ( PropsRef props1, PropsRef props2 ) { return QSharedPointer<Props>( new CRPropsImpl(((CRPropsImpl*)props1.data())->getRef() & ((CRPropsImpl*)props2.data())->getRef())); } /// returns added or changed items of props2 compared to props1 PropsRef operator ^ ( PropsRef props1, PropsRef props2 ) { return QSharedPointer<Props>( new CRPropsImpl(((CRPropsImpl*)props1.data())->getRef() ^ ((CRPropsImpl*)props2.data())->getRef())); } void cr2qt( QStringList & dst, const lString16Collection & src ) { dst.clear(); for ( unsigned i=0; i<src.length(); i++ ) { dst.append( cr2qt( src[i] ) ); } } void qt2cr(lString16Collection & dst, const QStringList & src) { dst.clear(); for ( int i=0; i<src.length(); i++ ) { dst.add( qt2cr( src[i] ) ); } } void crGetFontFaceList(QStringList & dst) { lString16Collection faceList; fontMan->getFaceList(faceList); cr2qt(dst, faceList); } QString crpercent(int p) { return QString().sprintf("%.2f %", (double)p/100); } QString crFileSize(int fsize) { if(fsize>1024*10) return QString().sprintf("%.1f MB", (double)fsize/(1024*1024)); else return QString("%1 KB").arg(fsize/1024); }
C++
#include "filepropsdlg.h" #include "ui_filepropsdlg.h" FilePropsDialog::FilePropsDialog(QWidget *parent, CR3View * docView ) : QDialog(parent), m_ui(new Ui::FilePropsDialog) ,_cr3v(docView) ,_docview(docView->getDocView()) { m_ui->setupUi(this); setWindowTitle(QString(CR_ENGINE_VERSION) + " // " + windowTitle()); m_ui->tableWidget->setItemDelegate(new FilePropsListDelegate()); m_ui->tableWidget->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); fillItems(); } FilePropsDialog::~FilePropsDialog() { delete m_ui; } bool FilePropsDialog::showDlg( QWidget * parent, CR3View * docView ) { FilePropsDialog *dlg = new FilePropsDialog(parent, docView); dlg->showMaximized(); return true; } QString FilePropsDialog::getDocText( const char * path, const char * delim ) { ldomDocument * doc = _docview->getDocument(); lString16 res; for ( int i=0; i<100; i++ ) { lString8 p = lString8(path) + "[" + lString8::itoa(i+1) + "]"; lString16 p16 = Utf8ToUnicode(p); ldomXPointer ptr = doc->createXPointer( p16 ); if ( ptr.isNull() ) break; lString16 s = ptr.getText( L' ' ); if ( s.empty() ) continue; if ( !res.empty() && delim!=NULL ) res << Utf8ToUnicode( lString8( delim ) ); res << s; } return cr2qt(res); } QString FilePropsDialog::getDocAuthors( const char * path, const char * delim ) { lString16 res; for ( int i=0; i<100; i++ ) { lString8 p = lString8(path) + "[" + lString8::itoa(i+1) + "]"; lString16 firstName = qt2cr(getDocText( (p + "/first-name").c_str(), " " )); lString16 lastName = qt2cr(getDocText( (p + "/last-name").c_str(), " " )); lString16 middleName = qt2cr(getDocText( (p + "/middle-name").c_str(), " " )); lString16 nickName = qt2cr(getDocText( (p + "/nickname").c_str(), " " )); lString16 homePage = qt2cr(getDocText( (p + "/homepage").c_str(), " " )); lString16 email = qt2cr(getDocText( (p + "/email").c_str(), " " )); lString16 s = firstName; if ( !middleName.empty() ) s << L" " << middleName; if ( !lastName.empty() ) { if ( !s.empty() ) s << L" "; s << lastName; } if ( !nickName.empty() ) { if ( !s.empty() ) s << L" "; s << nickName; } if ( !homePage.empty() ) { if ( !s.empty() ) s << L" "; s << homePage; } if ( !email.empty() ) { if ( !s.empty() ) s << L" "; s << email; } if ( s.empty() ) continue; if ( !res.empty() && delim!=NULL ) res << Utf8ToUnicode( lString8( delim ) ); res << s; } return cr2qt(res); } void FilePropsDialog::addPropLine(QString name, QString v) { if(!v.isEmpty()) { if(!_value.isEmpty()) _value += "\n"; _value += name + ": " + v; } } void FilePropsDialog::addInfoSection(QString name) { if(_value.isEmpty()) return; int y = m_ui->tableWidget->rowCount(); m_ui->tableWidget->setRowCount(y+2); QFont fontBold = m_ui->tableWidget->font(); fontBold.setBold(true); QFont fontItalic = m_ui->tableWidget->font(); fontItalic.setItalic(true); QTableWidgetItem * item1 = new QTableWidgetItem(name); item1->setFont(fontBold); m_ui->tableWidget->setItem(y, 0, item1); QTableWidgetItem * item2 = new QTableWidgetItem(_value); item2->setData(Qt::UserRole, QVariant(2)); item2->setFont(fontItalic); m_ui->tableWidget->setItem(y+1, 0, item2); _value.clear(); } void FilePropsDialog::fillItems() { _docview->savePosition(); CRPropRef props = _docview->getDocProps(); addPropLine(tr("Archive name"), cr2qt(props->getStringDef(DOC_PROP_ARC_NAME)) ); addPropLine(tr("Archive path"), cr2qt(props->getStringDef(DOC_PROP_ARC_PATH)) ); addPropLine(tr("Archive size"), cr2qt(props->getStringDef(DOC_PROP_ARC_SIZE)) ); addPropLine(tr("File name"), cr2qt(props->getStringDef(DOC_PROP_FILE_NAME)) ); addPropLine(tr("File path"), cr2qt(props->getStringDef(DOC_PROP_FILE_PATH)) ); addPropLine(tr("File size"), cr2qt(props->getStringDef(DOC_PROP_FILE_SIZE)) ); addPropLine(tr("File format"), cr2qt(props->getStringDef(DOC_PROP_FILE_FORMAT)) ); addInfoSection(tr("File info")); addPropLine(tr("Title"), cr2qt(props->getStringDef(DOC_PROP_TITLE)) ); addPropLine(tr("Author(s)"), cr2qt(props->getStringDef(DOC_PROP_AUTHORS)) ); addPropLine(tr("Series name"), cr2qt(props->getStringDef(DOC_PROP_SERIES_NAME)) ); addPropLine(tr("Series number"), cr2qt(props->getStringDef(DOC_PROP_SERIES_NUMBER)) ); addPropLine(tr("Date"), getDocText( "/FictionBook/description/title-info/date", ", " ) ); addPropLine(tr("Genres"), getDocText( "/FictionBook/description/title-info/genre", ", " ) ); addPropLine(tr("Translator"), getDocText( "/FictionBook/description/title-info/translator", ", " ) ); addInfoSection(tr("Book info") ); addPropLine(tr("Document author"), getDocAuthors( "/FictionBook/description/document-info/author", " " ) ); addPropLine(tr("Document date"), getDocText( "/FictionBook/description/document-info/date", " " ) ); addPropLine(tr("Document source URL"), getDocText( "/FictionBook/description/document-info/src-url", " " ) ); addPropLine(tr("OCR by"), getDocText( "/FictionBook/description/document-info/src-ocr", " " ) ); addPropLine(tr("Document version"), getDocText( "/FictionBook/description/document-info/version", " " ) ); addInfoSection( tr("Document info") ); addPropLine(tr("Publication name"), getDocText( "/FictionBook/description/publish-info/book-name", " " ) ); addPropLine(tr("Publisher"), getDocText( "/FictionBook/description/publish-info/publisher", " " ) ); addPropLine(tr("Publisher city"), getDocText( "/FictionBook/description/publish-info/city", " " ) ); addPropLine(tr("Publication year"), getDocText( "/FictionBook/description/publish-info/year", " " ) ); addPropLine(tr("ISBN"), getDocText( "/FictionBook/description/publish-info/isbn", " " ) ); addInfoSection(tr("Publication info")); addPropLine(tr("Custom info"), getDocText( "/FictionBook/description/custom-info", " " ) ); } void FilePropsDialog::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } }
C++
#ifndef RecentBooksDlg_H #define RecentBooksDlg_H #include <QDialog> #include <QMessageBox> #include <QItemDelegate> #include <QPainter> #include <QTableWidget> #include <math.h> #include "cr3widget.h" #include "crqtutil.h" #include "lvdocview.h" namespace Ui { class RecentBooksDlg; } class CR3View; class RecentBooksDlg : public QDialog { Q_OBJECT Q_DISABLE_COPY(RecentBooksDlg) public: virtual ~RecentBooksDlg(); static bool showDlg(QWidget * parent, CR3View * docView); protected: explicit RecentBooksDlg(QWidget *parent, CR3View * docView); virtual void changeEvent(QEvent *e); bool eventFilter(QObject *obj, QEvent *event); private: Ui::RecentBooksDlg *m_ui; CR3View * m_docview; void openBook(int index); int getBookNum(); int pageCount; int curPage; QString titleMask; void ShowPage(int updown, int selectRow = 1); void SetPageCount(); // added 14.12.2011 void removeFile(LVPtrVector<CRFileHistRecord> & files, int num); private slots: void on_actionRemoveBook_triggered(); void on_actionRemoveAll_triggered(); void on_actionSelectBook_triggered(); void on_actionNextPage_triggered(); void on_actionPrevPage_triggered(); }; class RecentBooksListDelegate : public QItemDelegate { public: RecentBooksListDelegate(QObject *pobj = 0) : QItemDelegate(pobj) { } void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem newOption; QVariant value; newOption = option; newOption.state &= ~QStyle::State_HasFocus; value = index.data(Qt::UserRole); int id; if(value.isValid() && !value.isNull()) { id=value.toInt(); if(id==3 || id==4) newOption.font.setPointSize(newOption.font.pointSize()-4); } QItemDelegate::paint(painter, newOption, index); painter->save(); if(index.flags() & Qt::ItemIsSelectable) { Qt::GlobalColor lineColor; if(newOption.state & QStyle::State_Selected) lineColor = Qt::black; else lineColor = Qt::gray; QPen pen(lineColor, 2, Qt::SolidLine); painter->setPen(pen); painter->drawLine(newOption.rect.left(), newOption.rect.bottom(), newOption.rect.right(), newOption.rect.bottom()); } painter->restore(); } }; #endif // RecentBooksDlg_H
C++
#include "settings.h" #include "ui_settings.h" static bool initDone = false; static bool ItemSelected = false; SettingsDlg::SettingsDlg(QWidget *parent, CR3View * docView ) : QDialog(parent), m_ui(new Ui::SettingsDlg), m_docview( docView ) { initDone = false; m_ui->setupUi(this); addAction(m_ui->actionSaveSettings); addAction(m_ui->actionNextTab); addAction(m_ui->actionPrevTab); m_props = m_docview->getOptions(); optionToUi(PROP_FOOTNOTES, m_ui->ShowFootNotes); optionToUi(PROP_SHOW_BATTERY, m_ui->ShowBattery); optionToUi(PROP_SHOW_BATTERY_PERCENT, m_ui->ShowBatteryInPercent); optionToUi(PROP_SHOW_TIME, m_ui->ShowClock); optionToUi(PROP_SHOW_TITLE, m_ui->ShowBookName); optionToUi(PROP_TXT_OPTION_PREFORMATTED, m_ui->TxtPreFormatted); optionToUi(PROP_FLOATING_PUNCTUATION, m_ui->FloatingPunctuation); optionToUi(PROP_STATUS_CHAPTER_MARKS, m_ui->ChapterMarks); optionToUi(PROP_SHOW_POS_PERCENT, m_ui->PositionPercent); int state1 = m_props->getIntDef(PROP_SHOW_PAGE_NUMBER, 1); int state2 = m_props->getIntDef(PROP_SHOW_PAGE_COUNT, 1); m_ui->PageNumber->setCheckState(state1==1 || state2==1? Qt::Checked : Qt::Unchecked); optionToUiInversed(PROP_STATUS_LINE, m_ui->ShowPageHeader); bool checked = !(m_props->getIntDef(PROP_STATUS_LINE, 1)==1); SwitchCBs(checked); m_ui->cbStartupAction->setCurrentIndex(m_props->getIntDef(PROP_APP_START_ACTION, 0 )); int lp = m_props->getIntDef(PROP_LANDSCAPE_PAGES, 2); m_ui->cbViewMode->setCurrentIndex(lp==1 ? 0 : 1); on_cbMarginSide_currentIndexChanged(0); QStringList faceList; crGetFontFaceList(faceList); m_ui->cbTextFontFace->addItems(faceList); m_ui->cbTitleFontFace->addItems(faceList); m_ui->sbTextFontSize->setMinimum(MIN_CR_FONT_SIZE); m_ui->sbTextFontSize->setMaximum(MAX_CR_FONT_SIZE); m_ui->sbTitleFontSize->setMinimum(MIN_CR_HEADER_FONT_SIZE); m_ui->sbTitleFontSize->setMaximum(MAX_CR_HEADER_FONT_SIZE); const char * defFontFace = "Arial"; static const char * goodFonts[] = { "Arial", "Verdana", NULL }; for(int i=0; goodFonts[i]; i++) { if(faceList.indexOf(QString(goodFonts[i]))>=0) { defFontFace = goodFonts[i]; break; } } fontToUi(PROP_FONT_FACE, PROP_FONT_SIZE, m_ui->cbTextFontFace, m_ui->sbTextFontSize, defFontFace); fontToUi(PROP_STATUS_FONT_FACE, PROP_STATUS_FONT_SIZE, m_ui->cbTitleFontFace, m_ui->sbTitleFontSize, defFontFace); m_ui->sbInterlineSpace->setValue(m_props->getIntDef(PROP_INTERLINE_SPACE, 100)); // translations QString v = m_props->getStringDef(PROP_WINDOW_LANG, "English"); QDir Dir(qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/i18n"))); QStringList Filter; Filter << "*.qm"; QStringList Files = Dir.entryList(Filter, QDir::Files, QDir::Name); m_ui->cbLanguage->addItem("English"); foreach(const QString &str, Files) { QString s = str; s.chop(3); m_ui->cbLanguage->addItem(s); } int ind = m_ui->cbLanguage->findText(v); m_ui->cbLanguage->setCurrentIndex(ind != -1 ? ind : 1); int hi = -1; v = m_props->getStringDef(PROP_HYPHENATION_DICT,"@algorithm"); for ( int i=0; i<HyphMan::getDictList()->length(); i++ ) { HyphDictionary * item = HyphMan::getDictList()->get( i ); if ( v == cr2qt(item->getFilename() ) ) hi = i; QString s = cr2qt( item->getTitle() ); if( item->getType()==HDT_NONE) s = tr("[No hyphenation]"); else if( item->getType()==HDT_ALGORITHM) s = tr("[Algorythmic hyphenation]"); m_ui->cbHyphenation->addItem(s); } m_ui->cbHyphenation->setCurrentIndex(hi>=0 ? hi : 1); double fgamma = m_props->getDoubleDef(PROP_FONT_GAMMA, "1"); m_ui->sbFontGamma->setValue(fgamma); lString16 testPhrase = qt2cr(tr("The quick brown fox jumps over the lazy dog. ")); m_ui->crSample->getDocView()->createDefaultDocument(lString16(), testPhrase+testPhrase+testPhrase+testPhrase+testPhrase+testPhrase); updateStyleSample(); initDone = true; } SettingsDlg::~SettingsDlg() { delete m_ui; } bool SettingsDlg::showDlg(QWidget * parent, CR3View * docView) { SettingsDlg * dlg = new SettingsDlg(parent, docView); dlg->showMaximized(); return true; } void SettingsDlg::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } void SettingsDlg::optionToUi( const char * optionName, QCheckBox * cb ) { int state = m_props->getIntDef(optionName, 1); cb->setCheckState(state==1 ? Qt::Checked : Qt::Unchecked); } void SettingsDlg::optionToUiInversed( const char * optionName, QCheckBox * cb ) { int state = m_props->getIntDef(optionName, 1); cb->setCheckState(state==1 ? Qt::Unchecked : Qt::Checked); } void SettingsDlg::setCheck(const char * optionName, bool checkState) { m_props->setInt(optionName, checkState); } void SettingsDlg::on_cbViewMode_currentIndexChanged(int index) { if(!initDone) return; m_props->setInt(PROP_LANDSCAPE_PAGES, index + 1); m_props->setInt(PROP_PAGE_VIEW_MODE, 1); } void SettingsDlg::on_ShowPageHeader_toggled(bool checked) { if(!initDone) return; setCheck(PROP_STATUS_LINE, !checked); SwitchCBs(checked); } void SettingsDlg::on_ShowBookName_toggled(bool checked) { if(!initDone) return; setCheck(PROP_SHOW_TITLE, checked); } void SettingsDlg::on_ShowClock_toggled(bool checked) { if(!initDone) return; setCheck(PROP_SHOW_TIME, checked); } void SettingsDlg::on_ShowBattery_toggled(bool checked) { if(!initDone) return; setCheck(PROP_SHOW_BATTERY, checked); } void SettingsDlg::on_ShowBatteryInPercent_toggled(bool checked) { if(!initDone) return; setCheck(PROP_SHOW_BATTERY_PERCENT, checked); } void SettingsDlg::on_ShowFootNotes_toggled(bool checked) { if(!initDone) return; setCheck(PROP_FOOTNOTES, checked); } void SettingsDlg::updateStyleSample() { int i; m_props->getInt(PROP_FONT_SIZE, i); m_ui->crSample->propsApply(m_props); LVDocView *dv = m_ui->crSample->getDocView(); dv->setShowCover(false); dv->setViewMode(DVM_SCROLL, 1); dv->getPageImage(0); } void SettingsDlg::on_cbTitleFontFace_currentIndexChanged(QString s) { if(!initDone) return; m_props->setString(PROP_STATUS_FONT_FACE, s); } void SettingsDlg::on_cbTextFontFace_currentIndexChanged(QString s) { if(!initDone) return; m_props->setString(PROP_FONT_FACE, s); updateStyleSample(); } void SettingsDlg::fontToUi( const char * faceOptionName, const char * sizeOptionName, QComboBox * faceCombo, QSpinBox * sizeSpinBox, const char * defFontFace ) { QString faceName = m_props->getStringDef(faceOptionName, defFontFace); int faceIndex = faceCombo->findText(faceName); if(faceIndex>=0) faceCombo->setCurrentIndex(faceIndex); int size; m_props->getInt(sizeOptionName, size); sizeSpinBox->setValue(size); } void SettingsDlg::on_cbHyphenation_currentIndexChanged(int index) { if(!initDone) return; const QStringList & dl(m_docview->getHyphDicts()); QString s = dl[index < dl.count() ? index : 1]; m_props->setString(PROP_HYPHENATION_DICT, s); } void SettingsDlg::on_cbStartupAction_currentIndexChanged(int index) { if(!initDone) return; m_props->setInt(PROP_APP_START_ACTION, index); } void SettingsDlg::on_cbLanguage_currentIndexChanged(const QString &arg1) { if(!initDone) return; m_props->setString(PROP_WINDOW_LANG, arg1); } void SettingsDlg::on_sbFontGamma_valueChanged(double arg1) { if(!initDone) return; m_props->setString(PROP_FONT_GAMMA, QString::number(arg1)); updateStyleSample(); } void SettingsDlg::on_actionSaveSettings_triggered() { m_docview->setOptions(m_props); close(); } void SettingsDlg::on_actionNextTab_triggered() { int CurrInd = m_ui->tabWidget->currentIndex(); if(CurrInd+1 == m_ui->tabWidget->count()) m_ui->tabWidget->setCurrentIndex(0); else m_ui->tabWidget->setCurrentIndex(CurrInd+1); } void SettingsDlg::on_actionPrevTab_triggered() { int CurrInd = m_ui->tabWidget->currentIndex(); if(CurrInd == 0) m_ui->tabWidget->setCurrentIndex(m_ui->tabWidget->count()-1); else m_ui->tabWidget->setCurrentIndex(CurrInd-1); } void SettingsDlg::on_sbTextFontSize_valueChanged(int arg1) { if(!initDone) return; m_props->setInt(PROP_FONT_SIZE, arg1); updateStyleSample(); } void SettingsDlg::on_sbTitleFontSize_valueChanged(int arg1) { if(!initDone) return; m_props->setInt(PROP_STATUS_FONT_SIZE, arg1); updateStyleSample(); } void SettingsDlg::on_sbInterlineSpace_valueChanged(int arg1) { if(!initDone) return; int newValue = m_docview->GetArrayNextValue(cr_interline_spaces, sizeof(cr_interline_spaces)/sizeof(int), m_props->getIntDef(PROP_INTERLINE_SPACE, 100), arg1); if(newValue!=arg1) m_ui->sbInterlineSpace->setValue(newValue); m_props->setInt(PROP_INTERLINE_SPACE, newValue); updateStyleSample(); } void SettingsDlg::on_TxtPreFormatted_toggled(bool checked) { if(!initDone) return; setCheck(PROP_TXT_OPTION_PREFORMATTED, checked); } void SettingsDlg::on_FloatingPunctuation_toggled(bool checked) { if(!initDone) return; setCheck(PROP_FLOATING_PUNCTUATION, checked); } void SettingsDlg::on_ChapterMarks_toggled(bool checked) { if(!initDone) return; setCheck(PROP_STATUS_CHAPTER_MARKS, checked); } void SettingsDlg::on_PositionPercent_toggled(bool checked) { if(!initDone) return; setCheck(PROP_SHOW_POS_PERCENT, checked); } void SettingsDlg::on_PageNumber_toggled(bool checked) { if(!initDone) return; setCheck(PROP_SHOW_PAGE_NUMBER, checked); setCheck(PROP_SHOW_PAGE_COUNT, checked); } void SettingsDlg::SwitchCBs(bool state) { m_ui->ShowBattery->setEnabled(state); m_ui->ShowBatteryInPercent->setEnabled(state); m_ui->ShowClock->setEnabled(state); m_ui->ShowBookName->setEnabled(state); m_ui->ChapterMarks->setEnabled(state); m_ui->PositionPercent->setEnabled(state); m_ui->PageNumber->setEnabled(state); } #define DEF_MARGIN 8 int GetMaxMargin(PropsRef props) { int top = props->getIntDef(PROP_PAGE_MARGIN_TOP, DEF_MARGIN); int bottom = props->getIntDef(PROP_PAGE_MARGIN_BOTTOM, DEF_MARGIN); int left = props->getIntDef(PROP_PAGE_MARGIN_LEFT, DEF_MARGIN); int right = props->getIntDef(PROP_PAGE_MARGIN_RIGHT, DEF_MARGIN); // get maximum int value = top>bottom ? top : bottom; value = value>left ? value : left; value = value>right ? value : right; } void SettingsDlg::on_cbMarginSide_currentIndexChanged(int index) { switch(index) { case 0: m_ui->sbMargin->setValue(m_props->getIntDef(PROP_PAGE_MARGIN_TOP, DEF_MARGIN)); break; case 1: m_ui->sbMargin->setValue(m_props->getIntDef(PROP_PAGE_MARGIN_BOTTOM, DEF_MARGIN)); break; case 2: m_ui->sbMargin->setValue(m_props->getIntDef(PROP_PAGE_MARGIN_LEFT, DEF_MARGIN)); break; case 3: m_ui->sbMargin->setValue(m_props->getIntDef(PROP_PAGE_MARGIN_RIGHT, DEF_MARGIN)); break; case 4: m_ui->sbMargin->setValue(GetMaxMargin(m_props)); } on_sbMargin_valueChanged(m_ui->sbMargin->value()); } void SettingsDlg::on_sbMargin_valueChanged(int arg1) { if(!initDone) return; int prevValue; int index = m_ui->cbMarginSide->currentIndex(); switch(index) { case 0: prevValue = m_props->getIntDef(PROP_PAGE_MARGIN_TOP, 8); break; case 1: prevValue = m_props->getIntDef(PROP_PAGE_MARGIN_BOTTOM, 8); break; case 2: prevValue = m_props->getIntDef(PROP_PAGE_MARGIN_LEFT, 8); break; case 3: prevValue = m_props->getIntDef(PROP_PAGE_MARGIN_RIGHT, 8); break; case 4: prevValue = GetMaxMargin(m_props); } int newValue = m_docview->GetArrayNextValue(def_margin, sizeof(def_margin)/sizeof(int), prevValue, arg1); if(newValue!=arg1) m_ui->sbMargin->setValue(newValue); switch(index) { case 0: m_props->setInt(PROP_PAGE_MARGIN_TOP, newValue); break; case 1: m_props->setInt(PROP_PAGE_MARGIN_BOTTOM, newValue); break; case 2: m_props->setInt(PROP_PAGE_MARGIN_LEFT, newValue); break; case 3: m_props->setInt(PROP_PAGE_MARGIN_RIGHT, newValue); break; case 4: { m_props->setInt(PROP_PAGE_MARGIN_TOP, newValue); m_props->setInt(PROP_PAGE_MARGIN_BOTTOM, newValue); m_props->setInt(PROP_PAGE_MARGIN_LEFT, newValue); m_props->setInt(PROP_PAGE_MARGIN_RIGHT, newValue); } } }
C++
#include "bookmarklistdlg.h" #include "ui_bookmarklistdlg.h" #define MAX_ITEM_LEN 50 static QString limit(QString s) { if(s.length() < MAX_ITEM_LEN) return s; s = s.left( MAX_ITEM_LEN ); return s + "..."; } BookmarkListDialog::BookmarkListDialog(QWidget *parent, CR3View * docView ) : QDialog(parent), m_ui(new Ui::BookmarkListDialog), _docview(docView) { m_ui->setupUi(this); addAction(m_ui->actionRemoveBookmark); addAction(m_ui->actionRemoveAllBookmarks); QAction *actionSelect = m_ui->actionSelectBookmark; actionSelect->setShortcut(Qt::Key_Select); addAction(actionSelect); int i = 0; m_ui->tableWidget->horizontalHeader()->setResizeMode( i++, QHeaderView::ResizeToContents); m_ui->tableWidget->horizontalHeader()->setResizeMode( i++, QHeaderView::Stretch ); m_ui->tableWidget->horizontalHeader()->setStretchLastSection(true); m_ui->tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); CRFileHistRecord * rec = _docview->getDocView()->getCurrentFileHistRecord(); if (!rec) return; LVPtrVector<CRBookmark> & list( rec->getBookmarks() ); int curpercent = _docview->getDocView()->getPosPercent(); int bestdiff = -1; int bestindex = -1; int y = 0; for ( int i=0; i<list.length(); i++ ) { CRBookmark * bm = list[i]; if ( bm->getType() == bmkt_lastpos ) continue; int diff = bm->getPercent() - curpercent; if ( diff < 0 ) diff = -diff; if ( bestindex==-1 || diff < bestdiff ) { bestindex = i; bestdiff = diff; } m_ui->tableWidget->setRowCount(y+1); { int i=0; _list.append( bm ); m_ui->tableWidget->setItem( y, i++, new QTableWidgetItem(crpercent( bm->getPercent()))); m_ui->tableWidget->setItem( y, i++, new QTableWidgetItem(limit(cr2qt(bm->getPosText())))); m_ui->tableWidget->verticalHeader()->setResizeMode(y, QHeaderView::ResizeToContents); } y++; } if (bestindex>=0) m_ui->tableWidget->selectRow(bestindex); m_ui->tableWidget->resizeColumnsToContents(); m_ui->tableWidget->resizeRowsToContents(); } BookmarkListDialog::~BookmarkListDialog() { delete m_ui; } bool BookmarkListDialog::showDlg( QWidget * parent, CR3View * docView ) { BookmarkListDialog *dlg = new BookmarkListDialog(parent, docView); dlg->showMaximized(); return true; } void BookmarkListDialog::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } CRBookmark * BookmarkListDialog::selectedBookmark() { int index = m_ui->tableWidget->currentRow(); if ( index<0 || index>=_list.length() || index>=m_ui->tableWidget->rowCount() ) return NULL; return _list[index]; } void BookmarkListDialog::on_actionRemoveBookmark_triggered() { CRBookmark * bm = selectedBookmark(); if ( bm ) { int index = m_ui->tableWidget->currentRow(); m_ui->tableWidget->removeRow(index); _list.removeAt(index); _docview->getDocView()->removeBookmark(bm); } } void BookmarkListDialog::on_actionRemoveAllBookmarks_triggered() { int rowcount = m_ui->tableWidget->rowCount(); while(rowcount) { CRBookmark * bm = _list[rowcount-1]; _docview->getDocView()->removeBookmark(bm); m_ui->tableWidget->removeRow(rowcount-1); --rowcount; } _list.clear(); } void BookmarkListDialog::on_actionSelectBookmark_triggered() { CRBookmark * bm = selectedBookmark(); if(bm) { _docview->goToBookmark(bm); close(); } }
C++
#ifndef SETTINGSDLG_H #define SETTINGSDLG_H #include <QDialog> #include <QCheckBox> #include <QComboBox> #include <QSpinBox> #include <QWSEvent> #include <QColorDialog> #include <QStyleFactory> #include <QDir> #include <QMessageBox> #include <QTranslator> #include "crqtutil.h" #include "cr3widget.h" namespace Ui { class SettingsDlg; } #define PROP_APP_START_ACTION "cr3.app.start.action" #define PROP_WINDOW_LANG "window.language" class CR3View; class SettingsDlg : public QDialog { Q_OBJECT Q_DISABLE_COPY(SettingsDlg) public: virtual ~SettingsDlg(); static bool showDlg(QWidget * parent, CR3View * docView); protected: explicit SettingsDlg(QWidget *parent, CR3View * docView ); virtual void changeEvent(QEvent *e); void setCheck(const char * optionName, bool checkState); void optionToUi( const char * optionName, QCheckBox * cb ); void setCheckInversed( const char * optionName, int checkState ); void optionToUiInversed( const char * optionName, QCheckBox * cb ); void fontToUi( const char * faceOptionName, const char * sizeOptionName, QComboBox * faceCombo, QSpinBox * sizeSpinBox, const char * defFontFace ); void updateStyleSample(); private: Ui::SettingsDlg *m_ui; CR3View * m_docview; PropsRef m_props; void SwitchCBs(bool state); private slots: void on_cbStartupAction_currentIndexChanged(int index); void on_cbHyphenation_currentIndexChanged(int index); void on_cbTextFontFace_currentIndexChanged(QString); void on_cbTitleFontFace_currentIndexChanged(QString); void on_cbViewMode_currentIndexChanged(int index); void on_cbLanguage_currentIndexChanged(const QString &arg1); void on_ShowFootNotes_toggled(bool checked); void on_ShowBattery_toggled(bool checked); void on_ShowBatteryInPercent_toggled(bool checked); void on_ShowClock_toggled(bool checked); void on_ShowBookName_toggled(bool checked); void on_ShowPageHeader_toggled(bool checked); void on_TxtPreFormatted_toggled(bool checked); void on_FloatingPunctuation_toggled(bool checked); void on_ChapterMarks_toggled(bool checked); void on_PositionPercent_toggled(bool checked); void on_PageNumber_toggled(bool checked); void on_sbFontGamma_valueChanged(double arg1); void on_sbTextFontSize_valueChanged(int arg1); void on_sbTitleFontSize_valueChanged(int arg1); void on_sbInterlineSpace_valueChanged(int arg1); void on_actionSaveSettings_triggered(); void on_actionNextTab_triggered(); void on_actionPrevTab_triggered(); void on_cbMarginSide_currentIndexChanged(int index); void on_sbMargin_valueChanged(int arg1); }; #endif // SETTINGSDLG_H
C++
#ifndef VIRTUALKEYSDLG_H #define VIRTUALKEYSDLG_H #include <QDialog> #include <QEvent> #include <QKeyEvent> #include <QtGui/QLineEdit> #include "lvstring.h" #include "cr3widget.h" namespace Ui { class VirtualKeysDialog; } class VirtualKeysDialog : public QDialog { Q_OBJECT public: VirtualKeysDialog(QWidget *parent, QLineEdit * editView); ~VirtualKeysDialog(); static bool showDlg( QWidget * parent, QLineEdit * editView ); private slots: void on_actionNextTab_triggered(); void on_actionPrevTab_triggered(); private: CR3View * _docview; QLineEdit * _editline; lString16 _lastPattern; Ui::VirtualKeysDialog *ui; }; #endif // VIRTUALKEYSDLG_H
C++
#include "tocdlg.h" #include "ui_tocdlg.h" #include <QKeyEvent> #include <math.h> #include "mainwindow.h" #include "ui_mainwindow.h" class TocItem : public QTreeWidgetItem { LVTocItem * _item; public: LVTocItem * getItem() { return _item; } TocItem(LVTocItem * item, int currPage, int & nearestPage, TocItem * & nearestItem) : QTreeWidgetItem(QStringList() << (item ? cr2qt(item->getName()) : "No TOC items") << (item ? cr2qt(lString16::itoa(item->getPage()+1)) : "")) , _item(item) { setTextAlignment(1, Qt::AlignRight|Qt::AlignVCenter); int page = item->getPage(); if (!nearestItem || (page <= currPage && page > nearestPage)) { nearestItem = this; nearestPage = page; } setData(0, Qt::UserRole, QVariant(cr2qt(item->getXPointer().toString()))); for (int i = 0; i < item->getChildCount(); i++) { addChild(new TocItem(item->getChild(i), currPage, nearestPage, nearestItem)); } } }; bool TocDlg::showDlg(QWidget * parent, CR3View * docView) { TocDlg * dlg = new TocDlg(parent, docView); dlg->showMaximized(); return true; } TocDlg::TocDlg(QWidget *parent, CR3View * docView) : QDialog(parent), m_ui(new Ui::TocDlg), m_docview(docView) { setAttribute(Qt::WA_DeleteOnClose, true); m_ui->setupUi(this); addAction(m_ui->actionNextPage); addAction(m_ui->actionPrevPage); addAction(m_ui->actionUpdatePage); QAction *actionSelect = m_ui->actionGotoPage; actionSelect->setShortcut(Qt::Key_Select); addAction(actionSelect); m_ui->treeWidget->setColumnCount(2); m_ui->treeWidget->header()->setResizeMode(0, QHeaderView::Stretch); m_ui->treeWidget->header()->setResizeMode(1, QHeaderView::ResizeToContents); int nearestPage = -1; int currPage = docView->getCurPage(); TocItem * nearestItem = NULL; LVTocItem * root = m_docview->getToc(); for (int i=0; i<root->getChildCount(); i++ ) m_ui->treeWidget->addTopLevelItem(new TocItem(root->getChild(i), currPage, nearestPage, nearestItem)); m_ui->treeWidget->expandAll(); if(nearestItem) m_ui->treeWidget->setCurrentItem(nearestItem); m_ui->pageNumEdit->setValidator(new QIntValidator(1, 999999999, this)); m_ui->pageNumEdit->installEventFilter(this); m_ui->treeWidget->installEventFilter(this); // code added 28.11.2011 countItems = 0; countItemsTotal = getMaxItemPosFromBegin(m_docview->getToc(),m_ui->treeWidget->currentItem(),0); isPageUpdated = false; } TocDlg::~TocDlg() { delete m_ui; } void TocDlg::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } void TocDlg::showEvent(QShowEvent *e) { fillOpts(); titleMask = windowTitle(); curPage = 1; // code added 28.11.2011 isPageUpdated = false; setCurrentItemPage(); titleMask = tr("Table of Contents"); updateTitle(); } void TocDlg::updateTitle() { int pagenum = m_docview->getCurPage()+1; setWindowTitle(titleMask + " (" + QString::number(curPage) + "/" + QString::number(pageCount) + ")" +QString(" "+QString::number(pagenum) ).rightJustified(24,' ',true) ); } void TocDlg::on_actionGotoPage_triggered() { int pagenum; if(m_ui->pageNumEdit->text().lastIndexOf('%')>0){ int percentNum = m_ui->pageNumEdit->text().left(m_ui->pageNumEdit->text().length()-1).toInt(); pagenum = ceil((double)m_docview->getPageCount()*percentNum/100); if(percentNum == 0) pagenum = 1; } else pagenum = m_ui->pageNumEdit->text().toInt(); if(pagenum && pagenum <= m_docview->getPageCount()) { m_docview->getDocView()->savePosToNavigationHistory(); m_docview->GoToPage(pagenum-1); close(); } else { // code added 28.11.2011 qDebug(focusWidget()->objectName().toAscii().data()); QString s = m_ui->treeWidget->currentIndex().data(Qt::UserRole).toString(); m_docview->goToXPointer(s); close(); } } bool TocDlg::eventFilter(QObject *obj, QEvent *event) { if(event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); QString text; switch(keyEvent->key()) { case Qt::Key_Q: text = "1"; break; case Qt::Key_W: text = "2"; break; case Qt::Key_E: text = "3"; break; case Qt::Key_R: text = "4"; break; case Qt::Key_T: text = "5"; break; case Qt::Key_Y: text = "6"; break; case Qt::Key_U: text = "7"; break; case Qt::Key_I: text = "8"; break; case Qt::Key_O: text = "9"; break; case Qt::Key_P: text = "0"; break; case 0x2e: text = "%"; break; case 0x01001103: text = "%"; break; // code added 28.11.2011 case Qt::Key_Up: //// if(obj == m_ui->treeWidget) { { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } int cur_num = getCurrentItemPosFromBegin(m_docview->getToc(),m_ui->treeWidget->currentItem(), 0); if((cur_num<=((curPage-1)*pageStrCount)+1) && (curPage==pageCount) && (pageCount>2)){ moveUpPage(); moveDownPage(); } moveUp(); } //// } break; // code added 28.11.2011 case Qt::Key_Down: //// if(obj == m_ui->treeWidget) { moveDown(); //// } break; case Qt::Key_Select: qDebug(focusWidget()->objectName().toAscii().data()); //// if(obj == m_ui->treeWidget) { { QString s = m_ui->treeWidget->currentIndex().data(Qt::UserRole).toString(); m_docview->goToXPointer(s); close(); return true; //// } } break; } if(keyEvent->key() >= Qt::Key_0 && keyEvent->key() <= Qt::Key_9) text = keyEvent->text(); if(!text.isEmpty()) { if(m_ui->pageNumEdit->text().lastIndexOf('%')>0) return true; if(text == QString('%')) { if(m_ui->pageNumEdit->text().toDouble()>100) return true; } m_ui->pageNumEdit->setText(m_ui->pageNumEdit->text() + text); return true; } } return false; } void TocDlg::moveUp(){ if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } int cur_num = getCurrentItemPosFromBegin(m_docview->getToc(),m_ui->treeWidget->currentItem(), 0); QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); // для отладки if((cur_num<=((curPage-1)*pageStrCount)+1) || (cur_num==1)){ // last page if((curPage-1)==0){ curPage=pageCount; scrollBar->setMaximum((pageCount-1) * pageStrCount); scrollBar->setValue(curPage*pageStrCount-pageStrCount); updateTitle(); ////break; return; } // previous page if(curPage-1>=1) { curPage-=1; scrollBar->setValue(scrollBar->value()-pageStrCount); updateTitle(); } } } void TocDlg::moveDown() { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } int cur_num = getCurrentItemPosFromBegin(m_docview->getToc(),m_ui->treeWidget->currentItem(), 0); int r_num = getMaxItemPosFromBegin(m_docview->getToc(),m_ui->treeWidget->currentItem(),0); QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); // для отладки if((cur_num>=(curPage*pageStrCount)) || (cur_num==r_num)){ // first page if(curPage+1>pageCount){ curPage=1; scrollBar->setValue(0); updateTitle(); return; } // next page if(curPage+1<=pageCount) { curPage+=1; scrollBar->setMaximum((pageCount-1) * pageStrCount); scrollBar->setValue(curPage*pageStrCount-pageStrCount); updateTitle(); } } } // code added 28.11.2011 int TocDlg::getCurrentItemPosFromBegin(LVTocItem * item_top,QTreeWidgetItem * LevelItem,int level) { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } // поиск позиции выделенного элемента в дереве int cur_num; if(level == 0){ cur_num = 0; countItems = 0; } for (int i=0; i<item_top->getChildCount(); i++ ) { countItems+=1; QTreeWidgetItem * LevelItem1 = LevelItem->child(i); if(level==0) LevelItem1 = m_ui->treeWidget->topLevelItem(i); if(LevelItem1 == m_ui->treeWidget->currentItem()) cur_num=countItems; if(cur_num>0) return cur_num;//break; if(LevelItem1->isExpanded()) cur_num = getCurrentItemPosFromBegin(item_top->getChild(i),LevelItem1, level+1); if(cur_num>0) return cur_num;//break; } return cur_num; } // code added 28.11.2011 int TocDlg::getMaxItemPosFromBegin(LVTocItem * item_top,QTreeWidgetItem * LevelItem,int level) { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } // подсчёт всего сколько элементов в дереве int r_num = item_top->getChildCount(); if(level == 0) countItems = 0; for (int i=0; i<item_top->getChildCount(); i++ ) { countItems+=1; QTreeWidgetItem * LevelItem1 = LevelItem->child(i); if(level==0) LevelItem1 = m_ui->treeWidget->topLevelItem(i); if(LevelItem1->isExpanded()) { r_num = r_num + getMaxItemPosFromBegin(item_top->getChild(i),LevelItem1, level+1); } else { } } if((level==0) && (r_num!=countItems)) r_num = countItems; return r_num; } // code added 28.11.2011 int TocDlg::getCurrentItemPage() { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); pageStrCount = scrollBar->pageStep(); int page_num = 1; int iCurrentItemPos = getCurrentItemPosFromBegin(m_docview->getToc(),m_ui->treeWidget->currentItem(), 0); if(iCurrentItemPos>pageStrCount) page_num = ceil((double)iCurrentItemPos/pageStrCount); return page_num; } void TocDlg::setCurrentItemPage() { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); int nearest_Page = getCurrentItemPage(); if((curPage!=nearest_Page) && (nearest_Page>1)){ if((nearest_Page==pageCount) && (pageCount>1)) { curPage=pageCount-1; scrollBar->setValue(scrollBar->value()-pageStrCount); updateTitle(); } // тут ошибка непонятная возникает с позиционированием скролбара на последней странице curPage = nearest_Page; scrollBar->setMaximum((pageCount-1) * pageStrCount); scrollBar->setValue(curPage*pageStrCount-pageStrCount); updateTitle(); } } // code added 28.11.2011 bool TocDlg::setCurrentItemFirstInPage(int page_num,LVTocItem * item_top,QTreeWidgetItem * LevelItem,int level) { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } // выбор первого на странице элемента при PageUp или PageDown QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); int cur_num = page_num*pageStrCount-pageStrCount+1; bool found_flag = false; if(level == 0) countItems = 0; for (int i=0; i<item_top->getChildCount(); i++ ) { countItems+=1; if(countItems == cur_num) { if(level == 0) m_ui->treeWidget->setCurrentItem(m_ui->treeWidget->topLevelItem(i)); else m_ui->treeWidget->setCurrentItem(LevelItem->child(i)); return true; } QTreeWidgetItem * LevelItem1 = LevelItem->child(i); if(level==0) LevelItem1 = m_ui->treeWidget->topLevelItem(i); if(LevelItem1->isExpanded()) { found_flag = setCurrentItemFirstInPage(page_num,item_top->getChild(i),LevelItem1, level+1); } else { // page recount } if(found_flag) return true; } return found_flag; } void TocDlg::moveDownPage() { if(curPage+1<=pageCount) { curPage+=1; QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); scrollBar->setMaximum((pageCount-1) * pageStrCount); scrollBar->setValue(curPage*pageStrCount-pageStrCount); //m_ui->treeWidget->setCurrentItem(); // code added 28.11.2011 //setCurrentItemFirstInPage(curPage); setCurrentItemFirstInPage(curPage,m_docview->getToc(),m_ui->treeWidget->currentItem(),0); updateTitle(); } } void TocDlg::moveUpPage() { if(curPage-1>=1) { curPage-=1; QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); scrollBar->setValue(scrollBar->value()-pageStrCount); // code added 28.11.2011 setCurrentItemFirstInPage(curPage,m_docview->getToc(),m_ui->treeWidget->currentItem(),0); updateTitle(); } } void TocDlg::on_actionUpdatePage_triggered() { isPageUpdated = true; // code added 28.11.2011 // page recount fillOpts(); updateTitle(); } void TocDlg::on_actionNextPage_triggered() { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } moveDownPage(); } void TocDlg::on_actionPrevPage_triggered() { if(isPageUpdated) { on_actionUpdatePage_triggered(); isPageUpdated = false; } if((curPage==pageCount) && (pageCount>2)){ moveUpPage(); moveDownPage(); } moveUpPage(); } void TocDlg::fillOpts() { QScrollBar * scrollBar = m_ui->treeWidget->verticalScrollBar(); pageStrCount = scrollBar->pageStep(); fullStrCount = scrollBar->maximum()-scrollBar->minimum()+pageStrCount; if(fullStrCount==pageStrCount) { pageCount = 1; return; } if(pageStrCount==1) { scrollBar->setMaximum(fullStrCount*2); pageStrCount = scrollBar->pageStep(); } pageCount = ceil((double)fullStrCount/pageStrCount); } void TocDlg::on_treeWidget_activated(const QModelIndex &index) { }
C++
#ifndef SEARCHDLG_H #define SEARCHDLG_H #include <QDialog> #include <QMessageBox> #include <QPainter> #include <QEvent> #include <QKeyEvent> #include <QWSEvent> #include <QDebug> #include "lvstring.h" #include "cr3widget.h" #include "virtualkeysdlg.h" namespace Ui { class SearchDialog; } class CR3View; class SearchDialog : public QDialog { Q_OBJECT public: SearchDialog(QWidget *parent, CR3View * docView); ~SearchDialog(); static bool showDlg( QWidget * parent, CR3View * docView ); bool findText( lString16 pattern, int origin, bool reverse, bool caseInsensitive ); protected: void changeEvent(QEvent *e); virtual void paintEvent (QPaintEvent * event); bool eventFilter(QObject *obj, QEvent *event); private: Ui::SearchDialog *ui; CR3View * _docview; lString16 _lastPattern; bool isKeyboardAlt; private slots: void on_btnFindNext_clicked(); void on_rbForward_toggled(bool checked); void on_rbBackward_toggled(bool checked); void on_actionVirtualKeys_triggered(); }; #endif // SEARCHDLG_H
C++
// CoolReader3 / Qt // main.cpp - entry point #include "mainwindow.h" MyApplication *pMyApp; int main(int argc, char *argv[]) { int res = 0; { lString16 exedir = LVExtractPath(LocalToUnicode(lString8(argv[0]))); LVAppendPathDelimiter(exedir); lString16 datadir = exedir + L"data/"; lString16 exefontpath = exedir + L"fonts"; lString16Collection fontDirs; fontDirs.add(exefontpath); #ifndef i386 fontDirs.add(lString16(L"/usr/java/lib/fonts")); fontDirs.add(lString16(L"/mnt/us/fonts")); #endif CRPropRef props = LVCreatePropsContainer(); { LVStreamRef cfg = LVOpenFileStream(UnicodeToUtf8(datadir + L"cr3.ini").data(), LVOM_READ); if(!cfg.isNull()) props->loadFromStream(cfg.get()); } lString16 lang = props->getStringDef(PROP_WINDOW_LANG, ""); // InitCREngineLog("./data/cr3.ini"); InitCREngineLog(props); CRLog::info("main()"); if(!InitCREngine(argv[0], fontDirs)) { printf("Cannot init CREngine - exiting\n"); return 2; } #ifndef i386 PrintString(1, 1, "crengine version: " + QString(CR_ENGINE_VERSION), "-c"); // open framebuffer device and read out info int fd = open("/dev/fb0", O_RDONLY); struct fb_var_screeninfo screeninfo; ioctl(fd, FBIOGET_VSCREENINFO, &screeninfo); int width = screeninfo.xres; int height = screeninfo.yres; QString message = "Please wait while application is loading..."; int xpos = ((width/12-1)-message.length())/2; int ypos = (height/20-2)/2; PrintString(xpos, ypos, message); #endif // set row count int rc = props->getIntDef(PROP_WINDOW_ROW_COUNT, 0); if(!rc) { #ifndef i386 props->setInt(PROP_WINDOW_ROW_COUNT, height==800 ? 10 : 16); #else props->setInt(PROP_WINDOW_ROW_COUNT, 10); #endif LVStreamRef cfg = LVOpenFileStream(UnicodeToUtf8(datadir + L"cr3.ini").data(), LVOM_WRITE); props->saveToStream(cfg.get()); } QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); MyApplication a(argc, argv); pMyApp = &a; // set app stylesheet #ifndef i386 QFile qss(QDir::toNativeSeparators(cr2qt(datadir)) + (width==600 ? "stylesheet_k3.qss" : "stylesheet_dx.qss")); #else QFile qss(QDir::toNativeSeparators(cr2qt(datadir)) + "stylesheet.qss"); #endif qss.open(QFile::ReadOnly); if(qss.error() == QFile::NoError) { a.setStyleSheet(qss.readAll()); qss.close(); } QString translations = cr2qt(datadir) + "i18n"; QTranslator myappTranslator; if(!lang.empty() && lang.compare(L"English")) { if(myappTranslator.load(cr2qt(lang), translations)) QApplication::installTranslator(&myappTranslator); else qDebug("Can`t load translation file %s from dir %s", UnicodeToUtf8(lang).c_str(), UnicodeToUtf8(qt2cr(translations)).c_str()); } MainWindow mainWin; mainWin.showFullScreen(); mainWin.doStartupActions(); res = a.exec(); } ShutdownCREngine(); return res; } void ShutdownCREngine() { HyphMan::uninit(); ShutdownFontManager(); CRLog::setLogger(NULL); } bool getDirectoryFonts( lString16Collection & pathList, lString16 ext, lString16Collection & fonts, bool absPath ) { int foundCount = 0; lString16 path; for (unsigned di=0; di<pathList.length();di++ ) { path = pathList[di]; LVContainerRef dir = LVOpenDirectory(path.c_str()); if(!dir.isNull()) { CRLog::trace("Checking directory %s", UnicodeToUtf8(path).c_str() ); for(int i=0; i < dir->GetObjectCount(); i++ ) { const LVContainerItemInfo * item = dir->GetObjectInfo(i); lString16 fileName = item->GetName(); if ( !item->IsContainer() && fileName.length()>4 && lString16(fileName, fileName.length()-4, 4)==ext ) { lString16 fn; if ( absPath ) { fn = path; if (!fn.empty() && fn[fn.length()-1]!=PATH_SEPARATOR_CHAR) fn << PATH_SEPARATOR_CHAR; } fn << fileName; foundCount++; fonts.add(fn); } } } } return foundCount > 0; } bool InitCREngine( const char * exename, lString16Collection & fontDirs) { CRLog::trace("InitCREngine(%s)", exename); InitFontManager(lString8()); // Load font definitions into font manager // fonts are in files font1.lbf, font2.lbf, ... font32.lbf // use fontconfig lString16 fontExt = L".ttf"; lString16Collection fonts; getDirectoryFonts( fontDirs, fontExt, fonts, true ); // load fonts from file CRLog::debug("%d font files found", fonts.length()); if (!fontMan->GetFontCount()) { for ( unsigned fi=0; fi<fonts.length(); fi++ ) { lString8 fn = UnicodeToLocal(fonts[fi]); CRLog::trace("loading font: %s", fn.c_str()); if ( !fontMan->RegisterFont(fn) ) CRLog::trace(" failed\n"); } } if (!fontMan->GetFontCount()) { printf("Fatal Error: Cannot open font file(s) .ttf \nCannot work without font\n" ); return false; } printf("%d fonts loaded.\n", fontMan->GetFontCount()); return true; } void InitCREngineLog(CRPropRef props) { if(props.isNull()) { CRLog::setStdoutLogger(); CRLog::setLogLevel( CRLog::LL_FATAL); return; } lString16 logfname = props->getStringDef(PROP_LOG_FILENAME, "stdout"); #ifdef _DEBUG // lString16 loglevelstr = props->getStringDef(PROP_LOG_LEVEL, "DEBUG"); lString16 loglevelstr = props->getStringDef(PROP_LOG_LEVEL, "OFF"); #else lString16 loglevelstr = props->getStringDef(PROP_LOG_LEVEL, "OFF"); #endif bool autoFlush = props->getBoolDef(PROP_LOG_AUTOFLUSH, false); CRLog::log_level level = CRLog::LL_INFO; if ( loglevelstr==L"OFF" ) { level = CRLog::LL_FATAL; logfname.clear(); } else if ( loglevelstr==L"FATAL" ) { level = CRLog::LL_FATAL; } else if ( loglevelstr==L"ERROR" ) { level = CRLog::LL_ERROR; } else if ( loglevelstr==L"WARN" ) { level = CRLog::LL_WARN; } else if ( loglevelstr==L"INFO" ) { level = CRLog::LL_INFO; } else if ( loglevelstr==L"DEBUG" ) { level = CRLog::LL_DEBUG; } else if ( loglevelstr==L"TRACE" ) { level = CRLog::LL_TRACE; } if ( !logfname.empty() ) { if ( logfname==L"stdout" ) CRLog::setStdoutLogger(); else if ( logfname==L"stderr" ) CRLog::setStderrLogger(); else CRLog::setFileLogger(UnicodeToUtf8( logfname ).c_str(), autoFlush); } CRLog::setLogLevel(level); CRLog::trace("Log initialization done."); } bool myEventFilter(void *message, long *) { QWSEvent * pev = (QWSEvent *) message; if(pev->type == QWSEvent::Key) { QWSKeyEvent *pke = (QWSKeyEvent *) message; QWidget *active, *modal, *popup; active = qApp->activeWindow(); modal = qApp->activeModalWidget(); popup = qApp->activePopupWidget(); // qDebug("act=%d, modal=%d, pup=%d", (int)active, (int)modal, (int)popup); #ifdef i386 if(pke->simpleData.keycode == Qt::Key_Return) { pke->simpleData.keycode = Qt::Key_Select; return false; } #endif if(pke->simpleData.keycode == Qt::Key_Sleep) { pMyApp->disconnectPowerDaemon(); return true; } if(pke->simpleData.keycode == Qt::Key_WakeUp) { if(!active->isFullScreen() && !active->isMaximized()) { QWidget *mainwnd = qApp->widgetAt(0,0); mainwnd->repaint(); } active->repaint(); pMyApp->connectPowerDaemon(); return true; } // qDebug("QWS key: key=%x, press=%x, uni=%x", pke->simpleData.keycode, pke->simpleData.is_press, pke->simpleData.unicode); return false; } return false; } void PrintString(int x, int y, const QString message, const QString opt) { QStringList list; QProcess *myProcess = new QProcess(); if(!opt.isEmpty()) list << opt; list << QString().number(x) << QString().number(y) << message; myProcess->start("/usr/sbin/eips", list); }
C++
#include "virtualkeysdlg.h" #include "ui_virtualkeysdlg.h" #include <QKeyEvent> #include <QSettings> VirtualKeysDialog::VirtualKeysDialog(QWidget *parent, QLineEdit * editView) : QDialog(parent), ui(new Ui::VirtualKeysDialog), _editline( editView ) { ui->setupUi(this); addAction(ui->actionNextTab); addAction(ui->actionPrevTab); ui->tabWidget->setCurrentIndex(0); ui->tableWidget->setFocus(); } bool VirtualKeysDialog::showDlg( QWidget * parent, QLineEdit * editView ) { VirtualKeysDialog *dlg = new VirtualKeysDialog(parent, editView); dlg->setWindowFlags(dlg->windowType() | Qt::FramelessWindowHint); dlg->show(); //editView->setText(QString('123')); return true; } VirtualKeysDialog::~VirtualKeysDialog() { // delete ui; } void VirtualKeysDialog::on_actionNextTab_triggered() { int CurrInd = ui->tabWidget->currentIndex(); if(CurrInd+1 == ui->tabWidget->count()) ui->tabWidget->setCurrentIndex(0); else ui->tabWidget->setCurrentIndex(CurrInd+1); } void VirtualKeysDialog::on_actionPrevTab_triggered() { int CurrInd = ui->tabWidget->currentIndex(); if(CurrInd == 0) ui->tabWidget->setCurrentIndex(ui->tabWidget->count()-1); else ui->tabWidget->setCurrentIndex(CurrInd-1); }
C++
#include "searchdlg.h" #include "ui_searchdlg.h" #include <QKeyEvent> #include <QSettings> bool SearchDialog::showDlg( QWidget * parent, CR3View * docView ) { SearchDialog *dlg = new SearchDialog(parent, docView); dlg->setWindowFlags(dlg->windowType() | Qt::FramelessWindowHint); dlg->show(); return true; } SearchDialog::SearchDialog(QWidget *parent, CR3View * docView) : QDialog(parent), ui(new Ui::SearchDialog), _docview( docView ) { ui->setupUi(this); ui->cbCaseSensitive->setCheckState(Qt::Unchecked); ui->rbForward->toggle(); ui->edPattern->installEventFilter(this); isKeyboardAlt = false; addAction(ui->actionVirtualKeys); } void SearchDialog::paintEvent (QPaintEvent * event) { QPainter painter(this); painter.drawRect(0, 0, width()-1, height()-1); } SearchDialog::~SearchDialog() { delete ui; } void SearchDialog::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } bool SearchDialog::eventFilter(QObject *obj, QEvent *event) { QSettings keyboard_settings("data/keyboard_alt.ini", QSettings::IniFormat); if(event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); QString text; bool isSHIFT = (keyEvent->modifiers()==Qt::ShiftModifier); bool isALT = (keyEvent->modifiers()==Qt::AltModifier); switch(keyEvent->key()) { case Qt::Key_Space: if(isSHIFT) { if(isKeyboardAlt) isKeyboardAlt = false; else isKeyboardAlt = true; } break; } if(isKeyboardAlt) text = text.fromUtf8( keyboard_settings.value( keyEvent->text() ).toString().toAscii() ); if(text.length()>0) { ui->edPattern->setText(ui->edPattern->text() + text); return true; } } return false; } bool SearchDialog::findText( lString16 pattern, int origin, bool reverse, bool caseInsensitive ) { if ( pattern.empty() ) return false; if ( pattern!=_lastPattern && origin==1 ) origin = 0; _lastPattern = pattern; LVArray<ldomWord> words; lvRect rc; _docview->getDocView()->GetPos( rc ); int pageHeight = rc.height(); int start = -1; int end = -1; if ( reverse ) { // reverse if ( origin == 0 ) { // from end current page to first page end = rc.bottom; } else if ( origin == -1 ) { // from last page to end of current page start = rc.bottom; } else { // origin == 1 // from prev page to first page end = rc.top; } } else { // forward if ( origin == 0 ) { // from current page to last page start = rc.top; } else if ( origin == -1 ) { // from first page to current page end = rc.top; } else { // origin == 1 // from next page to last start = rc.bottom; } } CRLog::debug("CRViewDialog::findText: Current page: %d .. %d", rc.top, rc.bottom); CRLog::debug("CRViewDialog::findText: searching for text '%s' from %d to %d origin %d", LCSTR(pattern), start, end, origin ); if ( _docview->getDocView()->getDocument()->findText( pattern, caseInsensitive, reverse, start, end, words, 200, pageHeight ) ) { CRLog::debug("CRViewDialog::findText: pattern found"); _docview->getDocView()->clearSelection(); _docview->getDocView()->selectWords( words ); ldomMarkedRangeList * ranges = _docview->getDocView()->getMarkedRanges(); if ( ranges ) { if ( ranges->length()>0 ) { int pos = ranges->get(0)->start.y; _docview->getDocView()->SetPos(pos); } } return true; } CRLog::debug("CRViewDialog::findText: pattern not found"); return false; } void SearchDialog::on_btnFindNext_clicked() { bool found = false; QString pattern = ui->edPattern->text(); lString16 p16 = qt2cr(pattern); bool reverse = ui->rbBackward->isChecked(); bool caseInsensitive = ui->cbCaseSensitive->checkState()!=Qt::Checked; found = findText(p16, 1, reverse , caseInsensitive); if ( !found ) found = findText(p16, -1, reverse, caseInsensitive); if ( !found ) { QMessageBox * mb = new QMessageBox( QMessageBox::Information, tr("Not found"), tr("Search pattern is not found in document"), QMessageBox::Close, this ); mb->setButtonText(QMessageBox::Close,tr("Close")); mb->exec(); } else { _docview->getDocView()->savePosToNavigationHistory(); _docview->update(); } } void SearchDialog::on_rbForward_toggled(bool checked) { ui->rbBackward->setChecked(!checked); } void SearchDialog::on_rbBackward_toggled(bool checked) { ui->rbForward->setChecked(!checked); } void SearchDialog::on_actionVirtualKeys_triggered() { VirtualKeysDialog::showDlg( this, ui->edPattern ); }
C++
#ifndef CRQTUTIL_H #define CRQTUTIL_H #include <QString> #include <QSharedPointer> #include "crengine.h" lString16 qt2cr( QString str ); QString cr2qt( lString16 str ); class Props; typedef QSharedPointer<Props> PropsRef; /// proxy class for CoolReader properties class Props { public: static PropsRef create(); static PropsRef clone( PropsRef v ); virtual int count() = 0; virtual const char * name( int index ) = 0; virtual QString value( int index ) = 0; virtual bool getString( const char * prop, QString & result ) = 0; virtual QString getStringDef( const char * prop, const char * defValue ) = 0; virtual void setString( const char * prop, const QString & value ) = 0; virtual void setInt( const char * prop, int value ) = 0; virtual bool getInt( const char * prop, int & result ) = 0; virtual int getIntDef( const char * prop, int defValue ) = 0; virtual void setHex( const char * propName, int value ) = 0; virtual bool hasProperty( const char * propName ) const = 0; virtual const CRPropRef & accessor() = 0; virtual ~Props() { } // fau+ virtual double getDoubleDef(const char * prop, const char * defValue) = 0; virtual void setDouble(const char * prop, const double value) = 0; }; /// returns common items from props1 not containing in props2 PropsRef operator - ( PropsRef props1, PropsRef props2 ); /// returns common items containing in props1 or props2 PropsRef operator | ( PropsRef props1, PropsRef props2 ); /// returns common items of props1 and props2 PropsRef operator & ( PropsRef props1, PropsRef props2 ); /// returns added or changed items of props2 compared to props1 PropsRef operator ^ ( PropsRef props1, PropsRef props2 ); /// adapter from coolreader property collection to qt PropsRef cr2qt( CRPropRef & ref ); /// adapter from qt property collection to coolreader const CRPropRef & qt2cr( PropsRef & ref ); void cr2qt( QStringList & dst, const lString16Collection & src ); void qt2cr( lString16Collection & dst, const QStringList & src ); /// format p as percent*100 - e.g. 1234->"12.34%" QString crpercent( int p ); // fau+ QString crFileSize(int size); void crGetFontFaceList( QStringList & dst ); class QWidget; /// save window position to properties //void saveWindowPosition( QWidget * window, CRPropRef props, const char * prefix ); /// restore window position from properties //void restoreWindowPosition( QWidget * window, CRPropRef props, const char * prefix, bool allowFullscreen = false ); #endif // CRQTUTIL_H
C++
#ifndef BOOKMARKLISTDLG_H #define BOOKMARKLISTDLG_H #include <QDialog> #include <QModelIndex> #include <QMenu> #include "cr3widget.h" namespace Ui { class BookmarkListDialog; } class CR3View; class CRBookmark; class BookmarkListDialog : public QDialog { Q_OBJECT public: ~BookmarkListDialog(); static bool showDlg( QWidget * parent, CR3View * docView); protected: explicit BookmarkListDialog(QWidget *parent, CR3View * docView); void changeEvent(QEvent *e); private: Ui::BookmarkListDialog *m_ui; CR3View * _docview; QList<CRBookmark*> _list; CRBookmark * selectedBookmark(); private slots: void on_actionRemoveBookmark_triggered(); void on_actionRemoveAllBookmarks_triggered(); void on_actionSelectBookmark_triggered(); }; #endif // BOOKMARKLISTDLG_H
C++
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <sys/ioctl.h> #include <fcntl.h> #include <linux/fb.h> #include <QApplication> #include <QMainWindow> #include <QtDBus/QDBusConnection> #include <QProcess> #include <QDebug> #include <QDecorationDefault> #include <QTranslator> #include <QTextCodec> #include <QClipboard> #include "cr3widget.h" #include "crqtutil.h" #include "crgui.h" #include "crengine.h" #include "lvstring.h" #include "lvtinydom.h" #include "settings.h" #include "searchdlg.h" #include "openfiledlg.h" #include "tocdlg.h" #include "recentdlg.h" #include "bookmarklistdlg.h" #include "filepropsdlg.h" #define CMD_REFRESH 1001 #define CMD_ZOOM_FONT 1002 #define CMD_ZOOM_HEADER_FONT 1003 #define CMD_TOGGLE_HEADER 1004 #define CMD_JUMP_FROM_PAGE 1005 #define CMD_CHANGE_FONT 1006 #define CMD_CHANGE_HEADER_FONT 1007 #define CMD_CHANGE_FONT_GAMMA 1008 #define CMD_INTERLINE_SPACE 1009 // prototypes void InitCREngineLog(CRPropRef props); bool InitCREngine(const char * exename, lString16Collection & fontDirs); void ShutdownCREngine(); bool getDirectoryFonts( lString16Collection & pathList, lString16 ext, lString16Collection & fonts, bool absPath ); bool myEventFilter(void *message, long *result); #ifndef i386 void PrintString(int x, int y, const QString message, const QString opt = ""); #endif class MyDecoration : public QDecorationDefault { private: int titleHeight; public: MyDecoration() : QDecorationDefault() { titleHeight = qApp->font().pointSize() + 20; } QRegion region(const QWidget *widget, const QRect &rect, int decorationRegion = All) { // all QRegion region; QRect r(rect.left(), rect.top() - titleHeight, rect.width(), rect.height() + titleHeight); region = r; region -= rect; return region; } bool paint(QPainter *painter, const QWidget *widget, int decorationRegion = All, DecorationState state = Normal) { if(decorationRegion == None) return false; const QRect titleRect = QDecoration::region(widget, Title).boundingRect(); int titleWidth = titleRect.width(); Qt::WindowFlags flags = widget->windowFlags(); bool hasTitle = flags & Qt::WindowTitleHint; bool paintAll = (decorationRegion == int(All)); bool handled = false; if ((paintAll || decorationRegion & Title && titleWidth > 0) && state == Normal && hasTitle) { painter->save(); painter->fillRect(titleRect, QBrush(Qt::black)); painter->setPen(QPen(Qt::white)); QFont font = qApp->font(); font.setBold(true); painter->setFont(font); painter->drawText(titleRect.x() + 4, titleRect.y(), titleRect.width(), titleRect.height(), Qt::AlignVCenter, windowTitleFor(widget)); painter->restore(); handled |= true; } return handled; } }; class MyApplication : public QApplication { Q_OBJECT public: MyApplication(int &argc, char **argv) : QApplication(argc, argv) { connectPowerDaemon(); QPalette palette; palette.setColor(QPalette::Window, Qt::white); palette.setColor(QPalette::WindowText, Qt::black); palette.setColor(QPalette::Base, Qt::white); palette.setColor(QPalette::AlternateBase, Qt::white); palette.setColor(QPalette::Text, Qt::black); palette.setColor(QPalette::Button, Qt::white); palette.setColor(QPalette::ButtonText, Qt::black); palette.setColor(QPalette::Highlight, Qt::white); palette.setColor(QPalette::HighlightedText, Qt::black); setPalette(palette); setStyle("cleanlooks"); qwsSetDecoration(new MyDecoration()); setNavigationMode(Qt::NavigationModeKeypadTabOrder); setEventFilter(myEventFilter); } void connectPowerDaemon() { #ifndef i386 QDBusConnection::systemBus().connect(QString(), QString(), "com.lab126.powerd", "outOfScreenSaver", this, SLOT(quitscreensaver())); // QDBusConnection::systemBus().connect(QString(), QString(), "com.lab126.powerd", "goingToScreenSaver", this, SLOT(screensaver())); #endif } void disconnectPowerDaemon() { #ifndef i386 QDBusConnection::systemBus().disconnect(QString(), QString(), "com.lab126.powerd", "outOfScreenSaver", this, SLOT(quitscreensaver())); // QDBusConnection::systemBus().disconnect(QString(), QString(), "com.lab126.powerd", "goingToScreenSaver", this, SLOT(MainWindow::screensaver())); #endif } private slots: void quitscreensaver() { sleep(3); if(!activeWindow()->isFullScreen() && !activeWindow()->isMaximized()) { QWidget *mainwnd = widgetAt(0,0); mainwnd->repaint(); } activeWindow()->repaint(); } }; namespace Ui { class MainWindowClass; } class MainWindow : public QMainWindow, public PropsChangeCallback { Q_OBJECT public: virtual void onPropsChange(PropsRef props); MainWindow(QWidget *parent = 0); ~MainWindow(); void doStartupActions(); private: Ui::MainWindowClass *ui; QString _filenameToOpen; CRGUIAcceleratorTableRef wndkeys; bool loadKeymaps(CRGUIWindowManager & winman, const char * locations[]); void doCommand(int cmd, int param = 0); bool isReservedKey(int key); protected: public slots: void contextMenu( QPoint pos ); void on_actionFindText_triggered(); private slots: void on_actionFileProperties_triggered(); void on_actionShowBookmarksList_triggered(); void on_actionAddBookmark_triggered(); void on_actionSettings_triggered(); void on_actionRecentBooks_triggered(); void on_actionTOC_triggered(); void on_actionPrevPage_triggered(); void on_actionNextPage_triggered(); void on_actionClose_triggered(); void on_actionOpen_triggered(); void on_actionShowMenu_triggered(); void on_actionEmpty_triggered(); private slots: void battLevelChanged(int fparam); }; #endif // MAINWINDOW_H
C++
#ifndef FILEPROPSDLG_H #define FILEPROPSDLG_H #include <QtGui/QDialog> #include <QItemDelegate> #include "lvdocview.h" #include "cr3version.h" #include "cr3widget.h" namespace Ui { class FilePropsDialog; } class FilePropsListDelegate : public QItemDelegate { public: FilePropsListDelegate(QObject *pobj = 0) : QItemDelegate(pobj) { } void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem newOption; QVariant value; newOption = option; value = index.data(Qt::UserRole); if(value.isValid() && !value.isNull()) { newOption.font.setPointSize(newOption.font.pointSize()-value.toInt()); } QItemDelegate::paint(painter, newOption, index); } }; class CR3View; class LVDocView; class FilePropsDialog : public QDialog { Q_OBJECT public: ~FilePropsDialog(); static bool showDlg( QWidget * parent, CR3View * docView ); protected: QString getDocText( const char * path, const char * delim ); QString getDocAuthors( const char * path, const char * delim ); void fillItems(); void addPropLine( QString name, QString value); void addInfoSection(QString name); explicit FilePropsDialog(QWidget *parent, CR3View * docView ); void changeEvent(QEvent *e); QString _value; private: Ui::FilePropsDialog *m_ui; CR3View * _cr3v; LVDocView * _docview; }; #endif // FILEPROPSDLG_H
C++
#include "mainwindow.h" #include "ui_mainwindow.h" #define DOC_CACHE_SIZE 128 * 0x100000 #define ENABLE_BOOKMARKS_DIR 1 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindowClass) { ui->setupUi(this); addAction(ui->actionOpen); addAction(ui->actionRecentBooks); addAction(ui->actionTOC); addAction(ui->actionSettings); addAction(ui->actionAddBookmark); addAction(ui->actionShowBookmarksList); addAction(ui->actionFindText); addAction(ui->actionFileProperties); // addAction(ui->actionCopy); QAction *actionShowMenu = ui->actionShowMenu; #ifdef i386 actionShowMenu->setShortcut(Qt::Key_M); #else actionShowMenu->setShortcut(Qt::Key_Menu); #endif addAction(actionShowMenu); QAction *actionClose = ui->actionClose; actionClose->setShortcut(Qt::ALT + Qt::Key_Escape); actionClose->setText(tr("Close") + "\tAlt+Back"); addAction(actionClose); QString dataDir = qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/")); QString cacheDir = dataDir + "cache"; QString bookmarksDir = dataDir + "bookmarks"; QString histFile = dataDir + "cr3hist.bmk"; QString iniFile = dataDir + "cr3.ini"; QString cssFile = dataDir + "fb2.css"; QString hyphDir = dataDir + "hyph" + QDir::separator(); ldomDocCache::init(qt2cr(cacheDir), DOC_CACHE_SIZE); ui->view->setPropsChangeCallback(this); ui->view->loadCSS(cssFile); ui->view->setHyphDir(hyphDir); ui->view->loadSettings(iniFile); ui->view->loadHistory(histFile); #if ENABLE_BOOKMARKS_DIR==1 ui->view->setBookmarksDir(bookmarksDir); #endif QString def = dataDir + "keydefs.ini"; QString map = dataDir + "keymaps.ini"; CRGUIAcceleratorTableList tables; if(tables.openFromFile(def.toAscii(), map.toAscii())) { wndkeys = tables.get(lString16("mainwindow")); if(wndkeys->length()>0) { for(unsigned i=0; i<wndkeys->length(); i++) { const CRGUIAccelerator * acc = wndkeys->get(i); int cmd = acc->commandId; int param = acc->commandParam; int key = acc->keyCode; int keyFlags = acc->keyFlags; if(isReservedKey(key + keyFlags)) continue; QString cmdstr; if(cmd) cmdstr = QString::number(cmd); if(param) cmdstr+= "|" + QString::number(param); if(!cmdstr.isEmpty()) { QAction *newAct = new QAction(this); newAct->setShortcut(key + keyFlags); newAct->setText(cmdstr); connect(newAct, SIGNAL(triggered()), this, SLOT(on_actionEmpty_triggered())); addAction(newAct); } // qDebug("cmd %i param %i key %i keyflag %i", cmd, param, key, keyFlags); } const CRGUIAccelerator *acc1 = wndkeys->findKeyAccelerator(Qt::Key_PageDown, 0); const CRGUIAccelerator *acc2 = wndkeys->findKeyAccelerator(Qt::Key_PageUp, 0); if(!acc1 || !acc2) { addAction(ui->actionNextPage); addAction(ui->actionPrevPage); } } } else { addAction(ui->actionNextPage); addAction(ui->actionPrevPage); } ui->view->getDocView()->setBatteryState(100); #ifndef i386 QDBusConnection::systemBus().connect(QString(), QString(), "com.lab126.powerd", "battLevelChanged", this, SLOT(battLevelChanged(int))); QStringList list; QProcess *myProcess = new QProcess(); list << "com.lab126.powerd" << "battLevel"; myProcess->start("/usr/bin/lipc-get-prop", list); if(myProcess->waitForReadyRead(1000)) { QByteArray array = myProcess->readAll(); array.truncate(array.indexOf("\n")); ui->view->getDocView()->setBatteryState(array.toInt()); } #endif } void MainWindow::battLevelChanged(int fparam) { #ifndef i386 ui->view->getDocView()->setBatteryState(fparam); #endif } MainWindow::~MainWindow() { #ifndef i386 QDBusConnection::systemBus().disconnect(QString(), QString(), "com.lab126.powerd", "battLevelChanged", this, SLOT(battLevelChanged(int))); #endif delete ui; } void MainWindow::on_actionOpen_triggered() { OpenFileDlg::showDlg(this, ui->view); } void MainWindow::on_actionClose_triggered() { close(); } //void elemwalker(ldomXPointerEx & node) //{ // qDebug(" word: %d", node.isText()) ; //} void MainWindow::on_actionNextPage_triggered() { doCommand(DCMD_PAGEDOWN); } void MainWindow::on_actionPrevPage_triggered() { doCommand(DCMD_PAGEUP); } void MainWindow::on_actionTOC_triggered() { TocDlg::showDlg(this, ui->view); } void MainWindow::on_actionRecentBooks_triggered() { RecentBooksDlg::showDlg(this, ui->view ); } void MainWindow::on_actionSettings_triggered() { SettingsDlg::showDlg(this, ui->view); } void MainWindow::onPropsChange(PropsRef props) { } void MainWindow::contextMenu( QPoint pos ) { QMenu *menu = new QMenu; menu->addAction(ui->actionOpen); menu->addAction(ui->actionRecentBooks); menu->addAction(ui->actionTOC); menu->addAction(ui->actionFindText); menu->addAction(ui->actionSettings); menu->addAction(ui->actionFileProperties); menu->addAction(ui->actionShowBookmarksList); menu->addAction(ui->actionAddBookmark); menu->addAction(ui->actionClose); menu->exec(ui->view->mapToGlobal(pos)); } void MainWindow::doStartupActions() { switch(ui->view->getOptions()->getIntDef(PROP_APP_START_ACTION, 0)) { case 0: // open recent book ui->view->loadLastDocument(); break; case 1: // show recent books dialog RecentBooksDlg::showDlg(this, ui->view); break; case 2: // show file open dialog OpenFileDlg::showDlg(this, ui->view); } } void MainWindow::on_actionAddBookmark_triggered() { ui->view->createBookmark(); } void MainWindow::on_actionShowBookmarksList_triggered() { BookmarkListDialog::showDlg(this, ui->view); } void MainWindow::on_actionFileProperties_triggered() { FilePropsDialog::showDlg(this, ui->view); } void MainWindow::on_actionFindText_triggered() { SearchDialog::showDlg(this, ui->view); } void MainWindow::on_actionShowMenu_triggered() { contextMenu(QPoint(5,5)); } void MainWindow::on_actionEmpty_triggered() { QAction *a = qobject_cast<QAction *>(sender()); if(a) { QString cmdstr = a->text(); int cmd = 0; int param = 0; int pos = cmdstr.indexOf("|"); if(pos!=-1) { param = cmdstr.mid(pos+1).toInt(); cmd = cmdstr.mid(0, pos).toInt(); } else cmd = cmdstr.toInt(); doCommand(cmd, param); } } bool MainWindow::isReservedKey(int key) { switch(key) { case Qt::Key_Menu: case Qt::Key_O: case Qt::Key_L: case Qt::Key_C: case Qt::Key_F: case Qt::Key_S: case Qt::Key_I: case Qt::Key_B: case Qt::SHIFT + Qt::Key_B: case Qt::ALT + Qt::Key_Escape: case Qt::ALT + Qt::SHIFT: return true; default: return false; } } void MainWindow::doCommand(int cmd, int param) { switch(cmd) { case CMD_TOGGLE_HEADER: ui->view->toggleProperty(PROP_STATUS_LINE); break; case CMD_REFRESH: ui->view->repaint(); break; case CMD_ZOOM_FONT: ui->view->zoomFont(param); break; case CMD_ZOOM_HEADER_FONT: ui->view->zoomHeaderFont(param); break; case CMD_JUMP_FROM_PAGE: { int pagenum = ui->view->getCurPage() + param; ui->view->doCommand(DCMD_GO_PAGE, pagenum); ui->view->update(); break; } case CMD_CHANGE_FONT_GAMMA: ui->view->ChangeFontGamma(param); break; case CMD_CHANGE_FONT: ui->view->ChangeFont(param); break; case CMD_CHANGE_HEADER_FONT: ui->view->ChangeHeaderFont(param); break; case CMD_INTERLINE_SPACE: ui->view->ChangeInterlineSpace(param); break; case DCMD_ROTATE_BY: ui->view->Rotate(param); break; case DCMD_LINK_BACK: case DCMD_LINK_FORWARD: ui->view->doCommand(cmd, 1); break; case DCMD_PAGEDOWN: case DCMD_PAGEUP: case DCMD_BEGIN: case DCMD_END: case DCMD_MOVE_BY_CHAPTER: case DCMD_TOGGLE_BOLD: ui->view->doCommand(cmd, param); } }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <comdef.h> #include "ffactivex.h" #include "scriptable.h" #include "axhost.h" #ifdef NO_REGISTRY_AUTHORIZE static const char *WellKnownProgIds[] = { NULL }; static const char *WellKnownClsIds[] = { NULL }; #endif static const bool AcceptOnlyWellKnown = false; static const bool TrustWellKnown = true; static bool isWellKnownProgId(const char *progid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!progid) { return false; } while (WellKnownProgIds[i]) { if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i]))) return true; ++i; } return false; #else return true; #endif } static bool isWellKnownClsId(const char *clsid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!clsid) { return false; } while (WellKnownClsIds[i]) { if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i]))) return true; ++i; } return false; #else return true; #endif } static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT result; CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA); if (!host) { return DefWindowProc(hWnd, msg, wParam, lParam); } switch (msg) { case WM_SETFOCUS: case WM_KILLFOCUS: case WM_SIZE: if (host->Site) { host->Site->OnDefWindowMessage(msg, wParam, lParam, &result); return result; } else { return DefWindowProc(hWnd, msg, wParam, lParam); } // Window being destroyed case WM_DESTROY: break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return true; } CAxHost::~CAxHost() { log(instance, 0, "AxHost.~AXHost: destroying the control..."); if (Window){ if (OldProc) ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } if (Sink) { Sink->UnsubscribeFromEvents(); Sink->Release(); } if (Site) { Site->Detach(); Site->Release(); } CoFreeUnusedLibraries(); } CAxHost::CAxHost(NPP inst): instance(inst), ClsID(CLSID_NULL), isValidClsID(false), Sink(NULL), Site(NULL), Window(NULL), OldProc(NULL), Props(), isKnown(false), CodeBaseUrl(NULL) { } void CAxHost::setWindow(HWND win) { if (win != Window) { if (win) { // subclass window so we can intercept window messages and // do our drawing to it OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc); // associate window with our CAxHost object so we can access // it in the window procedure ::SetWindowLong(win, GWL_USERDATA, (LONG)this); } else { if (OldProc) ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Window = win; } } HWND CAxHost::getWinfow() { return Window; } void CAxHost::UpdateRect(RECT rcPos) { HRESULT hr = -1; if (Site && Window) { if (Site->GetParentWindow() == NULL) { hr = Site->Attach(Window, rcPos, NULL); if (FAILED(hr)) { log(instance, 0, "AxHost.UpdateRect: failed to attach control"); } } else { Site->SetPosition(rcPos); } // Ensure clipping on parent to keep child controls happy ::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN); } } bool CAxHost::verifyClsID(LPOLESTR oleClsID) { CRegKey keyExplorer; if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"), KEY_READ)) { CRegKey keyCLSID; if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) { DWORD dwType = REG_DWORD; DWORD dwFlags = 0; DWORD dwBufSize = sizeof(dwFlags); if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID, _T("Compatibility Flags"), NULL, &dwType, (LPBYTE) &dwFlags, &dwBufSize)) { // Flags for this reg key const DWORD kKillBit = 0x00000400; if (dwFlags & kKillBit) { log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits"); return false; } } } } log(instance, 1, "AxHost.verifyClsID: verified successfully"); return true; } bool CAxHost::setClsID(const char *clsid) { HRESULT hr = -1; USES_CONVERSION; LPOLESTR oleClsID = A2OLE(clsid); if (isWellKnownClsId(clsid)) { isKnown = true; } else if (AcceptOnlyWellKnown) { log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list"); return false; } // Check the Internet Explorer list of vulnerable controls if (oleClsID && verifyClsID(oleClsID)) { hr = CLSIDFromString(oleClsID, &ClsID); if (SUCCEEDED(hr) && !::IsEqualCLSID(ClsID, CLSID_NULL)) { isValidClsID = true; log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid); return true; } } log(instance, 0, "AxHost.setClsID: failed to set the requested clsid"); return false; } void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl) { CodeBaseUrl = codeBaseUrl; } bool CAxHost::setClsIDFromProgID(const char *progid) { HRESULT hr = -1; CLSID clsid = CLSID_NULL; USES_CONVERSION; LPOLESTR oleClsID = NULL; LPOLESTR oleProgID = A2OLE(progid); if (AcceptOnlyWellKnown) { if (isWellKnownProgId(progid)) { isKnown = true; } else { log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list"); return false; } } hr = CLSIDFromProgID(oleProgID, &clsid); if (FAILED(hr)) { log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID"); return false; } hr = StringFromCLSID(clsid, &oleClsID); // Check the Internet Explorer list of vulnerable controls if ( SUCCEEDED(hr) && oleClsID && verifyClsID(oleClsID)) { ClsID = clsid; if (!::IsEqualCLSID(ClsID, CLSID_NULL)) { isValidClsID = true; log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid); return true; } } log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID"); return false; } bool CAxHost::hasValidClsID() { return isValidClsID; } bool CAxHost::CreateControl(bool subscribeToEvents) { if (!isValidClsID) { log(instance, 0, "AxHost.CreateControl: current location is not trusted"); return false; } // Create the control site CControlSiteInstance::CreateInstance(&Site); if (Site == NULL) { log(instance, 0, "AxHost.CreateControl: CreateInstance failed"); return false; } Site->m_bSupportWindowlessActivation = false; if (TrustWellKnown && isKnown) { Site->SetSecurityPolicy(NULL); Site->m_bSafeForScriptingObjectsOnly = false; } else { Site->m_bSafeForScriptingObjectsOnly = true; } Site->AddRef(); // Create the object HRESULT hr; hr = Site->Create(ClsID, Props, CodeBaseUrl); if (FAILED(hr)) { LPSTR lpMsgBuf; DWORD dw = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &lpMsgBuf, 0, NULL ); log(instance, 0, lpMsgBuf); log(instance, 0, "AxHost.CreateControl: failed to create site"); return false; } IUnknown *control = NULL; Site->GetControlUnknown(&control); if (!control) { log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)"); return false; } // Create the event sink CControlEventSinkInstance::CreateInstance(&Sink); Sink->AddRef(); Sink->instance = instance; hr = Sink->SubscribeToEvents(control); control->Release(); if (FAILED(hr) && subscribeToEvents) { LPSTR lpMsgBuf; DWORD dw = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &lpMsgBuf, 0, NULL ); log(instance, 0, lpMsgBuf); log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed"); return false; } log(instance, 1, "AxHost.CreateControl: control created successfully"); return true; } bool CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler) { HRESULT hr; DISPID id = 0; USES_CONVERSION; LPOLESTR oleName = name; if (!Sink) { log(instance, 0, "AxHost.AddEventHandler: no valid sink"); return false; } hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id); if (FAILED(hr)) { log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name"); return false; } Sink->events[id] = handler; log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name); return true; } int16 CAxHost::HandleEvent(void *event) { NPEvent *npEvent = (NPEvent *)event; LRESULT result = 0; if (!npEvent) { return 0; } // forward all events to the hosted control return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result); } NPObject * CAxHost::GetScriptableObject() { IUnknown *unk; NPObject *obj = NPNFuncs.createobject(instance, &ScriptableNPClass); Site->GetControlUnknown(&unk); ((Scriptable *)obj)->setControl(unk); ((Scriptable *)obj)->setInstance(instance); return obj; }
C++
// stdafx.cpp : source file that includes just the standard includes // ffactivex.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass ScriptableNPClass; class Scriptable: public NPObject { private: Scriptable(const Scriptable &); // This method iterates all members of the current interface, looking for the member with the // id of member_id. If not found within this interface, it will iterate all base interfaces // recursively, until a match is found, or all the hierarchy was searched. bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) { bool found = false; unsigned int i = 0; FUNCDESC *fDesc; for (i = 0; (i < attr->cFuncs) && !found; ++i) { HRESULT hr = info->GetFuncDesc(i, &fDesc); if ( SUCCEEDED(hr) && fDesc && (fDesc->memid == member_id)) { if (invKind & fDesc->invkind) found = true; } info->ReleaseFuncDesc(fDesc); } if (!found && (invKind & ~INVOKE_FUNC)) { VARDESC *vDesc; for (i = 0; (i < attr->cVars) && !found; ++i) { HRESULT hr = info->GetVarDesc(i, &vDesc); if ( SUCCEEDED(hr) && vDesc && (vDesc->memid == member_id)) { found = true; } info->ReleaseVarDesc(vDesc); } } if (!found) { // iterate inherited interfaces HREFTYPE refType = NULL; for (i = 0; (i < attr->cImplTypes) && !found; ++i) { ITypeInfoPtr baseInfo; TYPEATTR *baseAttr; if (FAILED(info->GetRefTypeOfImplType(0, &refType))) { continue; } if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) { continue; } if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) { continue; } found = find_member(baseInfo, baseAttr, member_id, invKind); baseInfo->ReleaseTypeAttr(baseAttr); } } return found; } DISPID ResolveName(NPIdentifier name, unsigned int invKind) { bool found = false; DISPID dID = -1; USES_CONVERSION; if (!name || !invKind) { return -1; } if (!NPNFuncs.identifierisstring(name)) { return -1; } NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name); LPOLESTR oleName = A2W(npname); IDispatchPtr disp = control.GetInterfacePtr(); if (!disp) { return -1; } disp->GetIDsOfNames(IID_NULL, &oleName, 1, LOCALE_SYSTEM_DEFAULT, &dID); if (dID != -1) { ITypeInfoPtr info; disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info); if (!info) { return -1; } TYPEATTR *attr; if (FAILED(info->GetTypeAttr(&attr))) { return -1; } found = find_member(info, attr, dID, invKind); info->ReleaseTypeAttr(attr); } return found ? dID : -1; } bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult) { IDispatchPtr disp = control.GetInterfacePtr(); if (!disp) { return false; } HRESULT hr = disp->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, pDispParams, pVarResult, NULL, NULL); return (SUCCEEDED(hr)) ? true : false; } IUnknownPtr control; NPP instance; bool invalid; public: Scriptable(): invalid(false), control(NULL), instance(NULL) { } ~Scriptable() {control->Release();} void setControl(IUnknown *unk) {control = unk;} void setControl(IDispatch *disp) {disp->QueryInterface(IID_IUnknown, (void **)&control);} void setInstance(NPP inst) {instance = inst;} void Invalidate() {invalid = true;} static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((Scriptable *)npobj)->Invoke(name, args, argCount, result); } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((Scriptable *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((Scriptable *)npobj)->SetProperty(name, value); } bool HasMethod(NPIdentifier name) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_FUNC); return (id != -1) ? true : false; } bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_FUNC); if (-1 == id) { return false; } VARIANT *vArgs = NULL; if (argCount) { vArgs = new VARIANT[argCount]; if (!vArgs) { return false; } for (unsigned int i = 0; i < argCount; ++i) { // copy the arguments in reverse order NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance); } } DISPPARAMS params = {NULL, NULL, 0, 0}; params.cArgs = argCount; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = vArgs; VARIANT vResult; bool rc = InvokeControl(id, DISPATCH_METHOD, &params, &vResult); if (vArgs) delete[] vArgs; if (!rc) { return false; } Variant2NPVar(&vResult, result, instance); return true; } bool HasProperty(NPIdentifier name) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT); return (id != -1) ? true : false; } bool GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYGET); if (-1 == id) { return false; } DISPPARAMS params; params.cArgs = 0; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = NULL; VARIANT vResult; if (!InvokeControl(id, DISPATCH_PROPERTYGET, &params, &vResult)) { return false; } Variant2NPVar(&vResult, result, instance); return true; } bool SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYPUT); if (-1 == id) { return false; } VARIANT val; NPVar2Variant(value, &val, instance); DISPPARAMS params; // Special initialization needed when using propery put. DISPID dispidNamed = DISPID_PROPERTYPUT; params.cNamedArgs = 1; params.rgdispidNamedArgs = &dispidNamed; params.cArgs = 1; params.rgvarg = &val; VARIANT vResult; if (!InvokeControl(id, DISPATCH_PROPERTYPUT, &params, &vResult)) { return false; } return true; } };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // dllmain.cpp : Defines the entry point for the DLL application. #include "ffactivex.h" #include "axhost.h" CComModule _Module; NPNetscapeFuncs NPNFuncs; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } // ============================== // ! Scriptability related code ! // ============================== // // here the plugin is asked by Mozilla to tell if it is scriptable // we should return a valid interface id and a pointer to // nsScriptablePeer interface which we should have implemented // and which should be defined in the corressponding *.xpt file // in the bin/components folder NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; if(instance == NULL) return NPERR_GENERIC_ERROR; CAxHost *host = (CAxHost *)instance->pdata; if(host == NULL) return NPERR_GENERIC_ERROR; switch (variable) { case NPPVpluginNameString: *((char **)value) = "ITSTActiveX"; break; case NPPVpluginDescriptionString: *((char **)value) = "IT Structures ActiveX for Firefox"; break; case NPPVpluginScriptableNPObject: *(NPObject **)value = host->GetScriptableObject(); break; default: rv = NPERR_GENERIC_ERROR; } return rv; } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int32_t NPP_WriteReady (NPP instance, NPStream *stream) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = 0x0fffffff; return rv; } int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = len; return rv; } NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname) { if(instance == NULL) return; } void NPP_Print (NPP instance, NPPrint* printInfo) { if(instance == NULL) return; } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if(instance == NULL) return; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int16 NPP_HandleEvent(NPP instance, void* event) { if(instance == NULL) return 0; int16 rv = 0; CAxHost *host = (CAxHost *)instance->pdata; if (host) rv = host->HandleEvent(event); return rv; } NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) { if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; if(pFuncs->size < sizeof(NPPluginFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; pFuncs->javaClass = NULL; return NPERR_NO_ERROR; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) /* * Initialize the plugin. Called the first time the browser comes across a * MIME Type this plugin is registered to handle. */ NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs) { // _asm {int 3}; if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; #ifdef NDEF // The following statements prevented usage of newer Mozilla sources than installed browser at runtime if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR) return NPERR_INCOMPATIBLE_VERSION_ERROR; if(pFuncs->size < sizeof(NPNetscapeFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; #endif if (!AtlAxWinInit()) { return NPERR_GENERIC_ERROR; } CoInitialize(NULL); _pAtlModule = &_Module; memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs)); memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs))); return NPERR_NO_ERROR; } /* * Shutdown the plugin. Called when no more instanced of this plugin exist and * the browser wants to unload it. */ NPError OSCALL NP_Shutdown(void) { AtlAxWinTerm(); return NPERR_NO_ERROR; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "scriptable.h" static NPObject* AllocateScriptable(NPP npp, NPClass *aClass) { return new Scriptable(); } static void DeallocateScriptable(NPObject *obj) { if (!obj) { return; } Scriptable *s = (Scriptable *)obj; delete s; } static void InvalidateScriptable(NPObject *obj) { if (!obj) { return; } ((Scriptable *)obj)->Invalidate(); } NPClass ScriptableNPClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateScriptable, /* deallocate */ DeallocateScriptable, /* invalidate */ InvalidateScriptable, /* hasMethod */ Scriptable::_HasMethod, /* invoke */ Scriptable::_Invoke, /* invokeDefault */ NULL, /* hasProperty */ Scriptable::_HasProperty, /* getProperty */ Scriptable::_GetProperty, /* setProperty */ Scriptable::_SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <map> #include <vector> #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass GenericNPObjectClass; typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); struct ltnum { bool operator()(long n1, long n2) const { return n1 < n2; } }; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); class GenericNPObject: public NPObject { private: GenericNPObject(const GenericNPObject &); bool invalid; DefaultInvoker defInvoker; void *defInvokerObject; std::vector<NPVariant> numeric_mapper; // the members of alpha mapper can be reassigned to anything the user wishes std::map<const char *, NPVariant, ltstr> alpha_mapper; // these cannot accept other types than they are initially defined with std::map<const char *, NPVariant, ltstr> immutables; public: friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *); GenericNPObject(NPP instance); GenericNPObject(NPP instance, bool isMethodObj); ~GenericNPObject(); void Invalidate() {invalid = true;} void SetDefaultInvoker(DefaultInvoker di, void *context) { defInvoker = di; defInvokerObject = context; } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result); } static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (((GenericNPObject *)npobj)->defInvoker) { return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result); } else { return false; } } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((GenericNPObject *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((GenericNPObject *)npobj)->SetProperty(name, value); } static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->RemoveProperty(name); } static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) { return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount); } bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool RemoveProperty(NPIdentifier name); bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); };
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winreg.h> #include "ffactivex.h" #include "common/stdafx.h" #include "axhost.h" #include "atlutil.h" #include "authorize.h" // ---------------------------------------------------------------------------- #define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/ffactivex\\MimeTypes\\application/x-itst-activex" // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId); BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId); BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value); HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType); // --------------------------------------------------------------------------- HKEY BaseKeys[] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }; // ---------------------------------------------------------------------------- BOOL TestAuthorization (NPP Instance, int16 ArgC, char *ArgN[], char *ArgV[], const char *MimeType) { BOOL ret = FALSE; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; int16 i; char *wrkHref; #ifdef NDEF _asm{int 3}; #endif if (Instance == NULL) { return (FALSE); } // Determine owning document // Get the window object. NPNFuncs.getvalue(Instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(Instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(Instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property"); return false; } ret = TRUE; wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1); memcpy(wrkHref, varHref.value.stringValue.UTF8Characters, varHref.value.stringValue.UTF8Length); wrkHref[varHref.value.stringValue.UTF8Length] = 0x00; NPNFuncs.releasevariantvalue(&varHref); for (i = 0; i < ArgC; ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CLSID, wrkHref, ArgV[i]); } else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_PROGID, wrkHref, ArgV[i]); } else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CODEBASEURL, wrkHref, ArgV[i]); } } log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False"); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId) { USES_CONVERSION; BOOL ret; ret = TestExplicitAuthorization(A2W(MimeType), A2W(AuthorizationType), A2W(DocumentUrl), A2W(ProgramId)); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId) { BOOL ret = FALSE; #ifndef NO_REGISTRY_AUTHORIZE HKEY hKey; HKEY hSubKey; ULONG i; ULONG j; ULONG keyNameLen; ULONG valueNameLen; wchar_t keyName[_MAX_PATH]; wchar_t valueName[_MAX_PATH]; if (DocumentUrl == NULL) { return (FALSE); } if (ProgramId == NULL) { return (FALSE); } #ifdef NDEF MessageBox(NULL, DocumentUrl, ProgramId, MB_OK); #endif if ((hKey = FindKey(MimeType, AuthorizationType)) != NULL) { for (i = 0; !ret; i++) { keyNameLen = sizeof(keyName); if (RegEnumKey(hKey, i, keyName, keyNameLen) == ERROR_SUCCESS) { if (WildcardMatch(keyName, DocumentUrl)) { if (RegOpenKeyEx(hKey, keyName, 0, KEY_QUERY_VALUE, &hSubKey) == ERROR_SUCCESS) { for (j = 0; ; j++) { valueNameLen = sizeof(valueName); if (RegEnumValue(hSubKey, j, valueName, &valueNameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } if (WildcardMatch(valueName, ProgramId)) { ret = TRUE; break; } } RegCloseKey(hSubKey); } if (ret) { break; } } } else { break; } } RegCloseKey(hKey); } #endif return (ret); } // ---------------------------------------------------------------------------- BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value) { size_t i; size_t j = 0; size_t maskLen; size_t valueLen; maskLen = wcslen(Mask); valueLen = wcslen(Value); for (i = 0; i < maskLen + 1; i++) { if (Mask[i] == '?') { j++; continue; } if (Mask[i] == '*') { for (; j < valueLen + 1; j++) { if (WildcardMatch(Mask + i + 1, Value + j)) { return (TRUE); } } return (FALSE); } if ((j <= valueLen) && (Mask[i] == tolower(Value[j]))) { j++; continue; } return (FALSE); } return (TRUE); } // ---------------------------------------------------------------------------- HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType) { HKEY ret = NULL; HKEY plugins; wchar_t searchKey[_MAX_PATH]; wchar_t pluginName[_MAX_PATH]; DWORD j; size_t i; for (i = 0; i < ARRAYSIZE(BaseKeys); i++) { if (RegOpenKeyEx(BaseKeys[i], L"SOFTWARE\\MozillaPlugins", 0, KEY_ENUMERATE_SUB_KEYS, &plugins) == ERROR_SUCCESS) { for (j = 0; ret == NULL; j++) { if (RegEnumKey(plugins, j, pluginName, sizeof(pluginName)) != ERROR_SUCCESS) { break; } wsprintf(searchKey, L"%s\\MimeTypes\\%s\\%s", pluginName, MimeType, AuthorizationType); if (RegOpenKeyEx(plugins, searchKey, 0, KEY_ENUMERATE_SUB_KEYS, &ret) == ERROR_SUCCESS) { break; } ret = NULL; } RegCloseKey(plugins); if (ret != NULL) { break; } } } return (ret); }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlbase.h> #include <atlsafe.h> #include <npapi.h> #include <npfunctions.h> #include <prtypes.h> #include <npruntime.h> #include "scriptable.h" #include "GenericNPObject.h" #include "variants.h" extern NPNetscapeFuncs NPNFuncs; BSTR Utf8StringToBstr(LPCSTR szStr, int iSize) { BSTR bstrVal; // Chars required for string int iReq = 0; if (iSize > 0) { if ((iReq = MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, 0, 0)) == 0) { return (0); } } // Account for terminating 0. if (iReq != -1) { ++iReq; } if ((bstrVal = ::SysAllocStringLen(0, iReq)) == 0) { return (0); } memset(bstrVal, 0, iReq * sizeof(wchar_t)); if (iSize > 0) { // Convert into the buffer. if (MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, bstrVal, iReq) == 0) { ::SysFreeString(bstrVal); return 0; } } return (bstrVal); } void BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance) { USES_CONVERSION; char *npStr = NULL; size_t sourceLen; size_t bytesNeeded; sourceLen = lstrlenW(bstr); bytesNeeded = WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, NULL, 0, NULL, NULL); bytesNeeded += 1; // complete lack of documentation on Mozilla's part here, I have no // idea how this string is supposed to be freed npStr = (char *)NPNFuncs.memalloc(bytesNeeded); if (npStr) { memset(npStr, 0, bytesNeeded); WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, npStr, bytesNeeded - 1, NULL, NULL); STRINGZ_TO_NPVARIANT(npStr, (*npvar)); } else { STRINGZ_TO_NPVARIANT(NULL, (*npvar)); } } void Dispatch2NPVar(IDispatch *disp, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &ScriptableNPClass); ((Scriptable *)obj)->setControl(disp); ((Scriptable *)obj)->setInstance(instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } void Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &ScriptableNPClass); ((Scriptable *)obj)->setControl(unk); ((Scriptable *)obj)->setInstance(instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } NPObject * SafeArray2NPObject(SAFEARRAY *parray, unsigned short dim, unsigned long *pindices, NPP instance) { unsigned long *indices = pindices; NPObject *obj = NULL; bool rc = true; if (!parray || !instance) { return NULL; } obj = NPNFuncs.createobject(instance, &GenericNPObjectClass); if (NULL == obj) { return NULL; } do { if (NULL == indices) { // just getting started SafeArrayLock(parray); indices = (unsigned long *)calloc(1, parray->cDims * sizeof(unsigned long)); if (NULL == indices) { rc = false; break; } } NPIdentifier id = NULL; NPVariant val; VOID_TO_NPVARIANT(val); for(indices[dim] = 0; indices[dim] < parray->rgsabound[dim].cElements; indices[dim]++) { if (dim == (parray->cDims - 1)) { // single dimension (or the bottom of the recursion) if (parray->fFeatures & FADF_VARIANT) { VARIANT variant; VariantInit(&variant); if(FAILED(SafeArrayGetElement(parray, (long *)indices, &variant))) { rc = false; break; } Variant2NPVar(&variant, &val, instance); VariantClear(&variant); } else if (parray->fFeatures & FADF_BSTR) { BSTR bstr; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &bstr))) { rc = false; break; } BSTR2NPVar(bstr, &val, instance); } else if (parray->fFeatures & FADF_DISPATCH) { IDispatch *disp; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &disp))) { rc = false; break; } Dispatch2NPVar(disp, &val, instance); } else if (parray->fFeatures & FADF_UNKNOWN) { IUnknown *unk; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &unk))) { rc = false; break; } Unknown2NPVar(unk, &val, instance); } } else { // recurse NPObject *o = SafeArray2NPObject(parray, dim + 1, indices, instance); if (NULL == o) { rc = false; break; } OBJECT_TO_NPVARIANT(o, val); } id = NPNFuncs.getintidentifier(parray->rgsabound[dim].lLbound + indices[dim]); // setproperty will call retainobject or copy the internal string, we should // release variant NPNFuncs.setproperty(instance, obj, id, &val); NPNFuncs.releasevariantvalue(&val); VOID_TO_NPVARIANT(val); } } while (0); if (false == rc) { if (!pindices && indices) { free(indices); indices = NULL; SafeArrayUnlock(parray); } if (obj) { NPNFuncs.releaseobject(obj); obj = NULL; } } return obj; } #define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val)) void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; SAFEARRAY *parray = NULL; if (!var || !npvar) { return; } VOID_TO_NPVARIANT(*npvar); switch (var->vt & ~VT_BYREF) { case VT_EMPTY: VOID_TO_NPVARIANT((*npvar)); break; case VT_NULL: NULL_TO_NPVARIANT((*npvar)); break; case VT_LPSTR: // not sure it can even appear in a VARIANT, but... STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar)); break; case VT_BSTR: BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance); break; case VT_I1: INT32_TO_NPVARIANT((int32)GETVALUE(var, cVal), (*npvar)); break; case VT_I2: INT32_TO_NPVARIANT((int32)GETVALUE(var, iVal), (*npvar)); break; case VT_I4: INT32_TO_NPVARIANT((int32)GETVALUE(var, lVal), (*npvar)); break; case VT_UI1: INT32_TO_NPVARIANT((int32)GETVALUE(var, bVal), (*npvar)); break; case VT_UI2: INT32_TO_NPVARIANT((int32)GETVALUE(var, uiVal), (*npvar)); break; case VT_UI4: INT32_TO_NPVARIANT((int32)GETVALUE(var, ulVal), (*npvar)); break; case VT_BOOL: BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar)); break; case VT_R4: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar)); break; case VT_R8: DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar)); break; case VT_DISPATCH: Dispatch2NPVar(GETVALUE(var, pdispVal), npvar, instance); break; case VT_UNKNOWN: Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance); break; case VT_CY: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, cyVal).int64 / 10000, (*npvar)); break; case VT_DATE: BSTR bstrVal; VarBstrFromDate(GETVALUE(var, date), 0, 0, &bstrVal); BSTR2NPVar(bstrVal, npvar, instance); break; default: if (var->vt & VT_ARRAY) { obj = SafeArray2NPObject(GETVALUE(var, parray), 0, NULL, instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } break; } } #undef GETVALUE void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance) { USES_CONVERSION; if (!var || !npvar) { return; } switch (npvar->type) { case NPVariantType_Void: var->vt = VT_VOID; var->ulVal = 0; break; case NPVariantType_Null: var->vt = VT_PTR; var->byref = NULL; break; case NPVariantType_Bool: var->vt = VT_BOOL; var->ulVal = npvar->value.boolValue; break; case NPVariantType_Int32: var->vt = VT_UI4; var->ulVal = npvar->value.intValue; break; case NPVariantType_Double: var->vt = VT_R8; var->dblVal = npvar->value.doubleValue; break; case NPVariantType_String: var->vt = VT_BSTR; var->bstrVal = Utf8StringToBstr(npvar->value.stringValue.UTF8Characters, npvar->value.stringValue.UTF8Length); break; case NPVariantType_Object: NPIdentifier *identifiers = NULL; uint32_t identifierCount = 0; NPObject *object = NPVARIANT_TO_OBJECT(*npvar); if (NPNFuncs.enumerate(instance, object, &identifiers, &identifierCount)) { CComSafeArray<VARIANT> variants; for (uint32_t index = 0; index < identifierCount; ++index) { NPVariant npVariant; if (NPNFuncs.getproperty(instance, object, identifiers[index], &npVariant)) { if (npVariant.type != NPVariantType_Object) { CComVariant variant; NPVar2Variant(&npVariant, &variant, instance); variants.Add(variant); } NPNFuncs.releasevariantvalue(&npVariant); } } NPNFuncs.memfree(identifiers); *reinterpret_cast<CComVariant*>(var) = variants; } else { var->vt = VT_VOID; var->ulVal = 0; } break; } }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <algorithm> #include <string> #include "GenericNPObject.h" static NPObject* AllocateGenericNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, false); } static NPObject* AllocateMethodNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, true); } static void DeallocateGenericNPObject(NPObject *obj) { if (!obj) { return; } GenericNPObject *m = (GenericNPObject *)obj; delete m; } static void InvalidateGenericNPObject(NPObject *obj) { if (!obj) { return; } ((GenericNPObject *)obj)->Invalidate(); } NPClass GenericNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateGenericNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; NPClass MethodNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateMethodNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; // Some standard JavaScript methods bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) { GenericNPObject *map = (GenericNPObject *)object; if (!map || map->invalid) return false; // no args expected or cared for... std::string out; std::vector<NPVariant>::iterator it; for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) { if (NPVARIANT_IS_VOID(*it)) { out += ","; } else if (NPVARIANT_IS_NULL(*it)) { out += ","; } else if (NPVARIANT_IS_BOOLEAN(*it)) { if ((*it).value.boolValue) { out += "true,"; } else { out += "false,"; } } else if (NPVARIANT_IS_INT32(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%d,", (*it).value.intValue); out += tmp; } else if (NPVARIANT_IS_DOUBLE(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%f,", (*it).value.doubleValue); out += tmp; } else if (NPVARIANT_IS_STRING(*it)) { out += (*it).value.stringValue.UTF8Characters; out += ","; } else if (NPVARIANT_IS_OBJECT(*it)) { out += "[object],"; } } // calculate how much space we need std::string::size_type size = out.length(); char *s = (char *)NPNFuncs.memalloc(size * sizeof(char)); if (NULL == s) { return false; } memcpy(s, out.c_str(), size); s[size - 1] = 0; // overwrite the last "," STRINGZ_TO_NPVARIANT(s, (*result)); return true; } // Some helpers static void free_numeric_element(NPVariant elem) { NPNFuncs.releasevariantvalue(&elem); } static void free_alpha_element(std::pair<const char *, NPVariant> elem) { NPNFuncs.releasevariantvalue(&(elem.second)); } // And now the GenericNPObject implementation GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj): invalid(false), defInvoker(NULL), defInvokerObject(NULL) { NPVariant val; INT32_TO_NPVARIANT(0, val); immutables["length"] = val; if (!isMethodObj) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &MethodNPObjectClass); if (NULL == obj) { throw NULL; } ((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this); OBJECT_TO_NPVARIANT(obj, val); immutables["toString"] = val; } } GenericNPObject::~GenericNPObject() { for_each(immutables.begin(), immutables.end(), free_alpha_element); for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element); for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element); } bool GenericNPObject::HasMethod(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL != immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault); } } } return false; } bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(immutables[key]) && immutables[key].value.objectValue->_class->invokeDefault) { return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result); } } else if (alpha_mapper.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(alpha_mapper[key]) && alpha_mapper[key].value.objectValue->_class->invokeDefault) { return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result); } } } return true; } bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (defInvoker) { defInvoker(defInvokerObject, args, argCount, result); } return true; } // This method is also called before the JS engine attempts to add a new // property, most likely it's trying to check that the key is supported. // It only returns false if the string name was not found, or does not // hold a callable object bool GenericNPObject::HasProperty(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL == immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault); } } return false; } return true; } static bool CopyNPVariant(NPVariant *dst, const NPVariant *src) { dst->type = src->type; if (NPVARIANT_IS_STRING(*src)) { NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8)); if (NULL == str) { return false; } dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length; memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length); str[dst->value.stringValue.UTF8Length] = 0; dst->value.stringValue.UTF8Characters = str; } else if (NPVARIANT_IS_OBJECT(*src)) { NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src)); dst->value.objectValue = src->value.objectValue; } else { dst->value = src->value; } return true; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (!CopyNPVariant(result, &(immutables[key]))) { return false; } } else if (alpha_mapper.count(key) > 0) { if (!CopyNPVariant(result, &(alpha_mapper[key]))) { return false; } } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { if (!CopyNPVariant(result, &(numeric_mapper[key]))) { return false; } } } } catch (...) { } return true; } bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { // the key is already defined as immutable, check the new value type if (value->type != immutables[key].type) { return false; } // Seems ok, copy the new value if (!CopyNPVariant(&(immutables[key]), value)) { return false; } } else if (!CopyNPVariant(&(alpha_mapper[key]), value)) { return false; } } else { // assume int... NPVariant var; if (!CopyNPVariant(&var, value)) { return false; } unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (key >= numeric_mapper.size()) { // there's a gap we need to fill NPVariant pad; VOID_TO_NPVARIANT(pad); numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad); } numeric_mapper.at(key) = var; NPVARIANT_TO_INT32(immutables["length"])++; } } catch (...) { } return true; } bool GenericNPObject::RemoveProperty(NPIdentifier name) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (alpha_mapper.count(key) > 0) { NPNFuncs.releasevariantvalue(&(alpha_mapper[key])); alpha_mapper.erase(key); } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { NPNFuncs.releasevariantvalue(&(numeric_mapper[key])); numeric_mapper.erase(numeric_mapper.begin() + key); } NPVARIANT_TO_INT32(immutables["length"])--; } } catch (...) { } return true; } bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) { if (invalid) return false; try { *identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size()); if (NULL == *identifiers) { return false; } *identifierCount = 0; std::vector<NPVariant>::iterator it; unsigned int i = 0; char str[10] = ""; for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) { // skip empty (padding) elements if (NPVARIANT_IS_VOID(*it)) continue; _snprintf(str, sizeof(str), "%u", i); (*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str); } } catch (...) { } return true; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ class CAxHost { private: CAxHost(const CAxHost &); NPP instance; bool isValidClsID; bool isKnown; protected: // The window handle to our plugin area in the browser HWND Window; WNDPROC OldProc; // The class/prog id of the control CLSID ClsID; LPCWSTR CodeBaseUrl; CControlEventSinkInstance *Sink; public: CAxHost(NPP inst); ~CAxHost(); CControlSiteInstance *Site; PropertyList Props; void setWindow(HWND win); HWND getWinfow(); void UpdateRect(RECT rcPos); bool verifyClsID(LPOLESTR oleClsID); bool setClsID(const char *clsid); bool setClsIDFromProgID(const char *progid); void setCodeBaseUrl(LPCWSTR clsid); bool hasValidClsID(); bool CreateControl(bool subscribeToEvents); bool AddEventHandler(wchar_t *name, wchar_t *handler); int16 HandleEvent(void *event); NPObject *GetScriptableObject(); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // ffactivex.cpp : Defines the exported functions for the DLL application. // #include "ffactivex.h" #include "common/stdafx.h" #include "axhost.h" #include "atlutil.h" #include "authorize.h" // A list of trusted domains // Each domain name may start with a '*' to specify that sub domains are // trusted as well // Note that a '.' is not enforced after the '*' static const char *TrustedLocations[] = {NULL}; static const unsigned int numTrustedLocations = 0; static const char *LocalhostName = "localhost"; static const bool TrustLocalhost = true; void * ffax_calloc(unsigned int size) { void *ptr = NULL; ptr = NPNFuncs.memalloc(size); if (ptr) { memset(ptr, 0, size); } return ptr; } void ffax_free(void *ptr) { if (ptr) NPNFuncs.memfree(ptr); } // // Gecko API // static unsigned int log_level = 0; static char *logger = NULL; void log(NPP instance, unsigned int level, char *message, ...) { NPVariant result; NPVariant args; NPObject *globalObj = NULL; bool rc = false; char *formatted = NULL; char *new_formatted = NULL; int buff_len = 0; int size = 0; va_list list; if (!logger || (level > log_level)) { return; } buff_len = strlen(message); buff_len += buff_len / 10; formatted = (char *)calloc(1, buff_len); while (true) { va_start(list, message); size = vsnprintf_s(formatted, buff_len, _TRUNCATE, message, list); va_end(list); if (size > -1 && size < buff_len) break; buff_len *= 2; new_formatted = (char *)realloc(formatted, buff_len); if (NULL == new_formatted) { free(formatted); return; } formatted = new_formatted; new_formatted = NULL; } NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(logger); STRINGZ_TO_NPVARIANT(formatted, args); bool success = NPNFuncs.invoke(instance, globalObj, handler, &args, 1, &result); NPNFuncs.releasevariantvalue(&result); NPNFuncs.releaseobject(globalObj); free(formatted); } static bool MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl) { USES_CONVERSION; bool rc = false; CUrl url; if (!numTrustedLocations) { return true; } rc = url.CrackUrl(matchUrl, ATL_URL_DECODE); if (!rc) { log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL"); return false; } if ( (url.GetScheme() == ATL_URL_SCHEME_FILE) || (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){ return TrustLocalhost; } for (unsigned int i = 0; i < numTrustedLocations; ++i) { if (TrustedLocations[i][0] == '*') { // sub domains are trusted unsigned int len = strlen(TrustedLocations[i]); bool match = 0; if (url.GetHostNameLength() < len) { // can't be a match continue; } --len; // skip the '*' match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name TrustedLocations[i] + 1, // skip the '*' len) == 0 ? true : false; if (match) { return true; } } else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) { return true; } } return false; } static bool VerifySiteLock(NPP instance) { USES_CONVERSION; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; // Get the window object. NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property"); return false; } rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters)); NPNFuncs.releasevariantvalue(&varHref); if (false == rc) { log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted"); } return rc; } /* * Create a new plugin instance, most probably through an embed/object HTML * element. * * Any private data we want to keep for this instance can be saved into * [instance->pdata]. * [saved] might hold information a previous instance that was invoked from the * same URL has saved for us. */ NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { NPError rc = NPERR_NO_ERROR; NPObject *browser = NULL; CAxHost *host = NULL; PropertyList events; int16 i = 0; USES_CONVERSION; //_asm {int 3}; if (!instance || (0 == NPNFuncs.size)) { return NPERR_INVALID_PARAM; } #ifdef NO_REGISTRY_AUTHORIZE // Verify that we're running from a trusted location if (!VerifySiteLock(instance)) { return NPERR_GENERIC_ERROR; } #endif instance->pdata = NULL; #ifndef NO_REGISTRY_AUTHORIZE if (!TestAuthorization (instance, argc, argn, argv, pluginType)) { return NPERR_GENERIC_ERROR; } #endif // TODO: Check the pluginType to make sure we're being called with the rigth MIME Type do { // Create a plugin instance, the actual control will be created once we // are given a window handle host = new CAxHost(instance); if (!host) { rc = NPERR_OUT_OF_MEMORY_ERROR; log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host"); break; } // Iterate over the arguments we've been passed for (i = 0; (i < argc) && (NPERR_NO_ERROR == rc); ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(argn[i], PARAM_CLSID, strlen(PARAM_CLSID))) { // The class id of the control we are asked to load host->setClsID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load host->setClsIDFromProgID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_DEBUG, strlen(PARAM_DEBUG))) { // Logging verbosity log_level = atoi(argv[i]); log(instance, 0, "AxHost.NPP_New: debug level set to %d", log_level); } else if (0 == strnicmp(argn[i], PARAM_LOGGER, strlen(PARAM_LOGGER))) { // Logger function logger = strdup(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_ONEVENT, strlen(PARAM_ONEVENT))) { // A request to handle one of the activex's events in JS events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i]))); } else if (0 == strnicmp(argn[i], PARAM_PARAM, strlen(PARAM_PARAM))) { CComBSTR paramName = argn[i] + strlen(PARAM_PARAM); CComBSTR paramValue(Utf8StringToBstr(argv[i], strlen(argv[i]))); // Check for existing params with the same name BOOL bFound = FALSE; for (unsigned long j = 0; j < host->Props.GetSize(); j++) { if (wcscmp(host->Props.GetNameOf(j), (BSTR) paramName) == 0) { bFound = TRUE; break; } } // If the parameter already exists, don't add it to the // list again. if (bFound) { continue; } // Add named parameter to list CComVariant v(paramValue); host->Props.AddNamedProperty(paramName, v); } else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) { host->setCodeBaseUrl(A2W(argv[i])); } else { log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location"); } } } if (NPERR_NO_ERROR != rc) break; // Make sure we have all the information we need to initialize a new instance if (!host->hasValidClsID()) { rc = NPERR_INVALID_PARAM; log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID"); break; } instance->pdata = host; // if no events were requested, don't fail if subscribing fails if (!host->CreateControl(events.GetSize() ? true : false)) { rc = NPERR_GENERIC_ERROR; log(instance, 0, "AxHost.NPP_New: failed to create the control"); break; } for (unsigned int j = 0; j < events.GetSize(); j++) { if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) { //rc = NPERR_GENERIC_ERROR; //break; } } if (NPERR_NO_ERROR != rc) break; } while (0); if (NPERR_NO_ERROR != rc) { delete host; } return rc; } /* * Destroy an existing plugin instance. * * [save] can be used to save information for a future instance of our plugin * that'll be invoked by the same URL. */ NPError NPP_Destroy(NPP instance, NPSavedData **save) { // _asm {int 3}; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } log(instance, 0, "NPP_Destroy: destroying the control..."); CAxHost *host = (CAxHost *)instance->pdata; delete host; instance->pdata = NULL; return NPERR_NO_ERROR; } /* * Sets an instance's window parameters. */ NPError NPP_SetWindow(NPP instance, NPWindow *window) { CAxHost *host = NULL; RECT rcPos; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } host = (CAxHost *)instance->pdata; host->setWindow((HWND)window->window); rcPos.left = 0; rcPos.top = 0; rcPos.right = window->width; rcPos.bottom = window->height; host->UpdateRect(rcPos); return NPERR_NO_ERROR; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "PropertyBag.h" CPropertyBag::CPropertyBag() { } CPropertyBag::~CPropertyBag() { } /////////////////////////////////////////////////////////////////////////////// // IPropertyBag implementation HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } VARTYPE vt = pVar->vt; VariantInit(pVar); for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++) { if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0) { const VARIANT *pvSrc = m_PropertyList.GetValueOf(i); if (!pvSrc) { return E_FAIL; } CComVariant vNew; HRESULT hr = (vt == VT_EMPTY) ? vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc); if (FAILED(hr)) { return E_FAIL; } // Copy the new value vNew.Detach(pVar); return S_OK; } } // Property does not exist in the bag return E_FAIL; } HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } CComBSTR bstrName(pszPropName); m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar); return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYBAG_H #define PROPERTYBAG_H #include "PropertyList.h" // Object wrapper for property list. This class can be set up with a // list of properties and used to initialise a control with them class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>, public IPropertyBag { // List of properties in the bag PropertyList m_PropertyList; public: // Constructor CPropertyBag(); // Destructor virtual ~CPropertyBag(); BEGIN_COM_MAP(CPropertyBag) COM_INTERFACE_ENTRY(IPropertyBag) END_COM_MAP() // IPropertyBag methods virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog); virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar); }; typedef CComObject<CPropertyBag> CPropertyBagInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITE_H #define CONTROLSITE_H #include "IOleCommandTargetImpl.h" #include "PropertyList.h" // If you created a class derived from CControlSite, use the following macro // in the interface map of the derived class to include all the necessary // interfaces. #define CCONTROLSITE_INTERFACES() \ COM_INTERFACE_ENTRY(IOleWindow) \ COM_INTERFACE_ENTRY(IOleClientSite) \ COM_INTERFACE_ENTRY(IOleInPlaceSite) \ COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless) \ COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless) \ COM_INTERFACE_ENTRY(IOleControlSite) \ COM_INTERFACE_ENTRY(IDispatch) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx) \ COM_INTERFACE_ENTRY(IOleCommandTarget) \ COM_INTERFACE_ENTRY(IServiceProvider) \ COM_INTERFACE_ENTRY(IBindStatusCallback) \ COM_INTERFACE_ENTRY(IWindowForBindingUI) // Temoporarily removed by bug 200680. Stops controls misbehaving and calling // windowless methods when they shouldn't. // COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \ // Class that defines the control's security policy with regards to // what controls it hosts etc. class CControlSiteSecurityPolicy { public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0; // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0; // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0; }; // // Class for hosting an ActiveX control // // This class supports both windowed and windowless classes. The normal // steps to hosting a control are this: // // CControlSiteInstance *pSite = NULL; // CControlSiteInstance::CreateInstance(&pSite); // pSite->AddRef(); // pSite->Create(clsidControlToCreate); // pSite->Attach(hwndParentWindow, rcPosition); // // Where propertyList is a named list of values to initialise the new object // with, hwndParentWindow is the window in which the control is being created, // and rcPosition is the position in window coordinates where the control will // be rendered. // // Destruction is this: // // pSite->Detach(); // pSite->Release(); // pSite = NULL; class CControlSite : public CComObjectRootEx<CComSingleThreadModel>, public CControlSiteSecurityPolicy, public IOleClientSite, public IOleInPlaceSiteWindowless, public IOleControlSite, public IAdviseSinkEx, public IDispatch, public IServiceProvider, public IOleCommandTargetImpl<CControlSite>, public IBindStatusCallback, public IWindowForBindingUI { public: // Site management values // Handle to parent window HWND m_hWndParent; // Position of the site and the contained object RECT m_rcObjectPos; // Flag indicating if client site should be set early or late unsigned m_bSetClientSiteFirst:1; // Flag indicating whether control is visible or not unsigned m_bVisibleAtRuntime:1; // Flag indicating if control is in-place active unsigned m_bInPlaceActive:1; // Flag indicating if control is UI active unsigned m_bUIActive:1; // Flag indicating if control is in-place locked and cannot be deactivated unsigned m_bInPlaceLocked:1; // Flag indicating if the site allows windowless controls unsigned m_bSupportWindowlessActivation:1; // Flag indicating if control is windowless (after being created) unsigned m_bWindowless:1; // Flag indicating if only safely scriptable controls are allowed unsigned m_bSafeForScriptingObjectsOnly:1; // Pointer to an externally registered service provider CComPtr<IServiceProvider> m_spServiceProvider; // Pointer to the OLE container CComPtr<IOleContainer> m_spContainer; // Return the default security policy object static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy(); protected: // Pointers to object interfaces // Raw pointer to the object CComPtr<IUnknown> m_spObject; // Pointer to objects IViewObject interface CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject; // Pointer to object's IOleObject interface CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject; // Pointer to object's IOleInPlaceObject interface CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject; // Pointer to object's IOleInPlaceObjectWindowless interface CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless; // CLSID of the control CLSID m_CLSID; // Parameter list PropertyList m_ParameterList; // Pointer to the security policy CControlSiteSecurityPolicy *m_pSecurityPolicy; // Binding variables // Flag indicating whether binding is in progress unsigned m_bBindingInProgress; // Result from the binding operation HRESULT m_hrBindResult; // Double buffer drawing variables used for windowless controls // Area of buffer RECT m_rcBuffer; // Bitmap to buffer HBITMAP m_hBMBuffer; // Bitmap to buffer HBITMAP m_hBMBufferOld; // Device context HDC m_hDCBuffer; // Clipping area of site HRGN m_hRgnBuffer; // Flags indicating how the buffer was painted DWORD m_dwBufferFlags; // Ambient properties // Locale ID LCID m_nAmbientLocale; // Foreground colour COLORREF m_clrAmbientForeColor; // Background colour COLORREF m_clrAmbientBackColor; // Flag indicating if control should hatch itself bool m_bAmbientShowHatching:1; // Flag indicating if control should have grab handles bool m_bAmbientShowGrabHandles:1; // Flag indicating if control is in edit/user mode bool m_bAmbientUserMode:1; // Flag indicating if control has a 3d border or not bool m_bAmbientAppearance:1; protected: // Notifies the attached control of a change to an ambient property virtual void FireAmbientPropertyChange(DISPID id); public: // Construction and destruction // Constructor CControlSite(); // Destructor virtual ~CControlSite(); BEGIN_COM_MAP(CControlSite) CCONTROLSITE_INTERFACES() END_COM_MAP() BEGIN_OLECOMMAND_TABLE() END_OLECOMMAND_TABLE() // Returns the window used when processing ole commands HWND GetCommandTargetWindow() { return NULL; // TODO } // Object creation and management functions // Creates and initialises an object virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(), LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL); // Attaches the object to the site virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL); // Detaches the object from the site virtual HRESULT Detach(); // Returns the IUnknown pointer for the object virtual HRESULT GetControlUnknown(IUnknown **ppObject); // Sets the bounding rectangle for the object virtual HRESULT SetPosition(const RECT &rcPos); // Draws the object using the provided DC virtual HRESULT Draw(HDC hdc); // Performs the specified action on the object virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL); // Sets an advise sink up for changes to the object virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie); // Removes an advise sink virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie); // Register an external service provider object virtual void SetServiceProvider(IServiceProvider *pSP) { m_spServiceProvider = pSP; } virtual void SetContainer(IOleContainer *pContainer) { m_spContainer = pContainer; } // Set the security policy object. Ownership of this object remains with the caller and the security // policy object is meant to exist for as long as it is set here. virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy) { m_pSecurityPolicy = pSecurityPolicy; } virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const { return m_pSecurityPolicy; } // Methods to set ambient properties virtual void SetAmbientUserMode(BOOL bUser); // Inline helper methods // Returns the object's CLSID virtual const CLSID &GetObjectCLSID() const { return m_CLSID; } // Tests if the object is valid or not virtual BOOL IsObjectValid() const { return (m_spObject) ? TRUE : FALSE; } // Returns the parent window to this one virtual HWND GetParentWindow() const { return m_hWndParent; } // Returns the inplace active state of the object virtual BOOL IsInPlaceActive() const { return m_bInPlaceActive; } // CControlSiteSecurityPolicy // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid); // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(const IID &iid); // IServiceProvider virtual HRESULT STDMETHODCALLTYPE QueryService(REFGUID guidService, REFIID riid, void** ppv); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); // IAdviseSink implementation virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed); virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex); virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk); virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void); virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void); // IAdviseSink2 virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk); // IAdviseSinkEx implementation virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus); // IOleWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleClientSite implementation virtual HRESULT STDMETHODCALLTYPE SaveObject(void); virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk); virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer); virtual HRESULT STDMETHODCALLTYPE ShowObject(void); virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow); virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void); // IOleInPlaceSite implementation virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void); virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo); virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant); virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void); virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void); virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void); virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect); // IOleInPlaceSiteEx implementation virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw); virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void); // IOleInPlaceSiteWindowless implementation virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void); virtual HRESULT STDMETHODCALLTYPE GetCapture(void); virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture); virtual HRESULT STDMETHODCALLTYPE GetFocus(void); virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus); virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC); virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC); virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip); virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc); virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult); // IOleControlSite implementation virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void); virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock); virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp); virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers); virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus); virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void); // IBindStatusCallback virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib); virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority); virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved); virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText); virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo); virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed); virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk); // IWindowForBindingUI virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd); }; typedef CComObject<CControlSite> CControlSiteInstance; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ItemContainer.h" CItemContainer::CItemContainer() { } CItemContainer::~CItemContainer() { } /////////////////////////////////////////////////////////////////////////////// // IParseDisplayName implementation HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut) { // TODO return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum) { HRESULT hr = E_NOTIMPL; /* if (ppenum == NULL) { return E_POINTER; } *ppenum = NULL; typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk; enumunk* p = NULL; p = new enumunk; if(p == NULL) { return E_OUTOFMEMORY; } hr = p->Init(); if (SUCCEEDED(hr)) { hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum); } if (FAILED(hRes)) { delete p; } */ return hr; } HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock) { // TODO return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleItemContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject) { if (pszItem == NULL) { return E_INVALIDARG; } if (ppvObject == NULL) { return E_INVALIDARG; } *ppvObject = NULL; return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage) { // TODO return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem) { // TODO return MK_E_NOOBJECT; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLEVENTSINK_H #define CONTROLEVENTSINK_H #include <map> // This class listens for events from the specified control class CControlEventSink : public CComObjectRootEx<CComSingleThreadModel>, public IDispatch { public: CControlEventSink(); // Current event connection point CComPtr<IConnectionPoint> m_spEventCP; CComPtr<ITypeInfo> m_spEventSinkTypeInfo; DWORD m_dwEventCookie; IID m_EventIID; typedef std::map<DISPID, wchar_t *> EventMap; EventMap events; NPP instance; protected: virtual ~CControlEventSink(); bool m_bSubscribed; static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw) { CControlEventSink *pThis = (CControlEventSink *) pv; if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) && IsEqualIID(pThis->m_EventIID, riid)) { return pThis->QueryInterface(__uuidof(IDispatch), ppv); } return E_NOINTERFACE; } public: BEGIN_COM_MAP(CControlEventSink) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI) END_COM_MAP() virtual HRESULT SubscribeToEvents(IUnknown *pControl); virtual void UnsubscribeFromEvents(); virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo); virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); }; typedef CComObject<CControlEventSink> CControlEventSinkInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "stdafx.h" #include "ControlSiteIPFrame.h" CControlSiteIPFrame::CControlSiteIPFrame() { m_hwndFrame = NULL; } CControlSiteIPFrame::~CControlSiteIPFrame() { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { if (phwnd == NULL) { return E_INVALIDARG; } *phwnd = m_hwndFrame; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceUIWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceFrame implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID) { return E_NOTIMPL; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_) #define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // under MSVC shut off copious warnings about debug symbol too long #ifdef _MSC_VER #pragma warning( disable: 4786 ) #endif //#include "jstypes.h" //#include "prtypes.h" // Mozilla headers //#include "jscompat.h" //#include "prthread.h" //#include "prprf.h" //#include "nsID.h" //#include "nsIComponentManager.h" //#include "nsIServiceManager.h" //#include "nsStringAPI.h" //#include "nsCOMPtr.h" //#include "nsComponentManagerUtils.h" //#include "nsServiceManagerUtils.h" //#include "nsIDocument.h" //#include "nsIDocumentObserver.h" //#include "nsVoidArray.h" //#include "nsIDOMNode.h" //#include "nsIDOMNodeList.h" //#include "nsIDOMDocument.h" //#include "nsIDOMDocumentType.h" //#include "nsIDOMElement.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_APARTMENT_THREADED //#define _ATL_STATIC_REGISTRY // #define _ATL_DEBUG_INTERFACES // ATL headers // The ATL headers that come with the platform SDK have bad for scoping #if _MSC_VER >= 1400 #pragma conform(forScope, push, atlhack, off) #endif #include <atlbase.h> //You may derive a class from CComModule and use it if you want to override //something, but do not change the name of _Module extern CComModule _Module; #include <atlcom.h> #include <atlctl.h> #if _MSC_VER >= 1400 #pragma conform(forScope, pop, atlhack) #endif #include <mshtml.h> #include <mshtmhst.h> #include <docobj.h> //#include <winsock2.h> #include <comdef.h> #include <vector> #include <list> #include <string> // New winsock2.h doesn't define this anymore typedef long int32; #define NS_SCRIPTABLE #include "nscore.h" #include "npapi.h" //#include "npupp.h" #include "npfunctions.h" #include "nsID.h" #include <npruntime.h> #include "../variants.h" #include "PropertyList.h" #include "PropertyBag.h" #include "ItemContainer.h" #include "ControlSite.h" #include "ControlSiteIPFrame.h" #include "ControlEventSink.h" extern NPNetscapeFuncs NPNFuncs; // Turn off warnings about debug symbols for templates being too long #pragma warning(disable : 4786) #define TRACE_METHOD(fn) \ { \ ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \ } #define TRACE_METHOD_ARGS(fn, pattern, args) \ { \ ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \ } //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #define NS_ASSERTION(x, y) #endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ControlEventSink.h" CControlEventSink::CControlEventSink() : m_dwEventCookie(0), m_bSubscribed(false), m_EventIID(GUID_NULL), events() { } CControlEventSink::~CControlEventSink() { UnsubscribeFromEvents(); } BOOL CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo) { iid = GUID_NULL; if (!pControl) { return E_INVALIDARG; } // IProvideClassInfo2 way is easiest // CComQIPtr<IProvideClassInfo2> classInfo2 = pControl; // if (classInfo2) // { // classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid); // if (!::IsEqualIID(iid, GUID_NULL)) // { // return TRUE; // } // } // Yuck, the hard way CComQIPtr<IProvideClassInfo> classInfo = pControl; if (!classInfo) { return FALSE; } // Search the class type information for the default source interface // which is the outgoing event sink. CComPtr<ITypeInfo> classTypeInfo; classInfo->GetClassInfo(&classTypeInfo); if (!classTypeInfo) { return FALSE; } TYPEATTR *classAttr = NULL; if (FAILED(classTypeInfo->GetTypeAttr(&classAttr))) { return FALSE; } INT implFlags = 0; for (UINT i = 0; i < classAttr->cImplTypes; i++) { // Search for the interface with the [default, source] attr if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) && implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE)) { CComPtr<ITypeInfo> eventSinkTypeInfo; HREFTYPE hRefType; if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) && SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo))) { TYPEATTR *eventSinkAttr = NULL; if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr))) { iid = eventSinkAttr->guid; if (typeInfo) { *typeInfo = eventSinkTypeInfo.p; (*typeInfo)->AddRef(); } eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr); } } break; } } classTypeInfo->ReleaseTypeAttr(classAttr); return (!::IsEqualIID(iid, GUID_NULL)); } void CControlEventSink::UnsubscribeFromEvents() { if (m_bSubscribed) { DWORD tmpCookie = m_dwEventCookie; m_dwEventCookie = 0; m_bSubscribed = false; // Unsubscribe and reset - This seems to complete release and destroy us... m_spEventCP->Unadvise(tmpCookie); // Unadvise handles the Release //m_spEventCP.Release(); } } HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl) { if (!pControl) { return E_INVALIDARG; } // Throw away any existing connections UnsubscribeFromEvents(); // Grab the outgoing event sink IID which will be used to subscribe // to events via the connection point container. IID iidEventSink; CComPtr<ITypeInfo> typeInfo; if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo)) { return E_FAIL; } // Get the connection point CComQIPtr<IConnectionPointContainer> ccp = pControl; CComPtr<IConnectionPoint> cp; if (!ccp) { return E_FAIL; } // Custom IID m_EventIID = iidEventSink; DWORD dwCookie = 0; if (!ccp || FAILED(ccp->FindConnectionPoint(m_EventIID, &cp)) || FAILED(cp->Advise(this, &dwCookie))) { return E_FAIL; } m_bSubscribed = true; m_spEventCP = cp; m_dwEventCookie = dwCookie; m_spEventSinkTypeInfo = typeInfo; return S_OK; } HRESULT CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { USES_CONVERSION; if (DISPATCH_METHOD != wFlags) { // any other reason to call us?! return S_FALSE; } EventMap::iterator cur = events.find(dispIdMember); if (events.end() != cur) { // invoke this event handler NPVariant result; NPVariant *args = NULL; if (pDispParams->cArgs > 0) { args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant)); if (!args) { return S_FALSE; } for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments in reverse order Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance); } } NPObject *globalObj = NULL; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second)); bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result); NPNFuncs.releaseobject(globalObj); for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments if (args[i].type == NPVariantType_String) { // was allocated earlier by Variant2NPVar NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters); } } if (!success) { return S_FALSE; } if (pVarResult) { // set the result NPVar2Variant(&result, pVarResult, instance); } NPNFuncs.releasevariantvalue(&result); } return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * Brent Booker * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include <Objsafe.h> #include "ControlSite.h" #include "PropertyBag.h" #include "ControlSiteIPFrame.h" class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy { // Test if the specified class id implements the specified category BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists); public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid); // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid); }; BOOL CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists) { bClassExists = FALSE; // Test if there is a CLSID entry. If there isn't then obviously // the object doesn't exist and therefore doesn't implement any category. // In this situation, the function returns REGDB_E_CLASSNOTREG. CRegKey key; if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS) { // Must fail if we can't even open this! return FALSE; } LPOLESTR szCLSID = NULL; if (FAILED(StringFromCLSID(clsid, &szCLSID))) { return FALSE; } USES_CONVERSION; CRegKey keyCLSID; LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ); CoTaskMemFree(szCLSID); if (lResult != ERROR_SUCCESS) { // Class doesn't exist return FALSE; } keyCLSID.Close(); // CLSID exists, so try checking what categories it implements bClassExists = TRUE; CComQIPtr<ICatInformation> spCatInfo; HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo); if (spCatInfo == NULL) { // Must fail if we can't open the category manager return FALSE; } // See what categories the class implements CComQIPtr<IEnumCATID> spEnumCATID; if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID))) { // Can't enumerate classes in category so fail return FALSE; } // Search for matching categories BOOL bFound = FALSE; CATID catidNext = GUID_NULL; while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK) { if (::IsEqualCATID(catid, catidNext)) { return TRUE; } } return FALSE; } // Test if the class is safe to host BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid) { return TRUE; } // Test if the specified class is marked safe for scripting BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) { // Test the category the object belongs to return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists); } // Test if the instantiated object is safe for scripting on the specified interface BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) { if (!pObject) { return FALSE; } // Ask the control if its safe for scripting CComQIPtr<IObjectSafety> spObjectSafety = pObject; if (!spObjectSafety) { return FALSE; } DWORD dwSupported = 0; // Supported options (mask) DWORD dwEnabled = 0; // Enabled options // Assume scripting via IDispatch if (FAILED(spObjectSafety->GetInterfaceSafetyOptions( iid, &dwSupported, &dwEnabled))) { // Interface is not safe or failure. return FALSE; } // Test if safe for scripting if (!(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER) { // Object says it is not set to be safe, but supports unsafe calling, // try enabling it and asking again. if(!(dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER) || FAILED(spObjectSafety->SetInterfaceSafetyOptions( iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER)) || FAILED(spObjectSafety->GetInterfaceSafetyOptions( iid, &dwSupported, &dwEnabled)) || !(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER) { return FALSE; } } return TRUE; } /////////////////////////////////////////////////////////////////////////////// // Constructor CControlSite::CControlSite() { TRACE_METHOD(CControlSite::CControlSite); m_hWndParent = NULL; m_CLSID = CLSID_NULL; m_bSetClientSiteFirst = FALSE; m_bVisibleAtRuntime = TRUE; memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos)); m_bInPlaceActive = FALSE; m_bUIActive = FALSE; m_bInPlaceLocked = FALSE; m_bWindowless = FALSE; m_bSupportWindowlessActivation = TRUE; m_bSafeForScriptingObjectsOnly = FALSE; m_pSecurityPolicy = GetDefaultControlSecurityPolicy(); // Initialise ambient properties m_nAmbientLocale = 0; m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT); m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW); m_bAmbientUserMode = true; m_bAmbientShowHatching = true; m_bAmbientShowGrabHandles = true; m_bAmbientAppearance = true; // 3d // Windowless variables m_hDCBuffer = NULL; m_hRgnBuffer = NULL; m_hBMBufferOld = NULL; m_hBMBuffer = NULL; } // Destructor CControlSite::~CControlSite() { TRACE_METHOD(CControlSite::~CControlSite); Detach(); } // Create the specified control, optionally providing properties to initialise // it with and a name. HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl, LPCWSTR szCodebase, IBindCtx *pBindContext) { TRACE_METHOD(CControlSite::Create); m_CLSID = clsid; m_ParameterList = pl; // See if security policy will allow the control to be hosted if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid)) { return E_FAIL; } // See if object is script safe BOOL checkForObjectSafety = FALSE; if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly) { BOOL bClassExists = FALSE; BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists); if (!bClassExists && szCodebase) { // Class doesn't exist, so allow code below to fetch it } else if (!bIsSafe) { // The class is not flagged as safe for scripting, so // we'll have to create it to ask it if its safe. checkForObjectSafety = TRUE; } } //Now Check if the control version needs to be updated. BOOL bUpdateControlVersion = FALSE; wchar_t *szURL = NULL; DWORD dwFileVersionMS = 0xffffffff; DWORD dwFileVersionLS = 0xffffffff; if(szCodebase) { HKEY hk = NULL; wchar_t wszKey[60] = L""; wchar_t wszData[MAX_PATH]; LPWSTR pwszClsid = NULL; DWORD dwSize = 255; DWORD dwHandle, dwLength, dwRegReturn; DWORD dwExistingFileVerMS = 0xffffffff; DWORD dwExistingFileVerLS = 0xffffffff; BOOL bFoundLocalVerInfo = FALSE; StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid); swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32"); if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS ) { dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize ); RegCloseKey( hk ); } if(dwRegReturn == ERROR_SUCCESS) { VS_FIXEDFILEINFO *pFileInfo; UINT uLen; dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle ); LPBYTE lpData = new BYTE[dwLength]; GetFileVersionInfoW(wszData, 0, dwLength, lpData ); bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen ); if(bFoundLocalVerInfo) { dwExistingFileVerMS = pFileInfo->dwFileVersionMS; dwExistingFileVerLS = pFileInfo->dwFileVersionLS; } delete [] lpData; } // Test if the code base ends in #version=a,b,c,d const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#')); if (szHash) { if (wcsnicmp(szHash, L"#version=", 9) == 0) { int a, b, c, d; if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4) { dwFileVersionMS = MAKELONG(b,a); dwFileVersionLS = MAKELONG(d,c); //If local version info was found compare it if(bFoundLocalVerInfo) { if(dwFileVersionMS > dwExistingFileVerMS) bUpdateControlVersion = TRUE; if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS)) bUpdateControlVersion = TRUE; } } } szURL = _wcsdup(szCodebase); // Terminate at the hash mark if (szURL) szURL[szHash - szCodebase] = wchar_t('\0'); } else { szURL = _wcsdup(szCodebase); } } CComPtr<IUnknown> spObject; HRESULT hr; //If the control needs to be updated do not call CoCreateInstance otherwise you will lock files //and force a reboot on CoGetClassObjectFromURL if(!bUpdateControlVersion) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { // Assume scripting via IDispatch if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch))) { return E_FAIL; } // Drop through, success! } } // Do we need to download the control? if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion)) { if (!szURL) return E_OUTOFMEMORY; CComPtr<IBindCtx> spBindContext; CComPtr<IBindStatusCallback> spBindStatusCallback; CComPtr<IBindStatusCallback> spOldBSC; // Create our own bind context or use the one provided? BOOL useInternalBSC = FALSE; if (!pBindContext) { useInternalBSC = TRUE; hr = CreateBindCtx(0, &spBindContext); if (FAILED(hr)) { free(szURL); return hr; } spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this); hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0); if (FAILED(hr)) { free(szURL); return hr; } } else { spBindContext = pBindContext; } //If the version from the CODEBASE value is greater than the installed control //Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt if(bUpdateControlVersion) { hr = CoGetClassObjectFromURL(CLSID_NULL, szCodebase, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER, 0, IID_IClassFactory, NULL); } else { hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown, NULL); } free(szURL); // Handle the internal binding synchronously so the object exists // or an error code is available when the method returns. if (useInternalBSC) { if (MK_S_ASYNCHRONOUS == hr) { m_bBindingInProgress = TRUE; m_hrBindResult = E_FAIL; // Spin around waiting for binding to complete HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); while (m_bBindingInProgress) { MSG msg; // Process pending messages while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!::GetMessage(&msg, NULL, 0, 0)) { m_bBindingInProgress = FALSE; break; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if (!m_bBindingInProgress) break; // Sleep for a bit or the next msg to appear ::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS); } ::CloseHandle(hFakeEvent); // Set the result hr = m_hrBindResult; } // Destroy the bind status callback & context if (spBindStatusCallback) { RevokeBindStatusCallback(spBindContext, spBindStatusCallback); spBindStatusCallback.Release(); spBindContext.Release(); } } //added to create control if (SUCCEEDED(hr)) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { // Assume scripting via IDispatch if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch))) { hr = E_FAIL; } } } //EOF test code } if (spObject) { m_spObject = spObject; } return hr; } // Attach the created control to a window and activate it HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream) { TRACE_METHOD(CControlSite::Attach); if (hwndParent == NULL) { NS_ASSERTION(0, "No parent hwnd"); return E_INVALIDARG; } m_hWndParent = hwndParent; m_rcObjectPos = rcPos; // Object must have been created if (m_spObject == NULL) { return E_UNEXPECTED; } m_spIViewObject = m_spObject; m_spIOleObject = m_spObject; if (m_spIOleObject == NULL) { return E_FAIL; } DWORD dwMiscStatus; m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus); if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST) { m_bSetClientSiteFirst = TRUE; } if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME) { m_bVisibleAtRuntime = FALSE; } // Some objects like to have the client site as the first thing // to be initialised (for ambient properties and so forth) if (m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } // If there is a parameter list for the object and no init stream then // create one here. CPropertyBagInstance *pPropertyBag = NULL; if (pInitStream == NULL && m_ParameterList.GetSize() > 0) { CPropertyBagInstance::CreateInstance(&pPropertyBag); pPropertyBag->AddRef(); for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++) { pPropertyBag->Write(m_ParameterList.GetNameOf(i), const_cast<VARIANT *>(m_ParameterList.GetValueOf(i))); } pInitStream = (IPersistPropertyBag *) pPropertyBag; } // Initialise the control from store if one is provided if (pInitStream) { CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream; CComQIPtr<IStream, &IID_IStream> spStream = pInitStream; CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject; CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject; if (spIPersistPropertyBag && spPropertyBag) { spIPersistPropertyBag->Load(spPropertyBag, NULL); } else if (spIPersistStream && spStream) { spIPersistStream->Load(spStream); } } else { // Initialise the object if possible CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject; if (spIPersistStreamInit) { spIPersistStreamInit->InitNew(); } } m_spIOleInPlaceObject = m_spObject; m_spIOleInPlaceObjectWindowless = m_spObject; if (m_spIOleInPlaceObject) { SetPosition(m_rcObjectPos); } // In-place activate the object if (m_bVisibleAtRuntime) { DoVerb(OLEIVERB_INPLACEACTIVATE); } // For those objects which haven't had their client site set yet, // it's done here. if (!m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } return S_OK; } // Unhook the control from the window and throw it all away HRESULT CControlSite::Detach() { TRACE_METHOD(CControlSite::Detach); if (m_spIOleInPlaceObjectWindowless) { m_spIOleInPlaceObjectWindowless.Release(); } if (m_spIOleInPlaceObject) { m_spIOleInPlaceObject->InPlaceDeactivate(); m_spIOleInPlaceObject.Release(); } if (m_spIOleObject) { m_spIOleObject->Close(OLECLOSE_NOSAVE); m_spIOleObject->SetClientSite(NULL); m_spIOleObject.Release(); } m_spIViewObject.Release(); m_spObject.Release(); return S_OK; } // Return the IUnknown of the contained control HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject) { *ppObject = NULL; if (m_spObject) { m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject); } return S_OK; } // Subscribe to an event sink on the control HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } if (pIUnkSink == NULL || pdwCookie == NULL) { return E_INVALIDARG; } return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie); } // Unsubscribe event sink from the control HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } return AtlUnadvise(m_spObject, iid, dwCookie); } // Draw the control HRESULT CControlSite::Draw(HDC hdc) { TRACE_METHOD(CControlSite::Draw); // Draw only when control is windowless or deactivated if (m_spIViewObject) { if (m_bWindowless || !m_bInPlaceActive) { RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos; m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0); } } else { // Draw something to indicate no control is there HBRUSH hbr = CreateSolidBrush(RGB(200,200,200)); FillRect(hdc, &m_rcObjectPos, hbr); DeleteObject(hbr); } return S_OK; } // Execute the specified verb HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg) { TRACE_METHOD(CControlSite::DoVerb); if (m_spIOleObject == NULL) { return E_FAIL; } return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos); } // Set the position on the control HRESULT CControlSite::SetPosition(const RECT &rcPos) { HWND hwnd; TRACE_METHOD(CControlSite::SetPosition); m_rcObjectPos = rcPos; if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd))) { m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos); } return S_OK; } void CControlSite::FireAmbientPropertyChange(DISPID id) { if (m_spObject) { CComQIPtr<IOleControl> spControl = m_spObject; if (spControl) { spControl->OnAmbientPropertyChange(id); } } } void CControlSite::SetAmbientUserMode(BOOL bUserMode) { bool bNewMode = bUserMode ? true : false; if (m_bAmbientUserMode != bNewMode) { m_bAmbientUserMode = bNewMode; FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE); } } /////////////////////////////////////////////////////////////////////////////// // CControlSiteSecurityPolicy implementation CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy() { static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy; return &defaultControlSecurityPolicy; } // Test if the class is safe to host BOOL CControlSite::IsClassSafeToHost(const CLSID & clsid) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsClassSafeToHost(clsid); return TRUE; } // Test if the specified class is marked safe for scripting BOOL CControlSite::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists); return TRUE; } // Test if the instantiated object is safe for scripting on the specified interface BOOL CControlSite::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsObjectSafeForScripting(pObject, iid); return TRUE; } BOOL CControlSite::IsObjectSafeForScripting(const IID &iid) { return IsObjectSafeForScripting(m_spObject, iid); } /////////////////////////////////////////////////////////////////////////////// // IServiceProvider implementation HRESULT STDMETHODCALLTYPE CControlSite::QueryService(REFGUID guidService, REFIID riid, void** ppv) { if (m_spServiceProvider) return m_spServiceProvider->QueryService(guidService, riid, ppv); return E_NOINTERFACE; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { if (wFlags & DISPATCH_PROPERTYGET) { CComVariant vResult; switch (dispIdMember) { case DISPID_AMBIENT_APPEARANCE: vResult = CComVariant(m_bAmbientAppearance); break; case DISPID_AMBIENT_FORECOLOR: vResult = CComVariant((long) m_clrAmbientForeColor); break; case DISPID_AMBIENT_BACKCOLOR: vResult = CComVariant((long) m_clrAmbientBackColor); break; case DISPID_AMBIENT_LOCALEID: vResult = CComVariant((long) m_nAmbientLocale); break; case DISPID_AMBIENT_USERMODE: vResult = CComVariant(m_bAmbientUserMode); break; case DISPID_AMBIENT_SHOWGRABHANDLES: vResult = CComVariant(m_bAmbientShowGrabHandles); break; case DISPID_AMBIENT_SHOWHATCHING: vResult = CComVariant(m_bAmbientShowHatching); break; default: return DISP_E_MEMBERNOTFOUND; } VariantCopy(pVarResult, &vResult); return S_OK; } return E_FAIL; } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink implementation void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed) { } void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex) { // Redraw the control InvalidateRect(NULL, FALSE); } void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk) { } void STDMETHODCALLTYPE CControlSite::OnSave(void) { } void STDMETHODCALLTYPE CControlSite::OnClose(void) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink2 implementation void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSinkEx implementation void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus) { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { *phwnd = m_hWndParent; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleClientSite implementation HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer) { if (!ppContainer) return E_INVALIDARG; *ppContainer = m_spContainer; if (*ppContainer) { (*ppContainer)->AddRef(); } return (*ppContainer) ? S_OK : E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSite implementation HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void) { m_bInPlaceActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void) { m_bUIActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo) { *lprcPosRect = m_rcObjectPos; *lprcClipRect = m_rcObjectPos; CControlSiteIPFrameInstance *pIPFrame = NULL; CControlSiteIPFrameInstance::CreateInstance(&pIPFrame); pIPFrame->AddRef(); *ppFrame = (IOleInPlaceFrame *) pIPFrame; *ppDoc = NULL; lpFrameInfo->fMDIApp = FALSE; lpFrameInfo->hwndFrame = NULL; lpFrameInfo->haccel = NULL; lpFrameInfo->cAccelEntries = 0; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable) { m_bUIActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect) { if (lprcPosRect == NULL) { return E_INVALIDARG; } SetPosition(m_rcObjectPos); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteEx implementation HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags) { m_bInPlaceActive = TRUE; if (pfNoRedraw) { *pfNoRedraw = FALSE; } if (dwFlags & ACTIVATE_WINDOWLESS) { if (!m_bSupportWindowlessActivation) { return E_INVALIDARG; } m_bWindowless = TRUE; } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void) { return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteWindowless implementation HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void) { // Allow windowless activation? return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC) { if (phDC == NULL) { return E_INVALIDARG; } // Can't do nested painting if (m_hDCBuffer != NULL) { return E_UNEXPECTED; } m_rcBuffer = m_rcObjectPos; if (pRect != NULL) { m_rcBuffer = *pRect; } m_hBMBuffer = NULL; m_dwBufferFlags = grfFlags; // See if the control wants a DC that is onscreen or offscreen if (m_dwBufferFlags & OLEDC_OFFSCREEN) { m_hDCBuffer = CreateCompatibleDC(NULL); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy); m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer); SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL); // TODO When OLEDC_PAINTBKGND we must draw every site behind this one } else { // TODO When OLEDC_PAINTBKGND we must draw every site behind this one // Get the window DC m_hDCBuffer = GetWindowDC(m_hWndParent); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } // Clip the control so it can't trash anywhere it isn't allowed to draw if (!(m_dwBufferFlags & OLEDC_NODRAW)) { m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer); // TODO Clip out opaque areas of sites behind this one SelectClipRgn(m_hDCBuffer, m_hRgnBuffer); } } *phDC = m_hDCBuffer; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC) { // Release the DC if (hDC == NULL || hDC != m_hDCBuffer) { return E_INVALIDARG; } // Test if the DC was offscreen or onscreen if ((m_dwBufferFlags & OLEDC_OFFSCREEN) && !(m_dwBufferFlags & OLEDC_NODRAW)) { // BitBlt the buffer into the control's object SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL); HDC hdc = GetWindowDC(m_hWndParent); long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY); ::ReleaseDC(m_hWndParent, hdc); } else { // TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one } // Clean up settings ready for next drawing if (m_hRgnBuffer) { SelectClipRgn(m_hDCBuffer, NULL); DeleteObject(m_hRgnBuffer); m_hRgnBuffer = NULL; } SelectObject(m_hDCBuffer, m_hBMBufferOld); if (m_hBMBuffer) { DeleteObject(m_hBMBuffer); m_hBMBuffer = NULL; } // Delete the DC if (m_dwBufferFlags & OLEDC_OFFSCREEN) { ::DeleteDC(m_hDCBuffer); } else { ::ReleaseDC(m_hWndParent, m_hDCBuffer); } m_hDCBuffer = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase) { // Clip the rectangle against the object's size and invalidate it RECT rcI = { 0, 0, 0, 0 }; if (pRect == NULL) { rcI = m_rcObjectPos; } else { IntersectRect(&rcI, &m_rcObjectPos, pRect); } ::InvalidateRect(m_hWndParent, &rcI, fErase); return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase) { if (hRGN == NULL) { ::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase); } else { // Clip the region with the object's bounding area HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos); if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR) { ::InvalidateRgn(m_hWndParent, hrgnClip, fErase); } DeleteObject(hrgnClip); } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc) { if (prc == NULL) { return E_INVALIDARG; } // Clip the rectangle against the object position RECT rcI = { 0, 0, 0, 0 }; IntersectRect(&rcI, &m_rcObjectPos, prc); *prc = rcI; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult) { if (plResult == NULL) { return E_INVALIDARG; } // Pass the message to the windowless control if (m_bWindowless && m_spIOleInPlaceObjectWindowless) { return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult); } else if (m_spIOleInPlaceObject) { HWND wnd; if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd))) SendMessage(wnd, msg, wParam, lParam); } return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleControlSite implementation HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock) { m_bInPlaceLocked = fLock; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags) { HRESULT hr = S_OK; if (pPtlHimetric == NULL) { return E_INVALIDARG; } if (pPtfContainer == NULL) { return E_INVALIDARG; } HDC hdc = ::GetDC(m_hWndParent); ::SetMapMode(hdc, MM_HIMETRIC); POINT rgptConvert[2]; rgptConvert[0].x = 0; rgptConvert[0].y = 0; if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER) { rgptConvert[1].x = pPtlHimetric->x; rgptConvert[1].y = pPtlHimetric->y; ::LPtoDP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x); pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y); } else if (dwFlags & XFORMCOORDS_POSITION) { pPtfContainer->x = (float)rgptConvert[1].x; pPtfContainer->y = (float)rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC) { rgptConvert[1].x = (int)(pPtfContainer->x); rgptConvert[1].y = (int)(pPtfContainer->y); ::DPtoLP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x; pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y; } else if (dwFlags & XFORMCOORDS_POSITION) { pPtlHimetric->x = rgptConvert[1].x; pPtlHimetric->y = rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else { hr = E_INVALIDARG; } ::ReleaseDC(m_hWndParent, hdc); return hr; } HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IBindStatusCallback implementation HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved, IBinding __RPC_FAR *pib) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError) { m_bBindingInProgress = FALSE; m_hrBindResult = hresult; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF, BINDINFO __RPC_FAR *pbindInfo) { *pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE; pbindInfo->cbSize = sizeof(BINDINFO); pbindInfo->szExtraInfo = NULL; memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM)); pbindInfo->grfBindInfoF = 0; pbindInfo->dwBindVerb = 0; pbindInfo->szCustomVerb = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC __RPC_FAR *pformatetc, STGMEDIUM __RPC_FAR *pstgmed) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid, IUnknown __RPC_FAR *punk) { return S_OK; } // IWindowForBindingUI HRESULT STDMETHODCALLTYPE CControlSite::GetWindow( /* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd) { *phwnd = NULL; return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITEIPFRAME_H #define CONTROLSITEIPFRAME_H class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>, public IOleInPlaceFrame { public: CControlSiteIPFrame(); virtual ~CControlSiteIPFrame(); HWND m_hwndFrame; BEGIN_COM_MAP(CControlSiteIPFrame) COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY(IOleInPlaceFrame) END_COM_MAP() // IOleWindow virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleInPlaceUIWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName); // IOleInPlaceFrame implementation virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject); virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText); virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID); }; typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef IOLECOMMANDIMPL_H #define IOLECOMMANDIMPL_H // Implementation of the IOleCommandTarget interface. The template is // reasonably generic and reusable which is a good thing given how needlessly // complicated this interface is. Blame Microsoft for that and not me. // // To use this class, derive your class from it like this: // // class CComMyClass : public IOleCommandTargetImpl<CComMyClass> // { // ... Ensure IOleCommandTarget is listed in the interface map ... // BEGIN_COM_MAP(CComMyClass) // COM_INTERFACE_ENTRY(IOleCommandTarget) // // etc. // END_COM_MAP() // ... And then later on define the command target table ... // BEGIN_OLECOMMAND_TABLE() // OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page") // OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page") // OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode") // END_OLECOMMAND_TABLE() // ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ... // HWND GetCommandTargetWindow() const // { // return m_hWnd; // } // ... Now procedures that OLECOMMAND_HANDLER calls ... // static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); // } // // The command table defines which commands the object supports. Commands are // defined by a command id and a command group plus a WM_COMMAND id or procedure, // and a verb and short description. // // Notice that there are two macros for handling Ole Commands. The first, // OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from // GetCommandTargetWindow() (that the derived class must implement if it uses // this macro). // // The second, OLECOMMAND_HANDLER calls a static handler procedure that // conforms to the OleCommandProc typedef. The first parameter, pThis means // the static handler has access to the methods and variables in the class // instance. // // The OLECOMMAND_HANDLER macro is generally more useful when a command // takes parameters or needs to return a result to the caller. // template< class T > class IOleCommandTargetImpl : public IOleCommandTarget { struct OleExecData { const GUID *pguidCmdGroup; DWORD nCmdID; DWORD nCmdexecopt; VARIANT *pvaIn; VARIANT *pvaOut; }; public: typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); struct OleCommandInfo { ULONG nCmdID; const GUID *pCmdGUID; ULONG nWindowsCmdID; OleCommandProc pfnCommandProc; wchar_t *szVerbText; wchar_t *szStatusText; }; // Query the status of the specified commands (test if is it supported etc.) virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText) { T* pT = static_cast<T*>(this); if (prgCmds == NULL) { return E_INVALIDARG; } OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); BOOL bCmdGroupFound = FALSE; BOOL bTextSet = FALSE; // Iterate through list of commands and flag them as supported/unsupported for (ULONG nCmd = 0; nCmd < cCmds; nCmd++) { // Unsupported by default prgCmds[nCmd].cmdf = 0; // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != prgCmds[nCmd].cmdID) { continue; } // Command is supported so flag it and possibly enable it prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED; if (pCI->nWindowsCmdID != 0) { prgCmds[nCmd].cmdf |= OLECMDF_ENABLED; } // Copy the status/verb text for the first supported command only if (!bTextSet && pCmdText) { // See what text the caller wants wchar_t *pszTextToCopy = NULL; if (pCmdText->cmdtextf & OLECMDTEXTF_NAME) { pszTextToCopy = pCI->szVerbText; } else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS) { pszTextToCopy = pCI->szStatusText; } // Copy the text pCmdText->cwActual = 0; memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t)); if (pszTextToCopy) { // Don't exceed the provided buffer size size_t nTextLen = wcslen(pszTextToCopy); if (nTextLen > pCmdText->cwBuf) { nTextLen = pCmdText->cwBuf; } wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen); pCmdText->cwActual = nTextLen; } bTextSet = TRUE; } break; } } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return S_OK; } // Execute the specified command virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut) { T* pT = static_cast<T*>(this); BOOL bCmdGroupFound = FALSE; OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != nCmdID) { continue; } // Send ourselves a WM_COMMAND windows message with the associated // identifier and exec data OleExecData cData; cData.pguidCmdGroup = pguidCmdGroup; cData.nCmdID = nCmdID; cData.nCmdexecopt = nCmdexecopt; cData.pvaIn = pvaIn; cData.pvaOut = pvaOut; if (pCI->pfnCommandProc) { pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut); } else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP) { HWND hwndTarget = pT->GetCommandTargetWindow(); if (hwndTarget) { ::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData); } } else { // Command supported but not implemented continue; } return S_OK; } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return OLECMDERR_E_NOTSUPPORTED; } }; // Macros to be placed in any class derived from the IOleCommandTargetImpl // class. These define what commands are exposed from the object. #define BEGIN_OLECOMMAND_TABLE() \ OleCommandInfo *GetCommandTable() \ { \ static OleCommandInfo s_aSupportedCommands[] = \ { #define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \ { id, group, cmd, NULL, verb, desc }, #define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \ { id, group, 0, handler, verb, desc }, #define END_OLECOMMAND_TABLE() \ { 0, &GUID_NULL, 0, NULL, NULL, NULL } \ }; \ return s_aSupportedCommands; \ }; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYLIST_H #define PROPERTYLIST_H // A simple array class for managing name/value pairs typically fed to controls // during initialization by IPersistPropertyBag class PropertyList { struct Property { BSTR bstrName; VARIANT vValue; } *mProperties; unsigned long mListSize; unsigned long mMaxListSize; bool EnsureMoreSpace() { // Ensure enough space exists to accomodate a new item const unsigned long kGrowBy = 10; if (!mProperties) { mProperties = (Property *) malloc(sizeof(Property) * kGrowBy); if (!mProperties) return false; mMaxListSize = kGrowBy; } else if (mListSize == mMaxListSize) { Property *pNewProperties; pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy)); if (!pNewProperties) return false; mProperties = pNewProperties; mMaxListSize += kGrowBy; } return true; } public: PropertyList() : mProperties(NULL), mListSize(0), mMaxListSize(0) { } ~PropertyList() { } void Clear() { if (mProperties) { for (unsigned long i = 0; i < mListSize; i++) { SysFreeString(mProperties[i].bstrName); // Safe even if NULL VariantClear(&mProperties[i].vValue); } free(mProperties); mProperties = NULL; } mListSize = 0; mMaxListSize = 0; } unsigned long GetSize() const { return mListSize; } const BSTR GetNameOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return mProperties[nIndex].bstrName; } const VARIANT *GetValueOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return &mProperties[nIndex].vValue; } bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName) return false; for (unsigned long i = 0; i < GetSize(); i++) { // Case insensitive if (wcsicmp(mProperties[i].bstrName, bstrName) == 0) { return SUCCEEDED( VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue))); } } return AddNamedProperty(bstrName, vValue); } bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName || !EnsureMoreSpace()) return false; Property *pProp = &mProperties[mListSize]; pProp->bstrName = ::SysAllocString(bstrName); if (!pProp->bstrName) { return false; } VariantInit(&pProp->vValue); if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue)))) { SysFreeString(pProp->bstrName); return false; } mListSize++; return true; } }; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef ITEMCONTAINER_H #define ITEMCONTAINER_H // typedef std::map<tstring, CIUnkPtr> CNamedObjectList; // Class for managing a list of named objects. class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>, public IOleItemContainer { // CNamedObjectList m_cNamedObjectList; public: CItemContainer(); virtual ~CItemContainer(); BEGIN_COM_MAP(CItemContainer) COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer) END_COM_MAP() // IParseDisplayName implementation virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut); // IOleContainer implementation virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum); virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock); // IOleItemContainer implementation virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage); virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem); }; typedef CComObject<CItemContainer> CItemContainerInstance; #endif
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winbase.h> // ---------------------------------------------------------------------------- int main (int ArgC, char *ArgV[]) { const char *sourceName; const char *targetName; HANDLE targetHandle; void *versionPtr; DWORD versionLen; int lastError; int ret = 0; if (ArgC < 3) { fprintf(stderr, "Usage: %s <source> <target>\n", ArgV[0]); exit (1); } sourceName = ArgV[1]; targetName = ArgV[2]; if ((versionLen = GetFileVersionInfoSize(sourceName, NULL)) == 0) { fprintf(stderr, "Could not retrieve version len from %s\n", sourceName); exit (2); } if ((versionPtr = calloc(1, versionLen)) == NULL) { fprintf(stderr, "Error allocating temp memory\n"); exit (3); } if (!GetFileVersionInfo(sourceName, NULL, versionLen, versionPtr)) { fprintf(stderr, "Could not retrieve version info from %s\n", sourceName); exit (4); } if ((targetHandle = BeginUpdateResource(targetName, FALSE)) == INVALID_HANDLE_VALUE) { fprintf(stderr, "Could not begin update of %s\n", targetName); free(versionPtr); exit (5); } if (!UpdateResource(targetHandle, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), versionPtr, versionLen)) { lastError = GetLastError(); fprintf(stderr, "Error %d updating resource\n", lastError); ret = 6; } if (!EndUpdateResource(targetHandle, FALSE)) { fprintf(stderr, "Error finishing update\n"); ret = 7; } free(versionPtr); return (ret); }
C++
[Files] Source: {#xbasepath}\Release\npffax.dll; DestDir: {app}; DestName: npffax.dll; Flags: overwritereadonly restartreplace uninsrestartdelete [Registry] Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; Flags: uninsdeletekey Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Description; ValueData: {#MyAppName} {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: ProductName; ValueData: {#MyAppName} {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Path; ValueData: {app}\npffax.dll Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Version; ValueData: {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes; ValueType: string; ValueName: Dummy; ValueData: {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex; ValueType: string; ValueName: "Dummy"; ValueData: "{#xversion}"
C++
;================================================================ ; Edit the Report Descriptor here. ; The example descriptor below defines two vendor defined report: ; One Input Report and one Output Report of 8 bits size data. movf FRAME_NUMBER,W xorlw 0x01 btfsc STATUS,Z goto GRD_Frame1 movf FRAME_NUMBER,W xorlw 0x02 btfsc STATUS,Z goto GRD_Frame2 movf FRAME_NUMBER,W xorlw 0x03 btfsc STATUS,Z goto GRD_Frame3 GRD_Frame0: movlw 0x06 ; Usage Page movwf TX_BUFFER+1 movlw 0xA0 ; vendor-defined low movwf TX_BUFFER+2 movlw 0xFF ; vendor-defined high movwf TX_BUFFER+3 movlw 0x09 ; Usage movwf TX_BUFFER+4 movlw 0x01 ; vendor-defined movwf TX_BUFFER+5 movlw 0xA1 ; Collection movwf TX_BUFFER+6 movlw 0x01 ; application movwf TX_BUFFER+7 movlw 0x09 ; Usage movwf TX_BUFFER+8 return GRD_Frame1: movlw 0x03 ; vendor-defined movwf TX_BUFFER+1 movlw 0x15 ; Logical Minimum movwf TX_BUFFER+2 clrf TX_BUFFER+3 ; 0 movlw 0x26 ; Logical Maximum movwf TX_BUFFER+4 movlw 0xFF ; 255 movwf TX_BUFFER+5 clrf TX_BUFFER+6 ; 0 movlw 0x75 ; Report Size movwf TX_BUFFER+7 movlw 0x08 ; 8 bits movwf TX_BUFFER+8 return GRD_Frame2: movlw 0x95 ; Report Count movwf TX_BUFFER+1 movlw 0x01 ; 1 byte movwf TX_BUFFER+2 movlw 0x81 ; Input movwf TX_BUFFER+3 movlw 0x02 ; (Data, Variable, Absolute) movwf TX_BUFFER+4 movlw 0x09 ; Usage movwf TX_BUFFER+5 movlw 0x04 movwf TX_BUFFER+6 ; vendor-defined movlw 0x91 ; Output movwf TX_BUFFER+7 movlw 0x02 ; (Data, Variable, Absolute) movwf TX_BUFFER+8 return GRD_Frame3: movlw 0xC0 ; End Collection movwf TX_BUFFER+1 return
C++
;================================================================ ; Edit the Report Descriptor here. ; The example descriptor below defines two vendor defined report: ; One Input Report and one Output Report of 8 bits size data. movf FRAME_NUMBER,W xorlw 0x01 btfsc STATUS,Z goto GRD_Frame1 movf FRAME_NUMBER,W xorlw 0x02 btfsc STATUS,Z goto GRD_Frame2 movf FRAME_NUMBER,W xorlw 0x03 btfsc STATUS,Z goto GRD_Frame3 GRD_Frame0: movlw 0x06 ; Usage Page movwf TX_BUFFER+1 movlw 0xA0 ; vendor-defined low movwf TX_BUFFER+2 movlw 0xFF ; vendor-defined high movwf TX_BUFFER+3 movlw 0x09 ; Usage movwf TX_BUFFER+4 movlw 0x01 ; vendor-defined movwf TX_BUFFER+5 movlw 0xA1 ; Collection movwf TX_BUFFER+6 movlw 0x01 ; application movwf TX_BUFFER+7 movlw 0x09 ; Usage movwf TX_BUFFER+8 return GRD_Frame1: movlw 0x03 ; vendor-defined movwf TX_BUFFER+1 movlw 0x15 ; Logical Minimum movwf TX_BUFFER+2 clrf TX_BUFFER+3 ; 0 movlw 0x26 ; Logical Maximum movwf TX_BUFFER+4 movlw 0xFF ; 255 movwf TX_BUFFER+5 clrf TX_BUFFER+6 ; 0 movlw 0x75 ; Report Size movwf TX_BUFFER+7 movlw 0x08 ; 8 bits movwf TX_BUFFER+8 return GRD_Frame2: movlw 0x95 ; Report Count movwf TX_BUFFER+1 movlw 0x01 ; 1 byte movwf TX_BUFFER+2 movlw 0x81 ; Input movwf TX_BUFFER+3 movlw 0x02 ; (Data, Variable, Absolute) movwf TX_BUFFER+4 movlw 0x09 ; Usage movwf TX_BUFFER+5 movlw 0x04 movwf TX_BUFFER+6 ; vendor-defined movlw 0x91 ; Output movwf TX_BUFFER+7 movlw 0x02 ; (Data, Variable, Absolute) movwf TX_BUFFER+8 return GRD_Frame3: movlw 0xC0 ; End Collection movwf TX_BUFFER+1 return
C++
;================================================================ ; Edit the Report Descriptor here. ; The example descriptor below defines two vendor defined report: ; One Input Report and one Output Report of 8 bits size data. movf FRAME_NUMBER,W xorlw 0x01 btfsc STATUS,Z goto GRD_Frame1 movf FRAME_NUMBER,W xorlw 0x02 btfsc STATUS,Z goto GRD_Frame2 movf FRAME_NUMBER,W xorlw 0x03 btfsc STATUS,Z goto GRD_Frame3 GRD_Frame0: movlw 0x06 ; Usage Page movwf TX_BUFFER+1 movlw 0xA0 ; vendor-defined low movwf TX_BUFFER+2 movlw 0xFF ; vendor-defined high movwf TX_BUFFER+3 movlw 0x09 ; Usage movwf TX_BUFFER+4 movlw 0x01 ; vendor-defined movwf TX_BUFFER+5 movlw 0xA1 ; Collection movwf TX_BUFFER+6 movlw 0x01 ; application movwf TX_BUFFER+7 movlw 0x09 ; Usage movwf TX_BUFFER+8 return GRD_Frame1: movlw 0x03 ; vendor-defined movwf TX_BUFFER+1 movlw 0x15 ; Logical Minimum movwf TX_BUFFER+2 clrf TX_BUFFER+3 ; 0 movlw 0x26 ; Logical Maximum movwf TX_BUFFER+4 movlw 0xFF ; 255 movwf TX_BUFFER+5 clrf TX_BUFFER+6 ; 0 movlw 0x75 ; Report Size movwf TX_BUFFER+7 movlw 0x08 ; 8 bits movwf TX_BUFFER+8 return GRD_Frame2: movlw 0x95 ; Report Count movwf TX_BUFFER+1 movlw 0x01 ; 1 byte movwf TX_BUFFER+2 movlw 0x81 ; Input movwf TX_BUFFER+3 movlw 0x02 ; (Data, Variable, Absolute) movwf TX_BUFFER+4 movlw 0x09 ; Usage movwf TX_BUFFER+5 movlw 0x04 movwf TX_BUFFER+6 ; vendor-defined movlw 0x91 ; Output movwf TX_BUFFER+7 movlw 0x02 ; (Data, Variable, Absolute) movwf TX_BUFFER+8 return GRD_Frame3: movlw 0xC0 ; End Collection movwf TX_BUFFER+1 return
C++
#pragma once #include "Node.h" class List{ public: List(); void Insert(int data); void Delete(int data); void Swap(int data1, int data2); void Sort(); void Print(); ~List(); private: Node* pHead; };
C++
#pragma once #include <iostream> using namespace std; class Node { public: Node() { data = 0; pNext = NULL; pPre = NULL; } void setData(int data) { this->data = data; } int getData() { return data; } void setNext(Node* pNext){ this->pNext = pNext; } Node* getNext() { return pNext; } void setPre(Node* pPre) { this->pPre = pPre; } Node* getPre() { return pPre; } ~Node() { } private: int data; Node* pNext; Node* pPre; };
C++
#include "ListNode.h" class DoubleLink { private: ListNode* pHead ; ListNode* pTail; public: DoubleLink(); void Insert(int node); bool Delete(int targetData); void Swap(int swapData_1, int swapData_2); void print(); };
C++
#include "node.h" class list{ private: node* pHead; node* pTail; public: list() { pHead = NULL; pTail = NULL; } ~list() {} void swap_data(int a, int b); void Insert(int _d); void Delete(int _d); void print(); void sort(); };
C++
#include <iostream> using namespace std;
C++
#include "global.h" class node{ private: node* pNext; node* pRear; int data; public: node() { pNext = NULL; pRear = NULL; data = 0; } ~node() {} void setNext(node* _n) {pNext = _n;} node* getNext() {return pNext;} void setRear(node* _n) {pRear = _n;} node* getRear() {return pRear;} void setData(int _d) {data = _d;} int getData() {return data;} };
C++
#include "list.h" void list::Insert(int _d){ node* pNew = new node; pNew->setData(_d); if(pHead == NULL){ pHead = pNew; pTail = pNew; } else{ pTail->setNext(pNew); pNew->setRear(pTail); pTail = pNew; } } void list::Delete(int _d){ node* pCur = pHead; node* pPre = pCur; node* ptemp = NULL; if(pHead == NULL){ cout<<"pHead is NULL!"<<endl; return; } if(pHead->getData() == _d){ pHead = pHead->getNext(); pHead->setRear(NULL); delete pCur; return; } else if(pTail->getData() == _d){ pCur = pTail; pTail = pTail->getRear(); pTail->setNext(NULL); delete pCur; return; } //target delete data is not head or tail; while(pCur){ if(pPre->getData() == _d){ break; } pPre = pCur; pCur = pCur->getNext(); } pPre->getRear()->setNext(pPre->getNext() ); pPre->getNext()->setRear(pPre->getRear() ); delete pPre; } void list::print(){ node* pCur = pHead; node* pPre = pCur; cout<<"=====PRINT Data====="<<endl; while(pPre != pTail){ cout<<pCur->getData()<<" "; pPre = pCur; pCur = pCur->getNext(); cout<<endl; } } void list::swap_data(int a, int b){ node* pCur = pHead; node* pPre = pCur; node* target_a = NULL; node* target_b = NULL; //search target. while(pCur){ pPre = pCur; pCur = pCur->getNext(); if(pPre->getData() == a) target_a = pPre; if(pPre->getData() == b) target_b = pPre; } if(target_a == NULL || target_b == NULL){ cout<<"data search fail"<<endl; return; } if(target_a->getNext() == target_b || target_b->getNext() == target_a){ //인접시 target_a->setNext(target_b->getNext()); target_b->setRear(target_a->getRear()); if(target_a->getRear() != NULL){ target_a->getRear()->setNext(target_b); } if(target_b->getNext() != NULL){ target_b->getNext()->setRear(target_a); } target_b->setNext(target_a); target_a->setRear(target_b); } else{ //비인접시 node* temp_a_next = target_a->getNext(); node* temp_b_rear = target_b->getRear(); target_a->getNext()->setRear(target_b); target_b->getRear()->setNext(target_a); if(target_a->getRear() != NULL){ target_a->getRear()->setNext(target_b); target_b->setRear(target_a->getRear()); } if(target_b->getNext() != NULL){ target_b->getNext()->setRear(target_a); target_a->setNext(target_b->getNext()); } target_b->setNext(temp_a_next); target_a->setRear(temp_b_rear); } if(target_a == pHead) pHead = target_b; if(target_b == pTail) pTail = target_a; } void list::sort(){ node* pCur = pHead; node* pPre = pCur; while(pPre != pTail){ if(pPre->getData() > pPre->getNext()->getData() ){ swap_data(pPre->getData(),pPre->getNext()->getData() ); pCur = pHead; pPre = pCur; } pPre = pCur; pCur = pCur->getNext(); } }
C++
#include "list.h" int main(){ list aa; aa.Insert(5); aa.Insert(3); aa.Insert(2); aa.Insert(10); aa.Insert(15); aa.Insert(13); aa.print(); aa.swap_data(5,13); //aa.sort(); aa.print(); return 0; }
C++
#include "node.h" class list{ private: node* pHead; node* pTail; public: list() { pHead = NULL; pTail = NULL; } ~list() {} void swap_data(int a, int b); void Insert(int _d); void Delete(int _d); void print(); };
C++
#include <iostream> using namespace std;
C++
#include "global.h" class node{ private: node* pNext; node* pRear; int data; public: node() { pNext = NULL; pRear = NULL; data = 0; } ~node() {} void setNext(node* _n) {pNext = _n;} node* getNext() {return pNext;} void setRear(node* _n) {pRear = _n;} node* getRear() {return pRear;} void setData(int _d) {data = _d;} int getData() {return data;} };
C++
#include "list.h" void list::Insert(int _d){ node* pNew = new node; pNew->setData(_d); pTail = pNew; node* pCur = pHead; node* pPre = pCur; if(pHead == NULL) pHead = pNew; else{ while(pCur){ pPre = pCur; pCur = pCur->getNext(); } pPre->setNext(pNew); //last node link pNew->setRear(pPre); //pNew link pre node } } void list::Delete(int _d){ node* pCur = pHead; node* pPre = pCur; node* temp = NULL; if(pHead == NULL){ cout<<"pHead is NULL"<<endl; return; } if(pHead->getData() == _d ) { temp = pHead; pHead = pHead->getNext(); delete temp; pHead->setRear(NULL); return; } else{//total node upper 2 while(pCur){ if(pPre->getData() == _d){ temp = pPre; break; } pPre = pCur; pCur = pCur->getNext(); } } if(temp == NULL){ cout<<"there is no target to delete !!"<<endl; return; } if(temp == pHead){ // target is pHead pHead = pHead->getNext(); pHead->setRear(NULL); delete temp; } else if(temp == pTail){ // target is tail; pTail->getRear()->setNext(NULL); delete temp; } else{ //target is middle temp->getRear()->setNext(temp->getNext() ); temp->getNext()->setRear(temp->getRear() ); delete temp; } } void list::print(){ node* pCur = pHead; node* pPre = pCur; cout<<"=====PRINT Data====="<<endl; while(pCur){ cout<<pCur->getData()<<" "; pPre = pCur; pCur = pCur->getNext(); cout<<endl; } } void list::swap_data(int a, int b){ node* pCur = pHead; node* pPre = pCur; node* target_a = NULL; node* target_b = NULL; node* temp = NULL; node* temp2 = NULL; if(pHead == NULL){ cout<<"pHead is NULL"<<endl; return; } while(pCur){ //match data pPre = pCur; pCur = pCur->getNext(); if(pPre->getData() == a){ target_a = pPre; } if(pPre->getData() == b){ target_b = pPre; } } if(target_a == NULL || target_b == NULL ) { cout<<a<<" or "<<b<<" are not here "<<endl; return; } if(target_a == pHead){ if(target_b == target_a->getNext() ) { //targetnodes are injected if(target_b->getNext() == NULL) { //2 node injected pHead = target_b; pTail = target_a; target_b->setNext(target_a); target_a->setRear(target_b); target_a->setNext(NULL); target_b->setRear(NULL); } else{ // 3 upper node injected target_a->setNext(target_b->getNext() ); target_a->setRear(target_b); target_b->setNext(target_a); target_b->setRear(NULL); pHead = target_b; } } else if(target_b == pTail){ pHead->setRear(pTail->getRear() ); pTail->setNext(pHead->getNext() ); pHead->setNext(NULL); pTail->setRear(NULL); } else{//target_b is middle temp = target_a->getNext(); target_a->setNext(target_b->getNext() ); target_b->getNext()->setRear(target_a); target_b->getRear()->setNext(target_a); target_a->setRear(target_b->getRear() ); target_b->setRear(NULL); target_b->setNext(temp); temp->setRear(target_b); pHead = target_b; } } else if(target_b == pTail){ if(target_a == target_b->getRear() ){ target_b->setRear(target_a->getRear() ); target_a->getRear()->setNext(target_b ); target_b->setNext(target_a); target_a->setRear(target_b); target_a->setNext(NULL); pTail = target_a; } else{ temp = target_b->getRear(); target_b->setNext(target_a->getNext() ); target_a->getNext()->setRear(target_b); target_b->setRear(target_a->getRear() ); target_a->getRear()->setNext(target_b); target_a->setRear(temp); temp->setNext(target_a); target_a->setNext(NULL); pTail = target_a; } } else{ //each are not tail,head temp = target_a->getNext(); temp2 = target_b->getRear(); target_a->setNext(target_b->getNext() ); temp2->setNext(target_a); target_b->setRear(target_a->getRear() ); target_b->getRear()->setNext(target_b); target_a->setRear(temp2); target_b->setNext(temp); temp->setRear(target_b); } }
C++
#include "list.h" int main(){ list aa; aa.Insert(5); aa.Insert(3); aa.Insert(2); aa.Insert(10); aa.Insert(15); aa.Insert(13); aa.print(); cout<<"swap"<<endl; aa.swap_data(3,15); aa.print(); return 0; }
C++
//빌딩 부시기. #include <iostream> #include <fstream> using namespace std; int check(int* array,int start_num,int B_num){ int cnt = 0; for(int i =0; i<B_num+1; i++){ if(array[start_num-1] <= array[i]) cnt++; } return cnt*start_num; } int main(){ ifstream fin; ofstream fout; fin.open("input"); fout.open("output"); int i = 0; int array[1000] = {0}; int B_num[1000] = {0}; fin>>B_num[0]; for(i = 0; i<B_num[0]; i++){ fin>>array[i]; cout<<array[i]<<" "; } cout<<endl; int cnt = 0; int max= 0; for(i=0; i<B_num[0]; i++){ B_num[i+1] = check(array,array[i],B_num[0]); } max = B_num[1]; for(i=0; i<6; i++){ cout<<B_num[i+1]<<" "; if(max <B_num[i+i]) max = B_num[i+1]; } cout<<endl; cout<<"max = "<<max<<endl; return 0; }
C++
#include "node.h" class list{ private: node* pHead; node* pTail; public: list() { pHead = NULL; pTail = NULL; } ~list() {} void swap_data(int a, int b); void Insert(int _d); void Delete(int _d); void print(); void sort(); };
C++
#include <iostream> using namespace std;
C++
#include "global.h" class node{ private: node* pNext; node* pRear; int data; public: node() { pNext = NULL; pRear = NULL; data = 0; } ~node() {} void setNext(node* _n) {pNext = _n;} node* getNext() {return pNext;} void setRear(node* _n) {pRear = _n;} node* getRear() {return pRear;} void setData(int _d) {data = _d;} int getData() {return data;} };
C++
#include "list.h" void list::Insert(int _d){ node* pNew = new node; pNew->setData(_d); pTail = pNew; node* pCur = pHead; node* pPre = pCur; if(pHead == NULL) pHead = pNew; else{ while(pCur){ pPre = pCur; pCur = pCur->getNext(); } pPre->setNext(pNew); //last node link pNew->setRear(pPre); //pNew link pre node } } void list::Delete(int _d){ node* pCur = pHead; node* pPre = pCur; node* temp = NULL; if(pHead == NULL){ cout<<"pHead is NULL"<<endl; return; } if(pHead->getData() == _d ) { temp = pHead; pHead = pHead->getNext(); delete temp; pHead->setRear(NULL); return; } else{//total node upper 2 while(pCur){ if(pPre->getData() == _d){ temp = pPre; break; } pPre = pCur; pCur = pCur->getNext(); } } if(temp == NULL){ cout<<"there is no target to delete !!"<<endl; return; } if(temp == pHead){ // target is pHead pHead = pHead->getNext(); pHead->setRear(NULL); delete temp; } else if(temp == pTail){ // target is tail; pTail->getRear()->setNext(NULL); delete temp; } else{ //target is middle temp->getRear()->setNext(temp->getNext() ); temp->getNext()->setRear(temp->getRear() ); delete temp; } } void list::print(){ node* pCur = pHead; node* pPre = pCur; cout<<"=====PRINT Data====="<<endl; while(pCur){ cout<<pCur->getData()<<" "; pPre = pCur; pCur = pCur->getNext(); cout<<endl; } } void list::swap_data(int a, int b){ node* pCur = pHead; node* pPre = pCur; node* target_a = NULL; node* target_b = NULL; node* temp = NULL; node* temp2 = NULL; if(pHead == NULL){ cout<<"pHead is NULL"<<endl; return; } while(pCur){ //match data pPre = pCur; pCur = pCur->getNext(); if(pPre->getData() == a){ target_a = pPre; } if(pPre->getData() == b){ target_b = pPre; } } if(target_a == NULL || target_b == NULL ) { cout<<a<<" or "<<b<<" are not here "<<endl; return; } if(target_a == pHead){ if(target_b == target_a->getNext() ) { //targetnodes are injected if(target_b->getNext() == NULL) { //2 node injected pHead = target_b; pTail = target_a; target_b->setNext(target_a); target_a->setRear(target_b); target_a->setNext(NULL); target_b->setRear(NULL); } else{ // 3 upper node injected target_a->setNext(target_b->getNext() ); target_a->setRear(target_b); target_b->setNext(target_a); target_b->setRear(NULL); pHead = target_b; } } else if(target_b == pTail){ pHead->setRear(pTail->getRear() ); pTail->setNext(pHead->getNext() ); pHead->setNext(NULL); pTail->setRear(NULL); } else{//target_b is middle temp = target_a->getNext(); target_a->setNext(target_b->getNext() ); target_b->getNext()->setRear(target_a); target_b->getRear()->setNext(target_a); target_a->setRear(target_b->getRear() ); target_b->setRear(NULL); target_b->setNext(temp); temp->setRear(target_b); pHead = target_b; } } else if(target_b == pTail){ if(target_a == target_b->getRear() ){ target_b->setRear(target_a->getRear() ); target_a->getRear()->setNext(target_b ); target_b->setNext(target_a); target_a->setRear(target_b); target_a->setNext(NULL); pTail = target_a; } else{ temp = target_b->getRear(); target_b->setNext(target_a->getNext() ); target_a->getNext()->setRear(target_b); target_b->setRear(target_a->getRear() ); target_a->getRear()->setNext(target_b); target_a->setRear(temp); temp->setNext(target_a); target_a->setNext(NULL); pTail = target_a; } } else{ //each are not tail,head if(target_a->getNext() != target_b){ temp = target_a->getNext(); temp2 = target_b->getRear(); target_a->setNext(target_b->getNext() ); temp2->setNext(target_a); target_b->setRear(target_a->getRear() ); target_b->getRear()->setNext(target_b); target_a->setRear(temp2); target_b->setNext(temp); temp->setRear(target_b); } else{ target_a->setNext(target_b->getNext()); target_b->getNext()->setRear(target_a); target_a->getRear()->setNext(target_b); target_b->setRear(target_a->getRear()); target_a->setRear(target_b); target_b->setNext(target_a); } } } void list::sort(){ node* pCur = pHead; node* pPre = pCur; while(pCur){ if(pPre->getData() > pPre->getNext()->getData() ){ swap_data(pPre->getData(),pPre->getNext()->getData() ); pCur = pHead; pPre = pCur; } pPre = pCur; pCur = pCur->getNext(); } }
C++
#include "list.h" int main(){ list aa; aa.Insert(5); aa.Insert(3); aa.Insert(2); aa.Insert(10); aa.Insert(15); aa.Insert(13); aa.print(); cout<<"swap"<<endl; aa.swap_data(3,2); aa.print(); aa.sort(); aa.print(); return 0; }
C++
//빌딩 부시기. #include <iostream> #include <fstream> using namespace std; int check(int* array,int start_num,int B_num){ int cnt = 0; for(int i =0; i<B_num+1; i++){ if(array[start_num-1] <= array[i]) cnt++; } return cnt*start_num; } int main(){ ifstream fin; ofstream fout; fin.open("input"); fout.open("output"); int i = 0; int array[1000] = {0}; int B_num[1000] = {0}; fin>>B_num[0]; for(i = 0; i<B_num[0]; i++){ fin>>array[i]; cout<<array[i]<<" "; } cout<<endl; int cnt = 0; int max= 0; for(i=0; i<B_num[0]; i++){ B_num[i+1] = check(array,array[i],B_num[0]); } max = B_num[1]; for(i=0; i<6; i++){ cout<<B_num[i+1]<<" "; if(max <B_num[i+i]) max = B_num[i+1]; } cout<<endl; cout<<"max = "<<max<<endl; return 0; }
C++
#include <iostream> #include <time.h> #include <stdlib.h> using namespace std; void monster1(){ int ID[7] = {0}; int m = 0; int i = 0; for(i = 0; i<10000000; i++){//천만 마리 처리. m = rand()%10000000; if(m >=0 && m <= 999) { ID[0]++; } else if (m >= 1000 && m <= 1999) { ID[1]++; } else if (m >=2000 && m <= 11999) { ID[2]++; } else if (m >= 12000 && m<= 21999) { ID[3]++; } else if (m >= 22000 && m <= 121999) { ID[4]++; } else if (m >= 122000 && m <= 1121999) { ID[5]++; } else{ ID[6]++; } } for(i=0; i<7; i++){ cout<<i+1<<"0 ITEM dropped : "<<ID[i]<<endl; } } int main() { srand((unsigned)time(NULL)); monster1(); return 0; }
C++
#include "DoubleList.h" DoubleList::DoubleList(void) { pHead=NULL; } DoubleList::~DoubleList(void) { if(pHead!=NULL){ Node* pTemp; Node* pCur=pHead; while(pCur->get_right()!=NULL){ pTemp=pCur; pCur=pCur->get_right(); delete pTemp; } } } void DoubleList::insert(int key){ Node* pNew=new Node; if(pHead==NULL){ pHead=pNew; pHead->set_data(key); } else{ Node* pCur=pHead; pNew->set_data(key); while(pCur->get_right()!=NULL){ pCur=pCur->get_right(); } pCur->set_right(pNew); pNew->set_left(pCur); } } void DoubleList::print(){ Node* pCur=pHead; cout<<"--------------------------------------"<<endl; while(pCur->get_right()!=NULL){ cout<<pCur->get_data()<<" "; pCur=pCur->get_right(); } cout<<endl; }
C++
#include <iostream> #include "DoubleList.h" using namespace std; int main(void){ DoubleList double_list; double_list.insert(1); double_list.insert(2); double_list.insert(3); double_list.insert(4); double_list.insert(5); double_list.insert(6); double_list.insert(7); double_list.insert(8); double_list.print(); system("pause"); return 0; }
C++
#include "Node.h" Node::Node(void) { Right=NULL; Left=NULL; data=0; } Node::~Node(void) { }
C++
#include "Node.h" #pragma once class DoubleList { private: Node* pHead; public: DoubleList(void); ~DoubleList(void); void Delete(int a); void insert(int a); void print(); };
C++
#include <iostream> #pragma once using namespace std; class Node { private: int data; Node* Right; Node* Left; public: Node(void); ~Node(void); int get_data(){return data;} void set_data(int a){data=a;} Node* get_right(){return Right;} Node* get_left(){return Left;} void set_right(Node* a){Right=a;} void set_left(Node* a){Left=a;} };
C++
#include "Node.h" Node::Node(void) { data=0; Right=NULL; Left=NULL; } Node::~Node(void) { }
C++
#include "Node.h" #pragma once class DoubleList { private: Node* pHead; public: DoubleList(void); ~DoubleList(void); void Delete(int a); void insert(int a); void print(); // void swap(Node** a, Node** b); void swap(int a, int b); Node* get_pHead(){return pHead;} void line_up(); };
C++
#pragma once #include <iostream> using namespace std; class Node { private: int data; Node* Right; Node* Left; public: Node(void); ~Node(void); int get_data(){return data;} void set_data(int a){data=a;} Node* get_right(){return Right;} Node* get_left(){return Left;} void set_right(Node* b){Right=b;} void set_left(Node* c){Left=c;} };
C++
#include "Node.h" Node::Node(void) { Right=NULL; Left=NULL; data=0; } Node::~Node(void) { }
C++
#include "DoubleList.h" DoubleList::DoubleList(void) { pHead=NULL; } DoubleList::~DoubleList(void) { if(pHead!=NULL){ Node* pTemp; Node* pCur=pHead; while(pCur->get_right()!=NULL){ pTemp=pCur; pCur=pCur->get_right(); delete pTemp; } } } void DoubleList::insert(int key){ Node* pNew=new Node; if(pHead==NULL){ pHead=pNew; pHead->set_data(key); } else{ Node* pCur=pHead; pNew->set_data(key); while(pCur->get_right()!=NULL){ pCur=pCur->get_right(); } pCur->set_right(pNew); pNew->set_left(pCur); } } void DoubleList::print(){ Node* pCur=pHead; while(pCur->get_right()!=NULL){ cout<<pCur->get_data()<<" "; pCur=pCur->get_right(); } cout<<endl; } void DoubleList::swap(Node** a,Node** b){ Node* temp; temp=*a; *a=*b; *b=temp; }
C++
#include "Node.h" #pragma once class DoubleList { private: Node* pHead; public: DoubleList(void); ~DoubleList(void); void Delete(int a); void insert(int a); void print(); void swap(Node** a, Node** b); Node* get_pHead(){return pHead;} };
C++
#pragma once #include <iostream> using namespace std; class Node { private: int data; Node* Right; Node* Left; public: Node(void); ~Node(void); int get_data(){return data;} void set_data(int a){data=a;} Node* get_right(){return Right;} Node* get_reft(){return Left;} void set_right(Node* b){Right=b;} void set_left(Node* c){Left=c;} };
C++
#include "Node.h" Node::Node(void) { Right=NULL; Left=NULL; data=0; } Node::~Node(void) { }
C++
#pragma once #include "node.h" class list { public: list(); void Insert(int num); void Delete(int num); void Swap(int a, int b); void Print(); ~list(); private: node* pHead; };
C++