void SCH_EDIT_FRAME::OnPreferencesOptions( wxCommandEvent& event )
{
    wxArrayString units;
    GRIDS grid_list = GetScreen()->GetGrids();
    bool saveProjectConfig = false;

    DIALOG_EESCHEMA_OPTIONS dlg( this );

    units.Add( GetUnitsLabel( INCHES ) );
    units.Add( GetUnitsLabel( MILLIMETRES ) );

    dlg.SetUnits( units, g_UserUnit );
    dlg.SetGridSizes( grid_list, GetScreen()->GetGridCmdId() );
    dlg.SetBusWidth( GetDefaultBusThickness() );
    dlg.SetLineWidth( GetDefaultLineThickness() );
    dlg.SetTextSize( GetDefaultTextSize() );
    dlg.SetRepeatHorizontal( GetRepeatStep().x );
    dlg.SetRepeatVertical( GetRepeatStep().y );
    dlg.SetRepeatLabel( GetRepeatDeltaLabel() );
    dlg.SetAutoSaveInterval( GetAutoSaveInterval() / 60 );
    dlg.SetRefIdSeparator( LIB_PART::GetSubpartIdSeparator(),
                           LIB_PART::GetSubpartFirstId() );

    dlg.SetShowGrid( IsGridVisible() );
    dlg.SetShowHiddenPins( m_showAllPins );
    dlg.SetEnableMousewheelPan( m_canvas->GetEnableMousewheelPan() );
    dlg.SetEnableZoomNoCenter( m_canvas->GetEnableZoomNoCenter() );
    dlg.SetEnableAutoPan( m_canvas->GetEnableAutoPan() );
    dlg.SetEnableHVBusOrientation( GetForceHVLines() );
    dlg.SetShowPageLimits( m_showPageLimits );
    dlg.SetFootprintPreview( m_footprintPreview );
    dlg.SetAutoplaceFields( m_autoplaceFields );
    dlg.SetAutoplaceJustify( m_autoplaceJustify );
    dlg.SetAutoplaceAlign( m_autoplaceAlign );
    dlg.Layout();
    dlg.Fit();
    dlg.SetMinSize( dlg.GetSize() );
    dlg.SetTemplateFields( m_TemplateFieldNames.GetTemplateFieldNames() );

    if( dlg.ShowModal() == wxID_CANCEL )
        return;

    g_UserUnit = (EDA_UNITS_T)dlg.GetUnitsSelection();

    wxRealPoint  gridsize = grid_list[ (size_t) dlg.GetGridSelection() ].m_Size;
    m_LastGridSizeId = GetScreen()->SetGrid( gridsize );

    int sep, firstId;
    dlg.GetRefIdSeparator( sep, firstId);

    if( sep != (int)LIB_PART::GetSubpartIdSeparator() ||
        firstId != (int)LIB_PART::GetSubpartFirstId() )
    {
        LIB_PART::SetSubpartIdNotation( sep, firstId );
        saveProjectConfig = true;
    }

    SetDefaultBusThickness( dlg.GetBusWidth() );
    SetDefaultLineThickness( dlg.GetLineWidth() );

    if( dlg.GetTextSize() != GetDefaultTextSize() )
    {
        SetDefaultTextSize( dlg.GetTextSize() );
        saveProjectConfig = true;
    }

    wxPoint step;
    step.x = dlg.GetRepeatHorizontal();
    step.y = dlg.GetRepeatVertical();
    SetRepeatStep( step );
    SetRepeatDeltaLabel( dlg.GetRepeatLabel() );

    SetAutoSaveInterval( dlg.GetAutoSaveInterval() * 60 );
    SetGridVisibility( dlg.GetShowGrid() );
    m_showAllPins = dlg.GetShowHiddenPins();
    m_canvas->SetEnableMousewheelPan( dlg.GetEnableMousewheelPan() );
    m_canvas->SetEnableZoomNoCenter( dlg.GetEnableZoomNoCenter() );
    m_canvas->SetEnableAutoPan( dlg.GetEnableAutoPan() );
    SetForceHVLines( dlg.GetEnableHVBusOrientation() );
    m_showPageLimits = dlg.GetShowPageLimits();
    m_autoplaceFields = dlg.GetAutoplaceFields();
    m_autoplaceJustify = dlg.GetAutoplaceJustify();
    m_autoplaceAlign = dlg.GetAutoplaceAlign();
    m_footprintPreview = dlg.GetFootprintPreview();

    // Delete all template fieldnames and then restore them using the template field data from
    // the options dialog
    DeleteAllTemplateFieldNames();
    TEMPLATE_FIELDNAMES newFieldNames = dlg.GetTemplateFields();

    for( TEMPLATE_FIELDNAMES::iterator dlgfld = newFieldNames.begin();
         dlgfld != newFieldNames.end(); ++dlgfld )
    {
        TEMPLATE_FIELDNAME fld = *dlgfld;
        AddTemplateFieldName( fld );
    }

    SaveSettings( config() );  // save values shared by eeschema applications.

    if( saveProjectConfig )
        SaveProjectSettings( true );

    m_canvas->Refresh( true );
}
bool QgsStyleV2ManagerDialog::addSymbol()
{
  // create new symbol with current type
  QgsSymbolV2* symbol;
  QString name = tr( "new symbol" );
  switch ( currentItemType() )
  {
    case QgsSymbolV2::Marker:
      symbol = new QgsMarkerSymbolV2();
      name = tr( "new marker" );
      break;
    case QgsSymbolV2::Line:
      symbol = new QgsLineSymbolV2();
      name = tr( "new line" );
      break;
    case QgsSymbolV2::Fill:
      symbol = new QgsFillSymbolV2();
      name = tr( "new fill symbol" );
      break;
    default:
      Q_ASSERT( 0 && "unknown symbol type" );
      return false;
  }

  // get symbol design
  // NOTE : Set the parent widget as "this" to notify the Symbol selector
  //        that, it is being called by Style Manager, so recursive calling
  //        of style manager and symbol selector can be arrested
  //        See also: editSymbol()
  QgsSymbolV2SelectorDialog dlg( symbol, mStyle, nullptr, this );
  if ( dlg.exec() == 0 )
  {
    delete symbol;
    return false;
  }

  // get unique name
  bool nameInvalid = true;

  while ( nameInvalid )
  {
    bool ok;
    name = QInputDialog::getText( this, tr( "Symbol Name" ),
                                  tr( "Please enter a name for new symbol:" ),
                                  QLineEdit::Normal, name, &ok );
    if ( !ok )
    {
      delete symbol;
      return false;
    }
    // validate name
    if ( name.isEmpty() )
    {
      QMessageBox::warning( this, tr( "Save symbol" ),
                            tr( "Cannot save symbol without name. Enter a name." ) );
    }
    else if ( mStyle->symbolNames().contains( name ) )
    {
      int res = QMessageBox::warning( this, tr( "Save symbol" ),
                                      tr( "Symbol with name '%1' already exists. Overwrite?" )
                                      .arg( name ),
                                      QMessageBox::Yes | QMessageBox::No );
      if ( res == QMessageBox::Yes )
      {
        nameInvalid = false;
      }
    }
    else
    {
      // valid name
      nameInvalid = false;
    }
  }

  // add new symbol to style and re-populate the list
  mStyle->addSymbol( name, symbol, true );
  // TODO groups and tags
  mModified = true;
  return true;
}
bool QgsStyleV2ManagerDialog::editColorRamp()
{
  QString name = currentItemName();
  if ( name.isEmpty() )
    return false;

  QgsVectorColorRampV2* ramp = mStyle->colorRamp( name );

  if ( ramp->type() == "gradient" )
  {
    QgsVectorGradientColorRampV2* gradRamp = static_cast<QgsVectorGradientColorRampV2*>( ramp );
    QgsVectorGradientColorRampV2Dialog dlg( gradRamp, this );
    if ( !dlg.exec() )
    {
      delete ramp;
      return false;
    }
  }
  else if ( ramp->type() == "random" )
  {
    QgsVectorRandomColorRampV2* randRamp = static_cast<QgsVectorRandomColorRampV2*>( ramp );
    QgsVectorRandomColorRampV2Dialog dlg( randRamp, this );
    if ( !dlg.exec() )
    {
      delete ramp;
      return false;
    }
  }
  else if ( ramp->type() == "colorbrewer" )
  {
    QgsVectorColorBrewerColorRampV2* brewerRamp = static_cast<QgsVectorColorBrewerColorRampV2*>( ramp );
    QgsVectorColorBrewerColorRampV2Dialog dlg( brewerRamp, this );
    if ( !dlg.exec() )
    {
      delete ramp;
      return false;
    }
  }
  else if ( ramp->type() == "cpt-city" )
  {
    QgsCptCityColorRampV2* cptCityRamp = static_cast<QgsCptCityColorRampV2*>( ramp );
    QgsCptCityColorRampV2Dialog dlg( cptCityRamp, this );
    if ( !dlg.exec() )
    {
      delete ramp;
      return false;
    }
    if ( dlg.saveAsGradientRamp() )
    {
      ramp = cptCityRamp->cloneGradientRamp();
      delete cptCityRamp;
    }
  }
  else
  {
    Q_ASSERT( 0 && "invalid ramp type" );
  }

  mStyle->addColorRamp( name, ramp, true );
  mModified = true;
  return true;
}
/**
 * Displays the general preferences dialogue, showing the "Fonts" page.
 * This slot is connected to the clicked() signal of the fonts button.
 */
