예제 #1
0
QSizeF FlowLayout::prefSize() const
{
    qreal left, right;
    getContentsMargins(&left, 0, &right, 0);

    QGraphicsLayoutItem *item;
    qreal maxh = 0;
    qreal totalWidth = 0;
    foreach (item, m_items) {
        if (totalWidth > 0)
            totalWidth += spacing(Qt::Horizontal);
        QSizeF pref = item->effectiveSizeHint(Qt::PreferredSize);
        totalWidth += pref.width();
        maxh = qMax(maxh, pref.height());
    }
    maxh += spacing(Qt::Vertical);

    const qreal goldenAspectRatio = 1.61803399;
    qreal w = qSqrt(totalWidth * maxh * goldenAspectRatio) + left + right;

    return minSize(QSizeF(w, -1));
}
예제 #2
0
    DiskLoc MmapV1ExtentManager::_createExtentInFile( OperationContext* txn,
                                                int fileNo,
                                                DataFile* f,
                                                int size,
                                                bool enforceQuota ) {

        _checkQuota( enforceQuota, fileNo - 1 );

        massert( 10358, "bad new extent size", size >= minSize() && size <= maxSize() );

        DiskLoc loc = f->allocExtentArea( txn, size );
        loc.assertOk();

        Extent *e = getExtent( loc, false );
        verify( e );

        *txn->recoveryUnit()->writing(&e->magic) = Extent::extentSignature;
        *txn->recoveryUnit()->writing(&e->myLoc) = loc;
        *txn->recoveryUnit()->writing(&e->length) = size;

        return loc;
    }
예제 #3
0
vector4 MyBOManager::GetSizeAndMid()
{
	vector3 maxSize(0.0f);
	vector3 minSize(0.0f);

	for (int nEntity = 0; nEntity < m_nObjectCount; nEntity++)
	{
		vector3 pos = m_lObject[nEntity]->GetCenterGlobal();
		for (int i = 0; i < 3; i++)
		{
			if (pos[i] > maxSize[i]) maxSize[i] = pos[i];
			if (pos[i] < minSize[i]) minSize[i] = pos[i];
		}
	}

	vector3 mid = maxSize - minSize;
	mid /= 2;

	float size;
	if (glm::distance(maxSize, vector3(0.0f)) > glm::distance(minSize, vector3(0.0f)))
	{
		for (int j = 0; j < 3; j++)
		{
			if (maxSize[j] < 0.0f) maxSize[j] *= -1;
			if (minSize[j] < 0.0f) maxSize[j] *= -1;
		}

		size = maxSize[0];
		if (maxSize[1] > size) size = maxSize[1];
		if (maxSize[2] > size) size = maxSize[2];
		if (minSize[1] > size) size = minSize[1];
		if (minSize[2] > size) size = minSize[2];
		if (minSize[0] > size) size = minSize[0];
	}

	return vector4(mid, size);
}
예제 #4
0
    void PlateDetection::plateDetectionRough(cv::Mat InputImage,std::vector<pr::PlateInfo>  &plateInfos,int min_w,int max_w){

        cv::Mat processImage;

         cv::cvtColor(InputImage,processImage,cv::COLOR_BGR2GRAY);


        std::vector<cv::Rect> platesRegions;
//        std::vector<PlateInfo> plates;
        cv::Size minSize(min_w,min_w/4);
        cv::Size maxSize(max_w,max_w/4);
//        cv::imshow("input",InputImage);
//                cv::waitKey(0);
        cascade.detectMultiScale( processImage, platesRegions,
                                  1.1, 3, cv::CASCADE_SCALE_IMAGE,minSize,maxSize);
        for(auto plate:platesRegions)
        {
            // extend rects
//            x -= w * 0.14
//            w += w * 0.28
//            y -= h * 0.6
//            h += h * 1.1;
            int zeroadd_w  = static_cast<int>(plate.width*0.30);
            int zeroadd_h = static_cast<int>(plate.height*2);
            int zeroadd_x = static_cast<int>(plate.width*0.15);
            int zeroadd_y = static_cast<int>(plate.height*1);
            plate.x-=zeroadd_x;
            plate.y-=zeroadd_y;
            plate.height += zeroadd_h;
            plate.width += zeroadd_w;
                cv::Mat plateImage = util::cropFromImage(InputImage,plate);
            PlateInfo plateInfo(plateImage,plate);
            plateInfos.push_back(plateInfo);

        }
    }
