int getList(char *dir_name, struct file_st **file_array_ptr) { int first_count=0; int count=0; DIR *dp; struct dirent *dirp; struct file_st *file_array; if ((dp = opendir(dir_name)) == NULL) { warn("cannot open directory %s",dir_name); return -1; } while ( (dirp=readdir(dp)) != NULL) { if ((fileFilter(dirp->d_name))==0) { continue; } first_count++; } if ((closedir(dp))<0) { err(EXIT_FAILURE,"cannot close directory %s",dir_name); } if ((*file_array_ptr=malloc(first_count*sizeof(struct file_st))) ==NULL) { err(EXIT_FAILURE, "out of memory"); } file_array = *file_array_ptr; if ((dp = opendir(dir_name)) == NULL) { warn("cannot open directory %s",dir_name); return -1; } while ( (dirp=readdir(dp)) != NULL) { if ((fileFilter(dirp->d_name))==0) { continue; } if ((file_array[count].file_name =malloc((strlen(dirp->d_name)+1)*sizeof(char)))==NULL) { err(EXIT_FAILURE, "out of memory"); } strcpy(file_array[count].file_name,dirp->d_name); if ( (count+1) > first_count ) { break; } count++; } if ((closedir(dp))<0) { err(EXIT_FAILURE,"cannot close directory %s",dir_name); } return count; }
bool LinkSaver::SaveEmbedded(const unsigned char *data, size_t len) { if (!HasPermission(Perm_DiskAccess)) return false; WCHAR dstFileName[MAX_PATH]; str::BufSet(dstFileName, dimof(dstFileName), fileName ? fileName : L""); CrashIf(fileName && str::FindChar(fileName, '/')); // Prepare the file filters (use \1 instead of \0 so that the // double-zero terminated string isn't cut by the string handling // methods too early on) ScopedMem<WCHAR> fileFilter(str::Format(L"%s\1*.*\1", _TR("All files"))); str::TransChars(fileFilter, L"\1", L"\0"); OPENFILENAME ofn = { 0 }; ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = this->parentHwnd; ofn.lpstrFile = dstFileName; ofn.nMaxFile = dimof(dstFileName); ofn.lpstrFilter = fileFilter; ofn.nFilterIndex = 1; ofn.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY; bool ok = GetSaveFileName(&ofn); if (!ok) return false; ok = file::WriteAll(dstFileName, data, len); if (ok && tab && IsUntrustedFile(tab->filePath, gPluginURL)) file::SetZoneIdentifier(dstFileName); return ok; }
void SkinDocument::saveAs() { /* Determining the directory to open */ QString directory = fileName; QSettings settings; settings.beginGroup("SkinDocument"); if(directory == "") directory = settings.value("defaultDirectory", "").toString(); fileName = QFileDialog::getSaveFileName(this, tr("Save Document"), directory, fileFilter()); directory = fileName; if(fileName == "") return; directory.chop(fileName.length() - fileName.lastIndexOf('/') - 1); settings.setValue("defaultDirectory", directory); settings.endGroup(); QFile fout(fileName); fout.open(QFile::WriteOnly); fout.write(editor->document()->toPlainText().toAscii()); fout.close(); saved = editor->document()->toPlainText(); QStringList decompose = fileName.split('/'); titleText = decompose[decompose.count() - 1]; emit titleChanged(titleText); }
int FindSymbolsJob::execute() { int ret = 2; if (std::shared_ptr<Project> proj = project()) { Set<Symbol> symbols; Location filter; const uint32_t filteredFile = fileFilter(); if (filteredFile) filter = Location(filteredFile, 0, 0); auto inserter = [proj, this, &symbols, &filter, filteredFile](Project::SymbolMatchType type, const String &symbolName, const Set<Location> &locations) { if (filter.fileId()) { auto it = locations.lower_bound(filter); if (it == locations.end() || it->fileId() != filteredFile) return; } if (type == Project::StartsWith) { const size_t paren = symbolName.indexOf('('); if (paren == String::npos || paren != string.size() || RTags::isFunctionVariable(symbolName)) return; } for (const auto &it : locations) { const Symbol sym = proj->findSymbol(it); if (!sym.isNull()) symbols.insert(sym); } }; proj->findSymbols(string, inserter, queryFlags()); if (!symbols.isEmpty()) { const List<RTags::SortedSymbol> sorted = proj->sort(symbols, queryFlags()); const Flags<WriteFlag> writeFlags = fileFilter() ? Unfiltered : NoWriteFlags; const int count = sorted.size(); ret = count ? 0 : 1; for (int i=0; i<count; ++i) { write(sorted.at(i).location, writeFlags); } } } return ret; }
void Encrypt(PK0304* le, AE_EXTRA* ae, char* password) { char *salt, *key1, *key2, *check, digest[40]; u32 key_len = KeySize*2 + 2; u32 dig_len = 40; salt = BUF; key1 = salt+SaltSize; key2 = key1+KeySize; check = key2+KeySize; /* Gets a random salt (8-16 byte) */ sprng_read(salt, SaltSize, 0); /* Generates 2 keys for AES and HMAC, plus 2-byte password verification value */ if (pkcs_5_alg2(password, strlen(password), salt, SaltSize, 1000, 0, key1, &key_len) != CRYPT_OK) Z_ERROR("Failed to derive encryption keys"); // dump("salt", salt, SaltSize); // dump("key", key1, KeySize); if (ctr_start(0, IV, key1, KeySize, 0, CTR_COUNTER_LITTLE_ENDIAN, &ctr) != CRYPT_OK) Z_ERROR("Failed to setup AES CTR encoder"); #ifdef GLADMAN_HMAC hmac_sha1_begin(&hmac); hmac_sha1_key(key2, KeySize, &hmac); #else if (hmac_init(&hmac, 0, key2, KeySize) != CRYPT_OK) Z_ERROR("Failed to setup HMAC-SHA1"); #endif if (AE2) le->Crc32 = 0; le->Flag |= 1; le->CompMethod = 99; le->ExtraLen += 11; le->CompSize += SaltSize + 12; /* variable salt, fixed password check and hmac */ safeWrite(ZOUT, le, sizeof(PK0304)); fileCopy(ZOUT, ZIN, le->NameLen+le->ExtraLen-11); safeWrite(ZOUT, ae, 11); safeWrite(ZOUT, salt, SaltSize); safeWrite(ZOUT, check, 2); /* encrypt contents */ fileFilter(ZOUT, ZIN, le->CompSize-SaltSize-12); #ifdef GLADMAN_HMAC hmac_sha1_end(digest, dig_len, &hmac); #else if (hmac_done(&hmac, digest, &dig_len) != CRYPT_OK) Z_ERROR("Failed to computate HMAC"); #endif safeWrite(ZOUT, digest, 10); ctr_done(&ctr); }
void DeviceProfileDialog::save() { QString fn = m_dlgGui->getSaveFileName(this, tr("Save Profile"), QString(), fileFilter()); if (fn.isEmpty()) return; if (QFileInfo(fn).completeSuffix().isEmpty()) { fn += QLatin1Char('.'); fn += QLatin1String(profileExtensionC); } QFile file(fn); if (!file.open(QIODevice::WriteOnly|QIODevice::Text)) { critical(tr("Save Profile - Error"), tr("Unable to open the file '%1' for writing: %2").arg(fn, file.errorString())); return; } file.write(deviceProfile().toXml().toUtf8()); }
void Document::setRichText(bool rich_text) { // Get new file name m_old_states[m_text->document()->availableUndoSteps()] = qMakePair(m_filename, m_rich_text); if (!m_filename.isEmpty()) { QString filename = m_filename; int suffix_index = filename.lastIndexOf(QChar('.')); int file_index = filename.lastIndexOf(QChar('/')); if (suffix_index > file_index) { filename.chop(filename.length() - suffix_index); } filename.append(rich_text ? ".proseup" : ".txt"); QString selected; m_filename = QFileDialog::getSaveFileName(window(), tr("Save File As"), filename, fileFilter(filename), &selected); if (!m_filename.isEmpty()) { m_filename = fileNameWithExtension(m_filename, selected); clearIndex(); } else { findIndex(); } } // Set file type m_rich_text = rich_text; m_text->setAcceptRichText(m_rich_text); // Always remove formatting to have something to undo QTextCursor cursor(m_text->document()); cursor.beginEditBlock(); cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); cursor.setBlockFormat(QTextBlockFormat()); cursor.setCharFormat(QTextCharFormat()); cleanUpDocument(); cursor.endEditBlock(); m_old_states[m_text->document()->availableUndoSteps()] = qMakePair(m_filename, m_rich_text); // Save file if (!m_filename.isEmpty()) { save(); updateState(); m_text->document()->setModified(false); } emit changedName(); emit formattingEnabled(m_rich_text); }
bool CCommonAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filterId, bool bOpen, const CString& initialDir, HWND hwndOwner) { HRESULT hr; // Create a new common save file dialog CComPtr<IFileDialog> pfd = NULL; hr = pfd.CoCreateInstance(bOpen ? CLSID_FileOpenDialog : CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER); if (SUCCEEDED(hr)) { // Set the dialog options DWORD dwOptions; if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) { if (bOpen) hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); else { hr = pfd->SetOptions(dwOptions | FOS_OVERWRITEPROMPT | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); hr = pfd->SetFileName(CPathUtils::GetFileNameFromPath(path)); } } // Set a title if (SUCCEEDED(hr) && title) { CString temp; temp.LoadString(title); CStringUtils::RemoveAccelerators(temp); pfd->SetTitle(temp); } if (filterId) { CSelectFileFilter fileFilter(filterId); hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter); } // set the default folder CComPtr<IShellItem> psiFolder; if (!initialDir.IsEmpty()) { hr = SHCreateItemFromParsingName(initialDir, NULL, IID_PPV_ARGS(&psiFolder)); if (SUCCEEDED(hr)) pfd->SetFolder(psiFolder); hr = S_OK; } // Show the save/open file dialog if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(hwndOwner))) { // Get the selection from the user CComPtr<IShellItem> psiResult = NULL; hr = pfd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { path = CString(pszPath); if (filterindex) { UINT fi = 0; pfd->GetFileTypeIndex(&fi); *filterindex = fi; } return true; } } } } else { OPENFILENAME ofn = {0}; // common dialog box structure TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH. ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hwndOwner; wcscpy_s(szFile, (LPCTSTR)path); ofn.lpstrFile = szFile; ofn.nMaxFile = _countof(szFile); CSelectFileFilter fileFilter; if (filterId) { fileFilter.Load(filterId); ofn.lpstrFilter = fileFilter; } ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; if (!initialDir.IsEmpty()) ofn.lpstrInitialDir = initialDir; CString temp; if (title) { temp.LoadString(title); CStringUtils::RemoveAccelerators(temp); } ofn.lpstrTitle = temp; if (bOpen) ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER; else ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER; // Display the Open dialog box. PreserveChdir preserveDir; bool bRet = false; if (bOpen) { bRet = !!GetOpenFileName(&ofn); } else { bRet = !!GetSaveFileName(&ofn); } if (bRet) { path = CString(ofn.lpstrFile); if (filterindex) *filterindex = ofn.nFilterIndex; return true; } } return false; }
bool Document::rename() { if (m_filename.isEmpty()) { return false; } QString selected; QString filename = QFileDialog::getSaveFileName(window(), tr("Rename File"), m_filename, fileFilter(m_filename), &selected); if (!filename.isEmpty()) { filename = fileNameWithExtension(filename, selected); if (QFile::exists(filename) && !QFile::remove(filename)) { QMessageBox::critical(window(), tr("Sorry"), tr("Unable to overwrite '%1'.").arg(filename)); return false; } if (!QFile::rename(m_filename, filename)) { QMessageBox::critical(window(), tr("Sorry"), tr("Unable to rename '%1'.").arg(m_filename)); return false; } m_filename = filename; updateSaveLocation(); m_text->document()->setModified(false); emit changedName(); return true; } else { return false; } }
bool SyncCommand::FileOpenSave(CString& path, BOOL& bWithLocals, bool bOpen, HWND hwndOwner) { HRESULT hr; bWithLocals = FALSE; // Create a new common save file dialog CComPtr<IFileDialog> pfd = NULL; hr = pfd.CoCreateInstance(bOpen ? CLSID_FileOpenDialog : CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER); if (SUCCEEDED(hr)) { // Set the dialog options DWORD dwOptions; if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) { if (bOpen) hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); else { hr = pfd->SetOptions(dwOptions | FOS_OVERWRITEPROMPT | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); hr = pfd->SetFileName(CPathUtils::GetFileNameFromPath(path)); } } // Set a title if (SUCCEEDED(hr)) { CString temp; temp.LoadString(IDS_SYNC_SETTINGSFILE); CStringUtils::RemoveAccelerators(temp); pfd->SetTitle(temp); } CSelectFileFilter fileFilter(IDS_EXPORTFILTER); hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter); if (!bOpen) { CComPtr<IFileDialogCustomize> pfdCustomize; hr = pfd.QueryInterface(&pfdCustomize); if (SUCCEEDED(hr)) { pfdCustomize->AddCheckButton(101, CString(MAKEINTRESOURCE(IDS_SYNC_INCLUDELOCAL)), FALSE); } } // Show the save/open file dialog if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(hwndOwner))) { // Get the selection from the user CComPtr<IShellItem> psiResult = NULL; hr = pfd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { path = CString(pszPath); if (!bOpen) { CComPtr<IFileDialogCustomize> pfdCustomize; hr = pfd.QueryInterface(&pfdCustomize); if (SUCCEEDED(hr)) { pfdCustomize->GetCheckButtonState(101, &bWithLocals); } } return true; } } } } return false; }
//OnConnectCamera-Method; represents one of the main parts of ToFConnectionWidget2. void QmitkToFConnectionWidget::OnConnectCamera() { //After connecting a device if (m_Controls->m_ConnectCameraButton->text()=="Connect") { //Getting the device- and the slectedCamera-variables using the ServiceListWidget as we did it in the CameraSelect-Method mitk::ToFCameraDevice* device = m_Controls->m_DeviceList->GetSelectedService<mitk::ToFCameraDevice>(); if (device) { QString tmpFileName(""); QString fileFilter(""); QString selectedCamera = QString::fromStdString(device->GetNameOfClass()); emit ToFCameraSelected(selectedCamera); //Feeding it with the Info from ServiceListWidget this->m_ToFImageGrabber->SetCameraDevice(device); // Calling Alex FixForKinect, if the Kinect is selected if (selectedCamera.contains("Kinect") ) { MITK_INFO<< "Kinect is connected here"; //If the particular property is selected, the suitable data-node will be generated this->m_ToFImageGrabber->SetBoolProperty("RGB", m_Controls->m_KinectParameterWidget->IsAcquisitionModeRGB());//-------------------------------------------------------- this->m_ToFImageGrabber->SetBoolProperty("IR", m_Controls->m_KinectParameterWidget->IsAcquisitionModeIR()); } //Activation of "PlayerMode". If the selectedCamera String contains "Player", we start the Player Mode if (selectedCamera.contains("Player")) { //IF PMD-Player selected if (selectedCamera.contains("PMD")) { fileFilter.append("PMD Files (*.pmd)"); //And seting the corresponding fileFilter } else { fileFilter.append("NRRD Images (*.nrrd);;PIC Images - deprecated (*.pic)"); } //open a QFileDialog to chose the corresponding file from the disc tmpFileName = QFileDialog::getOpenFileName(NULL, "Play Image From...", "", fileFilter); //If no fileName is returned by the Dialog,Button and Widget have to return to default(disconnected) + Opening a MessageBox if (tmpFileName.isEmpty()) { m_Controls->m_ConnectCameraButton->setChecked(false); m_Controls->m_ConnectCameraButton->setEnabled(true); //re-enabling the ConnectCameraButton m_Controls->m_DeviceList->setEnabled(true); //Reactivating ServiceListWidget this->OnSelectCamera(); //Calling the OnSelctCamera-Method -> Hides all Widget and just activates the needed ones QMessageBox::information( this, "Template functionality", "Please select a valid image before starting some action."); return; } if(selectedCamera.contains("PMDPlayer")) //If PMD-Player is selected, set ToFImageGrabberProperty correspondingly { this->m_ToFImageGrabber->SetStringProperty("PMDFileName", tmpFileName.toStdString().c_str() ); } else //Default action { std::string msg = ""; try { //get 3 corresponding file names std::string dir = itksys::SystemTools::GetFilenamePath( tmpFileName.toStdString() ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( tmpFileName.toStdString() ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( tmpFileName.toStdString() ); //"Incorrect format"-warning while using .nrrd or .pic files if (extension != ".pic" && extension != ".nrrd") { msg = msg + "Invalid file format, please select a \".nrrd\"-file"; throw std::logic_error(msg.c_str()); } //Checking for npos. If available, check for the Amplitude-, Intensity- and RGBImage int found = baseFilename.rfind("_DistanceImage"); //Defining "found" variable+checking if baseFilname contains "_DistanceImage". If not, found == npos(0) if (found == std::string::npos) //If found =0 { found = baseFilename.rfind("_AmplitudeImage"); //If "_AmplitudeImage" is found, the found variable is 1-> the next if statment is false } if (found == std::string::npos) { found = baseFilename.rfind("_IntensityImage"); //found = true if baseFilename cotains "_IntesityImage" } if (found == std::string::npos) { found = baseFilename.rfind("_RGBImage"); } if (found == std::string::npos) //If none of the Nodes is found, display an error { msg = msg + "Input file name must end with \"_DistanceImage\", \"_AmplitudeImage\", \"_IntensityImage\" or \"_RGBImage\"!"; throw std::logic_error(msg.c_str()); } std::string baseFilenamePrefix = baseFilename.substr(0,found);//Set the baseFilenamePrefix as a substring from baseFilname //Set corresponding FileNames std::string distanceImageFileName = dir + "/" + baseFilenamePrefix + "_DistanceImage" + extension; //Set the name as: directory+FilenamePrefix+""+extension std::string amplitudeImageFileName = dir + "/" + baseFilenamePrefix + "_AmplitudeImage" + extension; std::string intensityImageFileName = dir + "/" + baseFilenamePrefix + "_IntensityImage" + extension; std::string rgbImageFileName = dir + "/" + baseFilenamePrefix + "_RGBImage" + extension; if (!itksys::SystemTools::FileExists(distanceImageFileName.c_str(), true)) { this->m_ToFImageGrabber->SetStringProperty("DistanceImageFileName", ""); } else { this->m_ToFImageGrabber->SetStringProperty("DistanceImageFileName", distanceImageFileName.c_str()); } if (!itksys::SystemTools::FileExists(amplitudeImageFileName.c_str(), true)) { } else { this->m_ToFImageGrabber->SetStringProperty("AmplitudeImageFileName", amplitudeImageFileName.c_str()); } if (!itksys::SystemTools::FileExists(intensityImageFileName.c_str(), true)) { this->m_ToFImageGrabber->SetStringProperty("IntensityImageFileName", ""); } else { this->m_ToFImageGrabber->SetStringProperty("IntensityImageFileName", intensityImageFileName.c_str()); } if (!itksys::SystemTools::FileExists(rgbImageFileName.c_str(), true)) { this->m_ToFImageGrabber->SetStringProperty("RGBImageFileName", ""); } else { this->m_ToFImageGrabber->SetStringProperty("RGBImageFileName", rgbImageFileName.c_str()); } } catch (std::exception &e) { MITK_ERROR << e.what(); QMessageBox::critical( this, "Error", e.what() ); m_Controls->m_ConnectCameraButton->setChecked(false); m_Controls->m_ConnectCameraButton->setEnabled(true); m_Controls->m_DeviceList->setEnabled(true); this->OnSelectCamera(); return; } } } //End "PlayerMode" //Reset the ConnectCameraButton to disconnected m_Controls->m_ConnectCameraButton->setText("Disconnect"); //if a connection could be established try { if (this->m_ToFImageGrabber->ConnectCamera()) { this->m_Controls->m_PMDParameterWidget->SetToFImageGrabber(this->m_ToFImageGrabber); this->m_Controls->m_MESAParameterWidget->SetToFImageGrabber(this->m_ToFImageGrabber); this->m_Controls->m_KinectParameterWidget->SetToFImageGrabber(this->m_ToFImageGrabber); //Activating the respective widgets if (selectedCamera.contains("PMD")) { this->m_Controls->m_PMDParameterWidget->ActivateAllParameters(); } else if (selectedCamera.contains("MESA")) { this->m_Controls->m_MESAParameterWidget->ActivateAllParameters(); } else if (selectedCamera.contains("Kinect")) { this->m_Controls->m_KinectParameterWidget->ActivateAllParameters(); } else { this->HideAllParameterWidgets(); } // send connect signal to the caller functionality emit ToFCameraConnected(); } else //##### TODO: Remove this else part once all controllers are throwing exceptions //if they cannot to any device! { //Throw an error if the Connection failed and reset the Widgets <- better catch an exception! QMessageBox::critical( this, "Error", "Connection failed. Check if you have installed the latest driver for your system." ); m_Controls->m_ConnectCameraButton->setChecked(false); m_Controls->m_ConnectCameraButton->setEnabled(true); m_Controls->m_ConnectCameraButton->setText("Connect"); m_Controls->m_DeviceList->setEnabled(true); //Reactivating ServiceListWidget this->OnSelectCamera(); return; } }catch(std::exception &e) { //catch exceptions of camera which cannot connect give a better reason QMessageBox::critical( this, "Connection failed.", e.what() ); m_Controls->m_ConnectCameraButton->setChecked(false); m_Controls->m_ConnectCameraButton->setEnabled(true); m_Controls->m_ConnectCameraButton->setText("Connect"); m_Controls->m_DeviceList->setEnabled(true); //Reactivating ServiceListWidget this->OnSelectCamera(); return; } m_Controls->m_ConnectCameraButton->setEnabled(true); // ask wether camera parameters (intrinsics, ...) should be loaded if (QMessageBox::question(this,"Camera parameters","Do you want to specify your own camera intrinsics?",QMessageBox::Yes,QMessageBox::No)==QMessageBox::Yes) { QString fileName = QFileDialog::getOpenFileName(this,"Open camera intrinsics","/","*.xml"); mitk::CameraIntrinsics::Pointer cameraIntrinsics = mitk::CameraIntrinsics::New(); cameraIntrinsics->FromXMLFile(fileName.toStdString()); this->m_ToFImageGrabber->SetProperty("CameraIntrinsics",mitk::CameraIntrinsicsProperty::New(cameraIntrinsics)); } ////Reset the status of some GUI-Elements m_Controls->m_DeviceList->setEnabled(false); //Deactivating the Instance of QmitkServiceListWidget //repaint the widget this->repaint(); } else { QMessageBox::information(this,"Camera connection","No camera selected, please select a range camera"); m_Controls->m_ConnectCameraButton->setChecked(false); } } else if (m_Controls->m_ConnectCameraButton->text()=="Disconnect") { this->m_ToFImageGrabber->StopCamera(); this->m_ToFImageGrabber->DisconnectCamera(); m_Controls->m_ConnectCameraButton->setText("Connect"); m_Controls->m_DeviceList->setEnabled(true); //Reactivating ServiceListWidget this->OnSelectCamera(); // send disconnect signal to the caller functionality emit ToFCameraDisconnected(); } }
void DeviceProfileDialog::open() { const QString fn = m_dlgGui->getOpenFileName(this, tr("Open profile"), QString(), fileFilter()); if (fn.isEmpty()) return; QFile file(fn); if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) { critical(tr("Open Profile - Error"), tr("Unable to open the file '%1' for reading: %2").arg(fn, file.errorString())); return; } QString errorMessage; DeviceProfile newSettings; if (!newSettings.fromXml(QString::fromUtf8(file.readAll()), &errorMessage)) { critical(tr("Open Profile - Error"), tr("'%1' is not a valid profile: %2").arg(fn, errorMessage)); return; } setDeviceProfile(newSettings); }
void QmitkToFConnectionWidget::OnConnectCamera() { bool playerMode = false; if (m_Controls->m_ConnectCameraButton->text()=="Connect") { //reset the status of the GUI buttons m_Controls->m_ConnectCameraButton->setEnabled(false); m_Controls->m_SelectCameraCombobox->setEnabled(false); //repaint the widget this->repaint(); QString tmpFileName(""); QString fileFilter(""); //select the camera to connect with QString selectedCamera = m_Controls->m_SelectCameraCombobox->currentText(); if (selectedCamera == "PMD CamCube 2.0/3.0") { //PMD CamCube this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetPMDCamCubeImageGrabber(); } else if (selectedCamera == "PMD CamCubeRaw 2.0/3.0") { //PMD CamCube this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetPMDRawDataCamCubeImageGrabber(); } else if (selectedCamera == "PMD CamBoard") { //PMD CamBoard this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetPMDCamBoardImageGrabber(); } else if (selectedCamera == "PMD CamBoardRaw") { //PMD CamBoard this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetPMDRawDataCamBoardImageGrabber(); } else if (selectedCamera == "PMD O3D") {//PMD O3 this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetPMDO3ImageGrabber(); } else if (selectedCamera == "MESA Swissranger 4000") {//MESA SR4000 this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetMESASR4000ImageGrabber(); } else if (selectedCamera == "PMD Player") {//PMD player playerMode = true; fileFilter.append("PMD Files (*.pmd)"); this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetPMDPlayerImageGrabber(); } else if (selectedCamera == "PMD Raw Data Player") {//PMD MITK player playerMode = true; fileFilter.append("NRRD Images (*.nrrd);;PIC Images - deprecated (*.pic)"); this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetPMDMITKPlayerImageGrabber(); } else if (selectedCamera == "MITK Player") {//MITK player playerMode = true; fileFilter.append("NRRD Images (*.nrrd);;PIC Images - deprecated (*.pic)"); this->m_ToFImageGrabber = mitk::ToFImageGrabberCreator::GetInstance()->GetMITKPlayerImageGrabber(); } // if a player was selected ... if (playerMode) { //... open a QFileDialog to chose the corresponding file from the disc tmpFileName = QFileDialog::getOpenFileName(NULL, "Play Image From...", "", fileFilter); if (tmpFileName.isEmpty()) { m_Controls->m_ConnectCameraButton->setChecked(false); m_Controls->m_ConnectCameraButton->setEnabled(true); m_Controls->m_SelectCameraCombobox->setEnabled(true); this->OnSelectCamera(m_Controls->m_SelectCameraCombobox->currentText()); QMessageBox::information( this, "Template functionality", "Please select a valid image before starting some action."); return; } if(selectedCamera == "PMD Player") { //set the PMD file name this->m_ToFImageGrabber->SetStringProperty("PMDFileName", tmpFileName.toStdString().c_str() ); } if (selectedCamera == "PMD Raw Data Player" || selectedCamera == "MITK Player") { std::string msg = ""; try { //get 3 corresponding file names std::string dir = itksys::SystemTools::GetFilenamePath( tmpFileName.toStdString() ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( tmpFileName.toStdString() ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( tmpFileName.toStdString() ); if (extension != ".pic" && extension != ".nrrd") { msg = msg + "Invalid file format, please select a \".nrrd\"-file"; throw std::logic_error(msg.c_str()); } int found = baseFilename.rfind("_DistanceImage"); if (found == std::string::npos) { found = baseFilename.rfind("_AmplitudeImage"); } if (found == std::string::npos) { found = baseFilename.rfind("_IntensityImage"); } if (found == std::string::npos) { msg = msg + "Input file name must end with \"_DistanceImage.pic\", \"_AmplitudeImage.pic\" or \"_IntensityImage.pic\"!"; throw std::logic_error(msg.c_str()); } std::string baseFilenamePrefix = baseFilename.substr(0,found); std::string distanceImageFileName = dir + "/" + baseFilenamePrefix + "_DistanceImage" + extension; std::string amplitudeImageFileName = dir + "/" + baseFilenamePrefix + "_AmplitudeImage" + extension; std::string intensityImageFileName = dir + "/" + baseFilenamePrefix + "_IntensityImage" + extension; if (!itksys::SystemTools::FileExists(distanceImageFileName.c_str(), true)) { msg = msg + "Inputfile not exist! " + distanceImageFileName; throw std::logic_error(msg.c_str()); } if (!itksys::SystemTools::FileExists(amplitudeImageFileName.c_str(), true)) { msg = msg + "Inputfile not exist! " + amplitudeImageFileName; throw std::logic_error(msg.c_str()); } if (!itksys::SystemTools::FileExists(intensityImageFileName.c_str(), true)) { msg = msg + "Inputfile not exist! " + intensityImageFileName; throw std::logic_error(msg.c_str()); } //set the file names this->m_ToFImageGrabber->SetStringProperty("DistanceImageFileName", distanceImageFileName.c_str()); this->m_ToFImageGrabber->SetStringProperty("AmplitudeImageFileName", amplitudeImageFileName.c_str()); this->m_ToFImageGrabber->SetStringProperty("IntensityImageFileName", intensityImageFileName.c_str()); } catch (std::exception &e) { MITK_ERROR << e.what(); QMessageBox::critical( this, "Error", e.what() ); m_Controls->m_ConnectCameraButton->setChecked(false); m_Controls->m_ConnectCameraButton->setEnabled(true); m_Controls->m_SelectCameraCombobox->setEnabled(true); this->OnSelectCamera(m_Controls->m_SelectCameraCombobox->currentText()); return; } } } //if a connection could be established if (this->m_ToFImageGrabber->ConnectCamera()) { this->m_Controls->m_PMDParameterWidget->SetToFImageGrabber(this->m_ToFImageGrabber); this->m_Controls->m_MESAParameterWidget->SetToFImageGrabber(this->m_ToFImageGrabber); if ((selectedCamera == "PMD CamCube 2.0/3.0")||(selectedCamera == "PMD CamBoard")||(selectedCamera=="PMD O3D")|| (selectedCamera=="PMD CamBoardRaw")||(selectedCamera=="PMD CamCubeRaw 2.0/3.0")) { this->m_Controls->m_PMDParameterWidget->ActivateAllParameters(); } else if (selectedCamera=="MESA Swissranger 4000") { this->m_Controls->m_MESAParameterWidget->ActivateAllParameters(); } m_Controls->m_ConnectCameraButton->setText("Disconnect"); // send connect signal to the caller functionality emit ToFCameraConnected(); } else { QMessageBox::critical( this, "Error", "Connection failed. Check if you have installed the latest driver for your system." ); m_Controls->m_ConnectCameraButton->setChecked(false); m_Controls->m_ConnectCameraButton->setEnabled(true); m_Controls->m_SelectCameraCombobox->setEnabled(true); this->OnSelectCamera(m_Controls->m_SelectCameraCombobox->currentText()); return; } m_Controls->m_ConnectCameraButton->setEnabled(true); } else if (m_Controls->m_ConnectCameraButton->text()=="Disconnect") { this->m_ToFImageGrabber->StopCamera(); this->m_ToFImageGrabber->DisconnectCamera(); m_Controls->m_ConnectCameraButton->setText("Connect"); m_Controls->m_SelectCameraCombobox->setEnabled(true); this->OnSelectCamera(m_Controls->m_SelectCameraCombobox->currentText()); this->m_ToFImageGrabber = NULL; // send disconnect signal to the caller functionality emit ToFCameraDisconnected(); } }
void Decrypt(PK0304 *le, char *password) { char *salt, *key1, *key2, *check, digest[40]; u32 key_len, dig_len = 40, start, xlen; AE_EXTRA ae; start = ftell(ZIN); /* Searches for AE-1 header */ fseek(ZIN, le->NameLen, SEEK_CUR); for(xlen=le->ExtraLen; xlen;) { safeRead(&ae, ZIN, 4); xlen -= (4 + ae.Size); if (ae.Sig == 0x9901) { safeRead(&ae.Version, ZIN, 7); continue; } fseek(ZIN, ae.Size, SEEK_CUR); } if (ae.Sig != 0x9901) Z_ERROR("Fatal! Can't find AE extra header!"); if (ae.Strength < 1 || ae.Strength > 3) Z_ERROR("Bad encryption strength"); SaltSize = KS[ae.Strength].Salt; KeySize = KS[ae.Strength].Key; salt = BUF; key1 = salt+SaltSize; key2 = key1+KeySize; check = key2+KeySize; key_len = KeySize*2+2; /* Loads salt and password check value, and regenerates original crypto material */ fseek(ZIN, start+le->NameLen+le->ExtraLen, SEEK_SET); safeRead(salt, ZIN, SaltSize); safeRead(check+2, ZIN, 2); point1: if (pkcs_5_alg2(password, strlen(password), salt, SaltSize, 1000, 0, key1, &key_len) != CRYPT_OK) Z_ERROR("Failed to derive encryption keys"); if (memcmp(check, check+2, 2)) { printf("\nCan't decrypt data: try another password.\nNew password: "******"\n"); goto point1; } if (ctr_start(0, IV, key1, KeySize, 0, CTR_COUNTER_LITTLE_ENDIAN, &ctr) != CRYPT_OK) Z_ERROR("Failed to setup AES CTR decoder"); #ifdef GLADMAN_HMAC hmac_sha1_begin(&hmac); hmac_sha1_key(key2, KeySize, &hmac); #else if (hmac_init(&hmac, 0, key2, KeySize) != CRYPT_OK) Z_ERROR("Failed to setup HMAC-SHA1"); #endif /* Adjusts local header */ le->Flag ^= 1; le->CompMethod = ae.CompMethod; le->ExtraLen -= 11; le->CompSize -= (SaltSize + 12); /* Writes local header and copies extra, except 0x9901 */ safeWrite(ZOUT, le, sizeof(PK0304)); fseek(ZIN, start, SEEK_SET); fileCopy(ZOUT, ZIN, le->NameLen); for(xlen=le->ExtraLen+11; xlen;) { safeRead(&ae, ZIN, 4); xlen -= (4 + ae.Size); if (ae.Sig == 0x9901) { safeRead(&ae.Version, ZIN, 7); continue; } safeWrite(ZOUT, &ae, 4); fileCopy(ZOUT, ZIN, ae.Size); } fseek(ZIN, SaltSize+2, SEEK_CUR); fileFilter(ZOUT, ZIN, le->CompSize); #ifdef GLADMAN_HMAC hmac_sha1_end(digest, dig_len, &hmac); #else if (hmac_done(&hmac, digest, &dig_len) != CRYPT_OK) Z_ERROR("Failed to computate HMAC"); #endif /* Retrieves and checks HMACs */ safeRead(digest+10, ZIN, 10); if (memcmp(digest, digest+10, 10)) printf(" authentication failed, contents were lost!"); ctr_done(&ctr); }
// CTortoiseMergeApp initialization BOOL CTortoiseMergeApp::InitInstance() { SetDllDirectory(L""); SetTaskIDPerUUID(); CCrashReport::Instance().AddUserInfoToReport(L"CommandLine", GetCommandLine()); { DWORD len = GetCurrentDirectory(0, NULL); if (len) { std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]); if (GetCurrentDirectory(len, originalCurrentDirectory.get())) { sOrigCWD = originalCurrentDirectory.get(); sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD); } } } //set the resource dll for the required language CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033); long langId = loc; CString langDll; HINSTANCE hInst = NULL; do { langDll.Format(_T("%sLanguages\\TortoiseMerge%ld.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId); hInst = LoadLibrary(langDll); CString sVer = _T(STRPRODUCTVER); CString sFileVer = CPathUtils::GetVersionFromFile(langDll); if (sFileVer.Compare(sVer)!=0) { FreeLibrary(hInst); hInst = NULL; } if (hInst != NULL) AfxSetResourceHandle(hInst); else { DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } } while ((hInst == NULL) && (langId != 0)); TCHAR buf[6] = { 0 }; _tcscpy_s(buf, _T("en")); langId = loc; CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseMerge_en.chm"); free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseMerge_en.chm"); do { GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)); CString sLang = _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } sHelppath.Replace(sLang, _T("_en")); GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)); sLang += _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } sHelppath.Replace(sLang, _T("_en")); DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } while (langId); setlocale(LC_ALL, ""); // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage // The problems occures when the language of OS differs from the regional settings // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887 SetThreadLocale(LOCALE_SYSTEM_DEFAULT); // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. InitCommonControls(); CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); CMFCButton::EnableWindowsTheming(); EnableTaskbarInteraction(FALSE); // Initialize all Managers for usage. They are automatically constructed // if not yet present InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager (); CMFCToolTipInfo params; params.m_bVislManagerTheme = TRUE; GetTooltipManager ()->SetTooltipParams ( AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS (CMFCToolTipCtrl), ¶ms); CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine); g_sGroupingUUID = parser.GetVal(L"groupuuid"); if (parser.HasKey(_T("?")) || parser.HasKey(_T("help"))) { CString sHelpText; sHelpText.LoadString(IDS_COMMANDLINEHELP); MessageBox(NULL, sHelpText, _T("TortoiseGitMerge"), MB_ICONINFORMATION); return FALSE; } // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored SetRegistryKey(_T("TortoiseGitMerge")); if (CRegDWORD(_T("Software\\TortoiseGitMerge\\Debug"), FALSE)==TRUE) AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION); // To create the main window, this code creates a new frame window // object and then sets it as the application's main window object CMainFrame* pFrame = new CMainFrame; if (pFrame == NULL) return FALSE; m_pMainWnd = pFrame; // create and load the frame with its resources if (!pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL)) return FALSE; // Fill in the command line options pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(_T("base"))); pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(_T("basename"))); pFrame->m_Data.m_baseFile.SetReflectedName(parser.GetVal(_T("basereflectedname"))); pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(_T("theirs"))); pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(_T("theirsname"))); pFrame->m_Data.m_theirFile.SetReflectedName(parser.GetVal(_T("theirsreflectedname"))); pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(_T("mine"))); pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(_T("minename"))); pFrame->m_Data.m_yourFile.SetReflectedName(parser.GetVal(_T("minereflectedname"))); pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(_T("merged"))); pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(_T("mergedname"))); pFrame->m_Data.m_mergedFile.SetReflectedName(parser.GetVal(_T("mergedreflectedname"))); pFrame->m_Data.m_sPatchPath = parser.HasVal(_T("patchpath")) ? parser.GetVal(_T("patchpath")) : _T(""); pFrame->m_Data.m_sPatchPath.Replace('/', '\\'); if (parser.HasKey(_T("patchoriginal"))) pFrame->m_Data.m_sPatchOriginal = parser.GetVal(_T("patchoriginal")); if (parser.HasKey(_T("patchpatched"))) pFrame->m_Data.m_sPatchPatched = parser.GetVal(_T("patchpatched")); pFrame->m_Data.m_sDiffFile = parser.GetVal(_T("diff")); pFrame->m_Data.m_sDiffFile.Replace('/', '\\'); if (parser.HasKey(_T("oneway"))) pFrame->m_bOneWay = TRUE; if (parser.HasKey(_T("diff"))) pFrame->m_bOneWay = FALSE; if (parser.HasKey(_T("reversedpatch"))) pFrame->m_bReversedPatch = TRUE; if (parser.HasKey(_T("saverequired"))) pFrame->m_bSaveRequired = true; if (parser.HasKey(_T("saverequiredonconflicts"))) pFrame->m_bSaveRequiredOnConflicts = true; if (parser.HasKey(_T("deletebasetheirsmineonclose"))) pFrame->m_bDeleteBaseTheirsMineOnClose = true; if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse()) { pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile); } if ((!parser.HasKey(_T("patchpath")))&&(parser.HasVal(_T("diff")))) { // a patchfile was given, but not folder path to apply the patch to // If the patchfile is located inside a working copy, then use the parent directory // of the patchfile as the target directory, otherwise ask the user for a path. if (parser.HasKey(_T("wc"))) pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\')); else { CBrowseFolder fbrowser; fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS; if (fbrowser.Show(NULL, pFrame->m_Data.m_sPatchPath)==CBrowseFolder::CANCEL) return FALSE; } } if ((parser.HasKey(_T("patchpath")))&&(!parser.HasVal(_T("diff")))) { // A path was given for applying a patchfile, but // the patchfile itself was not. // So ask the user for that patchfile HRESULT hr; // Create a new common save file dialog CComPtr<IFileOpenDialog> pfd = NULL; hr = pfd.CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER); if (SUCCEEDED(hr)) { // Set the dialog options DWORD dwOptions; if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) { hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); } // Set a title if (SUCCEEDED(hr)) { CString temp; temp.LoadString(IDS_OPENDIFFFILETITLE); pfd->SetTitle(temp); } CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER); hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter); bool bAdvised = false; DWORD dwCookie = 0; CComObjectStackEx<PatchOpenDlgEventHandler> cbk; CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown(); { CComPtr<IFileDialogCustomize> pfdCustomize; hr = pfd->QueryInterface(IID_PPV_ARGS(&pfdCustomize)); if (SUCCEEDED(hr)) { // check if there's a unified diff on the clipboard and // add a button to the fileopen dialog if there is. UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF")); if ((cFormat)&&(OpenClipboard(NULL))) { HGLOBAL hglb = GetClipboardData(cFormat); if (hglb) { pfdCustomize->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD))); hr = pfd->Advise(pEvents, &dwCookie); bAdvised = SUCCEEDED(hr); } CloseClipboard(); } } } // Show the save file dialog if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(pFrame->m_hWnd))) { // Get the selection from the user CComPtr<IShellItem> psiResult = NULL; hr = pfd->GetResult(&psiResult); if (bAdvised) pfd->Unadvise(dwCookie); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { pFrame->m_Data.m_sDiffFile = pszPath; CoTaskMemFree(pszPath); } } else { // no result, which means we closed the dialog in our button handler std::wstring sTempFile; if (TrySavePatchFromClipboard(sTempFile)) pFrame->m_Data.m_sDiffFile = sTempFile.c_str(); } } else { if (bAdvised) pfd->Unadvise(dwCookie); return FALSE; } } else { OPENFILENAME ofn = {0}; // common dialog box structure TCHAR szFile[MAX_PATH] = {0}; // buffer for file name // Initialize OPENFILENAME ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = pFrame->m_hWnd; ofn.lpstrFile = szFile; ofn.nMaxFile = _countof(szFile); CString temp; temp.LoadString(IDS_OPENDIFFFILETITLE); if (temp.IsEmpty()) ofn.lpstrTitle = NULL; else ofn.lpstrTitle = temp; ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER; if( HasClipboardPatch() ) { ofn.Flags |= ( OFN_ENABLETEMPLATE | OFN_ENABLEHOOK ); ofn.hInstance = AfxGetResourceHandle(); ofn.lpTemplateName = MAKEINTRESOURCE(IDD_PATCH_FILE_OPEN_CUSTOM); ofn.lpfnHook = CreatePatchFileOpenHook; } CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER); ofn.lpstrFilter = fileFilter; ofn.nFilterIndex = 1; // Display the Open dialog box. if (GetOpenFileName(&ofn)==FALSE) { return FALSE; } pFrame->m_Data.m_sDiffFile = ofn.lpstrFile; } } if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() ) { int nArgs; LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if( NULL == szArglist ) { TRACE("CommandLineToArgvW failed\n"); } else { if ( nArgs==3 || nArgs==4 ) { // Four parameters: // [0]: Program name // [1]: BASE file // [2]: my file // [3]: THEIR file (optional) // This is the same format CAppUtils::StartExtDiff // uses if %base and %mine are not set and most // other diff tools use it too. if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) ) { pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]); pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]); if ( nArgs == 4 && PathFileExists(szArglist[3]) ) { pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]); } } } else if (nArgs == 2) { // only one path specified: use it to fill the "open" dialog if (PathFileExists(szArglist[1])) { pFrame->m_Data.m_yourFile.SetFileName(szArglist[1]); pFrame->m_Data.m_yourFile.StoreFileAttributes(); } } } // Free memory allocated for CommandLineToArgvW arguments. LocalFree(szArglist); } pFrame->m_bReadOnly = !!parser.HasKey(_T("readonly")); if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY) pFrame->m_bReadOnly = true; pFrame->m_bBlame = !!parser.HasKey(_T("blame")); // diffing a blame means no editing! if (pFrame->m_bBlame) pFrame->m_bReadOnly = true; pFrame->SetWindowTitle(); if (parser.HasKey(_T("createunifieddiff"))) { // user requested to create a unified diff file CString origFile = parser.GetVal(_T("origfile")); CString modifiedFile = parser.GetVal(_T("modifiedfile")); if (!origFile.IsEmpty() && !modifiedFile.IsEmpty()) { CString outfile = parser.GetVal(_T("outfile")); if (outfile.IsEmpty()) { CCommonAppUtils::FileOpenSave(outfile, NULL, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, NULL); } if (!outfile.IsEmpty()) { CRegStdDWORD regContextLines(L"Software\\TortoiseGitMerge\\ContextLines", (DWORD)-1); CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, regContextLines, false); return FALSE; } } } pFrame->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd") : 0; pFrame->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0; pFrame->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0; // The one and only window has been initialized, so show and update it pFrame->ActivateFrame(); pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow(); pFrame->ShowDiffBar(!pFrame->m_bOneWay); if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty()) { pFrame->OnFileOpen(pFrame->m_Data.m_yourFile.InUse()); return TRUE; } int line = -2; if (parser.HasVal(_T("line"))) { line = parser.GetLongVal(_T("line")); line--; // we need the index } return pFrame->LoadViews(line); }
bool Document::saveAs() { QString selected; QString filename = QFileDialog::getSaveFileName(window(), tr("Save File As"), m_filename, fileFilter(m_filename), &selected); if (!filename.isEmpty()) { filename = fileNameWithExtension(filename, selected); if (QFile::exists(filename) && !QFile::remove(filename)) { QMessageBox::critical(window(), tr("Sorry"), tr("Unable to overwrite '%1'.").arg(QDir::toNativeSeparators(filename))); return false; } qSwap(m_filename, filename); if (!save()) { m_filename = filename; return false; } clearIndex(); updateSaveLocation(); m_text->setReadOnly(false); m_text->document()->setModified(false); emit changedName(); return true; } else { return false; } }