void GraphPrefDlg::slotColorClicked()
{
	PreferencesDlg dlg(PreferencesDlg::Colors);

	dlg.exec();
}
void ManageNamesPage::on_submitNameButton_clicked()
{
    if (!walletModel)
        return;

    QString name = ui->registerName->text();

    bool avail = walletModel->nameAvailable(name);
    if (!avail)
    {
        QMessageBox::warning(this, tr("Name registration"), tr("Name not available"));
        ui->registerName->setFocus();
        return;
    }

    QString msg;
    if (name.startsWith("d/"))
        msg = tr("Are you sure you want to register domain name %1, which "
            "corresponds to domain %2? <br><br> NOTE: If your wallet is locked, you will be prompted "
            "to unlock it in 12 blocks.").arg(name).arg(name.mid(2) + ".bit");
    else
        msg = tr("Are you sure you want to register non-domain name %1? <br><br>"
            "NOTE: If your wallet is locked, you will be prompted "
            "to unlock it in 12 blocks.").arg(name);

    if (QMessageBox::Yes != QMessageBox::question(this, tr("Confirm name registration"),
          msg,
          QMessageBox::Yes | QMessageBox::Cancel,
          QMessageBox::Cancel))
    {
        return;
    }

    WalletModel::UnlockContext ctx(walletModel->requestUnlock());
    if (!ctx.isValid())
        return;

    QString err_msg;
    std::string strName = name.toStdString();

    try
    {
        NameNewReturn res = walletModel->nameNew(name);

        if (res.ok)
        {
            // save pending name firstupdate data ... this gets
            // picked up after the config name dialog is accepted
            pendingNameFirstUpdate[strName] = res;

            // reset UI text
            ui->registerName->setText("d/");
            ui->submitNameButton->setDefault(true);

            int newRowIndex;
            // FIXME: CT_NEW may have been sent from nameNew (via transaction).
            // Currently updateEntry is modified so it does not complain
            model->updateEntry(name, "", NameTableEntry::NAME_NEW, CT_NEW, &newRowIndex);
            ui->tableView->selectRow(newRowIndex);
            ui->tableView->setFocus();

            ConfigureNameDialog dlg(platformStyle, name, "", true, this);
            dlg.setModel(walletModel);

            if (dlg.exec() == QDialog::Accepted)
            {
                LOCK(cs_main);
                if (pendingNameFirstUpdate.count(strName) != 0)
                {
                    model->updateEntry(name, dlg.getReturnData(), NameTableEntry::NAME_NEW, CT_UPDATED);
                }
                else
                {
                    // name_firstupdate could have been sent, while the user was editing the value
                    // Do nothing
                }
            }

            return;
        }

        err_msg = QString(res.err_msg.c_str());
    }
    catch (std::exception& e)
    {
        err_msg = e.what();
        LogPrintf("ManageNamesPage::on_submitNameButton_clicked; %s", err_msg.toStdString().c_str());
    }

    if (err_msg == "ABORTED")
        return;

    QMessageBox::warning(this, tr("Name registration failed"), err_msg);
}
Exemple #6
0
void LIB_EDIT_FRAME::OnCreateNewPart( wxCommandEvent& event )
{
    m_canvas->EndMouseCapture( ID_NO_TOOL_SELECTED, GetGalCanvas()->GetDefaultCursor() );
    SetDrawItem( NULL );
    wxString lib = getTargetLib();

    if( !m_libMgr->LibraryExists( lib ) )
    {
        lib = SelectLibraryFromList();

        if( !m_libMgr->LibraryExists( lib ) )
            return;
    }

    DIALOG_LIB_NEW_COMPONENT dlg( this );
    dlg.SetMinSize( dlg.GetSize() );

    if( dlg.ShowModal() == wxID_CANCEL )
        return;

    if( dlg.GetName().IsEmpty() )
    {
        wxMessageBox( _( "This new symbol has no name and cannot be created." ) );
        return;
    }

    wxString name = dlg.GetName();
    // Currently, symbol names cannot include a space, that breaks libraries:
    name.Replace( " ", "_" );

    // Test if there is a component with this name already.
    if( !lib.empty() && m_libMgr->PartExists( name, lib ) )
    {
        wxString msg = wxString::Format( _( "Symbol \"%s\" already exists in library \"%s\"" ),
                                         name, lib );
        DisplayError( this, msg );
        return;
    }

    LIB_PART new_part( name );      // do not create part on the heap, it will be buffered soon
    new_part.GetReferenceField().SetText( dlg.GetReference() );
    new_part.SetUnitCount( dlg.GetUnitCount() );

    // Initialize new_part.m_TextInside member:
    // if 0, pin text is outside the body (on the pin)
    // if > 0, pin text is inside the body

    if( dlg.GetPinNameInside() )
    {
        new_part.SetPinNameOffset( dlg.GetPinTextPosition() );

        if( new_part.GetPinNameOffset() == 0 )
            new_part.SetPinNameOffset( 1 );
    }
    else
    {
        new_part.SetPinNameOffset( 0 );
    }

    ( dlg.GetPowerSymbol() ) ? new_part.SetPower() : new_part.SetNormal();
    new_part.SetShowPinNumbers( dlg.GetShowPinNumber() );
    new_part.SetShowPinNames( dlg.GetShowPinName() );
    new_part.LockUnits( dlg.GetLockItems() );

    if( dlg.GetUnitCount() < 2 )
        new_part.LockUnits( false );

    m_libMgr->UpdatePart( &new_part, lib );
    SyncLibraries( false );
    loadPart( name, lib, 1 );

    new_part.SetConversion( dlg.GetAlternateBodyStyle() );
    // must be called after loadPart, that calls SetShowDeMorgan, but
    // because the symbol is empty,it looks like it has no alternate body
    SetShowDeMorgan( dlg.GetAlternateBodyStyle() );

}
Exemple #7
0
/** Save the image under a new name
  * Set the modification flag
  * \return true on success, false on failure
  */