예제 #5
0
QSize QSplitter::minimumSizeHint() const
{
    constPolish();
    int l = 0;
    int t = 0;
    if ( children() ) {
	const QObjectList * c = children();
	QObjectListIt it( *c );
	QObject * o;

	while( (o=it.current()) != 0 ) {
	    ++it;
	    if ( o->isWidgetType() &&
		 !((QWidget*)o)->isHidden() ) {
		QSize s = minSize((QWidget*)o);
		if ( s.isValid() ) {
		    l += pick( s );
		    t = QMAX( t, trans( s ) );
		}
	    }
	}
    }
    return orientation() == Horizontal ? QSize( l, t ) : QSize( t, l );
}
예제 #6
0
void QSplitter::recalc( bool update )
{
    int fi = 2*frameWidth();
    int maxl = fi;
    int minl = fi;
    int maxt = QWIDGETSIZE_MAX;
    int mint = fi;
    int n = data->list.count();
    bool first = TRUE;
    /*
      The splitter before a hidden widget is always hidden.
      The splitter before the first visible widget is hidden.
      The splitter before any other visible widget is visible.
    */
    for ( int i = 0; i< n; i++ ) {
	QSplitterLayoutStruct *s = data->list.at(i);
	if ( !s->isSplitter ) {
	    QSplitterLayoutStruct *p = (i > 0) ? data->list.at( i-1 ) : 0;
	    if ( p && p->isSplitter )
		if ( first || s->wid->isHidden() )
		    p->wid->hide(); //may trigger new recalc
		else
		    p->wid->show(); //may trigger new recalc
	    if ( !s->wid->isHidden() )
		first = FALSE;
	}
    }

    bool empty=TRUE;
    for ( int j = 0; j< n; j++ ) {
	QSplitterLayoutStruct *s = data->list.at(j);
	if ( !s->wid->isHidden() ) {
	    empty = FALSE;
	    if ( s->isSplitter ) {
		minl += s->sizer;
		maxl += s->sizer;
	    } else {
		QSize minS = minSize(s->wid);
		minl += pick( minS );
		maxl += pick( s->wid->maximumSize() );
		mint = QMAX( mint, trans( minS ));
		int tm = trans( s->wid->maximumSize() );
		if ( tm > 0 )
		    maxt = QMIN( maxt, tm );
	    }
	}
    }
    if ( empty )
	maxl = maxt = 0;
    else
	maxl = QMIN( maxl, QWIDGETSIZE_MAX );
    if ( maxt < mint )
	maxt = mint;

    if ( orient == Horizontal ) {
	setMaximumSize( maxl, maxt );
	setMinimumSize( minl, mint );
    } else {
	setMaximumSize( maxt, maxl );
	setMinimumSize( mint, minl );
    }
    if ( update )
	doResize();
}
예제 #7
0
static bool java_createJavaVMInitArgs(struct JavaVMInitArgs* vm_args, const struct Properties* jvmProps) {

	// ### evaluate JNI version to use ###
	//jint jniVersion = JNI_VERSION_1_1;
	//jint jniVersion = JNI_VERSION_1_2;
	jint jniVersion = JNI_VERSION_1_4;
	//jint jniVersion = JNI_VERSION_1_6;
	if (jvmProps != NULL) {
		const char* jniVersionFromCfg = java_getValueByKey(jvmProps,
				"jvm.jni.version");
		if (jniVersionFromCfg != NULL) {
			unsigned long int jniVersion_tmp =
					strtoul(jniVersionFromCfg, NULL, 16);
			if (jniVersion_tmp != 0/* && jniVersion_tmp != ULONG_MAX*/) {
				jniVersion = (jint) jniVersion_tmp;
			}
		}
	}
	simpleLog_logL(SIMPLELOG_LEVEL_FINE, "JVM: JNI version: %#x", jniVersion);
	vm_args->version = jniVersion;

	// ### check if debug related JVM options should be used ###
	// if false, the JVM creation will fail if an
	// unknown or invalid option was specified
	bool useDebugOptions = true;
	const char* useDebugOptionsStr = "auto";
	if (jvmProps != NULL) {
		const char* useDebugOptionsFromCfg =
				util_map_getValueByKey(
				jvmProps->size, jvmProps->keys, jvmProps->values,
				"jvm.useDebugOptions");
		if (useDebugOptionsFromCfg != NULL) {
			useDebugOptionsStr = useDebugOptionsFromCfg;
		}
	}
	{
		if (strcmp(useDebugOptionsStr, "auto") == 0
				|| strcmp(useDebugOptionsStr, "Auto") == 0
				|| strcmp(useDebugOptionsStr, "AUTO") == 0
				|| strcmp(useDebugOptionsStr, "a") == 0
				|| strcmp(useDebugOptionsStr, "A") == 0)
		{
			// auto
#if       defined DEBUG
			useDebugOptions = true;
#else  // defined DEBUG
			useDebugOptions = false;
#endif // defined DEBUG
		} else {
			// true or false
			useDebugOptions = util_strToBool(useDebugOptionsStr);
		}
	}

	// ### check if unrecognized JVM options should be ignored ###
	// if false, the JVM creation will fail if an
	// unknown or invalid option was specified
	bool ignoreUnrecognized = true;
	if (jvmProps != NULL) {
		const char* ignoreUnrecognizedFromCfg = java_getValueByKey(jvmProps,
				"jvm.arguments.ignoreUnrecognized");
		if (ignoreUnrecognizedFromCfg != NULL
				&& !util_strToBool(ignoreUnrecognizedFromCfg)) {
			ignoreUnrecognized = false;
		}
	}
	if (ignoreUnrecognized) {
		simpleLog_logL(SIMPLELOG_LEVEL_FINE,
				"JVM: ignoring unrecognized options");
		vm_args->ignoreUnrecognized = JNI_TRUE;
	} else {
		simpleLog_logL(SIMPLELOG_LEVEL_FINE,
				"JVM: NOT ignoring unrecognized options");
		vm_args->ignoreUnrecognized = JNI_FALSE;
	}

	// ### create the Java class-path option ###
	// autogenerate the class path
	static const size_t classPath_sizeMax = 8 * 1024;
	char* classPath = util_allocStr(classPath_sizeMax);
	// ..., autogenerate it ...
	if (!java_createClassPath(classPath, classPath_sizeMax)) {
		simpleLog_logL(SIMPLELOG_LEVEL_ERROR,
				"Failed creating Java class-path.");
		return false;
	}
	if (jvmProps != NULL) {
		// ..., and append the part from the jvm options properties file,
		// if it is specified there
		const char* clsPathFromCfg = java_getValueByKey(jvmProps,
				"jvm.option.java.class.path");
		if (clsPathFromCfg != NULL) {
			STRCATS(classPath, classPath_sizeMax, ENTRY_DELIM);
			STRCATS(classPath, classPath_sizeMax, clsPathFromCfg);
		}
	}
	// create the java.class.path option
	static const size_t classPathOpt_sizeMax = 8 * 1024;
	char* classPathOpt = util_allocStr(classPathOpt_sizeMax);
	STRCPYS(classPathOpt, classPathOpt_sizeMax, "-Djava.class.path=");
	STRCATS(classPathOpt, classPathOpt_sizeMax, classPath);
	FREE(classPath);

	// ### create the Java library-path option ###
	// autogenerate the java library path
	static const size_t libraryPath_sizeMax = 4 * 1024;
	char* libraryPath = util_allocStr(libraryPath_sizeMax);
	// ..., autogenerate it ...
	if (!java_createNativeLibsPath(libraryPath, libraryPath_sizeMax)) {
		simpleLog_logL(SIMPLELOG_LEVEL_ERROR,
				"Failed creating Java library-path.");
		return false;
	}
	if (jvmProps != NULL) {
		// ..., and append the part from the jvm options properties file,
		// if it is specified there
		const char* libPathFromCfg = java_getValueByKey(jvmProps,
				"jvm.option.java.library.path");
		if (libPathFromCfg != NULL) {
			STRCATS(libraryPath, libraryPath_sizeMax, ENTRY_DELIM);
			STRCATS(libraryPath, libraryPath_sizeMax, libPathFromCfg);
		}
	}
	// create the java.library.path option ...
	// autogenerate it, and append the part from the jvm options file,
	// if it is specified there
	static const size_t libraryPathOpt_sizeMax = 4 * 1024;
	char* libraryPathOpt = util_allocStr(libraryPathOpt_sizeMax);
	STRCPYS(libraryPathOpt, libraryPathOpt_sizeMax, "-Djava.library.path=");
	STRCATS(libraryPathOpt, libraryPathOpt_sizeMax, libraryPath);
	FREE(libraryPath);

	// ### create and set all JVM options ###
	static const size_t strOptions_sizeMax = 64;
	const char* strOptions[strOptions_sizeMax];
	size_t op = 0;

	strOptions[op++] = classPathOpt;
	strOptions[op++] = libraryPathOpt;

	static const char* const JCPVAL = "-Djava.class.path=";
	const size_t JCPVAL_size = strlen(JCPVAL);
	static const char* const JLPVAL = "-Djava.library.path=";
	const size_t JLPVAL_size = strlen(JCPVAL);
	if (jvmProps != NULL) {
		// ### add string options from the JVM config file with property name "jvm.option.x" ###
		int i;
		for (i=0; i < jvmProps->size; ++i) {
			if (strcmp(jvmProps->keys[i], "jvm.option.x") == 0 ||
					(useDebugOptions && (strcmp(jvmProps->keys[i], "jvm.option.debug.x") == 0))) {
				const char* const val = jvmProps->values[i];
				const size_t val_size = strlen(val);
				// ignore "-Djava.class.path=..."
				// and "-Djava.library.path=..." options
				if (strncmp(val, JCPVAL, minSize(val_size, JCPVAL_size)) != 0 &&
					strncmp(val, JLPVAL, minSize(val_size, JLPVAL_size)) != 0) {
					strOptions[op++] = val;
				}
			}
		}
	} else {
		// ### ... or set default ones, if the JVM config file was not found ###
		simpleLog_logL(SIMPLELOG_LEVEL_WARNING, "JVM: properties file ("JVM_PROPERTIES_FILE") not found; using default options.");

		strOptions[op++] = "-Xms4M";
		strOptions[op++] = "-Xmx64M";
		strOptions[op++] = "-Xss512K";
		strOptions[op++] = "-Xoss400K";

#if       defined DEBUG
		strOptions[op++] = "-Xcheck:jni";
		strOptions[op++] = "-verbose:jni";
		strOptions[op++] = "-XX:+UnlockDiagnosticVMOptions";
		strOptions[op++] = "-XX:+LogVMOutput";

		strOptions[op++] = "-Xdebug";
		strOptions[op++] = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=7777";
		// disable JIT (required for debugging under the classical VM)
		strOptions[op++] = "-Djava.compiler=NONE";
		// disable old JDB
		strOptions[op++] = "-Xnoagent";
#endif // defined DEBUG
	}

	const size_t options_size = op;

	vm_args->options = (struct JavaVMOption*) calloc(options_size, sizeof(struct JavaVMOption));

	// fill strOptions into the JVM options
	simpleLog_logL(SIMPLELOG_LEVEL_FINE, "JVM: options:", options_size);
	char* dd_rw = callback->DataDirs_allocatePath(interfaceId,
			"", true, true, true, false);
	size_t i;
	jint nOptions = 0;
	for (i = 0; i < options_size; ++i) {
		char* tmpOptionString = util_allocStrReplaceStr(strOptions[i],
				"${home-dir}", dd_rw);
		// do not add empty options
		if (tmpOptionString != NULL) {
			if (strlen(tmpOptionString) > 0) {
				vm_args->options[nOptions].optionString = tmpOptionString;
				vm_args->options[nOptions].extraInfo = NULL;
				simpleLog_logL(SIMPLELOG_LEVEL_FINE, "JVM option %ul: %s", nOptions, tmpOptionString);
				nOptions++;
			} else {
				free(tmpOptionString);
				tmpOptionString = NULL;
			}
		}
	}
	vm_args->nOptions = nOptions;

	FREE(dd_rw);
	FREE(classPathOpt);
	FREE(libraryPathOpt);
	simpleLog_logL(SIMPLELOG_LEVEL_FINE, "");

	return true;
}
예제 #8
0
void CVerifyCertDialog::ShowVerificationDialog(CCertificateNotification& notification, bool displayOnly /*=false*/)
{
	LoadTrustedCerts();

	m_pDlg = new wxDialogEx;
	if (displayOnly)
		m_pDlg->Load(0, _T("ID_DISPLAYCERT"));
	else {
		m_pDlg->Load(0, _T("ID_VERIFYCERT"));

		m_pDlg->WrapText(m_pDlg, XRCID("ID_DESC"), 400);

		if (COptions::Get()->GetOptionVal(OPTION_DEFAULT_KIOSKMODE) == 2)
			XRCCTRL(*m_pDlg, "ID_ALWAYS", wxCheckBox)->Hide();
	}

	m_certificates = notification.GetCertificates();
	if (m_certificates.size() == 1) {
		XRCCTRL(*m_pDlg, "ID_CHAIN_DESC", wxStaticText)->Hide();
		XRCCTRL(*m_pDlg, "ID_CHAIN", wxChoice)->Hide();
	}
	else {
		wxChoice* pChoice = XRCCTRL(*m_pDlg, "ID_CHAIN", wxChoice);
		for (unsigned int i = 0; i < m_certificates.size(); ++i) {
			pChoice->Append(wxString::Format(_T("%d"), i));
		}
		pChoice->SetSelection(0);

		pChoice->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(CVerifyCertDialog::OnCertificateChoice), 0, this);
	}

	m_pDlg->SetChildLabel(XRCID("ID_HOST"), wxString::Format(_T("%s:%d"), notification.GetHost(), notification.GetPort()));

	m_pSubjectSizer = XRCCTRL(*m_pDlg, "ID_SUBJECT_DUMMY", wxStaticText)->GetContainingSizer();
	m_pSubjectSizer->Clear(true);

	m_pIssuerSizer = XRCCTRL(*m_pDlg, "ID_ISSUER_DUMMY", wxStaticText)->GetContainingSizer();
	m_pIssuerSizer->Clear(true);

	wxSize minSize(0, 0);
	for (unsigned int i = 0; i < m_certificates.size(); ++i) {
		DisplayCert(m_pDlg, m_certificates[i]);
		m_pDlg->Layout();
		m_pDlg->GetSizer()->Fit(m_pDlg);
		minSize.IncTo(m_pDlg->GetSizer()->GetMinSize());
	}
	m_pDlg->GetSizer()->SetMinSize(minSize);

	bool warning = DisplayCert(m_pDlg, m_certificates[0]);

	m_pDlg->SetChildLabel(XRCID("ID_PROTOCOL"), notification.GetProtocol());
	m_pDlg->SetChildLabel(XRCID("ID_KEYEXCHANGE"), notification.GetKeyExchange());
	m_pDlg->SetChildLabel(XRCID("ID_CIPHER"), notification.GetSessionCipher());
	m_pDlg->SetChildLabel(XRCID("ID_MAC"), notification.GetSessionMac());

	if (warning) {
		XRCCTRL(*m_pDlg, "ID_IMAGE", wxStaticBitmap)->SetBitmap(wxArtProvider::GetBitmap(wxART_WARNING));
		if (!displayOnly)
			XRCCTRL(*m_pDlg, "ID_ALWAYS", wxCheckBox)->Enable(false);
	}

	m_pDlg->GetSizer()->Fit(m_pDlg);
	m_pDlg->GetSizer()->SetSizeHints(m_pDlg);

	int res = m_pDlg->ShowModal();

	if (!displayOnly) {
		if (res == wxID_OK) {
			wxASSERT(!IsTrusted(notification));

			notification.m_trusted = true;

			if (!warning && XRCCTRL(*m_pDlg, "ID_ALWAYS", wxCheckBox)->GetValue())
				SetPermanentlyTrusted(notification);
			else {
				t_certData cert;
				cert.host = notification.GetHost();
				cert.port = notification.GetPort();
				const unsigned char* data = m_certificates[0].GetRawData(cert.len);
				cert.data = new unsigned char[cert.len];
				memcpy(cert.data, data, cert.len);
				m_sessionTrustedCerts.push_back(cert);
			}
		}
		else
			notification.m_trusted = false;
	}

	delete m_pDlg;
	m_pDlg = 0;
}
예제 #9
0
void W32Table::setPosition(int x, int y, Size size) {
	std::vector<short> widths, heights, lefts, rights;
	calculateSizes(widths, heights);

	if ((widths.size() == 0) || (heights.size() == 0)) {
		return;
	}

	Size minSize(
		leftMargin() + rightMargin() + myHorizontalSpacing * (widths.size() - 1),
		topMargin() + bottomMargin()
	);
	for (std::vector<short>::const_iterator it = widths.begin(); it != widths.end(); ++it) {
		minSize.Width += *it;
	}
	int hCount = 0;
	for (std::vector<short>::const_iterator it = heights.begin(); it != heights.end(); ++it) {
		if (*it > 0) {
			minSize.Height += *it;
			++hCount;
		}
	}
	if (hCount == 0) {
		return;
	}
	minSize.Height += myVerticalSpacing * (hCount - 1);

	{
		short delta = size.Width - minSize.Width;
		int len = widths.size();
		lefts.reserve(len);
		rights.reserve(len);
		short currentX = x + leftMargin();
		for (int i = 0; i < len; ++i) {
			short d = delta / (len - i);
			widths[i] += d;
			delta -= d;
			lefts.push_back(currentX);
			currentX += widths[i];
			rights.push_back(currentX);
			currentX += myHorizontalSpacing;
		}
	}

	{
		short delta = size.Height - minSize.Height;
		int len = hCount;
		for (std::vector<short>::iterator it = heights.begin(); len > 0; ++it) {
			if (*it > 0) {
				short d = delta / len;
				*it += d;
				delta -= d;
				--len;
			}
		}
	}

	int ey = y + topMargin();
	for (std::vector<RowList>::const_iterator it = myRows.begin(); it != myRows.end(); ++it) {
		short h = heights[it - myRows.begin()];
		if (h > 0) {
			for (RowList::const_iterator jt = it->begin(); jt != it->end(); ++jt) {
				if (jt->Widget->isVisible()) {
					jt->Widget->setPosition(lefts[jt->XFrom], ey, Size(rights[jt->XTo] - lefts[jt->XFrom], h));
				}
			}
			ey += h + myVerticalSpacing;
		}
	}
}
예제 #10
0
/**
* Crea la vista preliminar borrando la previa.
*/
void VisualEditor::Create()
{
	if ( IsShown() )
	{
		Freeze(); // Prevent flickering
	}

	// Delete objects which had no parent
	DeleteAbstractObjects();

	// Clear selections, delete objects
	m_back->SetSelectedItem(NULL);
	m_back->SetSelectedSizer(NULL);
	m_back->SetSelectedObject(PObjectBase());
	ClearComponents( m_back->GetFrameContentPanel() );
	m_back->GetFrameContentPanel()->DestroyChildren();
	m_back->GetFrameContentPanel()->SetSizer( NULL ); // *!*

	// Clear all associations between ObjectBase and wxObjects
	m_wxobjects.clear();
	m_baseobjects.clear();

	m_form = AppData()->GetSelectedForm();
	if ( m_form )
	{
		m_back->Show(true);

		// --- [1] Configure the size of the form ---------------------------

		// Get size properties
		wxSize minSize( m_form->GetPropertyAsSize( wxT("minimum_size") ) );
		m_back->SetMinSize( minSize );

		wxSize maxSize( m_form->GetPropertyAsSize( wxT("maximum_size") ) );
		m_back->SetMaxSize( maxSize );

		wxSize size( m_form->GetPropertyAsSize( wxT("size") ) );

		// Determine necessary size for back panel
		wxSize backSize = size;
		if ( backSize.GetWidth() < minSize.GetWidth() && backSize.GetWidth() != wxDefaultCoord )
		{
			backSize.SetWidth( minSize.GetWidth() );
		}
		if ( backSize.GetHeight() < minSize.GetHeight() && backSize.GetHeight() != wxDefaultCoord )
		{
			backSize.SetHeight( minSize.GetHeight() );
		}
		if ( backSize.GetWidth() > maxSize.GetWidth() && maxSize.GetWidth() != wxDefaultCoord )
		{
			backSize.SetWidth( maxSize.GetWidth() );
		}
		if ( backSize.GetHeight() > maxSize.GetHeight() && maxSize.GetHeight() != wxDefaultCoord )
		{
			backSize.SetHeight( maxSize.GetHeight() );
		}

		// Modify size property to match
		if ( size != backSize )
		{
			PProperty psize = m_form->GetProperty( wxT("size") );
			if ( psize )
			{
				AppData()->ModifyProperty( psize, TypeConv::SizeToString( backSize ) );
			}
		}

		// --- [2] Set the color of the form -------------------------------
		PProperty background( m_form->GetProperty( wxT("bg") ) );
		if ( background && !background->GetValue().empty() )
		{
			m_back->GetFrameContentPanel()->SetBackgroundColour( TypeConv::StringToColour( background->GetValue() ) );
		}
		else
		{
			if ( m_form->GetClassName() == wxT("Frame") )
			{
				m_back->GetFrameContentPanel()->SetOwnBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_APPWORKSPACE ) );
			}
			else
			{
				m_back->GetFrameContentPanel()->SetOwnBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
			}
		}


		// --- [3] Title bar Setup
		if (  m_form->GetClassName() == wxT("Frame") || m_form->GetClassName() == wxT("Dialog") )
		{
			m_back->SetTitle( m_form->GetPropertyAsString( wxT("title") ) );
			long style = m_form->GetPropertyAsInteger( wxT("style") );
			m_back->SetTitleStyle( style );
			m_back->ShowTitleBar( (style & wxCAPTION) != 0 );
		}
		else
		  m_back->ShowTitleBar(false);

		// --- [4] Create the components of the form -------------------------

		// Used to save frame objects for later display
		PObjectBase menubar;
		wxWindow* statusbar = NULL;
		wxWindow* toolbar = NULL;

		for ( unsigned int i = 0; i < m_form->GetChildCount(); i++ )
		{
			PObjectBase child = m_form->GetChild( i );

			if (child->GetObjectTypeName() == wxT("menubar") )
			{
				// Create the menubar later
				menubar = child;
			}
			else
			{
				// Recursively generate the ObjectTree
				try
				{
				  // we have to put the content frame panel as parentObject in order
				  // to SetSizeHints be called.
					Generate( child, m_back->GetFrameContentPanel(), m_back->GetFrameContentPanel() );
				}
				catch ( wxFBException& ex )
				{
					wxLogError ( ex.what() );
				}
			}

			// Attach the status bar (if any) to the frame
			if ( child->GetClassName() == wxT("wxStatusBar") )
			{
				ObjectBaseMap::iterator it = m_baseobjects.find( child.get() );
				statusbar = wxDynamicCast( it->second, wxStatusBar );
			}

			// Attach the toolbar (if any) to the frame
			if (child->GetClassName() == wxT("wxToolBar") )
			{
				ObjectBaseMap::iterator it = m_baseobjects.find( child.get() );
				toolbar = wxDynamicCast( it->second, wxToolBar );
			}
		}

		if ( menubar || statusbar || toolbar )
		{
			m_back->SetFrameWidgets( menubar, toolbar, statusbar );
		}

		m_back->Layout();

		if ( backSize.GetHeight() == wxDefaultCoord || backSize.GetWidth() == wxDefaultCoord )
		{
		    m_back->GetSizer()->Fit( m_back );
			m_back->SetSize( m_back->GetBestSize() );
		}

		// Set size after fitting so if only one dimesion is -1, it still fits that dimension
		m_back->SetSize( backSize );

		PProperty enabled( m_form->GetProperty( wxT("enabled") ) );
		if ( enabled )
		{
			m_back->Enable( TypeConv::StringToInt( enabled->GetValue() ) != 0 );
		}

		PProperty hidden( m_form->GetProperty( wxT("hidden") ) );
		if ( hidden )
		{
			m_back->Show( TypeConv::StringToInt( hidden->GetValue() ) == 0 );
		}
	}
	else
	{
		// There is no form to display
		m_back->Show(false);
	}

	if ( IsShown() )
	{
		Thaw();
	}

	UpdateVirtualSize();
}
예제 #11
0
bool AnchorPointSelector::detectEyeCorners(cv::Mat image, double resolution, cv::Point2f points[]) {
	cv::Rect largestObject(0, 0, 0, 0);
	double scaleFactor = 1.1;
	int minNeighbors = 10;
	int flags = CV_HAAR_DO_CANNY_PRUNING;
	cv::Size minSize(64, 16);

	if (resolution != 480) {
		double factor = resolution/480;
		minSize.width = round(factor*minSize.width);
		minSize.height = round(factor*minSize.height);
	}

	// Detect objects
	if(!detectLargestObject(eyeCascade, image, largestObject, scaleFactor, minNeighbors, CV_HAAR_DO_CANNY_PRUNING, minSize)) {
		std::cout << "Detect largest object (for eyes) failed!!" << std::endl;
		return false;
	}

	//std::cout << "Resolution: " << resolution << ", both eye reg.:" << largestObject.width << ", " << largestObject.height << std::endl;

	//cv::Rectangle(image, cv::Point2f(largestObject.x, largestObject.y), cv::Point2f(largestObject.x + largestObject.width, largestObject.y + largestObject.height), CV_RGB(0, 255, 0), 2, 8, 0);

	int cornerCount = 100;
	cv::Mat eyeRegionImage(cv::Size(largestObject.width, largestObject.height), CV_8UC3);
	cv::Mat eyeRegionImageGray(cv::Size(largestObject.width, largestObject.height), CV_8UC1);

	image(largestObject).copyTo(eyeRegionImage);
	cv::cvtColor(eyeRegionImage, eyeRegionImageGray, CV_RGB2GRAY);

	Utils::normalizeGrayScaleImage(&eyeRegionImageGray, 127, 80);

	std::vector<cv::Point2f> *corners = detectCornersInGrayscale(eyeRegionImageGray, cornerCount);

	int leftEyeCornersXSum = 0;
	int leftEyeCornersYSum = 0;
	int leftEyeCornersCount = 0;

	int rightEyeCornersXSum = 0;
	int rightEyeCornersYSum = 0;
	int rightEyeCornersCount = 0;

	/// Drawing a circle around corners
	for (int j = 0; j < corners->size(); j++ ) {
		if ((*corners)[j].x < largestObject.width * 0.4) {
			leftEyeCornersXSum += (*corners)[j].x;
			leftEyeCornersYSum += (*corners)[j].y;
			leftEyeCornersCount++;
			//cv::circle(eyeRegionImage, cv::Point2f(corners[j].x, corners[j].y), 3, CV_RGB(255,0,0), -1, 8,0);
		} else if ((*corners)[j].x > largestObject.width * 0.6) {
			rightEyeCornersXSum += (*corners)[j].x;
			rightEyeCornersYSum += (*corners)[j].y;
			rightEyeCornersCount++;
			//cv::circle(eyeRegionImage, cv::Point2f(corners[j].x, corners[j].y), 3, CV_RGB(255,0,0), -1, 8,0);
		}
	}

	double leftEyeCenterX = largestObject.x + (leftEyeCornersXSum / (double)leftEyeCornersCount);
	double leftEyeCenterY = largestObject.y + (leftEyeCornersYSum / (double)leftEyeCornersCount);

	double rightEyeCenterX = largestObject.x + (rightEyeCornersXSum / (double)rightEyeCornersCount);
	double rightEyeCenterY = largestObject.y + (rightEyeCornersYSum / (double)rightEyeCornersCount);

	double xDiff = rightEyeCenterX - leftEyeCenterX;
	double yDiff = rightEyeCenterY - leftEyeCenterY;

	double eyeSeparation = 0.29;
	points[0] = cv::Point2f(leftEyeCenterX - eyeSeparation * xDiff, leftEyeCenterY - eyeSeparation * yDiff);
	points[1] = cv::Point2f(rightEyeCenterX + eyeSeparation * xDiff, rightEyeCenterY + eyeSeparation * yDiff);

	/// Drawing a circle around corners
	//for (int i = 0; i < cornerCount; i++) {
	//	cv::circle(eyeRegionImage, cv::Point2f(corners[i].x, corners[i].y), 3, CV_RGB(255,0,0), -1, 8, 0);
	//}

	//cv::circle(image, cv::Point2f(points[0].x, points[0].y), 3, CV_RGB(0,255,0), -1, 8, 0);
	//cv::circle(image, cv::Point2f(points[1].x, points[1].y), 3, CV_RGB(0,255,0), -1, 8, 0);
	return true;
}
예제 #12
0
bool wxRibbonToolBar::Realize()
{
    if(m_art == NULL)
        return false;

    // Calculate the size of each group and the position/size of each tool
    wxMemoryDC temp_dc;
    size_t group_count = m_groups.GetCount();
    size_t g, t;
    for(g = 0; g < group_count; ++g)
    {
        wxRibbonToolBarToolBase* prev = NULL;
        wxRibbonToolBarToolGroup* group = m_groups.Item(g);
        size_t tool_count = group->tools.GetCount();
        int tallest = 0;
        for(t = 0; t < tool_count; ++t)
        {
            wxRibbonToolBarToolBase* tool = group->tools.Item(t);
            tool->size = m_art->GetToolSize(temp_dc, this,
                tool->bitmap.GetSize(), tool->kind, t == 0,
                t == (tool_count - 1), &tool->dropdown);
            if(t == 0)
                tool->state |= wxRIBBON_TOOLBAR_TOOL_FIRST;
            if(t == tool_count - 1)
                tool->state |= wxRIBBON_TOOLBAR_TOOL_LAST;
            if(tool->size.GetHeight() > tallest)
                tallest = tool->size.GetHeight();
            if(prev)
            {
                tool->position = prev->position;
                tool->position.x += prev->size.x;
            }
            else
            {
                tool->position = wxPoint(0, 0);
            }
            prev = tool;
        }
        if(tool_count == 0)
            group->size = wxSize(0, 0);
        else
        {
            group->size = wxSize(prev->position.x + prev->size.x, tallest);
            for(t = 0; t < tool_count; ++t)
                group->tools.Item(t)->size.SetHeight(tallest);
        }
    }

    // Calculate the minimum size for each possible number of rows
    int nrows, r;
    int sep = m_art->GetMetric(wxRIBBON_ART_TOOL_GROUP_SEPARATION_SIZE);
    int smallest_area = INT_MAX;
    wxSize* row_sizes = new wxSize[m_nrows_max];
    wxOrientation major_axis = m_art->GetFlags() & wxRIBBON_BAR_FLOW_VERTICAL ?
        wxVERTICAL : wxHORIZONTAL;

    SetMinSize(wxSize(0, 0));
    wxSize minSize(INT_MAX, INT_MAX);

    // See if we're sizing flexibly (i.e. wrapping), and set min size differently
    bool sizingFlexibly = false;
    wxRibbonPanel* panel = wxDynamicCast(GetParent(), wxRibbonPanel);
    if (panel && (panel->GetFlags() & wxRIBBON_PANEL_FLEXIBLE))
        sizingFlexibly = true;

    // Without this, there will be redundant horizontal space because SetMinSize will
    // use the smallest possible height (and therefore largest width).
    if (sizingFlexibly)
        major_axis = wxHORIZONTAL;

    for(nrows = m_nrows_min; nrows <= m_nrows_max; ++nrows)
    {
        for(r = 0; r < nrows; ++r)
            row_sizes[r] = wxSize(0, 0);
        for(g = 0; g < group_count; ++g)
        {
            wxRibbonToolBarToolGroup* group = m_groups.Item(g);
            int shortest_row = 0;
            for(r = 1; r < nrows; ++r)
            {
                if(row_sizes[r].GetWidth() < row_sizes[shortest_row].GetWidth())
                    shortest_row = r;
            }
            row_sizes[shortest_row].x += group->size.x + sep;
            if(group->size.y > row_sizes[shortest_row].y)
                row_sizes[shortest_row].y = group->size.y;
        }
        wxSize size(0, 0);
        for(r = 0; r < nrows; ++r)
        {
            if(row_sizes[r].GetWidth() != 0)
                row_sizes[r].DecBy(sep, 0);
            if(row_sizes[r].GetWidth() > size.GetWidth())
                size.SetWidth(row_sizes[r].GetWidth());
            size.IncBy(0, row_sizes[r].y);
        }
        m_sizes[nrows - m_nrows_min] = size;

        if(GetSizeInOrientation(size, major_axis) < smallest_area)
        {
            smallest_area = GetSizeInOrientation(size, major_axis);
            SetMinSize(size);
        }

        if (sizingFlexibly)
        {
            if (size.x < minSize.x)
                minSize.x = size.x;
            if (size.y < minSize.y)
                minSize.y = size.y;
        }
    }

    if (sizingFlexibly)
    {
        // Give it the min size in either direction regardless of row,
        // so that we're able to vary the size of the panel according to
        // the space the toolbar takes up.
        SetMinSize(minSize);
    }
    delete[] row_sizes;

    // Position the groups
    wxSizeEvent dummy_event(GetSize());
    OnSize(dummy_event);

    return true;
}
예제 #13
0
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QGraphicsScene scene;
    scene.setSceneRect(0, 0, 800, 480);

    QSizeF minSize(30, 100);
    QSizeF prefSize(210, 100);
    QSizeF maxSize(300, 100);

    QGraphicsProxyWidget *a = createItem(minSize, prefSize, maxSize, "A");
    QGraphicsProxyWidget *b = createItem(minSize, prefSize, maxSize, "B");
    QGraphicsProxyWidget *c = createItem(minSize, prefSize, maxSize, "C");
    QGraphicsProxyWidget *d = createItem(minSize, prefSize, maxSize, "D");
    QGraphicsProxyWidget *e = createItem(minSize, prefSize, maxSize, "E");
    QGraphicsProxyWidget *f = createItem(QSizeF(30, 50), QSizeF(150, 50), maxSize, "F (overflow)");
    QGraphicsProxyWidget *g = createItem(QSizeF(30, 50), QSizeF(30, 100), maxSize, "G (overflow)");

    QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
    l->setSpacing(0);

    QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window);
    w->setPos(20, 20);
    w->setLayout(l);

    // vertical
    QGraphicsAnchor *anchor = l->addAnchor(a, Qt::AnchorTop, l, Qt::AnchorTop);
    anchor = l->addAnchor(b, Qt::AnchorTop, l, Qt::AnchorTop);

    anchor = l->addAnchor(c, Qt::AnchorTop, a, Qt::AnchorBottom);
    anchor = l->addAnchor(c, Qt::AnchorTop, b, Qt::AnchorBottom);
    anchor = l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop);
    anchor = l->addAnchor(c, Qt::AnchorBottom, e, Qt::AnchorTop);

    anchor = l->addAnchor(d, Qt::AnchorBottom, l, Qt::AnchorBottom);
    anchor = l->addAnchor(e, Qt::AnchorBottom, l, Qt::AnchorBottom);

    anchor = l->addAnchor(c, Qt::AnchorTop, f, Qt::AnchorTop);
    anchor = l->addAnchor(c, Qt::AnchorVerticalCenter, f, Qt::AnchorBottom);
    anchor = l->addAnchor(f, Qt::AnchorBottom, g, Qt::AnchorTop);
    anchor = l->addAnchor(c, Qt::AnchorBottom, g, Qt::AnchorBottom);

    // horizontal
    anchor = l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
    anchor = l->addAnchor(l, Qt::AnchorLeft, d, Qt::AnchorLeft);
    anchor = l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);

    anchor = l->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft);
    anchor = l->addAnchor(c, Qt::AnchorRight, e, Qt::AnchorLeft);

    anchor = l->addAnchor(b, Qt::AnchorRight, l, Qt::AnchorRight);
    anchor = l->addAnchor(e, Qt::AnchorRight, l, Qt::AnchorRight);
    anchor = l->addAnchor(d, Qt::AnchorRight, e, Qt::AnchorLeft);

    anchor = l->addAnchor(l, Qt::AnchorLeft, f, Qt::AnchorLeft);
    anchor = l->addAnchor(l, Qt::AnchorLeft, g, Qt::AnchorLeft);
    anchor = l->addAnchor(f, Qt::AnchorRight, g, Qt::AnchorRight);


    scene.addItem(w);
    scene.setBackgroundBrush(Qt::darkGreen);
    QGraphicsView *view = new QGraphicsView(&scene);
    view->show();

    return app.exec();
}
예제 #14
0
파일: multicell.cpp 프로젝트: nealey/vera
//---------------------------------------------------------------------------
void wxMultiCellSizer::RecalcSizes()
{
    if (m_children.GetCount() == 0)
        return;
    wxSize size = GetSize();
    wxPoint pos = GetPosition();

    GetMinimums();

    // We need to take the unused space and equally give it out to all the rows/columns
    // which are stretchable

    int unUsedWidth = size.GetWidth() - Sum(m_maxWidth, m_cell_count.GetWidth());
    int unUsedHeight = size.GetHeight() - Sum(m_maxHeight, m_cell_count.GetHeight());
    int totalWidthWeight = 0;
    int totalHeightWeight = 0;
    int x;

    for (x = 0; x < wxMax(m_cell_count.GetHeight(), m_cell_count.GetWidth()); x++)
    {
        if (m_rowStretch[x])
        {
            totalHeightWeight += m_weights[x]->GetHeight();
        }
        if (x < m_cell_count.GetWidth() && m_colStretch[x])
        {
            totalWidthWeight += m_weights[x]->GetWidth();
        }
    }
    for (x = 0; x < wxMax(m_cell_count.GetHeight(), m_cell_count.GetWidth()); x++)
    {
        if (x < m_cell_count.GetHeight() && m_rowStretch[x])
        {
            m_maxHeight[x] += unUsedHeight * m_weights[x]->GetHeight() / totalHeightWeight;
        }
        if (x < m_cell_count.GetWidth() && m_colStretch[x])
        {
            m_maxWidth[x] += unUsedWidth * m_weights[x]->GetWidth() / totalWidthWeight;
        }
    }
    // We now have everything we need to figure each cell position and size
    // The arrays m_maxHeight and m_maxWidth now contain the final widths and height of
    // each row and column.

    double cell_width = (double)size.GetWidth() / (double)m_cell_count.GetWidth();
    double cell_height = (double)size.GetHeight() / (double)m_cell_count.GetHeight();
    wxPoint c_point;
    wxSize  c_size;

    wxSizerItemList::compatibility_iterator current = m_children.GetFirst();
    while (current)
    {
        wxSizerItem *item = current->GetData();

        wxMultiCellItemHandle *rect;
        if (item != NULL &&
            (rect = (wxMultiCellItemHandle *)item->GetUserData()) != NULL)
        {
            c_point.x = pos.x + (int)(rect->GetColumn() * cell_width);
            c_point.y = pos.y + (int)(rect->GetRow() * cell_height);

            c_point.x = pos.x + Sum(m_maxWidth, rect->GetColumn());
            c_point.y = pos.y + Sum(m_maxHeight, rect->GetRow());


            c_size = rect->GetLocalSize();
            wxSize minSize( item->CalcMin() );
            if (c_size.GetHeight() != wxDefaultCoord ||
                c_size.GetWidth() != wxDefaultCoord)
            {
                minSize.SetHeight(wxMax(minSize.GetHeight(), c_size.GetHeight()));
                minSize.SetWidth(wxMax(minSize.GetWidth(), c_size.GetWidth()));
            }
            if (rect->GetStyle() & wxHORIZONTAL_RESIZABLE ||
                rect->GetWidth() > 1
                || m_minSizes[rect->GetColumn()]->GetWidth() < 0)
            {
                int w = 0;
                for (int x = 0; x < rect->GetWidth(); x++)
                {
                    w += m_maxWidth[rect->GetColumn() + x];
                }
                c_size.SetWidth(w);
            }
            else
            {
                c_size.SetWidth(minSize.GetWidth() );
            }
            if (rect->GetStyle() & wxVERTICAL_RESIZABLE ||
                rect->GetHeight() > 1 ||
                m_minSizes[rect->GetRow()]->GetHeight() < 0)
            {
                int h = 0;
                for (int x = 0; x < rect->GetHeight(); x++)
                {
                    h += m_maxHeight[rect->GetRow() + x];
                }
                c_size.SetHeight(h);
            }
            else
            {
                c_size.SetHeight(minSize.GetHeight());
            }
            int extraHeight = (m_maxHeight[rect->GetRow()] - c_size.GetHeight());
            int extraWidth = (m_maxWidth[rect->GetColumn()] - c_size.GetWidth());

            if (rect->GetWidth() == 1 && rect->GetAlignment() & wxALIGN_CENTER_HORIZONTAL)
            {
                c_point.x += extraWidth / 2;
            }
            if (rect->GetWidth() == 1 && rect->GetAlignment() & wxALIGN_RIGHT)
            {
                c_point.x += extraWidth;
            }
            if (rect->GetHeight() == 1 && rect->GetAlignment() & wxALIGN_CENTER_VERTICAL)
            {
                c_point.y += extraHeight / 2;
            }
            if (rect->GetHeight() == 1 && rect->GetAlignment() & wxALIGN_BOTTOM)
            {
                c_point.y += extraHeight;
            }
            item->SetDimension(c_point, c_size);
        }
        current = current->GetNext();
    }
}
예제 #15
0
PrimitiveSurface * Material::getSurface( DisplayDevice * pDisplay, Image::Link pImage, int nFrame, bool bMipMap )
{
	// generate a unique key from the components
	WidgetKey nKey = pImage.key() + nFrame;
	if ( bMipMap )
		nKey += MIPMAP_KEY;

	AutoLock lock( &sm_SurfaceHashLock );
	SurfaceHash::Iterator it = sm_SurfaceHash.find( nKey );
	if ( it.valid() )
		return *it;
	lock.release();

	// surface not found, create and cache the surface
	PrimitiveSurface::Ref pSurface;
	if ( pImage.valid() && pImage->frameCount() > 0 )
	{
		// find a format for our surface first, findBestFormat() will always try to use the images current format
		// if supported by the hardware.
		ColorFormat::Format eFormat = findBestFormat( pDisplay, pImage, true );
		if ( eFormat == ColorFormat::INVALID )
		{
			TRACE( "ERROR: Failed to find a suitable surface format for texture!" );
			return NULL;
		}

		SizeInt imageSize( pImage->size() );
		SizeInt maxSize( pDisplay->textureMaxSize() );
		SizeInt minSize( pDisplay->textureMinSize() );

		// use the smaller max size
		maxSize.width = Min( sm_MaxTextureSize.width, maxSize.width );
		maxSize.height = Min( sm_MaxTextureSize.height, maxSize.height );

		// validate the texture dimensions
		SizeInt validSize( Max( Min( imageSize.width, maxSize.width ), minSize.width), 
			Max( Min( imageSize.height, maxSize.height ), minSize.height) );
		if ( pDisplay->textureP2() && !pImage->isP2() )
			validSize = SizeInt( 1 << GetLastBit( validSize.width ), 1 << GetLastBit( validSize.height) );
		if ( pDisplay->textureSquare() && validSize.width != validSize.height )
			validSize = SizeInt( Max( validSize.width, validSize.height ), Max( validSize.width, validSize.height) );

		if ( validSize != imageSize || eFormat != pImage->format() )
		{
			// image is the wrong size or format, make a copy so we don't modify the original..
			pImage = new Image( *pImage );

			if ( pImage->size() != validSize )
			{
				// image has to be resized - switch the format to an uncompressed format, DXT compression is too slow
				// to do on the fly..
				eFormat = findBestFormat( pDisplay, pImage, false );
				if ( eFormat != pImage->format() )
				{
					TRACE( CharString().format( "Image: Reformat %s -> %s", ColorFormat::formatText( pImage->format() ),
						ColorFormat::formatText( eFormat ) ) );
					if (! pImage->setFormat( eFormat ) )
						return NULL;
				}

				TRACE( CharString().format( "Image: Resize %dx%d -> %dx%d", imageSize.width, imageSize.height, 
					validSize.width, validSize.height ) );

				pImage->resample( validSize );
				if ( bMipMap && pImage->mipMap() != NULL )
					pImage->createMipMaps();
			}
			else if ( pImage->format() != eFormat )
			{
				TRACE( CharString().format( "Image: Reformat %s -> %s", ColorFormat::formatText( pImage->format() ),
					ColorFormat::formatText( eFormat ) ) );
				if (! pImage->setFormat( eFormat ) )
					return NULL;		// failed to convert to the desired format..
			}
		}

		if ( bMipMap && pImage->mipMap() == NULL )
			bMipMap = false;		// no mipmap levels in image, disable mipmaps

		// create the primitives, note having neither a diffuse or alpha texture is also a valid material
		pDisplay->create( pSurface );

		// create the surface
		SizeInt surfaceSize( pImage->size() );
		pSurface->initialize( 
			surfaceSize.width,
			surfaceSize.height, 
			eFormat,
			bMipMap );

		nFrame = nFrame % pImage->frameCount();

		Image * pMipMap = pImage;
		for(int i=0;i<pSurface->levels();++i)
		{
			if (! pMipMap )
			{
				TRACE( CharString().format("ERROR: Mipmap level %d is missing!", i ) );
				break;
			}

			void * pPixels = pSurface->lock( i );
			if (! pPixels )
			{
				TRACE( "ERROR: Failed to lock surface!" );
				break;
			}

			memcpy( pPixels, pMipMap->frame( nFrame ), pMipMap->frameSize( nFrame ) );
			pSurface->unlock();

			// next mipmap level of our image..
			pMipMap = pMipMap->mipMap();
		}
	}

	// cache the surface now
	lock.set( &sm_SurfaceHashLock );
	sm_SurfaceHash[ nKey ] = pSurface;
	return pSurface;
}
예제 #16
0
NS_IMETHODIMP
nsPopupSetFrame::DoLayout(nsBoxLayoutState& aState)
{
  // lay us out
  nsresult rv = nsBoxFrame::DoLayout(aState);

  // lay out all of our currently open popups.
  nsPopupFrameList* currEntry = mPopupList;
  while (currEntry) {
    nsIFrame* popupChild = currEntry->mPopupFrame;
    if (popupChild) {
      NS_ASSERTION(popupChild->IsBoxFrame(), "popupChild is not box!!");

      // then get its preferred size
      nsSize prefSize(0,0);
      nsSize minSize(0,0);
      nsSize maxSize(0,0);

      popupChild->GetPrefSize(aState, prefSize);
      popupChild->GetMinSize(aState, minSize);
      popupChild->GetMaxSize(aState, maxSize);

      BoundsCheck(minSize, prefSize, maxSize);

      // if the pref size changed then set bounds to be the pref size
      // and sync the view. Also set new pref size.
     // if (currEntry->mLastPref != prefSize) {
        popupChild->SetBounds(aState, nsRect(0,0,prefSize.width, prefSize.height));
        RepositionPopup(currEntry, aState);
        currEntry->mLastPref = prefSize;
     // }

      // is the new size too small? Make sure we handle scrollbars correctly
      nsIBox* child;
      popupChild->GetChildBox(&child);

      nsRect bounds(popupChild->GetRect());

      nsCOMPtr<nsIScrollableFrame> scrollframe = do_QueryInterface(child);
      if (scrollframe &&
          scrollframe->GetScrollbarStyles().mVertical == NS_STYLE_OVERFLOW_AUTO) {
        // if our pref height
        if (bounds.height < prefSize.height) {
          // layout the child
          popupChild->Layout(aState);

          nsMargin scrollbars = scrollframe->GetActualScrollbarSizes();
          if (bounds.width < prefSize.width + scrollbars.left + scrollbars.right)
          {
            bounds.width += scrollbars.left + scrollbars.right;
            //printf("Width=%d\n",width);
            popupChild->SetBounds(aState, bounds);
          }
        }
      }
    
      // layout the child
      popupChild->Layout(aState);

      // only size popup if open
      if (currEntry->mCreateHandlerSucceeded) {
        nsIView* view = popupChild->GetView();
        nsIViewManager* viewManager = view->GetViewManager();
        nsRect r(0, 0, bounds.width, bounds.height);
        viewManager->ResizeView(view, r);
        viewManager->SetViewVisibility(view, nsViewVisibility_kShow);
      }
    }

    currEntry = currEntry->mNextPopup;
  }

  SyncLayout(aState);

  return rv;
}
예제 #17
0
void SplitPanel::updateLayout(void)
{
    Pnt2f TopLeft, BottomRight;
    getInsideBorderBounds(TopLeft, BottomRight);
    Vec2f BorderSize(BottomRight - TopLeft);

    UInt32 AxisIndex(0);
    if(getOrientation() != SplitPanel::HORIZONTAL_ORIENTATION ) AxisIndex = 1;

    Vec2f minSize(0,0);
    Vec2f maxSize(0,0);
    Vec2f divSize(0,0);
    Pnt2f minPos(0,0);
    Pnt2f maxPos(0,0);
    Pnt2f divPos(0,0);

    if (getDividerPosition() < 0.0)
        setDividerPosition(0.5);
    if (getMinDividerPosition() < 0.0)
        setMinDividerPosition(0.0);
    if (getMaxDividerPosition() < 0.0)
        setMaxDividerPosition(1.0);

    UInt32 dividerPosition(getDividerPosition());
    if (getDividerPosition() <= 1.0)
        dividerPosition = BorderSize[AxisIndex] * getDividerPosition();

    // check the divider's min and max
    if (getMinDividerPosition() <= 1.0)
    {
        if (dividerPosition < getMinDividerPosition() * BorderSize[AxisIndex])
            dividerPosition = getMinDividerPosition() * BorderSize[AxisIndex];
    }
    else
    {
        if (dividerPosition < getMinDividerPosition())
            dividerPosition = getMinDividerPosition();
    }
    if (getMaxDividerPosition() <= 1.0)
    {
        if (dividerPosition > getMaxDividerPosition() * BorderSize[AxisIndex])
            dividerPosition = getMaxDividerPosition() * BorderSize[AxisIndex];
    }
    else
    {
        if (dividerPosition > getMaxDividerPosition())
            dividerPosition = getMaxDividerPosition();
    }

    // set the minimum component's size
    minSize[AxisIndex] = dividerPosition - getDividerSize()/2;

    // check its min and max
    if (getMinComponent() != NULL)
    {
        if (minSize[AxisIndex] < getMinComponent()->getMinSize()[AxisIndex])
        {
            dividerPosition -= getMinComponent()->getMinSize()[AxisIndex] - minSize[AxisIndex];
            minSize[AxisIndex] = getMinComponent()->getMinSize()[AxisIndex];
        }
        if (minSize[AxisIndex] > getMinComponent()->getMaxSize()[AxisIndex])
        {
            dividerPosition += minSize[AxisIndex] - getMinComponent()->getMaxSize()[AxisIndex];
            minSize[AxisIndex] = getMinComponent()->getMaxSize()[AxisIndex];
        }
    }

    // set the maximum component's size
    maxSize[AxisIndex] = BorderSize[AxisIndex] - minSize[AxisIndex] - getDividerSize();

    // check its min and max
    if (getMaxComponent() != NULL)
    {
        if (maxSize[AxisIndex] < getMaxComponent()->getMinSize()[AxisIndex])
        {
            dividerPosition -= getMaxComponent()->getMinSize()[AxisIndex] - maxSize[AxisIndex];
            minSize[AxisIndex] -= getMaxComponent()->getMinSize()[AxisIndex] - maxSize[AxisIndex];
            maxSize[AxisIndex] = getMaxComponent()->getMinSize()[AxisIndex];
        }
        if (maxSize[AxisIndex] > getMaxComponent()->getMaxSize()[AxisIndex])
        {
            dividerPosition += maxSize[AxisIndex] - getMaxComponent()->getMaxSize()[AxisIndex];
            minSize[AxisIndex] += maxSize[AxisIndex] - getMaxComponent()->getMaxSize()[AxisIndex];
            maxSize[AxisIndex] = getMaxComponent()->getMaxSize()[AxisIndex];
        }
    }

    // set the minor axis' size and max's position
    minSize[(AxisIndex+1)%2] = maxSize[(AxisIndex+1)%2] = BorderSize[(AxisIndex+1)%2];
    maxPos[AxisIndex] = minSize[AxisIndex] + getDividerSize();

    // set the divider's size and position
    divSize[AxisIndex] = getDividerSize();
    divSize[(AxisIndex+1)%2] = BorderSize[(AxisIndex+1)%2];
    divPos[AxisIndex] = dividerPosition - getDividerSize()/2;

    // set the components to the right size and positions
    if (getMinComponent() != NULL)
    {
        if(getMinComponent()->getSize() != minSize)
        {
            getMinComponent()->setSize(minSize);
        }
        if(getMinComponent()->getPosition() != minPos)
        {
            getMinComponent()->setPosition(minPos);
        }
    }
    if (getMaxComponent() != NULL)
    {
        if(getMaxComponent()->getSize() != maxSize)
        {
            getMaxComponent()->setSize(maxSize);
        }
        if(getMaxComponent()->getPosition() != maxPos)
        {
            getMaxComponent()->setPosition(maxPos);
        }
    }
    if (getDividerDrawObject() != NULL)
    {
        if(getDividerDrawObject()->getSize() != divSize)
        {
            getDividerDrawObject()->setSize(divSize);
        }
        if(getDividerDrawObject()->getPosition() != divPos)
        {
            getDividerDrawObject()->setPosition(divPos);
        }
    }
}
예제 #18
0
void makeHavokObject(int ID)
{
	std::vector<CMeshDesc> vecMeshDescs;
	g_pFactoryMediator->getRenderingPropertiesByID(ID, vecMeshDescs);

	CPhysicalProp physicalProp;
	g_pFactoryMediator->getPhysicalPropertiesByID(ID, physicalProp);

	// Is the object a ball?
	if (vecMeshDescs[0].ObjectType == "Ball" || vecMeshDescs[0].ObjectType == "Star")
	{	
		float radius = vecMeshDescs[0].scale.x * 0.5f;
		float mass = radius * 0.5f;
		CVector3f position(physicalProp.position);
		CVector4f Qrotation(physicalProp.orientation.x, physicalProp.orientation.y,
			physicalProp.orientation.z, 0.0f);
		std::wstringstream ss;
		ss << ID;
		if (vecMeshDescs[0].ObjectType == "Star")
			::g_pPhysicsManager->CreateRigidBody(ss.str(), radius, mass, position, Qrotation, true, true);// Size == max (in this example)
		else
			::g_pPhysicsManager->CreateRigidBody(ss.str(), radius, mass, position, Qrotation, true, false);// Size == max (in this example)
	}

	else if (vecMeshDescs[0].ObjectType == "Box")
	{	
		CVector3f boxSize(vecMeshDescs[0].scale);
		CVector3f position(physicalProp.position);
		CVector4f Qrotation(physicalProp.orientation.x, physicalProp.orientation.y,
			physicalProp.orientation.z, 0.0f);
		float mass = 5.f;
		float friction = 0.5f;
		std::wstringstream ss;
		ss << ID;
		::g_pPhysicsManager->CreateRigidBody(ss.str(), boxSize, mass, friction, position, Qrotation, true);
	}

	else if (vecMeshDescs[0].ObjectType == "Vehicle")
	{	
		CPlyInfo modelInfo;
		g_pModelLoader->GetRenderingInfoByModelFileName(vecMeshDescs[0].modelName, modelInfo);
		float truckWidth = modelInfo.maxExtentX.x - modelInfo.minExtentX.x;
		float truckHeight = modelInfo.maxExtentY.y - modelInfo.minExtentY.y; 
		float truckLength = modelInfo.maxExtentZ.z - modelInfo.minExtentZ.z;

		truckWidth *= vecMeshDescs[0].scale.x;
		truckHeight *= vecMeshDescs[0].scale.y;
		truckLength *= vecMeshDescs[0].scale.z;

		float mass = 5.f;
		CVector3f boxSize(truckWidth, truckHeight, truckLength);
		CVector3f position(physicalProp.position);
		CVector4f Qrotation(physicalProp.orientation.x, physicalProp.orientation.y,
			physicalProp.orientation.z, 0.0f);
		std::wstringstream ss;
		ss << ID;
		bool isPlayer;
		if (ID == ::g_Player_ID)
			isPlayer = true;
		else isPlayer = false;
		::g_pPhysicsManager->BuildVehicle(ss.str(), boxSize, mass, position, Qrotation, true, isPlayer);
	}

	else if (vecMeshDescs[0].ObjectType == "GroundFloor" || vecMeshDescs[0].ObjectType == "IceFloor")
	{	
		CVector3f boxSize(vecMeshDescs[0].scale.x, 1.0f, vecMeshDescs[0].scale.x);
		CVector3f position(physicalProp.position.x, physicalProp.position.y, physicalProp.position.z);
		CVector4f Qrotation(physicalProp.orientation.x, physicalProp.orientation.y,
			physicalProp.orientation.z, 0.0f);

		float friction = 0.6f;
		if (vecMeshDescs[0].ObjectType == "IceFloor")
			friction = 0.1f;
		std::wstringstream ss;
		ss << ID;
		::g_pPhysicsManager->CreateRigidBody(ss.str(), boxSize, 0.0f,	// Will be infinite (unmoving)
			friction, position, Qrotation, false);	// Infinite mass
	}

	else if (vecMeshDescs[0].ObjectType == "CheckPoint")
	{
		/* Text file entry
		<Model>
			<Type> CheckPoint </Type>
			<PlyFile> Cube2.ply </PlyFile>
			<Position> 0.0 0.0 -10.0 </Position>
		</Model>*/
		CVector3f minSize(physicalProp.position);
		CVector3f maxSize(physicalProp.position.x + 5.0f, physicalProp.position.y + 5.0f, physicalProp.position.z + 5.0f);
		std::wstringstream ss;
		ss << ID;
		::g_pPhysicsManager->CreatePhantomCheckPoint(ss.str(), minSize, maxSize);
	}
}
예제 #19
0
/**
* Crea la vista preliminar borrando la previa.
*/
void VisualEditor::Create()
{
#if wxVERSION_NUMBER < 2900 && !defined(__WXGTK__ )
    if ( IsShown() )
    {
        Freeze();   // Prevent flickering on wx 2.8,
        // Causes problems on wx 2.9 in wxGTK (e.g. wxNoteBook objects)
    }
#endif
    // Delete objects which had no parent
    DeleteAbstractObjects();

    // Clear selections, delete objects
    m_back->SetSelectedItem(NULL);
    m_back->SetSelectedSizer(NULL);
    m_back->SetSelectedObject(PObjectBase());

    ClearAui();
    ClearWizard();
    ClearComponents( m_back->GetFrameContentPanel() );

    m_back->GetFrameContentPanel()->DestroyChildren();
    m_back->GetFrameContentPanel()->SetSizer( NULL ); // *!*

    // Clear all associations between ObjectBase and wxObjects
    m_wxobjects.clear();
    m_baseobjects.clear();

    if( IsShown() )
    {
        m_form = AppData()->GetSelectedForm();
        if ( m_form )
        {
            m_back->Show(true);

            // --- [1] Configure the size of the form ---------------------------

            // Get size properties
            wxSize minSize( m_form->GetPropertyAsSize( wxT("minimum_size") ) );
            m_back->SetMinSize( minSize );

            wxSize maxSize( m_form->GetPropertyAsSize( wxT("maximum_size") ) );
            m_back->SetMaxSize( maxSize );

            wxSize size( m_form->GetPropertyAsSize( wxT("size") ) );

            // Determine necessary size for back panel
            wxSize backSize = size;
            if ( backSize.GetWidth() < minSize.GetWidth() && backSize.GetWidth() != wxDefaultCoord )
            {
                backSize.SetWidth( minSize.GetWidth() );
            }
            if ( backSize.GetHeight() < minSize.GetHeight() && backSize.GetHeight() != wxDefaultCoord )
            {
                backSize.SetHeight( minSize.GetHeight() );
            }
            if ( backSize.GetWidth() > maxSize.GetWidth() && maxSize.GetWidth() != wxDefaultCoord )
            {
                backSize.SetWidth( maxSize.GetWidth() );
            }
            if ( backSize.GetHeight() > maxSize.GetHeight() && maxSize.GetHeight() != wxDefaultCoord )
            {
                backSize.SetHeight( maxSize.GetHeight() );
            }

            // Modify size property to match
            if ( size != backSize )
            {
                PProperty psize = m_form->GetProperty( wxT("size") );
                if ( psize )
                {
                    AppData()->ModifyProperty( psize, TypeConv::SizeToString( backSize ) );
                }
            }

            // --- [2] Set the color of the form -------------------------------
            PProperty background( m_form->GetProperty( wxT("bg") ) );
            if ( background && !background->GetValue().empty() )
            {
                m_back->GetFrameContentPanel()->SetBackgroundColour( TypeConv::StringToColour( background->GetValue() ) );
            }
            else
            {
                if ( m_form->GetClassName() == wxT("Frame") )
                {
                    m_back->GetFrameContentPanel()->SetOwnBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_APPWORKSPACE ) );
                }
                else
                {
#ifdef __WXGTK__
                    wxVisualAttributes attribs = wxToolBar::GetClassDefaultAttributes();
                    m_back->GetFrameContentPanel()->SetOwnBackgroundColour( attribs.colBg );
#else
                    m_back->GetFrameContentPanel()->SetOwnBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
#endif
                }
            }

            // --- [3] Title bar Setup
            if (  m_form->GetClassName() == wxT("Frame")  ||
                    m_form->GetClassName() == wxT("Dialog") ||
                    m_form->GetClassName() == wxT("Wizard") )
            {
                m_back->SetTitle( m_form->GetPropertyAsString( wxT("title") ) );
                long style = m_form->GetPropertyAsInteger( wxT("style") );
                m_back->SetTitleStyle( style );
                m_back->ShowTitleBar( (style & wxCAPTION) != 0 );
            }
            else
                m_back->ShowTitleBar(false);

            // --- AUI
            if(  m_form->GetObjectTypeName() == wxT("form") )
            {
                if(  m_form->GetPropertyAsInteger( wxT("aui_managed") ) == 1)
                {
                    m_auipanel = new wxPanel( m_back->GetFrameContentPanel() );
                    m_auimgr = new wxAuiManager( m_auipanel, m_form->GetPropertyAsInteger( wxT("aui_manager_style") ) );
                }
            }

            // --- Wizard
            if ( m_form->GetClassName() == wxT("Wizard") )
            {
                m_wizard = new Wizard( m_back->GetFrameContentPanel() );

                bool showbutton = false;
                PProperty pextra_style = m_form->GetProperty( wxT("extra_style") );
                if ( pextra_style )
                {
                    showbutton = pextra_style->GetValue().Contains( wxT("wxWIZARD_EX_HELPBUTTON") );
                }

                m_wizard->ShowHelpButton( showbutton );

                if ( !m_form->GetProperty( wxT("bitmap") )->IsNull() )
                {
                    wxBitmap bmp = m_form->GetPropertyAsBitmap( wxT("bitmap") );
                    if ( bmp.IsOk() )
                    {
                        m_wizard->SetBitmap( bmp );
                    }
                }
            }

            // --- [4] Create the components of the form -------------------------

            // Used to save frame objects for later display
            PObjectBase menubar;
            wxWindow* statusbar = NULL;
            wxWindow* toolbar = NULL;

            for ( unsigned int i = 0; i < m_form->GetChildCount(); i++ )
            {
                PObjectBase child = m_form->GetChild( i );

                if( !menubar && (m_form->GetObjectTypeName() == wxT("menubar_form")) )
                {
                    // main form acts as a menubar
                    menubar = m_form;
                }
                else if (child->GetObjectTypeName() == wxT("menubar") )
                {
                    // Create the menubar later
                    menubar = child;
                }
                else if( !toolbar && (m_form->GetObjectTypeName() == wxT("toolbar_form")) )
                {
                    Generate( m_form, m_back->GetFrameContentPanel(), m_back->GetFrameContentPanel() );

                    ObjectBaseMap::iterator it = m_baseobjects.find( m_form.get() );
                    toolbar = wxDynamicCast( it->second, wxToolBar );

                    break;
                }
                else
                {
                    // Recursively generate the ObjectTree
                    try
                    {
                        // we have to put the content frame panel as parentObject in order
                        // to SetSizeHints be called.
                        if( m_auipanel )
                        {
                            Generate( child, m_auipanel, m_auipanel );
                        }
                        else if( m_wizard )
                        {
                            Generate( child, m_wizard, m_wizard );
                        }
                        else
                            Generate( child, m_back->GetFrameContentPanel(), m_back->GetFrameContentPanel() );

                    }
                    catch ( wxFBException& ex )
                    {
                        wxLogError ( ex.what() );
                    }
                }

                // Attach the toolbar (if any) to the frame
                if (child->GetClassName() == wxT("wxToolBar") )
                {
                    ObjectBaseMap::iterator it = m_baseobjects.find( child.get() );
                    toolbar = wxDynamicCast( it->second, wxToolBar );
                }
                else if (child->GetClassName() == wxT("wxAuiToolBar") )
                {
                    ObjectBaseMap::iterator it = m_baseobjects.find( child.get() );
                    toolbar = wxDynamicCast( it->second, wxAuiToolBar );
                }

                // Attach the status bar (if any) to the frame
                if ( child->GetClassName() == wxT("wxStatusBar") )
                {
                    ObjectBaseMap::iterator it = m_baseobjects.find( child.get() );
                    statusbar = wxDynamicCast( it->second, wxStatusBar );
                }

                // Add toolbar(s) to AuiManager and update content
                if( m_auimgr && toolbar )
                {
                    SetupAui( GetObjectBase( toolbar ), toolbar );
                    toolbar = NULL;
                }
            }

            if ( menubar || statusbar || toolbar || m_auipanel || m_wizard )
            {
                if( m_auimgr )
                {
                    m_back->SetFrameWidgets( menubar, NULL, statusbar, m_auipanel );
                }
                else if( m_wizard )
                {
                    m_back->SetFrameWidgets( menubar, NULL, NULL, m_wizard );
                }
                else
                    m_back->SetFrameWidgets( menubar, toolbar, statusbar, m_auipanel );
            }

            m_back->Layout();

            if ( backSize.GetHeight() == wxDefaultCoord || backSize.GetWidth() == wxDefaultCoord )
            {
                m_back->GetSizer()->Fit( m_back );
                m_back->SetSize( m_back->GetBestSize() );
            }

            // Set size after fitting so if only one dimesion is -1, it still fits that dimension
            m_back->SetSize( backSize );

            if( m_auimgr ) m_auimgr->Update();
            else
                m_back->Refresh();

            PProperty enabled( m_form->GetProperty( wxT("enabled") ) );
            if ( enabled )
            {
                m_back->Enable( TypeConv::StringToInt( enabled->GetValue() ) != 0 );
            }

            PProperty hidden( m_form->GetProperty( wxT("hidden") ) );
            if ( hidden )
            {
                m_back->Show( TypeConv::StringToInt( hidden->GetValue() ) == 0 );
            }
        }
        else
        {
            // There is no form to display
            m_back->Show(false);
            Refresh();
        }
