mainwindow.cc

来自「c++的guiQt做的开发」· CC 代码 · 共 1,250 行 · 第 1/3 页

CC
1,250
字号
/** @file MainWindow - class representing main application window*/#include "mainwindow.h"#include "aboutwindow.h"#include "commandline.h"#include "dialog.h"#include "image.h"#include "imageview.h"#include "info.h"#include "lookandfeel.h"#include "main.h"#include "menu.h"#include "mpviewoptionwindow.h"#include "paramdialog.h"#include "settings.h"#include "statusbar.h"#include "toolbar.h"#include "version.h"#include <assert.h>#include <iostream>#include <util.h>#include <QAction>#include <QApplication>#include <QCloseEvent>#include <QDesktopWidget>#include <QDir>#include <QFile>#include <QFont>#include <QMenuBar>#include <QMessageBox>#include <QPushButton>#include <QRegExp>#include <QSplitter>#include <QString>#include <QWidget>namespace gui {using namespace std;using namespace util;/** constructor of MainWindow, creates window and fills it with elements @param parent parent widget containing this control @param fName Name of file to open in this window. If empty or null, no file will be opened */MainWindow::MainWindow(const QString &fName/*=QString::null*/,QWidget *parent/*=0*/):QMainWindow(parent,Qt::Window) { QWidget::setAttribute(Qt::WA_DeleteOnClose); menuSystem=new Menu(this); //Splitter between command line and preview window splCmd=new QSplitter(Qt::Vertical,this); splTop=new QSplitter(Qt::Horizontal,splCmd); main=new ImageView(splTop); setFocusProxy(main); addFunctions(); //Commandline cmdLine=new CommandLine(splCmd); cmdLine->setAutoCompleter(commandList()); status=new StatusBar(this); status->setMinimumWidth(2); setStatusBar(status); //Connections connect(cmdLine,SIGNAL(commandExecuted(QString)),SLOT(runScript(QString))); connect(globalSettings,SIGNAL(settingChanged(QString)),SLOT(settingUpdate(QString))); connect(main,SIGNAL(zoomChanged(int)),SLOT(zoomChanged(int))); connect(main,SIGNAL(info(const QString &)),status,SLOT(message(const QString &))); connect(main,SIGNAL(selectionInfo(const QString &)),status,SLOT(receiveCoordsText(const QString &))); connect(main,SIGNAL(selectionChanged()),this,SLOT(updateMenus())); updateConsoleVisibility(); initMenuToolbar(); this->setCentralWidget(splCmd); //Icon const QPixmap *appIcon=menuSystem->getIcon(globalSettings->read("icon/app","icon_32.png")); if (appIcon) {  setWindowIcon(*appIcon); } if (!fName.isNull()) openFile(fName); setTitle();}/** update menus when availability of selection or something other changes*/void MainWindow::updateMenus() { menuSystem->enableByName("/needrect",main->haveSelection()); Image *i=main->getImage();  menuSystem->enableByName("/needimage",i); int c=0; if (i) c=i->channels(); for (int q=1;q<=4;q++) {  menuSystem->enableByName(QString("/needimage_n%1").arg(q),c && c!=q); } menuSystem->enableByName("/needundo",i && i->haveUndo()); menuSystem->checkByName("/have_scale",main->isSet("scale")); menuSystem->checkByName("/have_antialias",main->isSet("antialias")); menuSystem->checkByName("/have_console",globalSettings->readBool("gui/console"));}/** Creates menus and toolbars*/void MainWindow::initMenuToolbar() { //Menu connect(menuSystem,SIGNAL(action(const QString &)),this,SLOT(menuActivated(const QString &))); connect(menuSystem,SIGNAL(helpText(const QString&)),this,SLOT(receiveHelpText(const QString&))); try {  QMenuBar *qb=menuSystem->loadMenu(this);  assert(qb);  setMenuBar(qb);  //ToolBars  menuSystem->loadToolBars();  updateMenus(); } catch (InvalidMenuException &e) {  fatalError(e.message()); }}/** Removes menus and toolbars*/void MainWindow::removeMenuToolbar() { disconnect(menuSystem,0,this,0); menuSystem->reset();}/** Register all functions and their parameters that are used withing commandline*/void MainWindow::addFunctions() { //First (re)register enums registerEnum("interp",tr("raw memory resizing|no interpolation - additional space filled with 0|nearest point|moving average interpolation|linear interpolation|grid interpolation|bi-cubic interpolation"),-1); registerEnum("noisetype",tr("gaussian|uniform|salt and pepper")); registerEnum("flipdir",tr("horizontally|vertically"),"H|V"); registerEnum("imagetype",tr("greyscale|greyscale with alpha|RGB|RGBA"),1); //Register functions and parameters addFunc("about",	&MainWindow::about,	tr("Show about window")); addFunc("blur",	&MainWindow::blur,	tr("Blur the image with a Canny-Deriche filter.")); addFuncParam("blur","float","sigma",tr("Strength of blur")); addFuncParam("blur","bordercb","cond",tr("Border Condition"),QString::null,"1"); addFunc("blur_a",	&MainWindow::blur_a,	tr("Blur the image with an anisotropic exponential filter (Deriche filter of order 0).")); addFuncParam("blur_a","float","sigmax",tr("Strength of blur in %1 axis").arg("X")); addFuncParam("blur_a","float","sigmay",tr("Strength of blur in %1 axis").arg("Y")); addFuncParam("blur_a","bordercb","cond",tr("Border Condition"),QString::null,"1"); addFunc("capture",	&MainWindow::capture,	tr("Capture the screen")); addFunc("clampabove",	&MainWindow::clipAbove,tr("Clamp pixel values above specified value")); addFuncParam("clampabove","pixelvalue","value",tr("Pixel values larger than this value will be set to this value"),tr("Clamp value")); addFunc("clampbelow",	&MainWindow::clipBelow,tr("Clamp pixel values below specified value")); addFuncParam("clampbelow","pixelvalue","value",tr("Pixel values smaller than this value will be set to this value"),tr("Clamp value")); addFunc("close",	&MainWindow::closeWindow,tr("Close current window")); addFunc("copy",	&MainWindow::copy,	tr("Copy image to clipbard")); addFunc("crop",	&MainWindow::crop,	tr("Crop image, replace it by its subregion")); addFuncParam("crop","intscale","x1",tr("X position of region's first corner")); addFuncParam("crop","intscale","y1",tr("Y position of region's first corner")); addFuncParam("crop","intscale","x2",tr("X position of region's second corner")); addFuncParam("crop","intscale","y2",tr("Y position of region's second corner")); addFuncParamHelp("crop",tr("Coordinates can be specified in pixels or as percentage (for example \"50%\") of image width/height")); addFunc("delete",	&MainWindow::deleteImage,tr("Delete currently shown image file")); addFuncParam("delete","int","offset",tr("Keep current file loaded (0), move to next (+1) or previous (-1) file once the image gets deleted."),tr("File move offset after delete"),"0"); addFunc("dialog",	&MainWindow::dialog,	tr("Run dialog to pick parameters for given command, then run the command. Any extra parameters are passed to command to initialize its parameter with default values")); addFuncParam("dialog","string","command",tr("Command to run")); addFunc("echo",	&MainWindow::echo,	tr("Echo all parameters to the console")); addFunc("eqhist",	&MainWindow::equalizeHistogram,tr("Equalize histogram of image")); addFunc("file",	&MainWindow::fileSwitch,tr("Move to another file in directory")); addFuncParam("file","int","offset",tr("Move forward (+1), backwards (-1), to \"start\" of directory with offset<-1 and to \"end\" of directory with offset>1."),tr("File move offset")); addFunc("flip",	&MainWindow::flip,	tr("Flip image horizontally or vertically")); addFuncParam("flip","flipdir","direction",tr("Flip direction")); addFunc("greyscale",	&MainWindow::greyscale,	tr("Convert image to greyscale")); addFunc("help",	&MainWindow::help,	tr("Show all commands and their description")); addFunc("info",	&MainWindow::imageInfo,	tr("Show information about currently shown image")); addFunc("lang",	&MainWindow::lang,	tr("Change language")); addFuncParam("lang","string","language",tr("Identifier of new language")); addFunc("load",	&MainWindow::load,	tr("Load image from given file or show dialog to load a file if no parameter given")); addFuncParam("load","file","filename",tr("Filename to load")); addFunc("median",	&MainWindow::median,	tr("Run median filter on image")); addFuncParam("median","int","size",tr("Size of mask"),QString::null,"3"); addFunc("mul",		&MainWindow::mul,	tr("Multiply image")); addFuncParam("mul","float","value",tr("Each pixel will be multiplied by this value")); addFunc("neg",		&MainWindow::negative,	tr("Create negative image")); addFunc("noise",	&MainWindow::noise,	tr("Add noise to image")); addFuncParam("noise","noisetype","type",tr("Type of noise"),QString::null,"0"); addFuncParam("noise","floatscale","power",tr("Power of noise. Can be specified as absolute value or as percentage of maximum image value."),tr("Power of noise"),"20%"); addFunc("normalize",	&MainWindow::normalize,	tr("Normalize image")); addFuncParam("normalize","int","from",tr("Lower pixel value")); addFuncParam("normalize","int","to",tr("Upper pixel value")); addFuncParamHelp("normalize",tr("Image values will be normalized between lower and upper values")); addFunc("options",	&MainWindow::options,	tr("Show option dialog")); addFunc("paste",	&MainWindow::paste,	tr("Paste image from clipbard")); addFunc("quantize",	&MainWindow::quantize,	tr("Quantize image into discrete levels")); addFuncParam("quantize","uint","levels",tr("Number of levels to use during quantization"),tr("Number of levels"),"256"); addFunc("quit",	&MainWindow::quit,	tr("Quit program")); addFunc("resize",	&MainWindow::resize,	tr("Resize image to specified size")); addFuncParam("resize","intscale","x",tr("New width")); addFuncParam("resize","intscale","y",tr("New height")); addFuncParam("resize","interp","int",tr("Interpolation type"),QString::null,"1"); addFuncParam("resize","borderc","border",tr("Border Condition"),QString::null,"-1"); addFuncParamHelp("resize",tr("Width and height can be specified in pixels or as percentage (for example \"50%\") of original value")); addFunc("rotate",	&MainWindow::rotate,	tr("Rotate image")); addFuncParam("rotate","float","angle",tr("Angle to rotate in degrees"),QString::null,"90"); addFunc("save",	&MainWindow::save,	tr("Save image to given file or show dialog to save a file if no parameter given")); addFuncParam("save","file","filename",tr("Filename to save")); addFunc("convert",	&MainWindow::set_channels,tr("Convert image to specified format")); addFuncParam("convert","imagetype","channels",tr("Desired number of channels, specifying format"),tr("Image format")); addFunc("sharpen",	&MainWindow::sharpen,	tr("Sharpen image using anisotropic shock filters")); addFuncParam("sharpen","float","amplitude",tr("Amplitude"),QString::null,"50.0");	//TODO: document parameter better addFuncParam("sharpen","float","edge",tr("Edge"),QString::null,"1.0");		//TODO: document parameter better addFuncParam("sharpen","float","alpha",tr("Alpha"),QString::null,"0.0");		//TODO: document parameter better addFuncParam("sharpen","float","sigma",tr("Sigma"),QString::null,"0.0");		//TODO: document parameter better addFunc("sqrt",	&MainWindow::sqrt,	tr("Pixelwise square root")); addFunc("toggle",	&MainWindow::toggleSetting,tr("Toggle given settings value")); addFuncParam("toggle","string","setting",tr("Key in setting to toggle. If the value evaluates to true, it will be set to false, otherwise to true"),tr("Key in settings")); addFunc("undo",	&MainWindow::undo,	tr("Undo last operation (if undo is enabled)")); addFunc("view",	&MainWindow::setView,	tr("Set features for viewing image according to parameters.")); addFuncParam("view","featurename","feature",tr("Name of the feature to set")); addFuncParam("view","boolstate","state",tr("New state of feature: 1 (on), 0 (off) or 'toggle'")); addFunc("zoom",	&MainWindow::zoom,	tr("Set zoom level for viewing image. Must be between %1 and %2").arg(MIN_ZOOM).arg(MAX_ZOOM)); addFuncParam("zoom","zoomlevel","zoomlevel",tr("Zoom level in percent")); addFunc("zoomstep",	&MainWindow::zoomStep,	tr("Alter zoom by specified number of steps")); addFuncParam("zoomstep","int","steps",tr("How many steps to zoom in (positive) or out (negative)"));}/** Sharpen image using anisotropic shock filters. @param param Command parameters*/void MainWindow::sharpen(const QStringList &param) { Image *i=getImageAndParams(param); if (!i) return; float amp=getParamFloat("amplitude"); float edge=getParamFloat("edge"); float alpha=getParamFloat("alpha"); float sigma=getParamFloat("sigma"); i->sharpen(amp,edge,alpha,sigma); postOp(i);}/** Median filter @param param Command parameters*/void MainWindow::median(const QStringList &param) { Image *i=getImageAndParams(param); if (!i) return; int size=getParamInt("size"); i->median(size); postOp(i);}/** Copy to clipbard*/void MainWindow::copy() { Image *i=getImage(); if (!i) return; i->copy(); postOp(i,false);}/** Paste from clipbard*/void MainWindow::paste() { if (!main->loadImagePaste()) {  cmdLine->addError(tr("No image found in clipboard")); } else {  setTitle();  postOp(getImage(),false); }}/** Multiply @param param Command parameters*/void MainWindow::mul(const QStringList &param) { Image *i=getImageAndParams(param); if (!i) return; float v=getParamFloat("value"); i->multiply(v); postOp(i);}/** Noise @param param Command parameters*/void MainWindow::noise(const QStringList &param) { Image *i=getImageAndParams(param); if (!i) return; double power=getParamScaleDouble("power"); int typ=getParamInt("type"); i->noise(power,typ); postOp(i);}/** Invoke dialog for given command @param param Command parameters*/void MainWindow::dialog(const QStringList &param) { if (param.count()<1) {  minParam(1,currentFunction());  return; } QStringList rParam=param; QString cmd=param[0]; rParam.removeFirst(); //This contain parameter default values if other values are not specified SMap m=paramMap(cmd,rParam); QStringList pn=paramNames(cmd); QStringList tp=paramTypes(cmd); QStringList ht=paramHelps(cmd); QStringList capt=paramCaptions(cmd); if (!pn.size()) {  cmdLine->addError(tr("Command '%1' does not exist or have no parameters").arg(cmd));  return; } ParamDialog p(cmd,this,this); while (rParam.size()<pn.size()) rParam.push_back(QString::null); assert(pn.size()==tp.size()); assert(pn.size()==ht.size()); assert(pn.size()<=rParam.size()); QString bef=beforeParamHelp(cmd); QString aft=afterParamHelp(cmd); if (!bef.isNull()) p.addText(bef); for(int i=0;i<pn.size();i++) {  //Create editing widgets  p.addParam(pn[i],capt[i],tp[i],rParam[i],((ht[i]==capt[i])?(QString::null):ht[i])); } if (!aft.isNull()) p.addText(aft); //Set default values for(int i=0;i<pn.size();i++) {  p.setValue(pn[i],m[pn[i]]); } if (p.exec()==QDialog::Accepted) {  for(int i=0;i<pn.size();i++) {   rParam[i]=p.getValue(pn[i]);  }  cmdLine->addCommand(cmd+" "+rParam.join(" "));  invokeCommand(this,cmd,rParam); }}/** Normalize image @param param Command parameters*/void MainWindow::normalize(const QStringList &param) { Image *i=getImageAndParams(param); if (!i) return; int a=getParamInt("from"); int b=getParamInt("to"); i->normalize(a,b); postOp(i);}/** Quantize image @param param Command parameters*/void MainWindow::quantize(const QStringList &param) { Image *i=getImageAndParams(param); if (!i) return; unsigned int n=getParamInt("levels"); i->quantize(n); postOp(i);}/** Square root*/void MainWindow::sqrt() { Image *i=getImage(); if (!i) return; i->sqrt(); postOp(i);}/** Negative image*/void MainWindow::negative() { Image *i=getImage(); if (!i) return; i->negative(); postOp(i);}/** Open image with given name @param name name of image*/void MainWindow::openFile(const QString &name) { main->loadImage(name); setTitle(); postOp(getImage(),false);}/** Create image from given Pixmap @param px Pixmap*/void MainWindow::openFile(QPixmap px) { main->loadImage(px); setTitle(); postOp(getImage(),false);}/** Return suggested filters to use in a save/load dialog @param useGeneric Add generic filters "all images/all files" if true (default)

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?