bool XPMEditorBase::SaveAs(void)
{
    wxFileName fname;
    fname.Assign(m_Filename);
    ConfigManager* mgr = Manager::Get()->GetConfigManager(_T("app"));
    int StoredIndex = 0;
    wxString Filters = FileFilters::GetFilterString();
    wxString Path = fname.GetPath();
    wxString Extension = fname.GetExt();
    wxString Filter;
    if (!Extension.IsEmpty())
    {    // use the current extension as the filter
        // Select filter belonging to this file type:
        Extension.Prepend(_T("."));
        Filter = FileFilters::GetFilterString(Extension);
    }
    else if(mgr)
    {
        // File type is unknown. Select the last used filter:
        Filter = mgr->Read(_T("/file_dialogs/save_file_as/filter"), _T("bitmap files"));
    }
    if(!Filter.IsEmpty())
    {
        // We found a filter, look up its index:
        int sep = Filter.find(_T("|"));
        if (sep != wxNOT_FOUND)
        {
            Filter.Truncate(sep);
        }
        if (!Filter.IsEmpty())
        {
            FileFilters::GetFilterIndexFromName(Filters, Filter, StoredIndex);
        }
    }
    if(mgr && Path.IsEmpty())
    {
        Path = mgr->Read(_T("/file_dialogs/save_file_as/directory"), Path);
    }
    wxFileDialog dlg(Manager::Get()->GetAppWindow(),
                                         _("Save file"),
                                         Path,
                                         fname.GetFullName(),
                                         Filters,
                                         wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
    dlg.SetFilterIndex(StoredIndex);
    PlaceWindow(&dlg);
    if (dlg.ShowModal() != wxID_OK)
    {  // cancelled out
        return(false);
    }
    m_Filename = dlg.GetPath();
    Manager::Get()->GetLogManager()->Log(m_Filename);
    fname.Assign(m_Filename);
    m_Shortname = fname.GetFullName();
    SetTitle(m_Shortname);
    // invalidate m_pProjectFile, because if kept, it would point to the ProjectFile with old name and
    // cause ProjectManager::RemoveFileFromProject called via context menu to crash
    if (m_pProjectFile) m_pProjectFile->SetFileState(fvsNormal); //so the original project file will be shown as unmodified.
    UpdateModified();
    SetProjectFile(0);
    //Manager::Get()->GetLogManager()->Log(mltDevDebug, "Filename=%s\nShort=%s", m_Filename.c_str(), m_Shortname.c_str());
    m_bIsFileNameOK = true;
    SetModified(true);
    // store the last used filter and directory
    if(mgr)
    {
        int Index = dlg.GetFilterIndex();
        wxString Filter;
        if(FileFilters::GetFilterNameFromIndex(Filters, Index, Filter))
        {
            mgr->Write(_T("/file_dialogs/save_file_as/filter"), Filter);
        }
        wxString Test = dlg.GetDirectory();
        mgr->Write(_T("/file_dialogs/save_file_as/directory"), dlg.GetDirectory());
    }
    return(Save());
}
Exemple #8
0
void qHPR::doAction()
{
	assert(m_app);
	if (!m_app)
		return;

	const ccHObject::Container& selectedEntities = m_app->getSelectedEntities();
	size_t selNum = selectedEntities.size();
    if (selNum!=1)
	{
		m_app->dispToConsole("Select only one cloud!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

    ccHObject* ent = selectedEntities[0];
    if (!ent->isA(CC_TYPES::POINT_CLOUD))
	{
		m_app->dispToConsole("Select a point cloud!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}
    ccPointCloud* cloud = static_cast<ccPointCloud*>(ent);

	ccGLWindow* win = m_app->getActiveGLWindow();
    if (!win)
	{
		m_app->dispToConsole("No active window!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		return;
	}

	//display parameters
	const ccViewportParameters& params =  win->getViewportParameters();
	if (!params.perspectiveView)
	{
		m_app->dispToConsole("Perspective mode only!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
        return;
	}

	ccHprDlg dlg(m_app->getMainWindow());
    if (!dlg.exec())
        return;

	//progress dialog
	ccProgressDialog progressCb(false,m_app->getMainWindow());

	//unique parameter: the octree subdivision level
	int octreeLevel = dlg.octreeLevelSpinBox->value();
	assert(octreeLevel>=0 && octreeLevel<=255);

	//compute octree if cloud hasn't any
    ccOctree* theOctree = cloud->getOctree();
    if (!theOctree)
        theOctree = cloud->computeOctree(&progressCb);

	if (!theOctree)
	{
		m_app->dispToConsole("Couldn't compute octree!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
        return;
	}

	CCVector3d viewPoint = params.cameraCenter;
	if (params.objectCenteredView)
	{
		CCVector3d PC = params.cameraCenter - params.pivotPoint;
		params.viewMat.inverse().apply(PC);
		viewPoint = params.pivotPoint + PC;
	}

    //HPR
	CCLib::ReferenceCloud* visibleCells = 0;
	{
		QElapsedTimer eTimer;
		eTimer.start();

		CCLib::ReferenceCloud* theCellCenters = CCLib::CloudSamplingTools::subsampleCloudWithOctreeAtLevel(cloud,(uchar)octreeLevel,CCLib::CloudSamplingTools::NEAREST_POINT_TO_CELL_CENTER,&progressCb,theOctree);
		if (!theCellCenters)
		{
			m_app->dispToConsole("Error while simplifying point cloud with octree!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
			return;
		}

		visibleCells = removeHiddenPoints(theCellCenters,viewPoint,3.5);
	
		m_app->dispToConsole(QString("[HPR] Cells: %1 - Time: %2 s").arg(theCellCenters->size()).arg(eTimer.elapsed()/1.0e3));

		//warning: after this, visibleCells can't be used anymore as a
		//normal cloud (as it's 'associated cloud' has been deleted).
		//Only its indexes are valid! (they are corresponding to octree cells)
		delete theCellCenters;
		theCellCenters = 0;
	}

    if (visibleCells)
    {
		//DGM: we generate a new cloud now, instead of playing with the points visiblity! (too confusing for the user)
		/*if (!cloud->isVisibilityTableInstantiated() && !cloud->resetVisibilityArray())
		{
			m_app->dispToConsole("Visibility array allocation failed! (Not enough memory?)",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
			return;
		}

		ccPointCloud::VisibilityTableType* pointsVisibility = cloud->getTheVisibilityArray();
		assert(pointsVisibility);
		pointsVisibility->fill(POINT_HIDDEN);
		//*/

		CCLib::ReferenceCloud visiblePoints(theOctree->associatedCloud());

		unsigned visiblePointCount = 0;
		unsigned visibleCellsCount = visibleCells->size();

		CCLib::DgmOctree::cellIndexesContainer cellIndexes;
		if (!theOctree->getCellIndexes((uchar)octreeLevel,cellIndexes))
		{
			m_app->dispToConsole("Couldn't fetch the list of octree cell indexes! (Not enough memory?)",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
			delete visibleCells;
			return;
		}

        for (unsigned i=0; i<visibleCellsCount; ++i)
        {
			//cell index
            unsigned index = visibleCells->getPointGlobalIndex(i);
            
			//points in this cell...
			CCLib::ReferenceCloud Yk(theOctree->associatedCloud());
			theOctree->getPointsInCellByCellIndex(&Yk,cellIndexes[index],static_cast<uchar>(octreeLevel));
			//...are all visible
			/*unsigned count = Yk.size();
            for (unsigned j=0;j<count;++j)
                pointsVisibility->setValue(Yk.getPointGlobalIndex(j),POINT_VISIBLE);
            visiblePointCount += count;
			//*/
			if (!visiblePoints.add(Yk))
			{
				m_app->dispToConsole("Not enough memory!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
				delete visibleCells;
				return;
			}
        }

        delete visibleCells;
		visibleCells = 0;

		m_app->dispToConsole(QString("[HPR] Visible points: %1").arg(visiblePointCount));

		if (visiblePoints.size() == cloud->size())
		{
			m_app->dispToConsole("No points were removed!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
		}
		else
		{
			//create cloud from visibility selection
			ccPointCloud* newCloud = cloud->partialClone(&visiblePoints);
			if (newCloud)
			{			
				newCloud->setDisplay(newCloud->getDisplay());
				newCloud->setVisible(true);
				newCloud->setName(cloud->getName()+QString(".visible_points"));
				cloud->setVisible(false);

				//add associated viewport object
				cc2DViewportObject* viewportObject = new cc2DViewportObject(QString("Viewport"));
				viewportObject->setParameters(params);
				newCloud->addChild(viewportObject);

				m_app->addToDB(newCloud);
				newCloud->redrawDisplay();
			}
			else
			{
				m_app->dispToConsole("Not enough memory!",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
			}
		}
    }

    //currently selected entities appearance may have changed!
	m_app->refreshAll();
}
Exemple #9
0
void WeightsManFrame::OnLoadBtn(wxCommandEvent& ev)
{
	wxFileDialog dlg( this, "Choose Weights File", "", "",
					 "Weights Files (*.gal, *.gwt)|*.gal;*.gwt");
	
    if (dlg.ShowModal() != wxID_OK) return;
	wxString path  = dlg.GetPath();
	wxString ext = GenUtils::GetFileExt(path).Lower();
	
	if (ext != "gal" && ext != "gwt") {
		wxString msg("Only 'gal' and 'gwt' weights files supported.");
		wxMessageDialog dlg(this, msg, "Error", wxOK|wxICON_ERROR);
		dlg.ShowModal();
		return;
	}
	
	WeightsMetaInfo wmi;
	wxString id_field = WeightUtils::ReadIdField(path);
	LOG(id_field);
	wmi.SetToCustom(id_field);
	wmi.filename = path;
	
	suspend_w_man_state_updates = true;
	
	// Check if weights already loaded and simply select and set as
	// new default if already loaded.
	boost::uuids::uuid id = w_man_int->FindIdByFilename(path);
	if (id.is_nil()) {
		LOG_MSG("could not find existing weight with filename: " + path);
		//id = w_man_int->FindIdByMetaInfo(wmi);
	}
	if (!id.is_nil()) {
		HighlightId(id);
		SelectId(id);
		Refresh();
		suspend_w_man_state_updates = false;
		return;
	}
	

	
	GalElement* tempGal = 0;
	if (ext == "gal") {
		tempGal = WeightUtils::ReadGal(path, table_int);
	} else {
		tempGal = WeightUtils::ReadGwtAsGal(path, table_int);
	}
	if (tempGal == NULL) {
		// WeightsUtils read functions already reported any issues
		// to user when NULL returned.
		suspend_w_man_state_updates = false;
		return;
	}
    
    id = w_man_int->RequestWeights(wmi);
    if (id.is_nil()) {
        wxString msg("There was a problem requesting the weights file.");
        wxMessageDialog dlg(this, msg, "Error", wxOK|wxICON_ERROR);
        dlg.ShowModal();
        suspend_w_man_state_updates = false;
        return;
    }
	
	GalWeight* gw = new GalWeight();
	gw->num_obs = table_int->GetNumberRows();
	gw->wflnm = wmi.filename;
    gw->id_field = id_field;
	gw->gal = tempGal;

	if (!((WeightsNewManager*) w_man_int)->AssociateGal(id, gw)) {
		wxString msg("There was a problem associating the weights file.");
		wxMessageDialog dlg(this, msg, "Error", wxOK|wxICON_ERROR);
		dlg.ShowModal();
		delete gw;
		suspend_w_man_state_updates = false;
		return;
	}
	ids.push_back(id);
	long last = ids.size()-1;
	w_list->InsertItem(last, wxEmptyString);
	w_list->SetItem(last, TITLE_COL, w_man_int->GetTitle(id));
	w_man_int->MakeDefault(id);
	HighlightId(id);
	SelectId(id);
	Refresh();
	suspend_w_man_state_updates = false;
}
Exemple #10
0
void WMain::OnAboutButton(wxCommandEvent&)
{
    WAbout dlg(this);
    dlg.ShowModal();
}
Exemple #11
0
void PCB_EDIT_FRAME::ToPlotter( wxCommandEvent& event )
{
    DIALOG_PLOT dlg( this );
    dlg.ShowModal();
}
Exemple #12
0
int DRAWING_TOOL::PlaceDXF( const TOOL_EVENT& aEvent )
{
    if( m_editModules && !m_board->m_Modules )
        return 0;

    DIALOG_DXF_IMPORT dlg( m_frame );
    int dlgResult = dlg.ShowModal();

    const std::list<BOARD_ITEM*>& list = dlg.GetImportedItems();

    if( dlgResult != wxID_OK || list.empty() )
        return 0;

    VECTOR2I cursorPos = m_controls->GetCursorPosition();
    VECTOR2I delta = cursorPos - (*list.begin())->GetPosition();

    // Add a VIEW_GROUP that serves as a preview for the new item
    KIGFX::VIEW_GROUP preview( m_view );

    // Build the undo list & add items to the current view
    std::list<BOARD_ITEM*>::const_iterator it, itEnd;
    for( it = list.begin(), itEnd = list.end(); it != itEnd; ++it )
    {
        KICAD_T type = (*it)->Type();
        assert( type == PCB_LINE_T || type == PCB_TEXT_T );

        if( type == PCB_LINE_T || type == PCB_TEXT_T )
            preview.Add( *it );
    }

    BOARD_ITEM* firstItem = static_cast<BOARD_ITEM*>( *preview.Begin() );
    m_view->Add( &preview );

    m_toolMgr->RunAction( COMMON_ACTIONS::selectionClear, true );
    m_controls->ShowCursor( true );
    m_controls->SetSnapping( true );

    Activate();

    // Main loop: keep receiving events
    while( OPT_TOOL_EVENT evt = Wait() )
    {
        cursorPos = m_controls->GetCursorPosition();

        if( evt->IsMotion() )
        {
            delta = cursorPos - firstItem->GetPosition();

            for( KIGFX::VIEW_GROUP::iter it = preview.Begin(), end = preview.End(); it != end; ++it )
                static_cast<BOARD_ITEM*>( *it )->Move( wxPoint( delta.x, delta.y ) );

            preview.ViewUpdate();
        }

        else if( evt->Category() == TC_COMMAND )
        {
            if( evt->IsAction( &COMMON_ACTIONS::rotate ) )
            {
                for( KIGFX::VIEW_GROUP::iter it = preview.Begin(), end = preview.End(); it != end; ++it )
                    static_cast<BOARD_ITEM*>( *it )->Rotate( wxPoint( cursorPos.x, cursorPos.y ),
                                                             m_frame->GetRotationAngle() );

                preview.ViewUpdate( KIGFX::VIEW_ITEM::GEOMETRY );
            }
            else if( evt->IsAction( &COMMON_ACTIONS::flip ) )
            {
                for( KIGFX::VIEW_GROUP::iter it = preview.Begin(), end = preview.End(); it != end; ++it )
                    static_cast<BOARD_ITEM*>( *it )->Flip( wxPoint( cursorPos.x, cursorPos.y ) );

                preview.ViewUpdate( KIGFX::VIEW_ITEM::GEOMETRY );
            }
            else if( evt->IsCancel() || evt->IsActivate() )
            {
                preview.FreeItems();
                break;
            }
        }

        else if( evt->IsClick( BUT_LEFT ) )
        {
            // Place the drawing
            if( m_editModules )
            {
                assert( m_board->m_Modules );
                m_frame->SaveCopyInUndoList( m_board->m_Modules, UR_MODEDIT );
                m_board->m_Modules->SetLastEditTime();

                for( KIGFX::VIEW_GROUP::iter it = preview.Begin(), end = preview.End(); it != end; ++it )
                {
                    BOARD_ITEM* item = static_cast<BOARD_ITEM*>( *it );
                    BOARD_ITEM* converted = NULL;

                    // Modules use different types for the same things,
                    // so we need to convert imported items to appropriate classes.
                    switch( item->Type() )
                    {
                    case PCB_TEXT_T:
                        converted = new TEXTE_MODULE( m_board->m_Modules );
                        // Copy coordinates, layer, etc.
                        *static_cast<TEXTE_PCB*>( converted ) = *static_cast<TEXTE_PCB*>( item );
                        static_cast<TEXTE_MODULE*>( converted )->SetLocalCoord();
                        break;

                    case PCB_LINE_T:
                        converted = new EDGE_MODULE( m_board->m_Modules );
                        // Copy coordinates, layer, etc.
                        *static_cast<DRAWSEGMENT*>( converted ) = *static_cast<DRAWSEGMENT*>( item );
                        static_cast<EDGE_MODULE*>( converted )->SetLocalCoord();
                        break;

                    default:
                        assert( false );
                        break;
                    }

                    delete item;

                    if( converted )
                    {
                        m_board->m_Modules->Add( converted );
                        m_view->Add( converted );
                    }
                }
            }
            else // !m_editModules case
            {
                PICKED_ITEMS_LIST picklist;

                for( KIGFX::VIEW_GROUP::iter it = preview.Begin(), end = preview.End(); it != end; ++it )
                {
                    BOARD_ITEM* item = static_cast<BOARD_ITEM*>( *it );
                    m_board->Add( item );

                    ITEM_PICKER itemWrapper( item, UR_NEW );
                    picklist.PushItem( itemWrapper );

                    m_view->Add( item );
                }

                m_frame->SaveCopyInUndoList( picklist, UR_NEW );
            }

            m_frame->OnModify();
            break;
        }
    }

    preview.Clear();

    m_controls->ShowCursor( false );
    m_controls->SetSnapping( false );
    m_controls->SetAutoPan( false );
    m_controls->CaptureCursor( false );
    m_view->Remove( &preview );

    return 0;
}
Exemple #13
0
void WarkeyDlg::OnAbout(wxCommandEvent&) {
  AboutDlg dlg(this);
  dlg.ShowModal();
}
Exemple #14
0
static int startApp()
{
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    // Stop daemon and exit?
    if (args->isSet("s"))
    {
        KDEsuClient client;
        if (client.ping() == -1)
        {
            kError(1206) << "Daemon not running -- nothing to stop\n";
            exit(1);
        }
        if (client.stopServer() != -1)
        {
            kDebug(1206) << "Daemon stopped\n";
            exit(0);
        }
        kError(1206) << "Could not stop daemon\n";
        exit(1);
    }

    QString icon;
    if ( args->isSet("i"))
	icon = args->getOption("i");

    bool prompt = true;
    if ( args->isSet("d"))
	prompt = false;

    // Get target uid
    QByteArray user = args->getOption("u").toLocal8Bit();
    QByteArray auth_user = user;
    struct passwd *pw = getpwnam(user);
    if (pw == 0L)
    {
        kError(1206) << "User " << user << " does not exist\n";
        exit(1);
    }
    bool other_uid = (getuid() != pw->pw_uid);
    bool change_uid = other_uid;
    if (!change_uid) {
        char *cur_user = getenv("USER");
        if (!cur_user)
            cur_user = getenv("LOGNAME");
        change_uid = (!cur_user || user != cur_user);
    }

    // If file is writeable, do not change uid
    QString file = args->getOption("f");
    if (other_uid && !file.isEmpty())
    {
        if (file.at(0) != '/')
        {
            KStandardDirs dirs;
            file = dirs.findResource("config", file);
            if (file.isEmpty())
            {
                kError(1206) << "Config file not found: " << file << "\n";
                exit(1);
            }
        }
        QFileInfo fi(file);
        if (!fi.exists())
        {
            kError(1206) << "File does not exist: " << file << "\n";
            exit(1);
        }
        change_uid = !fi.isWritable();
    }

    // Get priority/scheduler
    QString tmp = args->getOption("p");
    bool ok;
    int priority = tmp.toInt(&ok);
    if (!ok || (priority < 0) || (priority > 100))
    {
        KCmdLineArgs::usageError(i18n("Illegal priority: %1", tmp));
        exit(1);
    }
    int scheduler = SuProcess::SchedNormal;
    if (args->isSet("r"))
        scheduler = SuProcess::SchedRealtime;
    if ((priority > 50) || (scheduler != SuProcess::SchedNormal))
    {
        change_uid = true;
        auth_user = "******";
    }

    // Get command
    if (args->isSet("c"))
    {
        command = args->getOption("c").toLocal8Bit();
        // Accepting additional arguments here is somewhat weird,
        // but one can conceive use cases: have a complex command with
        // redirections and additional file names which need to be quoted
        // safely.
    }
    else
    {
        if( args->count() == 0 )
        {
            KCmdLineArgs::usageError(i18n("No command specified."));
            exit(1);
        }
    }
    for (int i = 0; i < args->count(); i++)
    {
        command += ' ';
        command += QFile::encodeName(KShell::quoteArg(args->arg(i)));
    }

    // Don't change uid if we're don't need to.
    if (!change_uid)
    {
        int result = system(command);
        result = WEXITSTATUS(result);
        return result;
    }

    // Check for daemon and start if necessary
    bool just_started = false;
    bool have_daemon = true;
    KDEsuClient client;
    if (!client.isServerSGID())
    {
        kWarning(1206) << "Daemon not safe (not sgid), not using it.\n";
        have_daemon = false;
    }
    else if (client.ping() == -1)
    {
        if (client.startServer() == -1)
        {
            kWarning(1206) << "Could not start daemon, reduced functionality.\n";
            have_daemon = false;
        }
        just_started = true;
    }

    // Try to exec the command with kdesud.
    bool keep = !args->isSet("n") && have_daemon;
    bool terminal = args->isSet("t");
    bool withIgnoreButton = args->isSet("ignorebutton");
    int winid = -1;
    bool attach = args->isSet("attach");
    if(attach) {
        winid = args->getOption("attach").toInt(&attach, 0);  //C style parsing.  If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
        if(!attach)
            kWarning(1206) << "Specified winid to attach to is not a valid number";
    } else if(args->isSet("embed")) {
        /* KDialog originally used --embed for attaching the dialog box.  However this is misleading and so we changed to --attach.
         * For consistancy, we silently map --embed to --attach */
        attach = true;
        winid = args->getOption("embed").toInt(&attach, 0);  //C style parsing.  If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
        if(!attach)
            kWarning(1206) << "Specified winid to attach to is not a valid number";
    }


    QList<QByteArray> env;
    QByteArray options;
    env << ( "DESKTOP_STARTUP_ID=" + kapp->startupId());

    if (pw->pw_uid)
    {
       // Only propagate KDEHOME for non-root users,
       // root uses KDEROOTHOME

       // Translate the KDEHOME of this user to the new user.
       QString kdeHome = KGlobal::dirs()->relativeLocation("home", KGlobal::dirs()->localkdedir());
       if (kdeHome[0] != '/')
          kdeHome.prepend("~/");
       else
          kdeHome.clear(); // Use default

       env << ("KDEHOME="+ QFile::encodeName(kdeHome));
    }

    KUser u;
    env << (QByteArray) ("KDESU_USER="******"rlimit(): " << ERR << "\n";
        exit(1);
    }

    // Read configuration
    KConfigGroup config(KGlobal::config(), "Passwords");
    int timeout = config.readEntry("Timeout", defTimeout);

    // Check if we need a password
    SuProcess proc;
    proc.setUser(auth_user);
    int needpw = proc.checkNeedPassword();
    if (needpw < 0)
    {
        QString err = i18n("Su returned with an error.\n");
        KMessageBox::error(0L, err);
        exit(1);
    }
    if (needpw == 0)
    {
        keep = 0;
        kDebug() << "Don't need password!!\n";
    }

    // Start the dialog
    QString password;
    if (needpw)
    {
#ifdef Q_WS_X11
        KStartupInfoId id;
        id.initId( kapp->startupId());
        KStartupInfoData data;
        data.setSilent( KStartupInfoData::Yes );
        KStartupInfo::sendChange( id, data );
#endif
        KDEsuDialog dlg(user, auth_user, keep && !terminal, icon, withIgnoreButton);
        if (prompt)
            dlg.addCommentLine(i18n("Command:"), QFile::decodeName(command));
        if (defKeep)
            dlg.setKeepPassword(true);

        if ((priority != 50) || (scheduler != SuProcess::SchedNormal))
        {
            QString prio;
            if (scheduler == SuProcess::SchedRealtime)
                prio += i18n("realtime: ");
            prio += QString("%1/100").arg(priority);
            if (prompt)
                dlg.addCommentLine(i18n("Priority:"), prio);
        }

	//Attach dialog
#ifdef Q_WS_X11
	if(attach)
            KWindowSystem::setMainWindow(&dlg, (WId)winid);
#endif
        int ret = dlg.exec();
        if (ret == KDEsuDialog::Rejected)
        {
#ifdef Q_WS_X11
            KStartupInfo::sendFinish( id );
#endif
            exit(1);
        }
        if (ret == KDEsuDialog::AsUser)
            change_uid = false;
        password = dlg.password();
        keep = dlg.keepPassword();
#ifdef Q_WS_X11
        data.setSilent( KStartupInfoData::No );
        KStartupInfo::sendChange( id, data );
#endif
    }

    // Some events may need to be handled (like a button animation)
    kapp->processEvents();

    // Run command
    if (!change_uid)
    {
        int result = system(command);
        result = WEXITSTATUS(result);
        return result;
    }
    else if (keep && have_daemon)
    {
        client.setPass(password.toLocal8Bit(), timeout);
        client.setPriority(priority);
        client.setScheduler(scheduler);
        int result = client.exec(command, user, options, env);
        if (result == 0)
        {
            result = client.exitCode();
            return result;
        }
    } else
    {
        SuProcess proc;
        proc.setTerminal(terminal);
        proc.setErase(true);
        proc.setUser(user);
        proc.setEnvironment(env);
        proc.setPriority(priority);
        proc.setScheduler(scheduler);
        proc.setCommand(command);
        int result = proc.exec(password.toLocal8Bit());
        return result;
    }
    return -1;
}
void SFTPTreeView::OnSftpSettings(wxCommandEvent& event)
{
    // Show the SFTP settings dialog
    SFTPSettingsDialog dlg(EventNotifier::Get()->TopFrame());
    dlg.ShowModal();
}
void CProfileDumpView::OnBnClickedProfileValidate()
{
  CProfileReportDlg dlg(this, GetDocument()->m_sProfilePath);

  dlg.DoModal();
}
Exemple #17
0
void WalletView::changePassphrase()
{
    AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
    dlg.setModel(walletModel);
    dlg.exec();
}
void mmNewAcctDialog::OnAttachments(wxCommandEvent& /*event*/)
{
	wxString RefType = Model_Attachment::reftype_desc(Model_Attachment::BANKACCOUNT);
	mmAttachmentDialog dlg(this, RefType, m_account->ACCOUNTID);
	dlg.ShowModal();
}
Exemple #19
0
void LIB_EDIT_FRAME::savePartAs()
{
    LIB_ID old_lib_id = getTargetLibId();
    wxString old_name = old_lib_id.GetLibItemName();
    wxString old_lib = old_lib_id.GetLibNickname();
    LIB_PART* part = m_libMgr->GetBufferedPart( old_name, old_lib );

    if( part )
    {
        SYMBOL_LIB_TABLE* tbl = Prj().SchSymbolLibTable();
        wxArrayString headers;
        std::vector< wxArrayString > itemsToDisplay;
        std::vector< wxString > libNicknames = tbl->GetLogicalLibs();

        headers.Add( _( "Nickname" ) );
        headers.Add( _( "Description" ) );

        for( const auto& name : libNicknames )
        {
            wxArrayString item;
            item.Add( name );
            item.Add( tbl->GetDescription( name ) );
            itemsToDisplay.push_back( item );
        }

        EDA_LIST_DIALOG dlg( this, _( "Save Copy of Symbol" ), headers, itemsToDisplay, old_lib,
                             nullptr, nullptr, /* sort */ false, /* show headers */ false );
        dlg.SetListLabel( _( "Save in library:" ) );
        dlg.SetOKLabel( _( "Save" ) );

        wxBoxSizer* bNameSizer = new wxBoxSizer( wxHORIZONTAL );

        wxStaticText* label = new wxStaticText( &dlg, wxID_ANY, _( "Name:" ),
                                                wxDefaultPosition, wxDefaultSize, 0 );
        bNameSizer->Add( label, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );

        wxTextCtrl* nameTextCtrl = new wxTextCtrl( &dlg, wxID_ANY, old_name,
                                                   wxDefaultPosition, wxDefaultSize, 0 );
        bNameSizer->Add( nameTextCtrl, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

        wxSizer* mainSizer = dlg.GetSizer();
        mainSizer->Prepend( bNameSizer, 0, wxEXPAND|wxTOP|wxLEFT|wxRIGHT, 5 );

        // Move nameTextCtrl to the head of the tab-order
        if( dlg.GetChildren().DeleteObject( nameTextCtrl ) )
            dlg.GetChildren().Insert( nameTextCtrl );

        dlg.SetInitialFocus( nameTextCtrl );

        dlg.Layout();
        mainSizer->Fit( &dlg );

        if( dlg.ShowModal() != wxID_OK )
            return;                   // canceled by user

        wxString new_lib = dlg.GetTextSelection();

        if( new_lib.IsEmpty() )
        {
            DisplayError( NULL, _( "No library specified.  Symbol could not be saved." ) );
            return;
        }

        wxString new_name = nameTextCtrl->GetValue();
        new_name.Trim( true );
        new_name.Trim( false );
        new_name.Replace( " ", "_" );

        if( new_name.IsEmpty() )
        {
            DisplayError( NULL, _( "No symbol name specified.  Symbol could not be saved." ) );
            return;
        }

        // Test if there is a component with this name already.
        if( m_libMgr->PartExists( new_name, new_lib ) )
        {
            wxString msg = wxString::Format( _( "Symbol \"%s\" already exists in library \"%s\"" ),
                                             new_name, new_lib );
            DisplayError( this, msg );
            return;
        }

        LIB_PART new_part( *part );
        new_part.SetName( new_name );

        fixDuplicateAliases( &new_part, new_lib );
        m_libMgr->UpdatePart( &new_part, new_lib );
        SyncLibraries( false );
        m_treePane->GetLibTree()->SelectLibId( LIB_ID( new_lib, new_part.GetName() ) );

        if( isCurrentPart( old_lib_id ) )
            loadPart( new_name, new_lib, m_unit );
    }
}
Exemple #20
0
bool frmMain::CheckAlive()
{
	bool userInformed = false;
	bool closeIt = false;

	wxTreeItemIdValue foldercookie;
	wxTreeItemId folderitem = browser->GetFirstChild(browser->GetRootItem(), foldercookie);
	while (folderitem)
	{
		if (browser->ItemHasChildren(folderitem))
		{
			wxCookieType cookie;
			wxTreeItemId serverItem = browser->GetFirstChild(folderitem, cookie);
			while (serverItem)
			{
				pgServer *server = (pgServer *)browser->GetObject(serverItem);

				if (server && server->IsCreatedBy(serverFactory) && server->connection())
				{
					if (server->connection()->IsAlive())
					{
						wxCookieType cookie2;
						wxTreeItemId item = browser->GetFirstChild(serverItem, cookie2);
						while (item)
						{
							pgObject *obj = browser->GetObject(item);
							if (obj && obj->IsCreatedBy(databaseFactory.GetCollectionFactory()))
							{
								wxCookieType cookie3;
								item = browser->GetFirstChild(obj->GetId(), cookie3);
								while (item)
								{
									pgDatabase *db = (pgDatabase *)browser->GetObject(item);
									if (db && db->IsCreatedBy(databaseFactory))
									{
										pgConn *conn = db->GetConnection();
										if (conn)
										{
											if (!conn->IsAlive() && (conn->GetStatus() == PGCONN_BROKEN || conn->GetStatus() == PGCONN_BAD))
											{
												conn->Close();
												if (!userInformed)
												{
													wxMessageDialog dlg(this, _("Do you want to attempt to reconnect to the database?"),
													                    wxString::Format(_("Connection to database %s lost."), db->GetName().c_str()),
													                    wxICON_EXCLAMATION | wxYES_NO | wxYES_DEFAULT);

													closeIt = (dlg.ShowModal() != wxID_YES);
													userInformed = true;
												}
												if (closeIt)
												{
													db->Disconnect();

													browser->DeleteChildren(db->GetId());
													db->UpdateIcon(browser);
												}
												else
												{
													// Create a server object and connect it.
													wxBusyInfo waiting(wxString::Format(_("Reconnecting to database %s"),
													                                    db->GetName().c_str()), this);

													// Give the UI a chance to redraw
													wxSafeYield();
													wxMilliSleep(100);
													wxSafeYield();

													if (!conn->Reconnect())
													{
														db->Disconnect();

														browser->DeleteChildren(db->GetId());
														db->UpdateIcon(browser);
													}
													else
														// Indicate things are back to normal
														userInformed = false;
												}

											}
										}
									}
									item = browser->GetNextChild(obj->GetId(), cookie3);
								}
							}
							item = browser->GetNextChild(serverItem, cookie2);
						}
					}
					else
					{
						if (server->connection()->GetStatus() == PGCONN_BROKEN || server->connection()->GetStatus() == PGCONN_BAD)
						{
							server->connection()->Close();
							if (!userInformed)
							{
								wxMessageDialog dlg(this, _("Do you want to attempt to reconnect to the server?"),
								                    wxString::Format(_("Connection to server %s lost."), server->GetName().c_str()),
								                    wxICON_EXCLAMATION | wxYES_NO | wxYES_DEFAULT);

								closeIt = (dlg.ShowModal() != wxID_YES);
								userInformed = true;
							}
							if (closeIt)
							{
								server->Disconnect(this);
								browser->SelectItem(serverItem);
								execSelChange(serverItem, true);
								browser->DeleteChildren(serverItem);
							}
							else
							{
								// Create a server object and connect it.
								wxBusyInfo waiting(wxString::Format(_("Reconnecting to server %s (%s:%d)"),
								                                    server->GetDescription().c_str(), server->GetName().c_str(), server->GetPort()), this);

								// Give the UI a chance to redraw
								wxSafeYield();
								wxMilliSleep(100);
								wxSafeYield();

								if (!server->connection()->Reconnect())
								{
									server->Disconnect(this);
									browser->SelectItem(serverItem);
									execSelChange(serverItem, true);
									browser->DeleteChildren(serverItem);
								}
								else
									// Indicate things are back to normal
									userInformed = false;
							}
						}
					}
				}

				serverItem = browser->GetNextChild(folderitem, cookie);
			}
		}
		folderitem = browser->GetNextChild(browser->GetRootItem(), foldercookie);
	}
	return userInformed;
}
/**
 * Displays the general preferences dialogue, showing the "Colours" page.
 * This slot is connected to the clicked() signal of the colours button.
 */
void GraphPrefDlg::slotFontClicked()
{
	PreferencesDlg dlg(PreferencesDlg::Fonts);

	dlg.exec();
}
void VtkCompositeTextureOnSurfaceFilter::init()
{
    this->_inputDataObjectType = VTK_DATA_SET;
    this->_outputDataObjectType = VTK_POLY_DATA;

    vtkSmartPointer<vtkDataSetSurfaceFilter> surfaceFilter;
    VtkTextureOnSurfaceFilter* surface = VtkTextureOnSurfaceFilter::New();

    if (dynamic_cast<vtkUnstructuredGrid*>(_inputAlgorithm->GetOutputDataObject(0)))
    {
        surfaceFilter = vtkSmartPointer<vtkDataSetSurfaceFilter>::New();
        surfaceFilter->SetInputConnection(_inputAlgorithm->GetOutputPort());
        surface->SetInputConnection(surfaceFilter->GetOutputPort());
    }
    else
        surface->SetInputConnection(_inputAlgorithm->GetOutputPort());

    QWidget* parent = nullptr;
    QSettings settings;
    QString fileName = QFileDialog::getOpenFileName(
        parent, "Select raster file to apply as texture",
        settings.value("lastOpenedTextureFileDirectory").toString(),
        "Raster files (*.asc *.grd *.bmp *.jpg *.png *.tif);;"
#ifdef OGS_USE_NETCDF
        "NetCDF files (*.nc);;"
#endif  // OGS_USE_NETCDF
    );
    QFileInfo fi(fileName);

    if ((fi.suffix().toLower() == "asc") || (fi.suffix().toLower() == "tif") ||
        (fi.suffix().toLower() == "png") || (fi.suffix().toLower() == "grd") ||
        (fi.suffix().toLower() == "jpg") || (fi.suffix().toLower() == "bmp"))
    {
        double x0(0), y0(0), scalingFactor(1);
        std::string name = fileName.toStdString();
        vtkImageAlgorithm* image = VtkRaster::loadImage(name, x0, y0, scalingFactor);
        surface->SetRaster(image, x0, y0, scalingFactor);
        surface->Update();

        QDir dir = QDir(fileName);
        settings.setValue("lastOpenedTextureFileDirectory", dir.absolutePath());
    }
#ifdef OGS_USE_NETCDF
    else if (fi.suffix().toLower() == "nc")
    {
        NetCdfConfigureDialog dlg(fileName.toStdString().c_str());
        dlg.exec();
        if (dlg.getRaster() != nullptr)
        {
            VtkGeoImageSource* image = dlg.getRaster();
            double origin[3];
            image->GetOutput()->GetOrigin(origin);
            double spacing[3];
            image->GetOutput()->GetSpacing(spacing);
            surface->SetRaster(image, origin[0], origin[1], spacing[0]);
            surface->Update();
        }
    }
#endif  // OGS_USE_NETCDF
    else
        ERR("VtkCompositeTextureOnSurfaceFilter::init(): Error reading texture file.");

    _outputAlgorithm = surface;
}
void FileNavCommand()
{
    LPCTSTR filterALL[] = {
        "*.*", NULL
    };
    LPCTSTR filterCPP[] = {
        "*.zip", "*.c", "*.cpp", "*.h", NULL
    };
    LPCTSTR filterDOC[] = {
        "*.doc", "*.txt", NULL
    };
    LPCTSTR filterDWG[] = {
        "*.dwg", "*.dxb", "*.dxf", NULL
    };
    LPCTSTR filterIMG[] = {
        "*.gif", "*.jpg", "*.tif", "*.tiff", NULL
    };
    LPCTSTR filterDescription[] = {
        "All files", "C++ files", "Documents", "Drawings", "Images", NULL
    };
    LPCTSTR *filterSpec[] = {
        filterALL, filterCPP, filterDOC, filterDWG, filterIMG, NULL
    };

    CNavFilter *f;
    int  i = 0, j;

    gFilterArray.RemoveAllData();

    while (filterSpec[i] != NULL) {
        // Append a new filter.
        f = gFilterArray.AddData();

        if (f != NULL) {
            // Set the filter's description.
            f->SetDescription(filterDescription[i]);

            // Assign the filter strings.
            j = 0;
            while (filterSpec[i][j] != NULL) {
                f->Add(filterSpec[i][j]);
                j++;
            }
        }

        // Prepare to add the next filter.
        i++;
    }
    while (true)
    {
        HWND acadHandle = adsw_acadMainWnd();
        ::EnableWindow (acadHandle, true);
        ::SetFocus (acadHandle);
        CWnd *pWnd = CWnd::FromHandle(acadHandle);

        CFileNavDlg dlg(gDataArray, gFilterArray, 0, pWnd);
        dlg.SetMultiSelectAllowed(TRUE);
        dlg.SetDialogCaption("Browse down to a file");


        if (dlg.DoModal() == IDOK)
        {
            for(int i = 0; i < gDataArray.GetCount(); i++)
            {
                LPITEMIDLIST id = gDataArray[i]->GetID();
                //able to get the text string entered/selected by user in File Name Combo
                //along with its full parth
                CString sText = gDataArray[i]->GetText();
                if (sText.GetLength() != 0)
                {
                    acutPrintf ("The file name is:\n%s\n",sText.GetBuffer(sText.GetLength()));
                }
            }

        }
        break;
    }
}
void NewGeneMainWindow::on_actionVacuum_output_database_triggered()
{
	VacuumDialog dlg(this, false);
	dlg.exec();
}
void myWindow::dialog(Glib::ustring msg)
{
    Gtk::MessageDialog dlg(msg, false, Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK, true);
    dlg.set_title("Gtkmm Tutorial 3");
    dlg.run();
}
int InvokeDialogAnnotate( SCH_EDIT_FRAME* aCaller, wxString message )
{
    DIALOG_ANNOTATE dlg( aCaller, message );

    return dlg.ShowModal();
}
QString QgsStyleV2ManagerDialog::addColorRampStatic( QWidget* parent, QgsStyleV2* style, QString rampType )
{
  // let the user choose the color ramp type if rampType is not given
  bool ok = true;
  if ( rampType.isEmpty() )
  {
    QStringList rampTypes;
    rampTypes << tr( "Gradient" ) << tr( "Random" ) << tr( "ColorBrewer" );
    rampTypes << tr( "cpt-city" ); // todo, only for rasters?
    rampType = QInputDialog::getItem( parent, tr( "Color ramp type" ),
                                      tr( "Please select color ramp type:" ), rampTypes, 0, false, &ok );
  }
  if ( !ok || rampType.isEmpty() )
    return QString();

  QString name = tr( "new ramp" );

  QgsVectorColorRampV2 *ramp = nullptr;
  if ( rampType == tr( "Gradient" ) )
  {
    QgsVectorGradientColorRampV2* gradRamp = new QgsVectorGradientColorRampV2();
    QgsVectorGradientColorRampV2Dialog dlg( gradRamp, parent );
    if ( !dlg.exec() )
    {
      delete gradRamp;
      return QString();
    }
    ramp = gradRamp;
    name = tr( "new gradient ramp" );
  }
  else if ( rampType == tr( "Random" ) )
  {
    QgsVectorRandomColorRampV2* randRamp = new QgsVectorRandomColorRampV2();
    QgsVectorRandomColorRampV2Dialog dlg( randRamp, parent );
    if ( !dlg.exec() )
    {
      delete randRamp;
      return QString();
    }
    ramp = randRamp;
    name = tr( "new random ramp" );
  }
  else if ( rampType == tr( "ColorBrewer" ) )
  {
    QgsVectorColorBrewerColorRampV2* brewerRamp = new QgsVectorColorBrewerColorRampV2();
    QgsVectorColorBrewerColorRampV2Dialog dlg( brewerRamp, parent );
    if ( !dlg.exec() )
    {
      delete brewerRamp;
      return QString();
    }
    ramp = brewerRamp;
    name = brewerRamp->schemeName() + QString::number( brewerRamp->colors() );
  }
  else if ( rampType == tr( "cpt-city" ) )
  {
    QgsCptCityColorRampV2* cptCityRamp = new QgsCptCityColorRampV2( "", "" );
    QgsCptCityColorRampV2Dialog dlg( cptCityRamp, parent );
    if ( !dlg.exec() )
    {
      delete cptCityRamp;
      return QString();
    }
    // name = dlg.selectedName();
    name = QFileInfo( cptCityRamp->schemeName() ).baseName() + cptCityRamp->variantName();
    if ( dlg.saveAsGradientRamp() )
    {
      ramp = cptCityRamp->cloneGradientRamp();
      delete cptCityRamp;
    }
    else
    {
      ramp = cptCityRamp;
    }
  }
  else
  {
    // Q_ASSERT( 0 && "invalid ramp type" );
    // bailing out is rather harsh!
    QgsDebugMsg( "invalid ramp type " + rampType );
    return QString();
  }

  // get unique name
  bool nameInvalid = true;

  while ( nameInvalid )
  {
    bool ok;
    name = QInputDialog::getText( parent, tr( "Color Ramp Name" ),
                                  tr( "Please enter a name for new color ramp:" ),
                                  QLineEdit::Normal, name, &ok );
    if ( !ok )
    {
      delete ramp;
      return QString();
    }
    // validate name
    if ( name.isEmpty() )
    {
      QMessageBox::warning( parent, tr( "Save Color Ramp" ),
                            tr( "Cannot save color ramp without name. Enter a name." ) );
    }
    else if ( style->colorRampNames().contains( name ) )
    {
      int res = QMessageBox::warning( parent, tr( "Save color ramp" ),
                                      tr( "Color ramp with name '%1' already exists. Overwrite?" )
                                      .arg( name ),
                                      QMessageBox::Yes | QMessageBox::No );
      if ( res == QMessageBox::Yes )
      {
        nameInvalid = false;
      }
    }
    else
    {
      // valid name
      nameInvalid = false;
    }
  }

  // add new symbol to style and re-populate the list
  style->addColorRamp( name, ramp, true );
  // TODO groups and tags, using saveColorRamp
  return name;
}
void SFTPTreeView::DoOpenSession()
{
    DoCloseSession();
    wxString accountName = m_choiceAccount->GetStringSelection();
    if(accountName.IsEmpty()) {
        return;
    }

    SFTPSettings settings;
    settings.Load();

    m_account = SSHAccountInfo();
    if(!settings.GetAccount(accountName, m_account)) {
        ::wxMessageBox(wxString() << _("Could not find account: ") << accountName, "codelite", wxICON_ERROR | wxOK);
        return;
    }

    wxString message;
#ifndef _WIN64
    wxProgressDialog dlg(_("SFTP"), wxString(' ', 100) + "\n\n", 10);
    dlg.Show();
    dlg.Update(1, wxString() << _("Connecting to: ") << accountName << "..." << _("\n(this may take a few seconds)"));
#else
    wxBusyCursor bc;
    clGetManager()->SetStatusMessage(wxString() << _("Connecting to: ") << accountName);
#endif

    // We know that there is a bug that libssh succeeded on connecting only on the second attempt..
    // to workaround it, we issue first connect with 1 second timeout, and then re-open the connection

    try {
        clSSH::Ptr_t ssh(
            new clSSH(m_account.GetHost(), m_account.GetUsername(), m_account.GetPassword(), m_account.GetPort()));
        ssh->Connect(wxNOT_FOUND);
    } catch(...) {
    }

    try {
        clSSH::Ptr_t ssh(
            new clSSH(m_account.GetHost(), m_account.GetUsername(), m_account.GetPassword(), m_account.GetPort()));
        ssh->Connect(5);
#ifndef _WIN64
        dlg.Update(5, _("Connected!"));
        dlg.Update(6, _("Authenticating server..."));
#endif

        if(!ssh->AuthenticateServer(message)) {
            if(::wxMessageBox(message, "SSH", wxYES_NO | wxCENTER | wxICON_QUESTION) == wxYES) {
#ifndef _WIN64
                dlg.Update(7, _("Accepting server authentication server..."));
#endif
                ssh->AcceptServerAuthentication();
            }
        } else {
#ifndef _WIN64
            dlg.Update(7, _("Server authenticated"));
#endif
        }

#ifndef _WIN64
        dlg.Update(8, _("Logging..."));
#endif
        ssh->Login();
        m_sftp.reset(new clSFTP(ssh));
        m_sftp->Initialize();
        m_sftp->SetAccount(m_account.GetAccountName());
        m_plugin->GetManager()->SetStatusMessage(wxString() << _("Done!"));

#ifndef _WIN64
        dlg.Update(9, _("Fetching directory list..."));
#endif
        DoBuildTree(m_account.GetDefaultFolder().IsEmpty() ? "/" : m_account.GetDefaultFolder());
#ifndef _WIN64
        dlg.Update(10, _("Done"));
#endif
    } catch(clException& e) {
        ::wxMessageBox(e.What(), "codelite", wxICON_ERROR | wxOK);
        DoCloseSession();
    }
}
Exemple #29
0
void Importer::importPipeline(const QFileInfo& pipeline, const QString& targetFileName, const QString& customData /*= QString()*/)
{
	m_filesToOverwrite.clear();
	m_alreadyCopied.clear();
	QFileInfo target(m_targetResourcePath, targetFileName);
	if (!target.absoluteDir().exists())
		m_targetResourcePath.mkpath(target.absolutePath());		
	const CopyJob job(pipeline, target);

	QFile file(pipeline.absoluteFilePath());
	if (!file.copy(target.absoluteFilePath()))
	{
		if (!customData.isEmpty())
		{
			if (QMessageBox::question(0, QObject::tr("Overwrite file?"), QObject::tr("Do you want to overwrite the existing pipeline\n%1").arg(target.absoluteFilePath()), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel | QMessageBox::Escape) != QMessageBox::Yes)
				return;
		}
		else if (!m_filesToOverwrite.contains(job) && !m_alreadyCopied.contains(job))
			m_filesToOverwrite.append(job);	
	}
	else
		m_alreadyCopied.append(job);

	if ( !customData.isEmpty() )
		file.setFileName(target.absoluteFilePath());

	if (!file.open(QIODevice::ReadWrite))
	{
		m_errorLog.push_back(QObject::tr("Couldn't open pipeline file %1: %2").arg(file.fileName()).arg(file.errorString()));
		return;
	}
	if ( !customData.isEmpty() )
	{		
		file.resize(customData.toLocal8Bit().size());
		file.write(customData.toLocal8Bit());
		file.seek(0);
	}
	QDomDocument root;
	root.setContent(&file);
	file.close();
	QDomNodeList materialNodes = root.documentElement().elementsByTagName("Stage");
	for( int i=0; i<materialNodes.size(); ++i )
		if( materialNodes.at(i).toElement().hasAttribute("link") )
			importMaterialFile(
				QFileInfo(m_sourceResourcePath, materialNodes.at(i).toElement().attribute("link")),
				materialNodes.at(i).toElement().attribute("link"),
				QString());

	materialNodes = root.documentElement().elementsByTagName("DrawQuad");
	for (int i=0; i<materialNodes.size(); ++i)
		if (materialNodes.at(i).toElement().hasAttribute("material"))
			importMaterialFile(
				QFileInfo(m_sourceResourcePath, materialNodes.at(i).toElement().attribute("material")),
				materialNodes.at(i).toElement().attribute("material"),
				QString());
	materialNodes = root.documentElement().elementsByTagName("SetUniform");
	for (int i=0; i<materialNodes.size(); ++i)
		if (materialNodes.at(i).toElement().hasAttribute("material"))
			importMaterialFile(
				QFileInfo(m_sourceResourcePath, materialNodes.at(i).toElement().attribute("material")),
				materialNodes.at(i).toElement().attribute("material"),
				QString());

	if (!m_filesToOverwrite.isEmpty())
	{
		OverwriteFilesDialog dlg(m_filesToOverwrite);
		if( dlg.numFilesToOverwrite() > 0 )
			dlg.exec();
	}
}
void SCH_EDIT_FRAME::Process_Config( wxCommandEvent& event )
{
    int        id = event.GetId();
    wxFileName fn;

    switch( id )
    {
    case ID_CONFIG_SAVE:
        SaveProjectSettings( true );
        break;

    case ID_CONFIG_READ:
        {
            fn = g_RootSheet->GetScreen()->GetFileName();
            fn.SetExt( ProjectFileExtension );

            wxFileDialog dlg( this, _( "Load Project File" ), fn.GetPath(),
                              fn.GetFullName(), ProjectFileWildcard(),
                              wxFD_OPEN | wxFD_FILE_MUST_EXIST );

            if( dlg.ShowModal() == wxID_CANCEL )
                break;

            wxString chosen = dlg.GetPath();

            if( chosen == Prj().GetProjectFullName() )
                LoadProjectFile();
            else
            {
                // Read library list and library path list
                Prj().ConfigLoad( Kiface().KifaceSearch(), GROUP_SCH,
                                  GetProjectFileParametersList() );
                // Read schematic editor setup
                Prj().ConfigLoad( Kiface().KifaceSearch(), GROUP_SCH_EDITOR,
                                  GetProjectFileParametersList() );
            }
        }
        break;

    // Hotkey IDs
    case ID_PREFERENCES_HOTKEY_EXPORT_CONFIG:
        ExportHotkeyConfigToFile( g_Eeschema_Hokeys_Descr, wxT( "eeschema" ) );
        break;

    case ID_PREFERENCES_HOTKEY_IMPORT_CONFIG:
        ImportHotkeyConfigFromFile( g_Eeschema_Hokeys_Descr, wxT( "eeschema" ) );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_EDITOR:
        InstallHotkeyFrame( this, g_Eeschema_Hokeys_Descr, g_Schematic_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_CURRENT_LIST:
        // Display current hotkey list for eeschema.
        DisplayHotkeyList( this, g_Schematic_Hokeys_Descr );
        break;

    default:
        DisplayError( this, wxT( "SCH_EDIT_FRAME::Process_Config error" ) );
    }
}