#if wxVERSION_NUMBER < 2900 && !defined(__WXGTK__)
        Thaw();
#endif
    }

    UpdateVirtualSize();
}
예제 #20
0
  vector<PlateRegion> DetectorCUDA::doCascade(Mat frame, int offset_x, int offset_y)
  {


    if (frame.cols > config->maxDetectionInputWidth)
    {
      // The frame is too wide
      this->scale_factor = ((float) config->maxDetectionInputWidth) / ((float) frame.cols);

      if (config->debugDetector)
        std::cout << "Input detection image is too wide.  Resizing with scale: " << this->scale_factor << endl;
    }
    else if (frame.rows > config->maxDetectionInputHeight)
    {
      // The frame is too tall
      this->scale_factor = ((float) config->maxDetectionInputHeight) / ((float) frame.rows);

      if (config->debugDetector)
        std::cout << "Input detection image is too tall.  Resizing with scale: " << this->scale_factor << endl;
    }

    int w = frame.size().width;
    int h = frame.size().height;

    vector<Rect> plates;

    equalizeHist( frame, frame );
    resize(frame, frame, Size(w * this->scale_factor, h * this->scale_factor));

    //-- Detect plates
    timespec startTime;
    getTimeMonotonic(&startTime);

    float maxWidth = ((float) w) * (config->maxPlateWidthPercent / 100.0f) * this->scale_factor;
    float maxHeight = ((float) h) * (config->maxPlateHeightPercent / 100.0f) * this->scale_factor;
    Size minSize(config->minPlateSizeWidthPx * this->scale_factor, config->minPlateSizeHeightPx * this->scale_factor);

    gpu::GpuMat cudaFrame, plateregions_buffer;
    Mat plateregions_downloaded;

    cudaFrame.upload(frame);
    int numdetected = cuda_cascade.detectMultiScale(cudaFrame, plateregions_buffer, (double) config->detection_iteration_increase, config->detectionStrictness, minSize);
    plateregions_buffer.colRange(0, numdetected).download(plateregions_downloaded);

    for (int i = 0; i < numdetected; ++i)
    {
      plates.push_back(plateregions_downloaded.ptr<cv::Rect>()[i]);
    }



    if (config->debugTiming)
    {
      timespec endTime;
      getTimeMonotonic(&endTime);
      cout << "LBP Time: " << diffclock(startTime, endTime) << "ms." << endl;
    }

    for( unsigned int i = 0; i < plates.size(); i++ )
    {
      plates[i].x = (plates[i].x / scale_factor) + offset_x;
      plates[i].y = (plates[i].y / scale_factor) + offset_y;
      plates[i].width = plates[i].width / scale_factor;
      plates[i].height = plates[i].height / scale_factor;
    }

    vector<PlateRegion> orderedRegions = aggregateRegions(plates);

    return orderedRegions;

  }
예제 #21
0
NS_IMETHODIMP
nsLeafBoxFrame::Reflow(nsPresContext*   aPresContext,
                     nsHTMLReflowMetrics&     aDesiredSize,
                     const nsHTMLReflowState& aReflowState,
                     nsReflowStatus&          aStatus)
{
  // This is mostly a copy of nsBoxFrame::Reflow().
  // We aren't able to share an implementation because of the frame
  // class hierarchy.  If you make changes here, please keep
  // nsBoxFrame::Reflow in sync.

  DO_GLOBAL_REFLOW_COUNT("nsLeafBoxFrame", aReflowState.reason);
  DISPLAY_REFLOW(aPresContext, this, aReflowState, aDesiredSize, aStatus);

  NS_ASSERTION(aReflowState.mComputedWidth >=0 && aReflowState.mComputedHeight >= 0, "Computed Size < 0");

#ifdef DO_NOISY_REFLOW
  printf("\n-------------Starting LeafBoxFrame Reflow ----------------------------\n");
  printf("%p ** nsLBF::Reflow %d R: ", this, myCounter++);
  switch (aReflowState.reason) {
    case eReflowReason_Initial:
      printf("Ini");break;
    case eReflowReason_Incremental:
      printf("Inc");break;
    case eReflowReason_Resize:
      printf("Rsz");break;
    case eReflowReason_StyleChange:
      printf("Sty");break;
    case eReflowReason_Dirty:
      printf("Drt ");
      break;
    default:printf("<unknown>%d", aReflowState.reason);break;
  }
  
  printSize("AW", aReflowState.availableWidth);
  printSize("AH", aReflowState.availableHeight);
  printSize("CW", aReflowState.mComputedWidth);
  printSize("CH", aReflowState.mComputedHeight);

  printf(" *\n");

#endif

  aStatus = NS_FRAME_COMPLETE;

  // create the layout state
  nsBoxLayoutState state(aPresContext, aReflowState, aDesiredSize);

  // coelesce reflows if we are root.
  state.HandleReflow(this);
  
  nsSize computedSize(aReflowState.mComputedWidth,aReflowState.mComputedHeight);

  nsMargin m;
  m = aReflowState.mComputedBorderPadding;

  //GetBorderAndPadding(m);

  // this happens sometimes. So lets handle it gracefully.
  if (aReflowState.mComputedHeight == 0) {
    nsSize minSize(0,0);
    GetMinSize(state, minSize);
    computedSize.height = minSize.height - m.top - m.bottom;
  }

  nsSize prefSize(0,0);

  // if we are told to layout intrinic then get our preferred size.
  if (computedSize.width == NS_INTRINSICSIZE || computedSize.height == NS_INTRINSICSIZE) {
     nsSize minSize(0,0);
     nsSize maxSize(0,0);
     GetPrefSize(state, prefSize);
     GetMinSize(state,  minSize);
     GetMaxSize(state,  maxSize);
     BoundsCheck(minSize, prefSize, maxSize);
  }

  // get our desiredSize
  if (aReflowState.mComputedWidth == NS_INTRINSICSIZE) {
    computedSize.width = prefSize.width;
  } else {
    computedSize.width += m.left + m.right;
  }

  if (aReflowState.mComputedHeight == NS_INTRINSICSIZE) {
    computedSize.height = prefSize.height;
  } else {
    computedSize.height += m.top + m.bottom;
  }

  // handle reflow state min and max sizes

  if (computedSize.width > aReflowState.mComputedMaxWidth)
    computedSize.width = aReflowState.mComputedMaxWidth;

  if (computedSize.height > aReflowState.mComputedMaxHeight)
    computedSize.height = aReflowState.mComputedMaxHeight;

  if (computedSize.width < aReflowState.mComputedMinWidth)
    computedSize.width = aReflowState.mComputedMinWidth;

  if (computedSize.height < aReflowState.mComputedMinHeight)
    computedSize.height = aReflowState.mComputedMinHeight;

  nsRect r(mRect.x, mRect.y, computedSize.width, computedSize.height);

  SetBounds(state, r);
 
  // layout our children
  Layout(state);
  
  // ok our child could have gotten bigger. So lets get its bounds
  
  // get the ascent
  nscoord ascent = mRect.height;

  // Only call GetAscent when not doing Initial reflow while in PP
  // or when it is Initial reflow while in PP and a chrome doc
  // If called again with initial reflow it crashes because the 
  // frames are fully constructed (I think).
  PRBool isChrome;
  PRBool isInitialPP = nsBoxFrame::IsInitialReflowForPrintPreview(state, isChrome);
  if (!isInitialPP || (isInitialPP && isChrome)) {
    GetAscent(state, ascent);
  }

  aDesiredSize.width  = mRect.width;
  aDesiredSize.height = mRect.height;
  aDesiredSize.ascent = ascent;
  aDesiredSize.descent = 0;

  // NS_FRAME_OUTSIDE_CHILDREN is set in SetBounds() above
  if (mState & NS_FRAME_OUTSIDE_CHILDREN) {
    nsRect* overflowArea = GetOverflowAreaProperty();
    NS_ASSERTION(overflowArea, "Failed to set overflow area property");
    aDesiredSize.mOverflowArea = *overflowArea;
  }

  // max sure the max element size reflects
  // our min width
  nscoord* maxElementWidth = state.GetMaxElementWidth();
  if (maxElementWidth)
  {
     nsSize minSize(0,0);
     GetMinSize(state,  minSize);

     if (mRect.width > minSize.width) {
       if (aReflowState.mComputedWidth == NS_INTRINSICSIZE) {
         *maxElementWidth = minSize.width;
       } else {
         *maxElementWidth = mRect.width;
       }
     } else {
        *maxElementWidth = mRect.width;
     }
  }
#ifdef DO_NOISY_REFLOW
  {
    printf("%p ** nsLBF(done) W:%d H:%d  ", this, aDesiredSize.width, aDesiredSize.height);

    if (maxElementWidth) {
      printf("MW:%d\n", *maxElementWidth); 
    } else {
      printf("MW:?\n"); 
    }

  }
#endif

  return NS_OK;
}
예제 #22
0
  vector<PlateRegion> DetectorCPU::doCascade(Mat frame, std::vector<cv::Rect> regionsOfInterest)
  {


    if (frame.cols > config->maxDetectionInputWidth)
    {
      // The frame is too wide
      this->scale_factor = ((float) config->maxDetectionInputWidth) / ((float) frame.cols);

      if (config->debugGeneral)
        std::cout << "Input detection image is too wide.  Resizing with scale: " << this->scale_factor << endl;
    }
    else if (frame.rows > config->maxDetectionInputHeight)
    {
      // The frame is too tall
      this->scale_factor = ((float) config->maxDetectionInputHeight) / ((float) frame.rows);

      if (config->debugGeneral)
        std::cout << "Input detection image is too tall.  Resizing with scale: " << this->scale_factor << endl;
    }

    int w = frame.size().width;
    int h = frame.size().height;

    vector<Rect> plates;

    equalizeHist( frame, frame );
    resize(frame, frame, Size(w * this->scale_factor, h * this->scale_factor));

    //-- Detect plates
    timespec startTime;
    getTime(&startTime);

    float maxWidth = ((float) w) * (config->maxPlateWidthPercent / 100.0f) * this->scale_factor;
    float maxHeight = ((float) h) * (config->maxPlateHeightPercent / 100.0f) * this->scale_factor;
    Size minSize(config->minPlateSizeWidthPx * this->scale_factor, config->minPlateSizeHeightPx * this->scale_factor);
    Size maxSize(maxWidth, maxHeight);

    plate_cascade.detectMultiScale( frame, plates, config->detection_iteration_increase, config->detectionStrictness,
                                      0,
                                      //0|CV_HAAR_SCALE_IMAGE,
                                      minSize, maxSize );


    if (config->debugTiming)
    {
      timespec endTime;
      getTime(&endTime);
      cout << "LBP Time: " << diffclock(startTime, endTime) << "ms." << endl;
    }

    for( uint i = 0; i < plates.size(); i++ )
    {
      plates[i].x = plates[i].x / scale_factor;
      plates[i].y = plates[i].y / scale_factor;
      plates[i].width = plates[i].width / scale_factor;
      plates[i].height = plates[i].height / scale_factor;
    }

    vector<PlateRegion> orderedRegions = aggregateRegions(plates);

    return orderedRegions;

  }
예제 #23
0
파일: appContext.cpp 프로젝트: nyorain/ny
//wndProc
LRESULT WinapiAppContext::eventProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam)
{
	auto wc = windowContext(window);

	WinapiEventData eventData;
	eventData.windowContext = wc;
	eventData.window = window;
	eventData.message = message;
	eventData.wparam = wparam;
	eventData.lparam = lparam;

	LRESULT result = 0;

	switch(message)
	{
		case WM_PAINT:
		{
			if(wc) wc->listener().draw(&eventData);
			result = ::DefWindowProc(window, message, wparam, lparam); //to validate the window
			break;
		}

		case WM_DESTROY:
		{
			if(wc) wc->listener().close(&eventData);
			break;
		}

		case WM_SIZE:
		{
			nytl::Vec2ui size(LOWORD(lparam), HIWORD(lparam));
			if(wc) wc->listener().resize(size, &eventData);
			break;
		}

		case WM_MOVE:
		{
			nytl::Vec2i position(LOWORD(lparam), HIWORD(lparam));
			if(wc) wc->listener().position(position, &eventData);
			break;
		}

		case WM_SYSCOMMAND:
		{
			if(wc)
			{
	            constexpr auto SC_DRAGMOVE = 0xf012;
				ToplevelState state;

				if(wparam == SC_MAXIMIZE) state = ToplevelState::maximized;
				else if(wparam == SC_MINIMIZE) state = ToplevelState::minimized;
				else if(wparam == SC_RESTORE) state = ToplevelState::normal;
                else if(wparam >= SC_SIZE && wparam <= SC_SIZE + 8)
                {
                    auto currentCursor = ::GetClassLongPtr(wc->handle(), -12);

                    auto edge = winapiToEdges(wparam - SC_SIZE);
                    auto cursor = sizeCursorFromEdge(edge);
                    wc->cursor(cursor);

			        result = ::DefWindowProc(window, message, wparam, lparam);
	                ::SetClassLongPtr(wc->handle(), -12, currentCursor);

                    break;
                }

				//TODO: shown parameter? check WS_VISIBLE?
				wc->listener().state(true, state, &eventData);
			}

			result = ::DefWindowProc(window, message, wparam, lparam);
			break;
		}

		case WM_GETMINMAXINFO:
		{
			if(wc)
			{
				::MINMAXINFO* mmi = reinterpret_cast<MINMAXINFO*>(lparam);
				mmi->ptMaxTrackSize.x = wc->maxSize().x;
				mmi->ptMaxTrackSize.y = wc->maxSize().y;
				mmi->ptMinTrackSize.x = wc->minSize().x;
				mmi->ptMinTrackSize.y = wc->minSize().y;
			}

			break;
		}

		case WM_ERASEBKGND:
		{
			//prevent the background erase
			result = 1;
			break;
		}

		//XXX: needed?
		case WM_CLIPBOARDUPDATE:
		{
			clipboardSequenceNumber_ = ::GetClipboardSequenceNumber();
			clipboardOffer_.reset();

			IDataObject* obj;
			::OleGetClipboard(&obj);
			if(obj) clipboardOffer_ = std::make_unique<winapi::DataOfferImpl>(*obj);
			break;
		}

		case WM_QUIT:
		{
			receivedQuit_ = 1;
			break;
		}

		default:
		{
			//process mouse/keyboard events
			if(keyboardContext_.processEvent(eventData, result)) break;
			if(mouseContext_.processEvent(eventData, result)) break;

			result = ::DefWindowProc(window, message, wparam, lparam);
			break;
		}
	}

	return result;
}
Foam::MGridGenGAMGAgglomeration::MGridGenGAMGAgglomeration
(
    const lduMesh& mesh,
    const dictionary& dict
)
:
    GAMGAgglomeration(mesh, dict),
    fvMesh_(refCast<const fvMesh>(mesh))
{
    // Min, max size of agglomerated cells
    label minSize(readLabel(dict.lookup("minSize")));
    label maxSize(readLabel(dict.lookup("maxSize")));


    // Get the finest-level interfaces from the mesh
    interfaceLevels_.set
    (
        0,
        new lduInterfacePtrsList(fvMesh_.boundary().interfaces())
    );

    // Start geometric agglomeration from the cell volumes and areas of the mesh
    scalarField* VPtr = const_cast<scalarField*>(&fvMesh_.cellVolumes());
    vectorField* SfPtr = const_cast<vectorField*>(&fvMesh_.faceAreas());

    // Create the boundary area cell field
    scalarField* SbPtr(new scalarField(fvMesh_.nCells(), 0));

    {
        scalarField& Sb = *SbPtr;

        const labelList& own = fvMesh_.faceOwner();
        const vectorField& Sf = fvMesh_.faceAreas();

        forAll(Sf, facei)
        {
            if (!fvMesh_.isInternalFace(facei))
            {
                Sb[own[facei]] += mag(Sf[facei]);
            }
        }
    }


    // Agglomerate until the required number of cells in the coarsest level
    // is reached

    label nCreatedLevels = 0;

    while (nCreatedLevels < maxLevels_ - 1)
    {
        label nCoarseCells = -1;

        tmp<labelField> finalAgglomPtr = agglomerate
        (
            nCoarseCells,
            minSize,
            maxSize,
            meshLevel(nCreatedLevels).lduAddr(),
            *VPtr,
            *SfPtr,
            *SbPtr
        );

        if (continueAgglomerating(nCoarseCells))
        {
            nCells_[nCreatedLevels] = nCoarseCells;
            restrictAddressing_.set(nCreatedLevels, finalAgglomPtr);
        }
        else
        {
            break;
        }

        agglomerateLduAddressing(nCreatedLevels);

        // Agglomerate the cell volumes field for the next level
        {
            scalarField* aggVPtr
            (
                new scalarField(meshLevels_[nCreatedLevels].size())
            );

            restrictField(*aggVPtr, *VPtr, nCreatedLevels);

            if (nCreatedLevels)
            {
                delete VPtr;
            }

            VPtr = aggVPtr;
        }

        // Agglomerate the face areas field for the next level
        {
            vectorField* aggSfPtr
            (
                new vectorField
                (
                    meshLevels_[nCreatedLevels].upperAddr().size(),
                    vector::zero
                )
            );

            restrictFaceField(*aggSfPtr, *SfPtr, nCreatedLevels);

            if (nCreatedLevels)
            {
                delete SfPtr;
            }

            SfPtr = aggSfPtr;
        }

        // Agglomerate the cell boundary areas field for the next level
        {
            scalarField* aggSbPtr
            (
                new scalarField(meshLevels_[nCreatedLevels].size())
            );

            restrictField(*aggSbPtr, *SbPtr, nCreatedLevels);

            delete SbPtr;
            SbPtr = aggSbPtr;
        }

        nCreatedLevels++;
    }

    // Shrink the storage of the levels to those created
    compactLevels(nCreatedLevels);

    // Delete temporary geometry storage
    if (nCreatedLevels)
    {
        delete VPtr;
        delete SfPtr;
    }
    delete SbPtr;
}
예제 #25
0
nsSize
nsSprocketLayout::GetMinSize(nsIFrame* aBox, nsBoxLayoutState& aState)
{
   nsSize minSize (0, 0);
   bool isHorizontal = IsHorizontal(aBox);

   nscoord biggestMin = 0;


   // run through all the children and get their min, max, and preferred sizes
   // return us the size of the box

   nsIFrame* child = nsBox::GetChildBox(aBox);
   nsFrameState frameState = nsFrameState(0);
   GetFrameState(aBox, frameState);
   bool isEqual = !!(frameState & NS_STATE_EQUAL_SIZE);
   int32_t count = 0;

   while (child) 
   {  
       // ignore collapsed children
      if (!child->IsCollapsed())
      {
        nsSize min = child->GetMinSize(aState);
        nsSize pref(0,0);
        
        // if the child is not flexible then
        // its min size is its pref size.
        if (child->GetFlex(aState) == 0) {
            pref = child->GetPrefSize(aState);
            if (isHorizontal)
               min.width = pref.width;
            else
               min.height = pref.height;
        }

        if (isEqual) {
          if (isHorizontal)
          {
            if (min.width > biggestMin)
              biggestMin = min.width;
          } else {
            if (min.height > biggestMin)
              biggestMin = min.height;
          }
        }

        AddMargin(child, min);
        AddLargestSize(minSize, min, isHorizontal);
        count++;
      }

      child = nsBox::GetNextBox(child);
   }

   
   if (isEqual) {
      if (isHorizontal)
         minSize.width = biggestMin*count;
      else
         minSize.height = biggestMin*count;
   }

  // now add our border and padding
  AddBorderAndPadding(aBox, minSize);

  return minSize;
}
예제 #26
0
    DiskLoc MmapV1ExtentManager::_allocFromFreeList( TransactionExperiment* txn,
                                               int approxSize,
                                               bool capped ) {
        // setup extent constraints

        int low, high;
        if ( capped ) {
            // be strict about the size
            low = approxSize;
            if ( low > 2048 ) low -= 256;
            high = (int) (approxSize * 1.05) + 256;
        }
        else {
            low = (int) (approxSize * 0.8);
            high = (int) (approxSize * 1.4);
        }
        if ( high <= 0 ) {
            // overflowed
            high = max(approxSize, maxSize());
        }
        if ( high <= minSize() ) {
            // the minimum extent size is 4097
            high = minSize() + 1;
        }

        // scan free list looking for something suitable

        int n = 0;
        Extent *best = 0;
        int bestDiff = 0x7fffffff;
        {
            Timer t;
            DiskLoc L = _getFreeListStart();
            while( !L.isNull() ) {
                Extent* e = getExtent( L );
                if ( e->length >= low && e->length <= high ) {
                    int diff = abs(e->length - approxSize);
                    if ( diff < bestDiff ) {
                        bestDiff = diff;
                        best = e;
                        if ( ((double) diff) / approxSize < 0.1 ) {
                            // close enough
                            break;
                        }
                        if ( t.seconds() >= 2 ) {
                            // have spent lots of time in write lock, and we are in [low,high], so close enough
                            // could come into play if extent freelist is very long
                            break;
                        }
                    }
                    else {
                        OCCASIONALLY {
                            if ( high < 64 * 1024 && t.seconds() >= 2 ) {
                                // be less picky if it is taking a long time
                                high = 64 * 1024;
                            }
                        }
                    }
                }
                L = e->xnext;
                ++n;
            }
            if ( t.seconds() >= 10 ) {
                log() << "warning: slow scan in allocFromFreeList (in write lock)" << endl;
            }
        }
예제 #27
0
void
nsSprocketLayout::PopulateBoxSizes(nsIFrame* aBox, nsBoxLayoutState& aState, nsBoxSize*& aBoxSizes, nscoord& aMinSize, nscoord& aMaxSize, int32_t& aFlexes)
{
  // used for the equal size flag
  nscoord biggestPrefWidth = 0;
  nscoord biggestMinWidth = 0;
  nscoord smallestMaxWidth = NS_INTRINSICSIZE;

  nsFrameState frameState = nsFrameState(0);
  GetFrameState(aBox, frameState);

  //if (frameState & NS_STATE_CURRENTLY_IN_DEBUG)
  //   printf("In debug\n");

  aMinSize = 0;
  aMaxSize = NS_INTRINSICSIZE;

  bool isHorizontal;

  if (IsHorizontal(aBox))
     isHorizontal = true;
  else
     isHorizontal = false;

  // this is a nice little optimization
  // it turns out that if we only have 1 flexable child
  // then it does not matter what its preferred size is
  // there is nothing to flex it relative. This is great
  // because we can avoid asking for a preferred size in this
  // case. Why is this good? Well you might have html inside it
  // and asking html for its preferred size is rather expensive.
  // so we can just optimize it out this way.

  // set flexes
  nsIFrame* child = nsBox::GetChildBox(aBox);

  aFlexes = 0;
  nsBoxSize* currentBox = nullptr;

#if 0
  nsBoxSize* start = aBoxSizes;
  
  while(child)
  {
    // ok if we started with a list move down the list
    // until we reach the end. Then start looking at childen.
    // This feature is used extensively for Grid.
    nscoord flex = 0;    

    if (!start) {
      if (!currentBox) {
        aBoxSizes      = new (aState) nsBoxSize();
        currentBox      = aBoxSizes;
      } else {
        currentBox->next      = new (aState) nsBoxSize();
        currentBox      = currentBox->next;
      }
    

      flex = child->GetFlex(aState);

      currentBox->flex = flex;
      currentBox->collapsed = child->IsCollapsed();
    } else {
      flex = start->flex;
      start = start->next;
    }
    
    if (flex > 0) 
       aFlexes++;
   
    child = GetNextBox(child);
  }
#endif

  // get pref, min, max
  child = nsBox::GetChildBox(aBox);
  currentBox = aBoxSizes;
  nsBoxSize* last = nullptr;

  nscoord maxFlex = 0;
  int32_t childCount = 0;

  while(child)
  {
    while (currentBox && currentBox->bogus) {
      last = currentBox;
      currentBox = currentBox->next;
    }
    ++childCount;
    nsSize pref(0,0);
    nsSize minSize(0,0);
    nsSize maxSize(NS_INTRINSICSIZE,NS_INTRINSICSIZE);
    nscoord ascent = 0;
    bool collapsed = child->IsCollapsed();

    if (!collapsed) {
    // only one flexible child? Cool we will just make its preferred size
    // 0 then and not even have to ask for it.
    //if (flexes != 1)  {

      pref = child->GetPrefSize(aState);
      minSize = child->GetMinSize(aState);
      maxSize = nsBox::BoundsCheckMinMax(minSize, child->GetMaxSize(aState));
      ascent = child->GetBoxAscent(aState);
      nsMargin margin;
      child->GetMargin(margin);
      ascent += margin.top;
    //}

      pref = nsBox::BoundsCheck(minSize, pref, maxSize);

      AddMargin(child, pref);
      AddMargin(child, minSize);
      AddMargin(child, maxSize);
    }

    if (!currentBox) {
      // create one.
      currentBox = new (aState) nsBoxSize();
      if (!aBoxSizes) {
        aBoxSizes = currentBox;
        last = aBoxSizes;
      } else {
        last->next = currentBox;
        last = currentBox;
      }

      nscoord minWidth;
      nscoord maxWidth;
      nscoord prefWidth;

      // get sizes from child
      if (isHorizontal) {
          minWidth  = minSize.width;
          maxWidth  = maxSize.width;
          prefWidth = pref.width;
      } else {
          minWidth = minSize.height;
          maxWidth = maxSize.height;
          prefWidth = pref.height;
      }

      nscoord flex = child->GetFlex(aState);

      // set them if you collapsed you are not flexible.
      if (collapsed) {
        currentBox->flex = 0;
      }
      else {
        if (flex > maxFlex) {
          maxFlex = flex;
        }
        currentBox->flex = flex;
      }

      // we specified all our children are equal size;
      if (frameState & NS_STATE_EQUAL_SIZE) {

        if (prefWidth > biggestPrefWidth) 
          biggestPrefWidth = prefWidth;

        if (minWidth > biggestMinWidth) 
          biggestMinWidth = minWidth;

        if (maxWidth < smallestMaxWidth) 
          smallestMaxWidth = maxWidth;
      } else { // not we can set our children right now.
        currentBox->pref    = prefWidth;
        currentBox->min     = minWidth;
        currentBox->max     = maxWidth;
      }

      NS_ASSERTION(minWidth <= prefWidth && prefWidth <= maxWidth,"Bad min, pref, max widths!");

    }

    if (!isHorizontal) {
      if (minSize.width > aMinSize)
        aMinSize = minSize.width;

      if (maxSize.width < aMaxSize)
        aMaxSize = maxSize.width;

    } else {
      if (minSize.height > aMinSize)
        aMinSize = minSize.height;

      if (maxSize.height < aMaxSize)
        aMaxSize = maxSize.height;
    }

    currentBox->collapsed = collapsed;
    aFlexes += currentBox->flex;

    child = nsBox::GetNextBox(child);

    last = currentBox;
    currentBox = currentBox->next;

  }

  if (childCount > 0) {
    nscoord maxAllowedFlex = nscoord_MAX / childCount;
  
    if (MOZ_UNLIKELY(maxFlex > maxAllowedFlex)) {
      // clamp all the flexes
      currentBox = aBoxSizes;
      while (currentBox) {
        currentBox->flex = std::min(currentBox->flex, maxAllowedFlex);
        currentBox = currentBox->next;      
      }
    }
  }
#ifdef DEBUG
  else {
    NS_ASSERTION(maxFlex == 0, "How did that happen?");
  }
#endif

  // we specified all our children are equal size;
  if (frameState & NS_STATE_EQUAL_SIZE) {
    smallestMaxWidth = std::max(smallestMaxWidth, biggestMinWidth);
    biggestPrefWidth = nsBox::BoundsCheck(biggestMinWidth, biggestPrefWidth, smallestMaxWidth);

    currentBox = aBoxSizes;

    while(currentBox)
    {
      if (!currentBox->collapsed) {
        currentBox->pref = biggestPrefWidth;
        currentBox->min = biggestMinWidth;
        currentBox->max = smallestMaxWidth;
      } else {
        currentBox->pref = 0;
        currentBox->min = 0;
        currentBox->max = 0;
      }
      currentBox = currentBox->next;
    }
  }

}
예제 #28
0
파일: multicell.cpp 프로젝트: nealey/vera
//---------------------------------------------------------------------------
void wxMultiCellSizer :: GetMinimums()
{
    // We first initial all the arrays EXCEPT for the m_minsizes array.

    memset(m_maxHeight, 0, sizeof(int) * m_cell_count.GetHeight());
    memset(m_maxWidth, 0, sizeof(int) * m_cell_count.GetWidth());
    memset(m_rowStretch, 0, sizeof(int) * m_cell_count.GetHeight());
    memset(m_colStretch, 0, sizeof(int) * m_cell_count.GetWidth());
    for (int x = 0; x < 1 + wxMax(m_cell_count.GetHeight(), m_cell_count.GetWidth()); x++)
    {
        m_weights[x]->SetHeight(0);
        m_weights[x]->SetWidth(0);
    }

    wxSizerItemList::compatibility_iterator     node = m_children.GetFirst();
    while (node)
    {
        wxSizerItem     *item = node->GetData();
        wxMultiCellItemHandle *rect;
        if (item != NULL &&
            (rect = (wxMultiCellItemHandle *)item->GetUserData()) != NULL)
        {
            int row = rect->GetRow();
            int col = rect->GetColumn();

            // First make sure that the control knows about the max rows and columns

            int changed = false;
            if (row + 1 > m_cell_count.GetHeight())
            {
                changed++;
                m_maxHeight = (int *)realloc(m_maxHeight, (1 + row) * sizeof(int));
                m_rowStretch = (int *)realloc(m_rowStretch, (1 + row) * sizeof(int));
                for (int x = m_cell_count.GetHeight(); x < row + 1; x++)
                {
                    m_maxHeight[x - 1] = 0;
                    m_rowStretch[x - 1] = 0;
                }
                m_cell_count.SetHeight(row + 1);
            }
            if (col + 1 > m_cell_count.GetWidth())
            {
                changed++;
                m_maxWidth = (int *)realloc(m_maxWidth, (1 + col) * sizeof(int));
                m_colStretch = (int *)realloc(m_colStretch, ( 1 + col) * sizeof(int));
                for (int x = m_cell_count.GetWidth(); x < col + 1; x++)
                {
                    m_maxWidth[x - 1] = 0;
                    m_colStretch[x - 1] = 0;
                }
                m_cell_count.SetWidth(col + 1);
            }
            if (changed)
            {
                m_weights = (wxSize **)realloc(m_weights, (1 + wxMax(m_cell_count.GetHeight(), m_cell_count.GetWidth())) * sizeof(wxSize *));
                m_minSizes = (wxSize **)realloc(m_minSizes, (1 + wxMax(m_cell_count.GetHeight(), m_cell_count.GetWidth())) * sizeof(wxSize *));
                for (int x = m_maxWeights; x < 1 + wxMax(m_cell_count.GetHeight(), m_cell_count.GetWidth()); x++)
                {
                    m_weights[x - 1] = new wxSize(0,0);
                    m_minSizes[x - 1] = new wxSize(0,0);
                }
                m_maxWeights = 1 + wxMax(m_cell_count.GetHeight(), m_cell_count.GetWidth());
            }

            // Sum the m_weights for each row/column, but only if they are resizable

            wxSize minSize( item->CalcMin() );
            wxSize c_size = rect->GetLocalSize();
            if (c_size.GetHeight() != wxDefaultCoord ||
                c_size.GetWidth() != wxDefaultCoord)
            {
                minSize.SetHeight(wxMax(minSize.GetHeight(), c_size.GetHeight()));
                minSize.SetWidth(wxMax(minSize.GetWidth(), c_size.GetWidth()));
            }

            // For each row, calculate the max height for those fields which are not
            // resizable in the vertical pane

            if (!(rect->GetStyle() & wxVERTICAL_RESIZABLE || m_minSizes[row]->GetHeight() < 0))
            {
                m_maxHeight[row] = wxMax(m_maxHeight[row], minSize.GetHeight() / rect->GetHeight());
            }
            else
            {
                m_rowStretch[row] = 1;
                if (m_minSizes[row]->GetHeight())
                {
                    m_maxHeight[row] = abs(m_minSizes[row]->GetHeight());
                }
                else
                {
                    m_maxHeight[row] = wxMax(m_maxHeight[row], m_defaultCellSize.GetHeight());
                }
                m_weights[row]->SetHeight(wxMax(m_weights[row]->GetHeight(), rect->GetWeight().GetHeight()));
            }

            // For each column, calculate the max width for those fields which are not
            // resizable in the horizontal pane

            if (!(rect->GetStyle() & wxHORIZONTAL_RESIZABLE || m_minSizes[col]->GetWidth() < 0))
            {
                if (m_minSizes[col]->GetWidth())
                {
                    m_maxWidth[col] = abs(m_minSizes[col]->GetWidth());
                }
                else
                {
                    m_maxWidth[col] = wxMax(m_maxWidth[col], minSize.GetWidth() / rect->GetWidth());
                }
            }
            else
            {
                m_colStretch[col] = 1;
                m_maxWidth[col] = wxMax(m_maxWidth[col], m_defaultCellSize.GetWidth());
                m_weights[col]->SetWidth(wxMax(m_weights[col]->GetWidth(), rect->GetWeight().GetWidth()));
            }
            node = node->GetNext();
        }
    }
} // wxMultiCellSizer :: GetMinimums
	virtual bool onVertex(TraversalData td[2][2][2])
	{
		TraversalData *l = minSize( minSize(&td[0][0][0], &td[1][0][0]), minSize(&td[0][1][0], &td[1][1][0]) );
		TraversalData *h = minSize( minSize(&td[0][0][1], &td[1][0][1]), minSize(&td[0][1][1], &td[1][1][1]) );
		return insideOrCrossing(l->z, h->z, h->z + h->cellsize, h->cellsize);
	}