text
stringlengths
54
60.6k
<commit_before>efaa892a-2e4c-11e5-9284-b827eb9e62be<commit_msg>efafaed2-2e4c-11e5-9284-b827eb9e62be<commit_after>efafaed2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>34d1a294-2e4e-11e5-9284-b827eb9e62be<commit_msg>34d6986c-2e4e-11e5-9284-b827eb9e62be<commit_after>34d6986c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0ba8b1ba-2e4d-11e5-9284-b827eb9e62be<commit_msg>0badc3a8-2e4d-11e5-9284-b827eb9e62be<commit_after>0badc3a8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1e6ba630-2e4e-11e5-9284-b827eb9e62be<commit_msg>1e70b2b0-2e4e-11e5-9284-b827eb9e62be<commit_after>1e70b2b0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dead10f2-2e4c-11e5-9284-b827eb9e62be<commit_msg>deb93e7c-2e4c-11e5-9284-b827eb9e62be<commit_after>deb93e7c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9e3dbf66-2e4d-11e5-9284-b827eb9e62be<commit_msg>9e42baa2-2e4d-11e5-9284-b827eb9e62be<commit_after>9e42baa2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fc7ee64e-2e4e-11e5-9284-b827eb9e62be<commit_msg>fc83f9e0-2e4e-11e5-9284-b827eb9e62be<commit_after>fc83f9e0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7f1d1bb8-2e4d-11e5-9284-b827eb9e62be<commit_msg>7f220d62-2e4d-11e5-9284-b827eb9e62be<commit_after>7f220d62-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>833fdcde-2e4e-11e5-9284-b827eb9e62be<commit_msg>8344ea30-2e4e-11e5-9284-b827eb9e62be<commit_after>8344ea30-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c6c2d602-2e4c-11e5-9284-b827eb9e62be<commit_msg>c6c7c68a-2e4c-11e5-9284-b827eb9e62be<commit_after>c6c7c68a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aa20dcec-2e4c-11e5-9284-b827eb9e62be<commit_msg>aa25c9fa-2e4c-11e5-9284-b827eb9e62be<commit_after>aa25c9fa-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>79bcbea2-2e4e-11e5-9284-b827eb9e62be<commit_msg>79c1c424-2e4e-11e5-9284-b827eb9e62be<commit_after>79c1c424-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fe373b46-2e4c-11e5-9284-b827eb9e62be<commit_msg>fe3c3420-2e4c-11e5-9284-b827eb9e62be<commit_after>fe3c3420-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>be58d2b8-2e4d-11e5-9284-b827eb9e62be<commit_msg>be5dd182-2e4d-11e5-9284-b827eb9e62be<commit_after>be5dd182-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>eab49294-2e4c-11e5-9284-b827eb9e62be<commit_msg>eab9843e-2e4c-11e5-9284-b827eb9e62be<commit_after>eab9843e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>464721d4-2e4e-11e5-9284-b827eb9e62be<commit_msg>464c2d50-2e4e-11e5-9284-b827eb9e62be<commit_after>464c2d50-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6a9622fc-2e4d-11e5-9284-b827eb9e62be<commit_msg>6a9b7842-2e4d-11e5-9284-b827eb9e62be<commit_after>6a9b7842-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2a21ef08-2e4d-11e5-9284-b827eb9e62be<commit_msg>2a26e7ba-2e4d-11e5-9284-b827eb9e62be<commit_after>2a26e7ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8948228a-2e4e-11e5-9284-b827eb9e62be<commit_msg>894d302c-2e4e-11e5-9284-b827eb9e62be<commit_after>894d302c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2a6546ca-2e4f-11e5-9284-b827eb9e62be<commit_msg>2a6a4c88-2e4f-11e5-9284-b827eb9e62be<commit_after>2a6a4c88-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0b1be130-2e4e-11e5-9284-b827eb9e62be<commit_msg>0b20d604-2e4e-11e5-9284-b827eb9e62be<commit_after>0b20d604-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cb9c1c6e-2e4d-11e5-9284-b827eb9e62be<commit_msg>cba115fc-2e4d-11e5-9284-b827eb9e62be<commit_after>cba115fc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fc488488-2e4d-11e5-9284-b827eb9e62be<commit_msg>fc4d748e-2e4d-11e5-9284-b827eb9e62be<commit_after>fc4d748e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ed07b246-2e4d-11e5-9284-b827eb9e62be<commit_msg>ed0cac10-2e4d-11e5-9284-b827eb9e62be<commit_after>ed0cac10-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8bb3df28-2e4e-11e5-9284-b827eb9e62be<commit_msg>8bb8e9dc-2e4e-11e5-9284-b827eb9e62be<commit_after>8bb8e9dc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>29830ec4-2e4d-11e5-9284-b827eb9e62be<commit_msg>298800e6-2e4d-11e5-9284-b827eb9e62be<commit_after>298800e6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a638e9e8-2e4d-11e5-9284-b827eb9e62be<commit_msg>a63ddf48-2e4d-11e5-9284-b827eb9e62be<commit_after>a63ddf48-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>db7535de-2e4e-11e5-9284-b827eb9e62be<commit_msg>db7a3d36-2e4e-11e5-9284-b827eb9e62be<commit_after>db7a3d36-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>036dd110-2e4d-11e5-9284-b827eb9e62be<commit_msg>0372ee98-2e4d-11e5-9284-b827eb9e62be<commit_after>0372ee98-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6ab48cb0-2e4d-11e5-9284-b827eb9e62be<commit_msg>6ab99200-2e4d-11e5-9284-b827eb9e62be<commit_after>6ab99200-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e58cab84-2e4d-11e5-9284-b827eb9e62be<commit_msg>e591b8fe-2e4d-11e5-9284-b827eb9e62be<commit_after>e591b8fe-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5206dba4-2e4e-11e5-9284-b827eb9e62be<commit_msg>520c48e6-2e4e-11e5-9284-b827eb9e62be<commit_after>520c48e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1cd2a0fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>1cd79410-2e4d-11e5-9284-b827eb9e62be<commit_after>1cd79410-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3a5d3548-2e4e-11e5-9284-b827eb9e62be<commit_msg>3a6257a8-2e4e-11e5-9284-b827eb9e62be<commit_after>3a6257a8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>28b1fdca-2e4d-11e5-9284-b827eb9e62be<commit_msg>28b6ff28-2e4d-11e5-9284-b827eb9e62be<commit_after>28b6ff28-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>133cf33a-2e4f-11e5-9284-b827eb9e62be<commit_msg>134203ca-2e4f-11e5-9284-b827eb9e62be<commit_after>134203ca-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>76fdb136-2e4d-11e5-9284-b827eb9e62be<commit_msg>7702ab32-2e4d-11e5-9284-b827eb9e62be<commit_after>7702ab32-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2bdcba70-2e4e-11e5-9284-b827eb9e62be<commit_msg>2be1cd80-2e4e-11e5-9284-b827eb9e62be<commit_after>2be1cd80-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>130e1c72-2e4f-11e5-9284-b827eb9e62be<commit_msg>1313328e-2e4f-11e5-9284-b827eb9e62be<commit_after>1313328e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ebc64b82-2e4c-11e5-9284-b827eb9e62be<commit_msg>ebcb4448-2e4c-11e5-9284-b827eb9e62be<commit_after>ebcb4448-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a6362bc6-2e4e-11e5-9284-b827eb9e62be<commit_msg>a63b385a-2e4e-11e5-9284-b827eb9e62be<commit_after>a63b385a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>56d785ca-2e4e-11e5-9284-b827eb9e62be<commit_msg>56dca6ea-2e4e-11e5-9284-b827eb9e62be<commit_after>56dca6ea-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>316fffca-2e4d-11e5-9284-b827eb9e62be<commit_msg>3174f566-2e4d-11e5-9284-b827eb9e62be<commit_after>3174f566-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f0b7e370-2e4d-11e5-9284-b827eb9e62be<commit_msg>f0bd013e-2e4d-11e5-9284-b827eb9e62be<commit_after>f0bd013e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>78ec1630-2e4e-11e5-9284-b827eb9e62be<commit_msg>78f137b4-2e4e-11e5-9284-b827eb9e62be<commit_after>78f137b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b3784f04-2e4d-11e5-9284-b827eb9e62be<commit_msg>b37d495a-2e4d-11e5-9284-b827eb9e62be<commit_after>b37d495a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>80cd2b32-2e4e-11e5-9284-b827eb9e62be<commit_msg>80d24d9c-2e4e-11e5-9284-b827eb9e62be<commit_after>80d24d9c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c66e4844-2e4c-11e5-9284-b827eb9e62be<commit_msg>c6735bfe-2e4c-11e5-9284-b827eb9e62be<commit_after>c6735bfe-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>58529d8c-2e4d-11e5-9284-b827eb9e62be<commit_msg>5857a64c-2e4d-11e5-9284-b827eb9e62be<commit_after>5857a64c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>91b2176e-2e4e-11e5-9284-b827eb9e62be<commit_msg>91b711d8-2e4e-11e5-9284-b827eb9e62be<commit_after>91b711d8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>755ef952-2e4d-11e5-9284-b827eb9e62be<commit_msg>7563f358-2e4d-11e5-9284-b827eb9e62be<commit_after>7563f358-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4a66c09a-2e4d-11e5-9284-b827eb9e62be<commit_msg>4a6bdf9e-2e4d-11e5-9284-b827eb9e62be<commit_after>4a6bdf9e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ad0232ee-2e4c-11e5-9284-b827eb9e62be<commit_msg>ad0725ce-2e4c-11e5-9284-b827eb9e62be<commit_after>ad0725ce-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fcd35b9e-2e4d-11e5-9284-b827eb9e62be<commit_msg>fcd85784-2e4d-11e5-9284-b827eb9e62be<commit_after>fcd85784-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>eca3cdd0-2e4d-11e5-9284-b827eb9e62be<commit_msg>eca8dbcc-2e4d-11e5-9284-b827eb9e62be<commit_after>eca8dbcc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>edbc8db6-2e4c-11e5-9284-b827eb9e62be<commit_msg>edc17e66-2e4c-11e5-9284-b827eb9e62be<commit_after>edc17e66-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ee50676a-2e4d-11e5-9284-b827eb9e62be<commit_msg>ee55796c-2e4d-11e5-9284-b827eb9e62be<commit_after>ee55796c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bb767e2a-2e4c-11e5-9284-b827eb9e62be<commit_msg>bb7b851e-2e4c-11e5-9284-b827eb9e62be<commit_after>bb7b851e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>96761e30-2e4e-11e5-9284-b827eb9e62be<commit_msg>967b2e16-2e4e-11e5-9284-b827eb9e62be<commit_after>967b2e16-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e1b05e02-2e4d-11e5-9284-b827eb9e62be<commit_msg>e1b56a32-2e4d-11e5-9284-b827eb9e62be<commit_after>e1b56a32-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * timeperiod.h - time period data entry widget * Program: kalarm * (C) 2003, 2004 by David Jarvie <software@astrojar.org.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "kalarm.h" #include <qwidgetstack.h> #include <qwhatsthis.h> #include <klocale.h> #include <kdialog.h> #include "combobox.h" #include "spinbox.h" #include "timespinbox.h" #include "timeperiod.moc" // Collect these widget labels together to ensure consistent wording and // translations across different modules. QString TimePeriod::i18n_hours_mins() { return i18n("hours/minutes"); } QString TimePeriod::i18n_Hours_Mins() { return i18n("Hours/Minutes"); } QString TimePeriod::i18n_days() { return i18n("days"); } QString TimePeriod::i18n_Days() { return i18n("Days"); } QString TimePeriod::i18n_weeks() { return i18n("weeks"); } QString TimePeriod::i18n_Weeks() { return i18n("Weeks"); } static const int maxMinutes = 100*60-1; // absolute maximum value for hours:minutes = 99H59M /*============================================================================= = Class TimePeriod = Contains a time unit combo box, plus a time spinbox, to select a time period. =============================================================================*/ TimePeriod::TimePeriod(bool allowHourMinute, QWidget* parent, const char* name) : QHBox(parent, name), mMaxDays(9999), mNoHourMinute(!allowHourMinute), mReadOnly(false) { setSpacing(KDialog::spacingHint()); mSpinStack = new QWidgetStack(this); mSpinBox = new SpinBox(mSpinStack); mSpinBox->setLineStep(1); mSpinBox->setLineShiftStep(10); mSpinBox->setRange(1, mMaxDays); connect(mSpinBox, SIGNAL(valueChanged(int)), SLOT(slotDaysChanged(int))); mSpinStack->addWidget(mSpinBox, 0); mTimeSpinBox = new TimeSpinBox(0, 99999, mSpinStack); mTimeSpinBox->setRange(1, maxMinutes); // max 99H59M connect(mTimeSpinBox, SIGNAL(valueChanged(int)), SLOT(slotTimeChanged(int))); mSpinStack->addWidget(mTimeSpinBox, 1); mSpinStack->setFixedSize(mSpinBox->sizeHint().expandedTo(mTimeSpinBox->sizeHint())); mHourMinuteRaised = mNoHourMinute; showHourMin(!mNoHourMinute); mUnitsCombo = new ComboBox(false, this); if (mNoHourMinute) mDateOnlyOffset = 1; else { mDateOnlyOffset = 0; mUnitsCombo->insertItem(i18n_hours_mins()); } mUnitsCombo->insertItem(i18n_days()); mUnitsCombo->insertItem(i18n_weeks()); mMaxUnitShown = WEEKS; mUnitsCombo->setFixedSize(mUnitsCombo->sizeHint()); connect(mUnitsCombo, SIGNAL(activated(int)), SLOT(slotUnitsSelected(int))); setFocusProxy(mUnitsCombo); setTabOrder(mUnitsCombo, mSpinStack); } void TimePeriod::setReadOnly(bool ro) { if (ro != mReadOnly) { mReadOnly = ro; mSpinBox->setReadOnly(ro); mTimeSpinBox->setReadOnly(ro); mUnitsCombo->setReadOnly(ro); } } /****************************************************************************** * Set whether the editor text is to be selected whenever spin buttons are * clicked. Default is to select them. */ void TimePeriod::setSelectOnStep(bool sel) { mSpinBox->setSelectOnStep(sel); mTimeSpinBox->setSelectOnStep(sel); } /****************************************************************************** * Set the input focus on the count field. */ void TimePeriod::setFocusOnCount() { mSpinStack->setFocus(); } /****************************************************************************** * Set the maximum values for the hours:minutes and days/weeks spinboxes. * If 'hourmin' = 0, the hours:minutes maximum is left unchanged. */ void TimePeriod::setMaximum(int hourmin, int days) { int oldmins = minutes(); if (hourmin > 0) { if (hourmin > maxMinutes) hourmin = maxMinutes; mTimeSpinBox->setRange(1, hourmin); } mMaxDays = (days >= 0) ? days : 0; adjustDayWeekShown(); setUnitRange(); int mins = minutes(); if (mins != oldmins) emit valueChanged(mins); } /****************************************************************************** * Get the specified number of minutes. * Reply = 0 if error. */ int TimePeriod::minutes() const { switch (mUnitsCombo->currentItem() + mDateOnlyOffset) { case HOURS_MINUTES: return mTimeSpinBox->value(); case DAYS: return mSpinBox->value() * 24*60; case WEEKS: return mSpinBox->value() * 7*24*60; } return 0; } /****************************************************************************** * Initialise the controls with a specified time period. * The time unit combo-box is initialised to 'defaultUnits', but if 'dateOnly' * is true, it will never be initialised to hours/minutes. */ void TimePeriod::setMinutes(int mins, bool dateOnly, TimePeriod::Units defaultUnits) { int oldmins = minutes(); if (!dateOnly && mNoHourMinute) dateOnly = true; int item; if (mins) { int count = mins; if (mins % (24*60)) item = HOURS_MINUTES; else if (mins % (7*24*60)) { item = DAYS; count = mins / (24*60); } else { item = WEEKS; count = mins / (7*24*60); } if (item < mDateOnlyOffset) item = mDateOnlyOffset; else if (item > mMaxUnitShown) item = mMaxUnitShown; mUnitsCombo->setCurrentItem(item - mDateOnlyOffset); if (item == HOURS_MINUTES) mTimeSpinBox->setValue(count); else mSpinBox->setValue(count); item = setDateOnly(mins, dateOnly, false); } else { item = defaultUnits; if (item < mDateOnlyOffset) item = mDateOnlyOffset; else if (item > mMaxUnitShown) item = mMaxUnitShown; mUnitsCombo->setCurrentItem(item - mDateOnlyOffset); if (dateOnly && !mDateOnlyOffset || !dateOnly && mDateOnlyOffset) item = setDateOnly(mins, dateOnly, false); } showHourMin(item == HOURS_MINUTES && !mNoHourMinute); int newmins = minutes(); if (newmins != oldmins) emit valueChanged(newmins); } /****************************************************************************** * Enable/disable hours/minutes units (if hours/minutes were permitted in the * constructor). */ TimePeriod::Units TimePeriod::setDateOnly(int mins, bool dateOnly, bool signal) { int oldmins; if (signal) oldmins = minutes(); int index = mUnitsCombo->currentItem(); Units units = static_cast<Units>(index + mDateOnlyOffset); if (!mNoHourMinute) { if (!dateOnly && mDateOnlyOffset) { // Change from date-only to allow hours/minutes mUnitsCombo->insertItem(i18n_hours_mins(), 0); mDateOnlyOffset = 0; adjustDayWeekShown(); mUnitsCombo->setCurrentItem(++index); } else if (dateOnly && !mDateOnlyOffset) { // Change from allowing hours/minutes to date-only mUnitsCombo->removeItem(0); mDateOnlyOffset = 1; if (index) --index; adjustDayWeekShown(); mUnitsCombo->setCurrentItem(index); if (units == HOURS_MINUTES) { // Set units to days and round up the warning period units = DAYS; mUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset); mSpinBox->setValue((mins + 1439) / 1440); } showHourMin(false); } } if (signal) { int newmins = minutes(); if (newmins != oldmins) emit valueChanged(newmins); } return units; } /****************************************************************************** * Adjust the days/weeks units shown to suit the maximum days limit. */ void TimePeriod::adjustDayWeekShown() { Units newMaxUnitShown = (mMaxDays >= 7) ? WEEKS : (mMaxDays || mDateOnlyOffset) ? DAYS : HOURS_MINUTES; if (newMaxUnitShown > mMaxUnitShown) { if (mMaxUnitShown < DAYS) mUnitsCombo->insertItem(i18n_days()); if (newMaxUnitShown == WEEKS) mUnitsCombo->insertItem(i18n_weeks()); } else if (newMaxUnitShown < mMaxUnitShown) { if (mMaxUnitShown == WEEKS) mUnitsCombo->removeItem(WEEKS - mDateOnlyOffset); if (newMaxUnitShown < DAYS) mUnitsCombo->removeItem(DAYS - mDateOnlyOffset); } mMaxUnitShown = newMaxUnitShown; } /****************************************************************************** * Set the maximum value which may be entered into the day/week count field, * depending on the current unit selection. */ void TimePeriod::setUnitRange() { int maxval; switch (static_cast<Units>(mUnitsCombo->currentItem() + mDateOnlyOffset)) { case WEEKS: maxval = mMaxDays / 7; if (maxval) break; mUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset); // fall through to DAYS case DAYS: maxval = mMaxDays ? mMaxDays : 1; break; case HOURS_MINUTES: default: return; } mSpinBox->setRange(1, maxval); } /****************************************************************************** * Called when a new item is made current in the time units combo box. */ void TimePeriod::slotUnitsSelected(int index) { setUnitRange(); showHourMin(index + mDateOnlyOffset == HOURS_MINUTES); emit valueChanged(minutes()); } /****************************************************************************** * Called when the value of the days/weeks spin box changes. */ void TimePeriod::slotDaysChanged(int) { if (!mHourMinuteRaised) emit valueChanged(minutes()); } /****************************************************************************** * Called when the value of the time spin box changes. */ void TimePeriod::slotTimeChanged(int value) { if (mHourMinuteRaised) emit valueChanged(value); } /****************************************************************************** * Set the currently displayed count widget. */ void TimePeriod::showHourMin(bool hourMinute) { if (hourMinute != mHourMinuteRaised) { mHourMinuteRaised = hourMinute; if (hourMinute) { mSpinStack->raiseWidget(mTimeSpinBox); mSpinStack->setFocusProxy(mTimeSpinBox); } else { mSpinStack->raiseWidget(mSpinBox); mSpinStack->setFocusProxy(mSpinBox); } } } /****************************************************************************** * Set separate WhatsThis texts for the count spinboxes and the units combobox. * If the hours:minutes text is omitted, both spinboxes are set to the same * WhatsThis text. */ void TimePeriod::setWhatsThis(const QString& units, const QString& dayWeek, const QString& hourMin) { QWhatsThis::add(mUnitsCombo, units); QWhatsThis::add(mSpinBox, dayWeek); QWhatsThis::add(mTimeSpinBox, (hourMin.isNull() ? dayWeek : hourMin)); } <commit_msg>Fix compile warning<commit_after>/* * timeperiod.h - time period data entry widget * Program: kalarm * (C) 2003, 2004 by David Jarvie <software@astrojar.org.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "kalarm.h" #include <qwidgetstack.h> #include <qwhatsthis.h> #include <klocale.h> #include <kdialog.h> #include "combobox.h" #include "spinbox.h" #include "timespinbox.h" #include "timeperiod.moc" // Collect these widget labels together to ensure consistent wording and // translations across different modules. QString TimePeriod::i18n_hours_mins() { return i18n("hours/minutes"); } QString TimePeriod::i18n_Hours_Mins() { return i18n("Hours/Minutes"); } QString TimePeriod::i18n_days() { return i18n("days"); } QString TimePeriod::i18n_Days() { return i18n("Days"); } QString TimePeriod::i18n_weeks() { return i18n("weeks"); } QString TimePeriod::i18n_Weeks() { return i18n("Weeks"); } static const int maxMinutes = 100*60-1; // absolute maximum value for hours:minutes = 99H59M /*============================================================================= = Class TimePeriod = Contains a time unit combo box, plus a time spinbox, to select a time period. =============================================================================*/ TimePeriod::TimePeriod(bool allowHourMinute, QWidget* parent, const char* name) : QHBox(parent, name), mMaxDays(9999), mNoHourMinute(!allowHourMinute), mReadOnly(false) { setSpacing(KDialog::spacingHint()); mSpinStack = new QWidgetStack(this); mSpinBox = new SpinBox(mSpinStack); mSpinBox->setLineStep(1); mSpinBox->setLineShiftStep(10); mSpinBox->setRange(1, mMaxDays); connect(mSpinBox, SIGNAL(valueChanged(int)), SLOT(slotDaysChanged(int))); mSpinStack->addWidget(mSpinBox, 0); mTimeSpinBox = new TimeSpinBox(0, 99999, mSpinStack); mTimeSpinBox->setRange(1, maxMinutes); // max 99H59M connect(mTimeSpinBox, SIGNAL(valueChanged(int)), SLOT(slotTimeChanged(int))); mSpinStack->addWidget(mTimeSpinBox, 1); mSpinStack->setFixedSize(mSpinBox->sizeHint().expandedTo(mTimeSpinBox->sizeHint())); mHourMinuteRaised = mNoHourMinute; showHourMin(!mNoHourMinute); mUnitsCombo = new ComboBox(false, this); if (mNoHourMinute) mDateOnlyOffset = 1; else { mDateOnlyOffset = 0; mUnitsCombo->insertItem(i18n_hours_mins()); } mUnitsCombo->insertItem(i18n_days()); mUnitsCombo->insertItem(i18n_weeks()); mMaxUnitShown = WEEKS; mUnitsCombo->setFixedSize(mUnitsCombo->sizeHint()); connect(mUnitsCombo, SIGNAL(activated(int)), SLOT(slotUnitsSelected(int))); setFocusProxy(mUnitsCombo); setTabOrder(mUnitsCombo, mSpinStack); } void TimePeriod::setReadOnly(bool ro) { if (ro != mReadOnly) { mReadOnly = ro; mSpinBox->setReadOnly(ro); mTimeSpinBox->setReadOnly(ro); mUnitsCombo->setReadOnly(ro); } } /****************************************************************************** * Set whether the editor text is to be selected whenever spin buttons are * clicked. Default is to select them. */ void TimePeriod::setSelectOnStep(bool sel) { mSpinBox->setSelectOnStep(sel); mTimeSpinBox->setSelectOnStep(sel); } /****************************************************************************** * Set the input focus on the count field. */ void TimePeriod::setFocusOnCount() { mSpinStack->setFocus(); } /****************************************************************************** * Set the maximum values for the hours:minutes and days/weeks spinboxes. * If 'hourmin' = 0, the hours:minutes maximum is left unchanged. */ void TimePeriod::setMaximum(int hourmin, int days) { int oldmins = minutes(); if (hourmin > 0) { if (hourmin > maxMinutes) hourmin = maxMinutes; mTimeSpinBox->setRange(1, hourmin); } mMaxDays = (days >= 0) ? days : 0; adjustDayWeekShown(); setUnitRange(); int mins = minutes(); if (mins != oldmins) emit valueChanged(mins); } /****************************************************************************** * Get the specified number of minutes. * Reply = 0 if error. */ int TimePeriod::minutes() const { switch (mUnitsCombo->currentItem() + mDateOnlyOffset) { case HOURS_MINUTES: return mTimeSpinBox->value(); case DAYS: return mSpinBox->value() * 24*60; case WEEKS: return mSpinBox->value() * 7*24*60; } return 0; } /****************************************************************************** * Initialise the controls with a specified time period. * The time unit combo-box is initialised to 'defaultUnits', but if 'dateOnly' * is true, it will never be initialised to hours/minutes. */ void TimePeriod::setMinutes(int mins, bool dateOnly, TimePeriod::Units defaultUnits) { int oldmins = minutes(); if (!dateOnly && mNoHourMinute) dateOnly = true; int item; if (mins) { int count = mins; if (mins % (24*60)) item = HOURS_MINUTES; else if (mins % (7*24*60)) { item = DAYS; count = mins / (24*60); } else { item = WEEKS; count = mins / (7*24*60); } if (item < mDateOnlyOffset) item = mDateOnlyOffset; else if (item > mMaxUnitShown) item = mMaxUnitShown; mUnitsCombo->setCurrentItem(item - mDateOnlyOffset); if (item == HOURS_MINUTES) mTimeSpinBox->setValue(count); else mSpinBox->setValue(count); item = setDateOnly(mins, dateOnly, false); } else { item = defaultUnits; if (item < mDateOnlyOffset) item = mDateOnlyOffset; else if (item > mMaxUnitShown) item = mMaxUnitShown; mUnitsCombo->setCurrentItem(item - mDateOnlyOffset); if (dateOnly && !mDateOnlyOffset || !dateOnly && mDateOnlyOffset) item = setDateOnly(mins, dateOnly, false); } showHourMin(item == HOURS_MINUTES && !mNoHourMinute); int newmins = minutes(); if (newmins != oldmins) emit valueChanged(newmins); } /****************************************************************************** * Enable/disable hours/minutes units (if hours/minutes were permitted in the * constructor). */ TimePeriod::Units TimePeriod::setDateOnly(int mins, bool dateOnly, bool signal) { int oldmins = 0; if (signal) oldmins = minutes(); int index = mUnitsCombo->currentItem(); Units units = static_cast<Units>(index + mDateOnlyOffset); if (!mNoHourMinute) { if (!dateOnly && mDateOnlyOffset) { // Change from date-only to allow hours/minutes mUnitsCombo->insertItem(i18n_hours_mins(), 0); mDateOnlyOffset = 0; adjustDayWeekShown(); mUnitsCombo->setCurrentItem(++index); } else if (dateOnly && !mDateOnlyOffset) { // Change from allowing hours/minutes to date-only mUnitsCombo->removeItem(0); mDateOnlyOffset = 1; if (index) --index; adjustDayWeekShown(); mUnitsCombo->setCurrentItem(index); if (units == HOURS_MINUTES) { // Set units to days and round up the warning period units = DAYS; mUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset); mSpinBox->setValue((mins + 1439) / 1440); } showHourMin(false); } } if (signal) { int newmins = minutes(); if (newmins != oldmins) emit valueChanged(newmins); } return units; } /****************************************************************************** * Adjust the days/weeks units shown to suit the maximum days limit. */ void TimePeriod::adjustDayWeekShown() { Units newMaxUnitShown = (mMaxDays >= 7) ? WEEKS : (mMaxDays || mDateOnlyOffset) ? DAYS : HOURS_MINUTES; if (newMaxUnitShown > mMaxUnitShown) { if (mMaxUnitShown < DAYS) mUnitsCombo->insertItem(i18n_days()); if (newMaxUnitShown == WEEKS) mUnitsCombo->insertItem(i18n_weeks()); } else if (newMaxUnitShown < mMaxUnitShown) { if (mMaxUnitShown == WEEKS) mUnitsCombo->removeItem(WEEKS - mDateOnlyOffset); if (newMaxUnitShown < DAYS) mUnitsCombo->removeItem(DAYS - mDateOnlyOffset); } mMaxUnitShown = newMaxUnitShown; } /****************************************************************************** * Set the maximum value which may be entered into the day/week count field, * depending on the current unit selection. */ void TimePeriod::setUnitRange() { int maxval; switch (static_cast<Units>(mUnitsCombo->currentItem() + mDateOnlyOffset)) { case WEEKS: maxval = mMaxDays / 7; if (maxval) break; mUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset); // fall through to DAYS case DAYS: maxval = mMaxDays ? mMaxDays : 1; break; case HOURS_MINUTES: default: return; } mSpinBox->setRange(1, maxval); } /****************************************************************************** * Called when a new item is made current in the time units combo box. */ void TimePeriod::slotUnitsSelected(int index) { setUnitRange(); showHourMin(index + mDateOnlyOffset == HOURS_MINUTES); emit valueChanged(minutes()); } /****************************************************************************** * Called when the value of the days/weeks spin box changes. */ void TimePeriod::slotDaysChanged(int) { if (!mHourMinuteRaised) emit valueChanged(minutes()); } /****************************************************************************** * Called when the value of the time spin box changes. */ void TimePeriod::slotTimeChanged(int value) { if (mHourMinuteRaised) emit valueChanged(value); } /****************************************************************************** * Set the currently displayed count widget. */ void TimePeriod::showHourMin(bool hourMinute) { if (hourMinute != mHourMinuteRaised) { mHourMinuteRaised = hourMinute; if (hourMinute) { mSpinStack->raiseWidget(mTimeSpinBox); mSpinStack->setFocusProxy(mTimeSpinBox); } else { mSpinStack->raiseWidget(mSpinBox); mSpinStack->setFocusProxy(mSpinBox); } } } /****************************************************************************** * Set separate WhatsThis texts for the count spinboxes and the units combobox. * If the hours:minutes text is omitted, both spinboxes are set to the same * WhatsThis text. */ void TimePeriod::setWhatsThis(const QString& units, const QString& dayWeek, const QString& hourMin) { QWhatsThis::add(mUnitsCombo, units); QWhatsThis::add(mSpinBox, dayWeek); QWhatsThis::add(mTimeSpinBox, (hourMin.isNull() ? dayWeek : hourMin)); } <|endoftext|>
<commit_before>/* -*- mode:C++; -*- */ /* MIT License -- MyThOS: The Many-Threads Operating System * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright 2014 Randolf Rotta, Maik Krüger, and contributors, BTU Cottbus-Senftenberg */ #include "cpu/LAPIC.hh" #include "cpu/hwthread_pause.hh" #include "cpu/ctrlregs.hh" #include "boot/mlog.hh" #include "util/assert.hh" namespace mythos { LAPIC lapic; void LAPIC::init() { MLOG_DETAIL(mlog::boot, "initializing local xAPIC"); Register value; // init the Destination Format Register and the Logical // Destination Register Intel recommends to set DFR, LDR and TPR // before enabling an APIC. See e.g. "AP-388 82489DX User's // Manual" (Intel document number 292116). value = read(REG_DFR); MLOG_DETAIL(mlog::boot, "APIC DFR", DVARhex(value.value)); value.model = 0xF; // flat mode write(REG_DFR, value); value = read(REG_LDR); MLOG_DETAIL(mlog::boot, "APIC LDR", DVARhex(value.value)); value.destination = 1; // will not be used anyway write(REG_LDR, value); // init the local interrupt sources // all of them should be in invalid state anyway value.value = 0; value.masked = 1; write(REG_LVT_TIMER, value); write(REG_LVT_THERMAL, value); write(REG_LVT_PERFCNT, value); write(REG_LVT_LINT0, value); write(REG_LVT_LINT1, value); write(REG_LVT_ERROR, value); // enable all interrupts by task priority 0 // see 10.8.6 Task Priority in IA-32e Mode // Loading the TPR with a task-priority class of 0 enables all external interrupts. // Loading the TPR with a task-priority class of 0FH (01111B) disables all external interrupts. // In 64-bit mode, software can read and write the TPR using the MOV CR8 instruction. value = read(REG_TASK_PRIO); value.task_prio_sub = 0; value.task_prio = 0; write(REG_TASK_PRIO, value); // After a crash, interrupts from previous run can still have ISR bit set. // Thus clear these with EndOfInterrupt. size_t queued = 0; for (size_t loops=0; loops<1000000; loops++) { for (size_t i=0; i<0x8; i++) queued |= read(REG_IRR + i*0x10).value; if (!queued) break; for (size_t i=0; i<0x8; i++) { value = read(REG_ISR + i*0x10); for (size_t j=0; j<32; j++) { if (value.value & (1<<j)) endOfInterrupt(); } } } // init the Spurious Interrupt Vector Register for handling local interrupt sources // after the reset SPURINT == 0xFF, setting bit 8 enables the APIC, for example 0x100 // the lowest 4 bits should be 0, the vector should be above 32 (processor internal interrupts) // but the acutal value does not matter, because it is configured for each separately... value = read(REG_SVR); MLOG_DETAIL(mlog::boot, "SVR before init", reinterpret_cast<void*>(value.value)); value.vector = 0xFF; // this interrupt should never be triggered anyway value.apic_enable = 1; value.focus_processor_checking = 0; value.eio_suppression = 0; MLOG_DETAIL(mlog::boot, "SVR writing", reinterpret_cast<void*>(value.value)); write(REG_SVR, value); MLOG_DETAIL(mlog::boot, "SVR after init", reinterpret_cast<void*>(read(REG_SVR).value)); MLOG_DETAIL(mlog::boot, "lapic", DVAR(x86::initialApicID()), DVAR(getId())); ASSERT(getId() == x86::initialApicID()); // init Error register write(REG_ESR, 0); read(REG_ESR); // Due to the Pentium erratum 3AP. value = read(REG_LVT_ERROR); value.vector = 0xFF; // should never happen because we leave it masked value.masked = 1; write(REG_LVT_ERROR, value); // spec says clear errors after enabling vector. write(REG_ESR, 0); read(REG_ESR); // Due to the Pentium erratum 3AP. } void LAPIC::enablePeriodicTimer(uint8_t irq, uint32_t count) { MLOG_INFO(mlog::boot, "enable periodic APIC timer", DVAR(irq), DVAR(count)); write(REG_TIMER_DCR, 0x0b); // divide bus clock by 0xa=128 or 0xb=1 setInitialCount(count); write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(PERIODIC).masked(0).vector(irq)); } void LAPIC::disableTimer() { MLOG_INFO(mlog::boot, "disable APIC timer"); write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(ONESHOT).masked(1).vector(0)); } bool LAPIC::broadcastInitIPIEdge() { write(REG_ESR, 0); // Be paranoid about clearing APIC errors. read(REG_ESR); writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_INIT, 0)); //hwthread_wait(10000); return true; } bool LAPIC::broadcastStartupIPI(size_t startIP) { ASSERT((startIP & 0x0FFF) == 0 && ((startIP>>12)>>8) == 0); write(REG_ESR, 0); // Be paranoid about clearing APIC errors. read(REG_ESR); writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_SIPI, uint8_t(startIP >> 12))); write(REG_ESR, 0); // Be paranoid about clearing APIC errors. uint32_t esr = read(REG_ESR).value & 0xEF; MLOG_DETAIL(mlog::boot, "SIPI broadcast result", DVARhex(esr)); return true; } bool LAPIC::sendNMI(size_t destination) { write(REG_ESR, 0); // Be paranoid about clearing APIC errors. read(REG_ESR); writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_NMI, 0)); write(REG_ESR, 0); // Be paranoid about clearing APIC errors. return true; } bool LAPIC::sendIRQ(size_t destination, uint8_t vector) { MLOG_INFO(mlog::boot, "send IRQ:", DVAR(destination), DVAR(vector)); //write(REG_ESR, 0); // Be paranoid about clearing APIC errors. //read(REG_ESR); writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_FIXED, vector)); //write(REG_ESR, 0); // Be paranoid about clearing APIC errors. return true; } void LAPIC::writeIPI(size_t destination, Register icrlow) { ASSERT(destination<256); MLOG_DETAIL(mlog::boot, "write ICR", DVAR(destination), DVARhex(icrlow.value)); while(read(REG_ICR_LOW).delivery_pending) hwthread_pause(); write(REG_ICR_HIGH, Register().destination(destination)); write(REG_ICR_LOW, icrlow); } } // namespace mythos <commit_msg>Quick fix and documentation.<commit_after>/* -*- mode:C++; -*- */ /* MIT License -- MyThOS: The Many-Threads Operating System * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright 2014 Randolf Rotta, Maik Krüger, and contributors, BTU Cottbus-Senftenberg */ #include "cpu/LAPIC.hh" #include "cpu/hwthread_pause.hh" #include "cpu/ctrlregs.hh" #include "boot/mlog.hh" #include "util/assert.hh" namespace mythos { LAPIC lapic; void LAPIC::init() { MLOG_DETAIL(mlog::boot, "initializing local xAPIC"); Register value; // init the Destination Format Register and the Logical // Destination Register Intel recommends to set DFR, LDR and TPR // before enabling an APIC. See e.g. "AP-388 82489DX User's // Manual" (Intel document number 292116). value = read(REG_DFR); MLOG_DETAIL(mlog::boot, "APIC DFR", DVARhex(value.value)); value.model = 0xF; // flat mode write(REG_DFR, value); value = read(REG_LDR); MLOG_DETAIL(mlog::boot, "APIC LDR", DVARhex(value.value)); value.destination = 1; // will not be used anyway write(REG_LDR, value); // init the local interrupt sources // all of them should be in invalid state anyway value.value = 0; value.masked = 1; write(REG_LVT_TIMER, value); write(REG_LVT_THERMAL, value); write(REG_LVT_PERFCNT, value); write(REG_LVT_LINT0, value); write(REG_LVT_LINT1, value); write(REG_LVT_ERROR, value); // enable all interrupts by task priority 0 // see 10.8.6 Task Priority in IA-32e Mode // Loading the TPR with a task-priority class of 0 enables all external interrupts. // Loading the TPR with a task-priority class of 0FH (01111B) disables all external interrupts. // In 64-bit mode, software can read and write the TPR using the MOV CR8 instruction. value = read(REG_TASK_PRIO); value.task_prio_sub = 0; value.task_prio = 0; write(REG_TASK_PRIO, value); // After a crash, interrupts from previous run can still have ISR bit set. // Thus clear these with EndOfInterrupt. size_t queued = 0; for (size_t loops=0; loops<1000000; loops++) { for (size_t i=0; i<0x8; i++) queued |= read(REG_IRR + i*0x10).value; if (!queued) break; for (size_t i=0; i<0x8; i++) { value = read(REG_ISR + i*0x10); for (size_t j=0; j<32; j++) { if (value.value & (1<<j)) endOfInterrupt(); } } } // init the Spurious Interrupt Vector Register for handling local interrupt sources // after the reset SPURINT == 0xFF, setting bit 8 enables the APIC, for example 0x100 // the lowest 4 bits should be 0, the vector should be above 32 (processor internal interrupts) // but the acutal value does not matter, because it is configured for each separately... value = read(REG_SVR); MLOG_DETAIL(mlog::boot, "SVR before init", reinterpret_cast<void*>(value.value)); value.vector = 0xFF; // this interrupt should never be triggered anyway value.apic_enable = 1; value.focus_processor_checking = 0; value.eio_suppression = 0; MLOG_DETAIL(mlog::boot, "SVR writing", reinterpret_cast<void*>(value.value)); write(REG_SVR, value); MLOG_DETAIL(mlog::boot, "SVR after init", reinterpret_cast<void*>(read(REG_SVR).value)); MLOG_DETAIL(mlog::boot, "lapic", DVAR(x86::initialApicID()), DVAR(getId())); ASSERT(getId() == x86::initialApicID()); // init Error register write(REG_ESR, 0); read(REG_ESR); // Due to the Pentium erratum 3AP. value = read(REG_LVT_ERROR); value.vector = 0xFF; // should never happen because we leave it masked value.masked = 1; write(REG_LVT_ERROR, value); // spec says clear errors after enabling vector. write(REG_ESR, 0); read(REG_ESR); // Due to the Pentium erratum 3AP. } void LAPIC::enablePeriodicTimer(uint8_t irq, uint32_t count) { MLOG_INFO(mlog::boot, "enable periodic APIC timer", DVAR(irq), DVAR(count)); write(REG_TIMER_DCR, 0x0b); // divide bus clock by 0xa=128 or 0xb=1 setInitialCount(count); write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(PERIODIC).masked(0).vector(irq)); } void LAPIC::disableTimer() { MLOG_INFO(mlog::boot, "disable APIC timer"); write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(ONESHOT).masked(1).vector(0)); } bool LAPIC::broadcastInitIPIEdge() { write(REG_ESR, 0); // Be paranoid about clearing APIC errors. read(REG_ESR); writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_INIT, 0)); /** * This delay must happen between `broadcastInitIPIEdge` and * `broadcastStartupIPI` in order for all hardware threads to * start on the real hardware (KNC). * * @todo How long should this delay be for a given architecture. * @todo Move the delay out of this low level function. */ hwthread_wait(10000); return true; } bool LAPIC::broadcastStartupIPI(size_t startIP) { ASSERT((startIP & 0x0FFF) == 0 && ((startIP>>12)>>8) == 0); write(REG_ESR, 0); // Be paranoid about clearing APIC errors. read(REG_ESR); writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_SIPI, uint8_t(startIP >> 12))); write(REG_ESR, 0); // Be paranoid about clearing APIC errors. uint32_t esr = read(REG_ESR).value & 0xEF; MLOG_DETAIL(mlog::boot, "SIPI broadcast result", DVARhex(esr)); return true; } bool LAPIC::sendNMI(size_t destination) { write(REG_ESR, 0); // Be paranoid about clearing APIC errors. read(REG_ESR); writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_NMI, 0)); write(REG_ESR, 0); // Be paranoid about clearing APIC errors. return true; } bool LAPIC::sendIRQ(size_t destination, uint8_t vector) { MLOG_INFO(mlog::boot, "send IRQ:", DVAR(destination), DVAR(vector)); //write(REG_ESR, 0); // Be paranoid about clearing APIC errors. //read(REG_ESR); writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_FIXED, vector)); //write(REG_ESR, 0); // Be paranoid about clearing APIC errors. return true; } void LAPIC::writeIPI(size_t destination, Register icrlow) { ASSERT(destination<256); MLOG_DETAIL(mlog::boot, "write ICR", DVAR(destination), DVARhex(icrlow.value)); while(read(REG_ICR_LOW).delivery_pending) hwthread_pause(); write(REG_ICR_HIGH, Register().destination(destination)); write(REG_ICR_LOW, icrlow); } } // namespace mythos <|endoftext|>
<commit_before>// This file is part of BlueSky // // BlueSky is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // BlueSky is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BlueSky; if not, see <http://www.gnu.org/licenses/>. // // C++ Implementation: bs_kernel_ston // // Description: // // // Author: Гагарин Александр Владимирович <GagarinAV@ufanipi.ru>, (C) 2008 // #include "bs_kernel.h" #include "thread_pool.h" #include "bs_report.h" #include "bs_log_scribers.h" //#define LOKI_CLASS_LEVEL_THREADING #include "loki/Singleton.h" using namespace Loki; using namespace std; namespace blue_sky { namespace bs_private { static bool kernel_alive = false; /*----------------------------------------------------------------------------- * Specific logging system wrappers *-----------------------------------------------------------------------------*/ struct bs_log_wrapper : public bs_log { bs_log_wrapper () { if (kernel_alive) { register_signals (); } this->add_channel (sp_channel (new bs_channel (OUT_LOG))); this->add_channel (sp_channel (new bs_channel (ERR_LOG))); char *c_dir = NULL; if (!(c_dir = getenv("BS_KERNEL_DIR"))) c_dir = (char *)"."; this->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber)); this->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string("/blue_sky.log"), ios::out|ios::app))); this->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber)); this->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string("/errors.log"), ios::out|ios::app))); this->get_locked (OUT_LOG) << output_time; this->get_locked (ERR_LOG) << output_time; } //static bool & //kernel_dead () //{ // static bool kernel_dead_ = false; // return kernel_dead_; //} bs_log & get_log () { return *this; } void register_signals () { this->add_signal (BS_SIGNAL_RANGE (bs_log)); } }; struct thread_log_wrapper : public thread_log { thread_log_wrapper () { } thread_log & get_log () { return *this; } void register_signals () { } //static bool & //kernel_dead () //{ // static bool kernel_dead_ = false; // return kernel_dead_; //} }; /// @brief Wrapper allowing to do some initialization on first give_kernel()::Instance() call /// just after the kernel class is created struct wrapper_kernel { kernel* k_; kernel& (wrapper_kernel::*ref_fun_)(); // constructor wrapper_kernel() : k_(new kernel), ref_fun_(&wrapper_kernel::initial_kernel_getter) { kernel_alive = true; } // normal getter - just returns kernel reference kernel& usual_kernel_getter() { return *k_; } // when kernel reference is obtained for the first time kernel& initial_kernel_getter() { // first switch to usual getter to avoid infinite constructor recursion during load_plugins() ref_fun_ = &wrapper_kernel::usual_kernel_getter; // initialize kernel k_->init(); #ifdef BS_AUTOLOAD_PLUGINS // load plugins k_->LoadPlugins(); #endif // return reference return *k_; } kernel& k_ref() { return (this->*ref_fun_)(); } ~wrapper_kernel() { // force kernel destruction delete k_; // signal that it is destroyed kernel_alive = false; //bs_log_wrapper::kernel_dead () = true; //thread_log_wrapper::kernel_dead () = true; } // kernel& k_ref() { // return k_; // } }; typedef SingletonHolder < bs_log_wrapper, CreateUsingNew, PhoenixSingleton > bs_log_holder; typedef SingletonHolder < thread_log_wrapper, CreateUsingNew, PhoenixSingleton > thread_log_holder; } // namespace bs_private /*----------------------------------------------------------------------------- * kernel signleton instantiation *-----------------------------------------------------------------------------*/ //! multithreaded kernel singleton - disables //typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew, // DefaultLifetime, ClassLevelLockable > kernel_holder; // kernel itself is fully multithreaded so we can use simple singleton // typedef SingletonHolder< bs_private::wrapper_kernel > kernel_holder; //kernel singletone - master, fabs die after kernel dies typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew, FollowIntoDeath::With< DefaultLifetime >::AsMasterLifetime > kernel_holder; template< > BS_API kernel& singleton< kernel >::Instance() { //cout << "give_kernel.Instance() entered" << endl; return kernel_holder::Instance().k_ref(); } //! thread pool singleton typedef SingletonHolder< blue_sky::worker_thread_pool, CreateUsingNew, FollowIntoDeath::AfterMaster< kernel_holder >::IsDestroyed > wtp_holder; typedef singleton< worker_thread_pool > give_wtp; template< > worker_thread_pool& singleton< worker_thread_pool >::Instance() { return wtp_holder::Instance(); } // void kernel::add_task(const blue_sky::sp_com& task) // { // give_wtp::Instance().add_command(task); // } /*----------------------------------------------------------------------------- * log singletons instantiation *-----------------------------------------------------------------------------*/ typedef singleton <bs_log> bs_log_singleton; typedef singleton <thread_log> thread_log_singleton; template <> bs_log & singleton <bs_log>::Instance() { return bs_private::bs_log_holder::Instance().get_log (); } template <> thread_log & singleton <thread_log>::Instance () { return bs_private::thread_log_holder::Instance ().get_log (); } bs_log & kernel::get_log () { return bs_log_singleton::Instance (); } thread_log & kernel::get_tlog () { return thread_log_singleton::Instance (); } } // namespace blue_sky <commit_msg>-- Safer and simplier version of commit on 20 Aug 2009<commit_after>// This file is part of BlueSky // // BlueSky is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // BlueSky is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BlueSky; if not, see <http://www.gnu.org/licenses/>. // // C++ Implementation: bs_kernel_ston // // Description: // // // Author: Гагарин Александр Владимирович <GagarinAV@ufanipi.ru>, (C) 2008 // #include "bs_kernel.h" #include "thread_pool.h" #include "bs_report.h" #include "bs_log_scribers.h" //#define LOKI_CLASS_LEVEL_THREADING #include "loki/Singleton.h" using namespace Loki; using namespace std; namespace blue_sky { namespace bs_private { static bool kernel_alive = false; /*----------------------------------------------------------------------------- * Specific logging system wrappers *-----------------------------------------------------------------------------*/ struct bs_log_wrapper : public bs_log { bs_log_wrapper () { if (kernel_alive) { register_signals (); } this->add_channel (sp_channel (new bs_channel (OUT_LOG))); this->add_channel (sp_channel (new bs_channel (ERR_LOG))); char *c_dir = NULL; if (!(c_dir = getenv("BS_KERNEL_DIR"))) c_dir = (char *)"."; this->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber)); this->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string("/blue_sky.log"), ios::out|ios::app))); this->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber)); this->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string("/errors.log"), ios::out|ios::app))); this->get_locked (OUT_LOG) << output_time; this->get_locked (ERR_LOG) << output_time; } //static bool & //kernel_dead () //{ // static bool kernel_dead_ = false; // return kernel_dead_; //} bs_log & get_log () { return *this; } void register_signals () { this->add_signal (BS_SIGNAL_RANGE (bs_log)); } }; struct thread_log_wrapper : public thread_log { thread_log_wrapper () { } thread_log & get_log () { return *this; } void register_signals () { } //static bool & //kernel_dead () //{ // static bool kernel_dead_ = false; // return kernel_dead_; //} }; /// @brief Wrapper allowing to do some initialization on first give_kernel()::Instance() call /// just after the kernel class is created struct wrapper_kernel { kernel k_; kernel& (wrapper_kernel::*ref_fun_)(); // constructor wrapper_kernel() : ref_fun_(&wrapper_kernel::initial_kernel_getter) { kernel_alive = true; } // normal getter - just returns kernel reference kernel& usual_kernel_getter() { return k_; } // when kernel reference is obtained for the first time kernel& initial_kernel_getter() { // first switch to usual getter to avoid infinite constructor recursion during load_plugins() ref_fun_ = &wrapper_kernel::usual_kernel_getter; // initialize kernel k_.init(); #ifdef BS_AUTOLOAD_PLUGINS // load plugins k_.LoadPlugins(); #endif // return reference return k_; } kernel& k_ref() { return (this->*ref_fun_)(); } ~wrapper_kernel() { // signal that it is destroyed kernel_alive = false; //bs_log_wrapper::kernel_dead () = true; //thread_log_wrapper::kernel_dead () = true; } //kernel& k_ref() { // return k_; //} }; typedef SingletonHolder < bs_log_wrapper, CreateUsingNew, PhoenixSingleton > bs_log_holder; typedef SingletonHolder < thread_log_wrapper, CreateUsingNew, PhoenixSingleton > thread_log_holder; } // namespace bs_private /*----------------------------------------------------------------------------- * kernel signleton instantiation *-----------------------------------------------------------------------------*/ //! multithreaded kernel singleton - disables //typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew, // DefaultLifetime, ClassLevelLockable > kernel_holder; // kernel itself is fully multithreaded so we can use simple singleton // typedef SingletonHolder< bs_private::wrapper_kernel > kernel_holder; //kernel singletone - master, fabs die after kernel dies typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew, FollowIntoDeath::With< DefaultLifetime >::AsMasterLifetime > kernel_holder; template< > BS_API kernel& singleton< kernel >::Instance() { //cout << "give_kernel.Instance() entered" << endl; return kernel_holder::Instance().k_ref(); } //! thread pool singleton typedef SingletonHolder< blue_sky::worker_thread_pool, CreateUsingNew, FollowIntoDeath::AfterMaster< kernel_holder >::IsDestroyed > wtp_holder; typedef singleton< worker_thread_pool > give_wtp; template< > worker_thread_pool& singleton< worker_thread_pool >::Instance() { return wtp_holder::Instance(); } // void kernel::add_task(const blue_sky::sp_com& task) // { // give_wtp::Instance().add_command(task); // } /*----------------------------------------------------------------------------- * log singletons instantiation *-----------------------------------------------------------------------------*/ typedef singleton <bs_log> bs_log_singleton; typedef singleton <thread_log> thread_log_singleton; template <> bs_log & singleton <bs_log>::Instance() { return bs_private::bs_log_holder::Instance().get_log (); } template <> thread_log & singleton <thread_log>::Instance () { return bs_private::thread_log_holder::Instance ().get_log (); } bs_log & kernel::get_log () { return bs_log_singleton::Instance (); } thread_log & kernel::get_tlog () { return thread_log_singleton::Instance (); } } // namespace blue_sky <|endoftext|>
<commit_before>/* Copyright 2009 Klarälvdalens Datakonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "importarchivedialog.h" #include "kmfolder.h" #include "folderrequester.h" #include "kmmainwidget.h" #include "importjob.h" #include <kurlrequester.h> #include <klocale.h> #include <kmessagebox.h> #include <qlayout.h> #include <qlabel.h> using namespace KMail; ImportArchiveDialog::ImportArchiveDialog( QWidget *parent ) : KDialog( parent ), mParentWidget( parent ) { setObjectName( "archive_folder_dialog" ); setCaption( i18n( "Archive Folder" ) ); setButtons( Ok|Cancel ); setDefaultButton( Ok ); setModal( true ); QWidget *mainWidget = new QWidget( this ); QGridLayout *mainLayout = new QGridLayout( mainWidget ); mainLayout->setSpacing( KDialog::spacingHint() ); mainLayout->setMargin( KDialog::marginHint() ); setMainWidget( mainWidget ); int row = 0; // TODO: Explaination label // TODO: Use QFormLayout in KDE4 // TODO: better label for "Ok" button QLabel *folderLabel = new QLabel( i18n( "Folder:" ), mainWidget ); mainLayout->addWidget( folderLabel, row, 0 ); mFolderRequester = new FolderRequester( mainWidget ); mFolderRequester->setFolderTree( kmkernel->getKMMainWidget()->mainFolderView() ); mainLayout->addWidget( mFolderRequester, row, 1 ); row++; QLabel *fileNameLabel = new QLabel( i18n( "Archive File:" ), mainWidget ); mainLayout->addWidget( fileNameLabel, row, 0 ); mUrlRequester = new KUrlRequester( mainWidget ); mUrlRequester->setMode( KFile::LocalOnly ); mUrlRequester->setFilter( "*.tar *.zip *.tar.gz *.tar.bz2" ); mainLayout->addWidget( mUrlRequester, row, 1 ); row++; // TODO: what's this, tooltips mainLayout->setColumnStretch( 1, 1 ); mainLayout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding ), row, 0 ); // Make it a bit bigger, else the folder requester cuts off the text too early resize( 500, minimumSize().height() ); } void ImportArchiveDialog::setFolder( KMFolder *defaultFolder ) { mFolderRequester->setFolder( defaultFolder ); } void ImportArchiveDialog::slotOk() { if ( !QFile::exists( mUrlRequester->url().path() ) ) { KMessageBox::information( this, i18n( "Please select an archive file that should be imported." ), i18n( "No archive file selected" ) ); return; } if ( !mFolderRequester->folder() ) { KMessageBox::information( this, i18n( "Please select the folder where the archive should be imported to." ), i18n( "No target folder selected" ) ); return; } // TODO: check if url is empty. or better yet, disable ok button until file is chosen ImportJob *importJob = new KMail::ImportJob( mParentWidget ); importJob->setFile( mUrlRequester->url() ); importJob->setRootFolder( mFolderRequester->folder() ); importJob->start(); accept(); } #include "importarchivedialog.moc" <commit_msg>SVN_MERGE Merged revisions 1048289 via svnmerge from svn+ssh://tmcguire@svn.kde.org/home/kde/branches/kdepim/enterprise4/kdepim<commit_after>/* Copyright 2009 Klarälvdalens Datakonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "importarchivedialog.h" #include "kmfolder.h" #include "folderrequester.h" #include "kmmainwidget.h" #include "importjob.h" #include <kurlrequester.h> #include <klocale.h> #include <kmessagebox.h> #include <qlayout.h> #include <qlabel.h> using namespace KMail; ImportArchiveDialog::ImportArchiveDialog( QWidget *parent ) : KDialog( parent ), mParentWidget( parent ) { setObjectName( "import_archive_dialog" ); setCaption( i18n( "Import Archive" ) ); setButtons( Ok|Cancel ); setDefaultButton( Ok ); setModal( true ); QWidget *mainWidget = new QWidget( this ); QGridLayout *mainLayout = new QGridLayout( mainWidget ); mainLayout->setSpacing( KDialog::spacingHint() ); mainLayout->setMargin( KDialog::marginHint() ); setMainWidget( mainWidget ); int row = 0; // TODO: Explaination label // TODO: Use QFormLayout in KDE4 // TODO: better label for "Ok" button QLabel *folderLabel = new QLabel( i18n( "Folder:" ), mainWidget ); mainLayout->addWidget( folderLabel, row, 0 ); mFolderRequester = new FolderRequester( mainWidget ); mFolderRequester->setFolderTree( kmkernel->getKMMainWidget()->mainFolderView() ); mainLayout->addWidget( mFolderRequester, row, 1 ); row++; QLabel *fileNameLabel = new QLabel( i18n( "Archive File:" ), mainWidget ); mainLayout->addWidget( fileNameLabel, row, 0 ); mUrlRequester = new KUrlRequester( mainWidget ); mUrlRequester->setMode( KFile::LocalOnly ); mUrlRequester->setFilter( "*.tar *.zip *.tar.gz *.tar.bz2" ); mainLayout->addWidget( mUrlRequester, row, 1 ); row++; // TODO: what's this, tooltips mainLayout->setColumnStretch( 1, 1 ); mainLayout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding ), row, 0 ); // Make it a bit bigger, else the folder requester cuts off the text too early resize( 500, minimumSize().height() ); } void ImportArchiveDialog::setFolder( KMFolder *defaultFolder ) { mFolderRequester->setFolder( defaultFolder ); } void ImportArchiveDialog::slotOk() { if ( !QFile::exists( mUrlRequester->url().path() ) ) { KMessageBox::information( this, i18n( "Please select an archive file that should be imported." ), i18n( "No archive file selected" ) ); return; } if ( !mFolderRequester->folder() ) { KMessageBox::information( this, i18n( "Please select the folder where the archive should be imported to." ), i18n( "No target folder selected" ) ); return; } // TODO: check if url is empty. or better yet, disable ok button until file is chosen ImportJob *importJob = new KMail::ImportJob( mParentWidget ); importJob->setFile( mUrlRequester->url() ); importJob->setRootFolder( mFolderRequester->folder() ); importJob->start(); accept(); } #include "importarchivedialog.moc" <|endoftext|>
<commit_before>/* KPilot ** ** Copyright (C) 1998-2001 by Dan Pilone ** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> ** ** This is all of KPilot's config-handling stuff. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. */ /* ** Bug reports and questions can be sent to kde-pim@kde.org */ #include "options.h" #include <stdlib.h> #include <qlineedit.h> #include <qcombobox.h> #include <qcheckbox.h> #include <kstandarddirs.h> #include <kconfig.h> #include <ksimpleconfig.h> #include <kcmdlineargs.h> #include <kmessagebox.h> #include <kglobalsettings.h> #include "kpilotSettings.h" #include "kpilotConfig.h" // This is a number indicating what configuration version // we're dealing with. Whenever new configuration options are // added that make it imperative for the user to take a // look at the configuration of KPilot (for example the // skipDB setting really needs user attention) we can change // (increase) this number. // // /* static */ const uint KPilotConfig::ConfigurationVersion = 443; /* static */ int KPilotConfig::getConfigVersion() { FUNCTIONSETUP; uint version = KPilotSettings::configVersion(); if (version < ConfigurationVersion) { WARNINGKPILOT << "Config file has old version " << version << endl; } else { #ifdef DEBUG DEBUGKPILOT << fname << ": Config file has version " << version << endl; #endif } return version; } /* static */ void KPilotConfig::updateConfigVersion() { FUNCTIONSETUP; KPilotSettings::setConfigVersion( ConfigurationVersion ); } /* static */ QString KPilotConfig::getDefaultDBPath() { FUNCTIONSETUP; QString lastUser = KPilotSettings::userName(); QString dbsubpath = CSL1("kpilot/DBBackup/"); QString defaultDBPath = KGlobal::dirs()-> saveLocation("data", dbsubpath + lastUser + CSL1("/")); return defaultDBPath; } /* static */ int KPilotConfig::getDebugLevel(KCmdLineArgs *p) { FUNCTIONSETUP; if (p) { if (p->isSet("debug")) { debug_level = p->getOption("debug").toInt(); } } return debug_level; } static QFont *thefont = 0L; /* static */ const QFont & KPilotConfig::fixed() { FUNCTIONSETUP; if (!thefont) thefont = new QFont(KGlobalSettings::fixedFont()); return *thefont; } void KPilotConfig::addDirtyDatabase(QString db) { FUNCTIONSETUP; QStringList l(KPilotSettings::dirtyDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setDirtyDatabases(l); } } void KPilotConfig::addAppBlockChangedDatabase(QString db) { QStringList l(KPilotSettings::appBlockChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setAppBlockChangedDatabases(l); } } void KPilotConfig::addFlagsChangedDatabase(QString db) { QStringList l(KPilotSettings::flagsChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setFlagsChangedDatabases(l); } } /* static */ QString KPilotConfig::versionDetails(int fileversion, bool run) { FUNCTIONSETUP; QString s = CSL1("<qt><p>"); s += i18n("The configuration file is outdated."); s += ' '; s += i18n("The configuration file has version %1, while KPilot " "needs version %2.").arg(fileversion).arg(ConfigurationVersion); if (run) { s += ' '; s += i18n("Please run KPilot and check the configuration carefully " "to update the file."); } s += CSL1("</p><p>"); s += i18n("Important changes to watch for are:"); s += ' '; if (fileversion < 440) { s += i18n("Renamed conduits, Kroupware and file installer have " "been made conduits as well."); s += ' '; s += i18n("Conflict resolution is now a global setting."); s += ' '; } if (fileversion < 443) { s += i18n("Changed format of no-backup databases."); s += ' '; } // Insert more recent additions here return s; } /* static */ void KPilotConfig::sorryVersionOutdated(int fileversion) { FUNCTIONSETUP; KMessageBox::detailedSorry(0L, i18n("The configuration file for KPilot is out-of " "date. Please run KPilot to update it."), KPilotConfig::versionDetails(fileversion,true), i18n("Configuration File Out-of Date")); } /* static */ KPilotConfig::RunMode KPilotConfig::interactiveUpdate() { FUNCTIONSETUP; int res = 0; unsigned int fileVersion = KPilotSettings::configVersion(); // FIXME better config handling -> Move the config entries using kconf_update // It's OK if we're already at the required level. if (fileVersion >= KPilotConfig::ConfigurationVersion) { return Normal; } if (0 == fileVersion) // No config file at all { res = KMessageBox::questionYesNoCancel(0L, i18n("KPilot is not configured for use. You may use " "the configuration wizard or the normal configure dialog " "to configure KPilot."), i18n("Not Configured"), KGuiItem(i18n("Use &Wizard")), KGuiItem(i18n("Use &Dialog"))); if (res == KMessageBox::Yes) return WizardAndContinue; if (res == KMessageBox::No) return ConfigureAndContinue; return Cancel; } res = KMessageBox::warningContinueCancel(0L, i18n("The configuration file for KPilot is out-of " "date. KPilot can update some parts of the " "configuration automatically. Do you wish to " "continue?"), i18n("Configuration File Out-of Date")); if (res!=KMessageBox::Continue) return Cancel; DEBUGKPILOT << fname << ": Updating from " << fileVersion << " to " << ConfigurationVersion << endl; KPilotConfig::updateConfigVersion(); KPilotSettings::writeConfig(); return ConfigureAndContinue; } void KPilotConfig::sync() { KPilotSettings::self()->config()->sync(); } <commit_msg>Fix i18n<commit_after>/* KPilot ** ** Copyright (C) 1998-2001 by Dan Pilone ** Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com> ** ** This is all of KPilot's config-handling stuff. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. */ /* ** Bug reports and questions can be sent to kde-pim@kde.org */ #include "options.h" #include <stdlib.h> #include <qlineedit.h> #include <qcombobox.h> #include <qcheckbox.h> #include <kstandarddirs.h> #include <kconfig.h> #include <ksimpleconfig.h> #include <kcmdlineargs.h> #include <kmessagebox.h> #include <kglobalsettings.h> #include "kpilotSettings.h" #include "kpilotConfig.h" // This is a number indicating what configuration version // we're dealing with. Whenever new configuration options are // added that make it imperative for the user to take a // look at the configuration of KPilot (for example the // skipDB setting really needs user attention) we can change // (increase) this number. // // /* static */ const uint KPilotConfig::ConfigurationVersion = 443; /* static */ int KPilotConfig::getConfigVersion() { FUNCTIONSETUP; uint version = KPilotSettings::configVersion(); if (version < ConfigurationVersion) { WARNINGKPILOT << "Config file has old version " << version << endl; } else { #ifdef DEBUG DEBUGKPILOT << fname << ": Config file has version " << version << endl; #endif } return version; } /* static */ void KPilotConfig::updateConfigVersion() { FUNCTIONSETUP; KPilotSettings::setConfigVersion( ConfigurationVersion ); } /* static */ QString KPilotConfig::getDefaultDBPath() { FUNCTIONSETUP; QString lastUser = KPilotSettings::userName(); QString dbsubpath = CSL1("kpilot/DBBackup/"); QString defaultDBPath = KGlobal::dirs()-> saveLocation("data", dbsubpath + lastUser + CSL1("/")); return defaultDBPath; } /* static */ int KPilotConfig::getDebugLevel(KCmdLineArgs *p) { FUNCTIONSETUP; if (p) { if (p->isSet("debug")) { debug_level = p->getOption("debug").toInt(); } } return debug_level; } static QFont *thefont = 0L; /* static */ const QFont & KPilotConfig::fixed() { FUNCTIONSETUP; if (!thefont) thefont = new QFont(KGlobalSettings::fixedFont()); return *thefont; } void KPilotConfig::addDirtyDatabase(QString db) { FUNCTIONSETUP; QStringList l(KPilotSettings::dirtyDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setDirtyDatabases(l); } } void KPilotConfig::addAppBlockChangedDatabase(QString db) { QStringList l(KPilotSettings::appBlockChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setAppBlockChangedDatabases(l); } } void KPilotConfig::addFlagsChangedDatabase(QString db) { QStringList l(KPilotSettings::flagsChangedDatabases()); if (!l.contains(db)) { l.append(db); KPilotSettings::setFlagsChangedDatabases(l); } } /* static */ QString KPilotConfig::versionDetails(int fileversion, bool run) { FUNCTIONSETUP; QString s = CSL1("<qt><p>"); s += i18n("The configuration file is outdated."); s += ' '; s += i18n("The configuration file has version %1, while KPilot " "needs version %2.",fileversion,ConfigurationVersion); if (run) { s += ' '; s += i18n("Please run KPilot and check the configuration carefully " "to update the file."); } s += CSL1("</p><p>"); s += i18n("Important changes to watch for are:"); s += ' '; if (fileversion < 440) { s += i18n("Renamed conduits, Kroupware and file installer have " "been made conduits as well."); s += ' '; s += i18n("Conflict resolution is now a global setting."); s += ' '; } if (fileversion < 443) { s += i18n("Changed format of no-backup databases."); s += ' '; } // Insert more recent additions here return s; } /* static */ void KPilotConfig::sorryVersionOutdated(int fileversion) { FUNCTIONSETUP; KMessageBox::detailedSorry(0L, i18n("The configuration file for KPilot is out-of " "date. Please run KPilot to update it."), KPilotConfig::versionDetails(fileversion,true), i18n("Configuration File Out-of Date")); } /* static */ KPilotConfig::RunMode KPilotConfig::interactiveUpdate() { FUNCTIONSETUP; int res = 0; unsigned int fileVersion = KPilotSettings::configVersion(); // FIXME better config handling -> Move the config entries using kconf_update // It's OK if we're already at the required level. if (fileVersion >= KPilotConfig::ConfigurationVersion) { return Normal; } if (0 == fileVersion) // No config file at all { res = KMessageBox::questionYesNoCancel(0L, i18n("KPilot is not configured for use. You may use " "the configuration wizard or the normal configure dialog " "to configure KPilot."), i18n("Not Configured"), KGuiItem(i18n("Use &Wizard")), KGuiItem(i18n("Use &Dialog"))); if (res == KMessageBox::Yes) return WizardAndContinue; if (res == KMessageBox::No) return ConfigureAndContinue; return Cancel; } res = KMessageBox::warningContinueCancel(0L, i18n("The configuration file for KPilot is out-of " "date. KPilot can update some parts of the " "configuration automatically. Do you wish to " "continue?"), i18n("Configuration File Out-of Date")); if (res!=KMessageBox::Continue) return Cancel; DEBUGKPILOT << fname << ": Updating from " << fileVersion << " to " << ConfigurationVersion << endl; KPilotConfig::updateConfigVersion(); KPilotSettings::writeConfig(); return ConfigureAndContinue; } void KPilotConfig::sync() { KPilotSettings::self()->config()->sync(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dicimp.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:50:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _LINGUISTIC_DICIMP_HXX_ #define _LINGUISTIC_DICIMP_HXX_ #include <com/sun/star/linguistic2/XDictionary1.hpp> #include <com/sun/star/linguistic2/XDictionary.hpp> #include <com/sun/star/frame/XStorable.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type #include <cppuhelper/implbase3.hxx> // helper for implementations #include <cppuhelper/implbase1.hxx> // helper for implementations #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #include "misc.hxx" /////////////////////////////////////////////////////////////////////////// #define DIC_MAX_ENTRIES 2000 int GetDicVersion( const sal_Char *pVerStr ); const String GetDicExtension(); /////////////////////////////////////////////////////////////////////////// class DictionaryNeo : public ::cppu::WeakImplHelper3 < ::com::sun::star::linguistic2::XDictionary1, ::com::sun::star::linguistic2::XDictionary, ::com::sun::star::frame::XStorable > { ::cppu::OInterfaceContainerHelper aDicEvtListeners; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > > aEntries; ::rtl::OUString aDicName; ::rtl::OUString aMainURL; ::com::sun::star::linguistic2::DictionaryType eDicType; INT16 nCount; INT16 nLanguage; INT16 nDicVersion; BOOL bNeedEntries; BOOL bIsModified; BOOL bIsActive; BOOL bIsReadonly; // disallow copy-constructor and assignment-operator for now DictionaryNeo(const DictionaryNeo &); DictionaryNeo & operator = (const DictionaryNeo &); void launchEvent(INT16 nEvent, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > xEntry); ULONG loadEntries(const ::rtl::OUString &rMainURL); ULONG saveEntries(const ::rtl::OUString &rMainURL); int cmpDicEntry(const ::rtl::OUString &rWord1, const ::rtl::OUString &rWord2, BOOL bSimilarOnly = FALSE); BOOL seekEntry(const ::rtl::OUString &rWord, INT32 *pPos, BOOL bSimilarOnly = FALSE); BOOL isSorted(); BOOL addEntry_Impl(const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > xDicEntry, BOOL bIsLoadEntries = FALSE); public: DictionaryNeo(); DictionaryNeo(const ::rtl::OUString &rName, INT16 nLang, ::com::sun::star::linguistic2::DictionaryType eType, const ::rtl::OUString &rMainURL); virtual ~DictionaryNeo(); // XNamed virtual ::rtl::OUString SAL_CALL getName() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException); // XDictionary1 (same as XDictionary but for sal_Int16 as language) // only the different ones are listed virtual sal_Int16 SAL_CALL getLanguage() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLanguage( sal_Int16 nLang ) throw(::com::sun::star::uno::RuntimeException); // XDictionary virtual ::com::sun::star::linguistic2::DictionaryType SAL_CALL getDictionaryType() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setActive( sal_Bool bActivate ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isActive() throw(::com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getCount() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::lang::Locale SAL_CALL getLocale() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLocale( const ::com::sun::star::lang::Locale& aLocale ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > SAL_CALL getEntry( const ::rtl::OUString& aWord ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL addEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry >& xDicEntry ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL add( const ::rtl::OUString& aWord, sal_Bool bIsNegative, const ::rtl::OUString& aRplcText ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL remove( const ::rtl::OUString& aWord ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isFull() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > > SAL_CALL getEntries() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clear() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL addDictionaryEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL removeDictionaryEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener ) throw(::com::sun::star::uno::RuntimeException); // XStorable virtual sal_Bool SAL_CALL hasLocation() throw(::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getLocation() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadonly() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL store() throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeAsURL( const ::rtl::OUString& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeToURL( const ::rtl::OUString& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); }; /////////////////////////////////////////////////////////////////////////// class DicEntry : public cppu::WeakImplHelper1 < ::com::sun::star::linguistic2::XDictionaryEntry > { ::rtl::OUString aDicWord, // including hyphen positions represented by "=" aReplacement; // including hyphen positions represented by "=" BOOL bIsNegativ; // disallow copy-constructor and assignment-operator for now DicEntry(const DicEntry &); DicEntry & operator = (const DicEntry &); void splitDicFileWord(const ::rtl::OUString &rDicFileWord, ::rtl::OUString &rDicWord, ::rtl::OUString &rReplacement); public: DicEntry(); DicEntry(const ::rtl::OUString &rDicFileWord, BOOL bIsNegativ); DicEntry(const ::rtl::OUString &rDicWord, BOOL bIsNegativ, const ::rtl::OUString &rRplcText); virtual ~DicEntry(); // XDictionaryEntry virtual ::rtl::OUString SAL_CALL getDictionaryWord() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isNegative() throw(::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getReplacementText() throw(::com::sun::star::uno::RuntimeException); }; /////////////////////////////////////////////////////////////////////////// #endif <commit_msg>INTEGRATION: CWS tl18 (1.5.24); FILE MERGED 2006/03/08 10:13:39 tl 1.5.24.1: #i60698# introducing new, optional tagged file format for user-dictionaries<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dicimp.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2006-05-05 08:10:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _LINGUISTIC_DICIMP_HXX_ #define _LINGUISTIC_DICIMP_HXX_ #include <com/sun/star/linguistic2/XDictionary1.hpp> #include <com/sun/star/linguistic2/XDictionary.hpp> #include <com/sun/star/frame/XStorable.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type #include <cppuhelper/implbase3.hxx> // helper for implementations #include <cppuhelper/implbase1.hxx> // helper for implementations #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #include "misc.hxx" /////////////////////////////////////////////////////////////////////////// #define DIC_MAX_ENTRIES 2000 int ReadDicVersion( SvStream *pStream, USHORT &nLng, BOOL &bNeg ); const String GetDicExtension(); /////////////////////////////////////////////////////////////////////////// class DictionaryNeo : public ::cppu::WeakImplHelper3 < ::com::sun::star::linguistic2::XDictionary1, ::com::sun::star::linguistic2::XDictionary, ::com::sun::star::frame::XStorable > { ::cppu::OInterfaceContainerHelper aDicEvtListeners; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > > aEntries; ::rtl::OUString aDicName; ::rtl::OUString aMainURL; ::com::sun::star::linguistic2::DictionaryType eDicType; INT16 nCount; INT16 nLanguage; INT16 nDicVersion; BOOL bNeedEntries; BOOL bIsModified; BOOL bIsActive; BOOL bIsReadonly; // disallow copy-constructor and assignment-operator for now DictionaryNeo(const DictionaryNeo &); DictionaryNeo & operator = (const DictionaryNeo &); void launchEvent(INT16 nEvent, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > xEntry); ULONG loadEntries(const ::rtl::OUString &rMainURL); ULONG saveEntries(const ::rtl::OUString &rMainURL); int cmpDicEntry(const ::rtl::OUString &rWord1, const ::rtl::OUString &rWord2, BOOL bSimilarOnly = FALSE); BOOL seekEntry(const ::rtl::OUString &rWord, INT32 *pPos, BOOL bSimilarOnly = FALSE); BOOL isSorted(); BOOL addEntry_Impl(const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > xDicEntry, BOOL bIsLoadEntries = FALSE); public: DictionaryNeo(); DictionaryNeo(const ::rtl::OUString &rName, INT16 nLang, ::com::sun::star::linguistic2::DictionaryType eType, const ::rtl::OUString &rMainURL); virtual ~DictionaryNeo(); // XNamed virtual ::rtl::OUString SAL_CALL getName() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException); // XDictionary1 (same as XDictionary but for sal_Int16 as language) // only the different ones are listed virtual sal_Int16 SAL_CALL getLanguage() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLanguage( sal_Int16 nLang ) throw(::com::sun::star::uno::RuntimeException); // XDictionary virtual ::com::sun::star::linguistic2::DictionaryType SAL_CALL getDictionaryType() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setActive( sal_Bool bActivate ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isActive() throw(::com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getCount() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::lang::Locale SAL_CALL getLocale() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLocale( const ::com::sun::star::lang::Locale& aLocale ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > SAL_CALL getEntry( const ::rtl::OUString& aWord ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL addEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry >& xDicEntry ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL add( const ::rtl::OUString& aWord, sal_Bool bIsNegative, const ::rtl::OUString& aRplcText ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL remove( const ::rtl::OUString& aWord ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isFull() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEntry > > SAL_CALL getEntries() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clear() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL addDictionaryEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL removeDictionaryEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener ) throw(::com::sun::star::uno::RuntimeException); // XStorable virtual sal_Bool SAL_CALL hasLocation() throw(::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getLocation() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadonly() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL store() throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeAsURL( const ::rtl::OUString& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeToURL( const ::rtl::OUString& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); }; /////////////////////////////////////////////////////////////////////////// class DicEntry : public cppu::WeakImplHelper1 < ::com::sun::star::linguistic2::XDictionaryEntry > { ::rtl::OUString aDicWord, // including hyphen positions represented by "=" aReplacement; // including hyphen positions represented by "=" BOOL bIsNegativ; // disallow copy-constructor and assignment-operator for now DicEntry(const DicEntry &); DicEntry & operator = (const DicEntry &); void splitDicFileWord(const ::rtl::OUString &rDicFileWord, ::rtl::OUString &rDicWord, ::rtl::OUString &rReplacement); public: DicEntry(); DicEntry(const ::rtl::OUString &rDicFileWord, BOOL bIsNegativ); DicEntry(const ::rtl::OUString &rDicWord, BOOL bIsNegativ, const ::rtl::OUString &rRplcText); virtual ~DicEntry(); // XDictionaryEntry virtual ::rtl::OUString SAL_CALL getDictionaryWord() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isNegative() throw(::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getReplacementText() throw(::com::sun::star::uno::RuntimeException); }; /////////////////////////////////////////////////////////////////////////// #endif <|endoftext|>
<commit_before><commit_msg>Added warning when zphot falls out of confidence interval<commit_after><|endoftext|>
<commit_before><commit_msg>Update fmcalc.cpp<commit_after><|endoftext|>
<commit_before><commit_msg>Fix check for existing serial connection before flashing fw.<commit_after><|endoftext|>
<commit_before>// This file provides a fast implementation of common vector operations, using // a templated and very lightweight vec class. The memory structure of a vec // instance is just a sequence of its components. // It also provides a vec_array class, whose memory structure is just the same // as a sequence of N*dimensions scalars. The [] operator is overloaded // to return vec instances. // The goal of these classes is to achieve similar performance as a primitive // array for the 1d case, while being able to write more general programs. // include guard #ifndef VEC_HPP #define VEC_HPP // need complex type for optimized template #include <complex> /* -- vec class -- */ template <int dim, typename Type> class vec { public: Type x[dim]; inline vec() {}; // copy constructor template <typename otherType> inline vec(const vec<dim,otherType> &other_vec) { for (int i=0; i<dim; i++) { x[i] = Type(other_vec.x[i]); } }; // intitialize with constant value template <typename otherType> inline vec(otherType val) { for (int i=0; i<dim; i++) { x[i] = Type(val); } }; // in-place summation template <typename otherType> inline vec<dim,Type> &operator+=(const vec<dim,otherType> &v) { for (int i=0; i<dim; i++) { x[i] += Type(v.x[i]); } return *this; }; // in-place subtraction template <typename otherType> inline vec<dim,Type> &operator-=(const vec<dim,otherType> &v) { for (int i=0; i<dim; i++) { x[i] -= Type(v.x[i]); } return *this; }; // in-place multiplication with scalar template <typename otherType> inline vec<dim,Type> &operator*=(const otherType &v) { for (int i=0; i<dim; i++) { x[i] *= Type(v); } return *this; }; // in-place division by scalar template <typename otherType> inline vec<dim,Type> &operator/=(const otherType &v) { for (int i=0; i<dim; i++) { x[i] /= Type(v); } return *this; }; // element-wise application of a function template <typename otherType> inline vec<dim,otherType> element_wise(otherType& (*func)(Type&)) { vec<dim,otherType> r; for (int i=0; i<dim; i++) { r.x[i] = (*func)(x[i]); } return r; }; }; /* -- common operations on vec -- */ // sum of vec instances template <int dim, typename Type> inline vec<dim,Type> operator+(const vec<dim,Type> &v, const vec<dim,Type> &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] + w.x[i]; } return r; }; // difference of vec instances template <int dim, typename Type> inline vec<dim,Type> operator-(const vec<dim,Type> &v, const vec<dim,Type> &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] - w.x[i]; } return r; }; // vec times scalar template <int dim, typename Type> inline vec<dim,Type> operator*(const vec<dim,Type> &v, const Type &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] * w; } return r; }; // scalar times vec template <int dim, typename Type> inline vec<dim,Type> operator*(const Type &w, const vec<dim,Type> &v) { return v*w; }; // division of vec by scalar template <int dim, typename Type> inline vec<dim,Type> operator/(const vec<dim,Type> &v, const Type &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] / w; } return r; }; // scalar product of vec instances template <int dim, typename Type> inline Type operator*(const vec<dim,Type> &v, const vec<dim,Type> &w) { Type r(0); for (int i=0; i<dim; i++) { r += v.x[i] * w.x[i]; } return r; }; // these more specialized templates gain some speed for scalar product of complex vec and real vec template <int dim, typename Type> inline std::complex<Type> operator*(const vec<dim,std::complex<Type> > &v, const vec<dim,Type> &w) { std::complex<Type> r(0); for (int i=0; i<dim; i++) { r += std::complex<Type>(v.x[i] * w.x[i]); } return r; }; template <int dim, typename Type> inline std::complex<Type> operator*(const vec<dim,Type> &w, const vec<dim,std::complex<Type> > &v) { return v*w; }; // implement real part of a vec template <int dim, typename Type> vec<dim,Type> real(const vec<dim,std::complex<Type> > &v) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = real(v.x[i]); } return r; }; // implement imaginary part of a vec template <int dim, typename Type> vec<dim,Type> imag(const vec<dim,std::complex<Type> > &v) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = imag(v.x[i]); } return r; }; // implement complex conjugation of a vec template <int dim, typename Type> vec<dim,std::complex<Type> > conj(const vec<dim,std::complex<Type> > &v) { vec<dim,std::complex<Type> > r; for (int i=0; i<dim; i++) { r.x[i] = conj(v.x[i]); } return r; }; // implement absolute value of a vec template <int dim, typename Type> Type abs(const vec<dim,Type> &v) { Type r, a; for (int i=0; i<dim; i++) { a = abs(v.x[i]); r += a*a; } return sqrt(r); }; /* -- implementation of vec_array -- */ template <int dim, typename Type> class vec_array { public: Type *x; inline vec_array() {}; inline vec_array(Type *a) { x = a; }; inline vec<dim,Type> &operator[](int i) { return *(vec<dim,Type> *)(&x[dim*i]); } }; /* -- macro to compute the square of vec instances -- */ #define SQR(x) ((x)*(x)) #endif // end of include guard <commit_msg>fix bug in vec.hpp<commit_after>// This file provides a fast implementation of common vector operations, using // a templated and very lightweight vec class. The memory structure of a vec // instance is just a sequence of its components. // It also provides a vec_array class, whose memory structure is just the same // as a sequence of N*dimensions scalars. The [] operator is overloaded // to return vec instances. // The goal of these classes is to achieve similar performance as a primitive // array for the 1d case, while being able to write more general programs. // include guard #ifndef VEC_HPP #define VEC_HPP // need complex type for optimized template #include <complex> /* -- vec class -- */ template <int dim, typename Type> class vec { public: Type x[dim]; inline vec() {}; // copy constructor template <typename otherType> inline vec(const vec<dim,otherType> &other_vec) { for (int i=0; i<dim; i++) { x[i] = Type(other_vec.x[i]); } }; // intitialize with constant value template <typename otherType> inline vec(otherType val) { for (int i=0; i<dim; i++) { x[i] = Type(val); } }; // in-place summation template <typename otherType> inline vec<dim,Type> &operator+=(const vec<dim,otherType> &v) { for (int i=0; i<dim; i++) { x[i] += Type(v.x[i]); } return *this; }; // in-place subtraction template <typename otherType> inline vec<dim,Type> &operator-=(const vec<dim,otherType> &v) { for (int i=0; i<dim; i++) { x[i] -= Type(v.x[i]); } return *this; }; // in-place multiplication with scalar template <typename otherType> inline vec<dim,Type> &operator*=(const otherType &v) { for (int i=0; i<dim; i++) { x[i] *= Type(v); } return *this; }; // in-place division by scalar template <typename otherType> inline vec<dim,Type> &operator/=(const otherType &v) { for (int i=0; i<dim; i++) { x[i] /= Type(v); } return *this; }; // element-wise application of a function template <typename otherType> inline vec<dim,otherType> element_wise(otherType& (*func)(Type&)) { vec<dim,otherType> r; for (int i=0; i<dim; i++) { r.x[i] = (*func)(x[i]); } return r; }; }; /* -- common operations on vec -- */ // sum of vec instances template <int dim, typename Type> inline vec<dim,Type> operator+(const vec<dim,Type> &v, const vec<dim,Type> &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] + w.x[i]; } return r; }; // difference of vec instances template <int dim, typename Type> inline vec<dim,Type> operator-(const vec<dim,Type> &v, const vec<dim,Type> &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] - w.x[i]; } return r; }; // vec times scalar template <int dim, typename Type> inline vec<dim,Type> operator*(const vec<dim,Type> &v, const Type &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] * w; } return r; }; // scalar times vec template <int dim, typename Type> inline vec<dim,Type> operator*(const Type &w, const vec<dim,Type> &v) { return v*w; }; // division of vec by scalar template <int dim, typename Type> inline vec<dim,Type> operator/(const vec<dim,Type> &v, const Type &w) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = v.x[i] / w; } return r; }; // scalar product of vec instances template <int dim, typename Type> inline Type operator*(const vec<dim,Type> &v, const vec<dim,Type> &w) { Type r(0); for (int i=0; i<dim; i++) { r += v.x[i] * w.x[i]; } return r; }; // these more specialized templates gain some speed for scalar product of complex vec and real vec template <int dim, typename Type> inline std::complex<Type> operator*(const vec<dim,std::complex<Type> > &v, const vec<dim,Type> &w) { std::complex<Type> r(0); for (int i=0; i<dim; i++) { r += std::complex<Type>(v.x[i] * w.x[i]); } return r; }; template <int dim, typename Type> inline std::complex<Type> operator*(const vec<dim,Type> &w, const vec<dim,std::complex<Type> > &v) { return v*w; }; // implement real part of a vec template <int dim, typename Type> vec<dim,Type> real(const vec<dim,std::complex<Type> > &v) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = real(v.x[i]); } return r; }; // implement imaginary part of a vec template <int dim, typename Type> vec<dim,Type> imag(const vec<dim,std::complex<Type> > &v) { vec<dim,Type> r; for (int i=0; i<dim; i++) { r.x[i] = imag(v.x[i]); } return r; }; // implement complex conjugation of a vec template <int dim, typename Type> vec<dim,std::complex<Type> > conj(const vec<dim,std::complex<Type> > &v) { vec<dim,std::complex<Type> > r; for (int i=0; i<dim; i++) { r.x[i] = conj(v.x[i]); } return r; }; // implement absolute value of a vec template <int dim, typename Type> Type abs(const vec<dim,Type> &v) { Type r(0), a; for (int i=0; i<dim; i++) { a = abs(v.x[i]); r += a*a; } return sqrt(r); }; /* -- implementation of vec_array -- */ template <int dim, typename Type> class vec_array { public: Type *x; inline vec_array() {}; inline vec_array(Type *a) { x = a; }; inline vec<dim,Type> &operator[](int i) { return *(vec<dim,Type> *)(&x[dim*i]); } }; /* -- macro to compute the square of vec instances -- */ #define SQR(x) ((x)*(x)) #endif // end of include guard <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * VapourSynth is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtCore/QMutex> #include <QtCore/QMutexLocker> #include <QtCore/QWaitCondition> #include <QtCore/QFile> #include <QtCore/QMap> #include "VSScript.h" #include "VSHelper.h" #ifdef _WIN32 static inline QString nativeToQString(const wchar_t *str) { return QString::fromWCharArray(str); } #else static inline QString nativeToQString(const char *str) { return QString::fromLocal8Bit(str); } #endif const VSAPI *vsapi = NULL; VSScript *se = NULL; VSNodeRef *node = NULL; FILE *outFile = NULL; int requests = 0; int outputIndex = 0; int outputFrames = 0; int requestedFrames = 0; int completedFrames = 0; int totalFrames = 0; int numPlanes = 0; bool y4m = false; bool outputError = false; bool showInfo = false; QMap<int, const VSFrameRef *> reorderMap; QString errorMessage; QWaitCondition condition; QMutex mutex; void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) { completedFrames++; if (f) { reorderMap.insert(n, f); while (reorderMap.contains(outputFrames)) { const VSFrameRef *frame = reorderMap.take(outputFrames); if (!outputError) { if (y4m) { if (!fwrite("FRAME\n", 6, 1, outFile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; } } if (!outputError) { const VSFormat *fi = vsapi->getFrameFormat(frame); for (int p = 0; p < fi->numPlanes; p++) { int stride = vsapi->getStride(frame, p); const uint8_t *readPtr = vsapi->getReadPtr(frame, p); int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample; int height = vsapi->getFrameHeight(frame, p); for (int y = 0; y < height; y++) { if (!fwrite(readPtr, rowSize, 1, outFile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; p = 100; // break out of the outer loop break; } readPtr += stride; } } } } vsapi->freeFrame(frame); outputFrames++; } } else { outputError = true; totalFrames = requestedFrames; if (errorMsg) errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg); else errorMessage = QString("Error: Failed to retrieve frame ") + n; } if (requestedFrames < totalFrames) { vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL); requestedFrames++; } if (totalFrames == completedFrames) { QMutexLocker lock(&mutex); condition.wakeOne(); } } bool outputNode() { if (requests < 1) { const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore()); requests = info->numThreads; } const VSVideoInfo *vi = vsapi->getVideoInfo(node); totalFrames = vi->numFrames; if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) { errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); return true; } QString y4mFormat; QString numBits; if (y4m) { if (vi->format->colorFamily == cmGray) { y4mFormat = "mono"; if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample); } else if (vi->format->colorFamily == cmYUV) { if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1) y4mFormat = "420"; else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0) y4mFormat = "422"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0) y4mFormat = "444"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2) y4mFormat = "410"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0) y4mFormat = "411"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1) y4mFormat = "440"; else { fprintf(stderr, "No y4m identifier exists for current format"); return true; } if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample); } else { fprintf(stderr, "No y4m identifier exists for current format"); return true; } } if (!y4mFormat.isEmpty()) y4mFormat = "C" + y4mFormat + " "; QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum) + ":" + QString::number(vi->fpsDen) + " Ip A0:0\n"; QByteArray rawHeader = header.toUtf8(); if (y4m) { if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) { errorMessage = "Error: fwrite() call failed"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); outputError = true; return outputError; } } QMutexLocker lock(&mutex); int intitalRequestSize = std::min(requests, totalFrames); requestedFrames = intitalRequestSize; for (int n = 0; n < intitalRequestSize; n++) vsapi->getFrameAsync(n, node, frameDoneCallback, NULL); condition.wait(&mutex); if (outputError) { fprintf(stderr, "%s", errorMessage.toUtf8().constData()); } return outputError; } const char *colorFamilyToString(int colorFamily) { switch (colorFamily) { case cmGray: return "Gray"; case cmRGB: return "RGB"; case cmYUV: return "YUV"; case cmYCoCg: return "YCoCg"; case cmCompat: return "Compat"; } return ""; } // fixme, only allow info without output #ifdef _WIN32 int wmain(int argc, wchar_t **argv) { #else int main(int argc, char **argv) { #endif if (argc < 3) { fprintf(stderr, "VSPipe usage:\n"); fprintf(stderr, "Show script info: vspipe script.vpy - -info\n"); fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n"); fprintf(stderr, "Write to file: vspipe script.vpy <outFile> [options]\n"); fprintf(stderr, "Available options:\n"); fprintf(stderr, "Select output index: -index N\n"); fprintf(stderr, "Set number of concurrent frame requests: -requests N\n"); fprintf(stderr, "Add YUV4MPEG headers: -y4m\n"); fprintf(stderr, "Show video info: -info (overrides other options)\n"); return 1; } QFile scriptFile(nativeToQString(argv[1])); if (!scriptFile.open(QIODevice::ReadOnly)) { fprintf(stderr, "Failed to to open script file for reading\n"); return 1; } if (scriptFile.size() > 1024*1024*16) { fprintf(stderr, "Script files bigger than 16MB not allowed\n"); return 1; } QByteArray scriptData = scriptFile.readAll(); scriptFile.close(); if (scriptData.isEmpty()) { fprintf(stderr, "Failed to read script file or file is empty\n"); return 1; } QString outputFilename = nativeToQString(argv[2]); if (outputFilename == "-") { outFile = stdout; } else { #ifdef _WIN32 outFile = _wfopen(outputFilename.toStdWString().c_str(), L"wb"); #else outFile = fopen(outputFilename.toLocal8Bit(), "wb"); #endif if (!outFile) { fprintf(stderr, "Failed to open output for writing\n"); return 1; } } for (int arg = 3; arg < argc; arg++) { QString argString = nativeToQString(argv[arg]); if (argString == "-y4m") { y4m = true; } else if (argString == "-info") { showInfo = true; } else if (argString == "-index") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No index number specified"); return 1; } QString numString = nativeToQString(argv[arg+1]); index = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else if (argString == "-requests") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No request number specified"); return 1; } QString numString = nativeToQString(argv[arg+1]); requests = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else { fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData()); return 1; } } if (!vseval_init()) { fprintf(stderr, "Failed to initialize VapourSynth environment\n"); return 1; } vsapi = vseval_getVSApi(); if (!vsapi) { fprintf(stderr, "Failed to get VapourSynth API pointer\n"); vseval_finalize(); return 1; } if (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) { fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se)); vseval_freeScript(se); vseval_finalize(); return 1; } node = vseval_getOutput(se, outputIndex); if (!node) { fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n"); vseval_freeScript(se); vseval_finalize(); return 1; } bool error = false; const VSVideoInfo *vi = vsapi->getVideoInfo(node); if (showInfo) { fprintf(outFile, "Width: %d\n", vi->width); fprintf(outFile, "Height: %d\n", vi->height); fprintf(outFile, "Frames: %d\n", vi->numFrames); fprintf(outFile, "FPS: %d/%d\n", vi->fpsNum, vi->fpsDen); if (vi->format) { fprintf(outFile, "Format Name: %s\n", vi->format->name); fprintf(outFile, "Color Family: %s\n", colorFamilyToString(vi->format->colorFamily)); fprintf(outFile, "Bits: %d\n", vi->format->bitsPerSample); fprintf(outFile, "SubSampling W: %d\n", vi->format->subSamplingW); fprintf(outFile, "SubSampling H: %d\n", vi->format->subSamplingH); } else { fprintf(outFile, "Format Name: Variable\n"); } } else { if (!isConstantFormat(vi) || vi->numFrames == 0) { fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n"); vseval_freeScript(se); vseval_finalize(); return 1; } error = outputNode(); } fflush(outFile); vseval_freeScript(se); vseval_finalize(); return error; } <commit_msg>Fix previous commit<commit_after>/* * Copyright (c) 2013 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * VapourSynth is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtCore/QMutex> #include <QtCore/QMutexLocker> #include <QtCore/QWaitCondition> #include <QtCore/QFile> #include <QtCore/QMap> #include "VSScript.h" #include "VSHelper.h" #ifdef _WIN32 static inline QString nativeToQString(const wchar_t *str) { return QString::fromWCharArray(str); } #else static inline QString nativeToQString(const char *str) { return QString::fromLocal8Bit(str); } #endif const VSAPI *vsapi = NULL; VSScript *se = NULL; VSNodeRef *node = NULL; FILE *outFile = NULL; int requests = 0; int outputIndex = 0; int outputFrames = 0; int requestedFrames = 0; int completedFrames = 0; int totalFrames = 0; int numPlanes = 0; bool y4m = false; bool outputError = false; bool showInfo = false; QMap<int, const VSFrameRef *> reorderMap; QString errorMessage; QWaitCondition condition; QMutex mutex; void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) { completedFrames++; if (f) { reorderMap.insert(n, f); while (reorderMap.contains(outputFrames)) { const VSFrameRef *frame = reorderMap.take(outputFrames); if (!outputError) { if (y4m) { if (!fwrite("FRAME\n", 6, 1, outFile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; } } if (!outputError) { const VSFormat *fi = vsapi->getFrameFormat(frame); for (int p = 0; p < fi->numPlanes; p++) { int stride = vsapi->getStride(frame, p); const uint8_t *readPtr = vsapi->getReadPtr(frame, p); int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample; int height = vsapi->getFrameHeight(frame, p); for (int y = 0; y < height; y++) { if (!fwrite(readPtr, rowSize, 1, outFile)) { errorMessage = "Error: fwrite() call failed"; totalFrames = requestedFrames; outputError = true; p = 100; // break out of the outer loop break; } readPtr += stride; } } } } vsapi->freeFrame(frame); outputFrames++; } } else { outputError = true; totalFrames = requestedFrames; if (errorMsg) errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg); else errorMessage = QString("Error: Failed to retrieve frame ") + n; } if (requestedFrames < totalFrames) { vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL); requestedFrames++; } if (totalFrames == completedFrames) { QMutexLocker lock(&mutex); condition.wakeOne(); } } bool outputNode() { if (requests < 1) { const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore()); requests = info->numThreads; } const VSVideoInfo *vi = vsapi->getVideoInfo(node); totalFrames = vi->numFrames; if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) { errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); return true; } QString y4mFormat; QString numBits; if (y4m) { if (vi->format->colorFamily == cmGray) { y4mFormat = "mono"; if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample); } else if (vi->format->colorFamily == cmYUV) { if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1) y4mFormat = "420"; else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0) y4mFormat = "422"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0) y4mFormat = "444"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2) y4mFormat = "410"; else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0) y4mFormat = "411"; else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1) y4mFormat = "440"; else { fprintf(stderr, "No y4m identifier exists for current format"); return true; } if (vi->format->bitsPerSample > 8) y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample); } else { fprintf(stderr, "No y4m identifier exists for current format"); return true; } } if (!y4mFormat.isEmpty()) y4mFormat = "C" + y4mFormat + " "; QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum) + ":" + QString::number(vi->fpsDen) + " Ip A0:0\n"; QByteArray rawHeader = header.toUtf8(); if (y4m) { if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) { errorMessage = "Error: fwrite() call failed"; fprintf(stderr, "%s", errorMessage.toUtf8().constData()); outputError = true; return outputError; } } QMutexLocker lock(&mutex); int intitalRequestSize = std::min(requests, totalFrames); requestedFrames = intitalRequestSize; for (int n = 0; n < intitalRequestSize; n++) vsapi->getFrameAsync(n, node, frameDoneCallback, NULL); condition.wait(&mutex); if (outputError) { fprintf(stderr, "%s", errorMessage.toUtf8().constData()); } return outputError; } const char *colorFamilyToString(int colorFamily) { switch (colorFamily) { case cmGray: return "Gray"; case cmRGB: return "RGB"; case cmYUV: return "YUV"; case cmYCoCg: return "YCoCg"; case cmCompat: return "Compat"; } return ""; } // fixme, only allow info without output #ifdef _WIN32 int wmain(int argc, wchar_t **argv) { #else int main(int argc, char **argv) { #endif if (argc < 3) { fprintf(stderr, "VSPipe usage:\n"); fprintf(stderr, "Show script info: vspipe script.vpy - -info\n"); fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n"); fprintf(stderr, "Write to file: vspipe script.vpy <outFile> [options]\n"); fprintf(stderr, "Available options:\n"); fprintf(stderr, "Select output index: -index N\n"); fprintf(stderr, "Set number of concurrent frame requests: -requests N\n"); fprintf(stderr, "Add YUV4MPEG headers: -y4m\n"); fprintf(stderr, "Show video info: -info (overrides other options)\n"); return 1; } QFile scriptFile(nativeToQString(argv[1])); if (!scriptFile.open(QIODevice::ReadOnly)) { fprintf(stderr, "Failed to to open script file for reading\n"); return 1; } if (scriptFile.size() > 1024*1024*16) { fprintf(stderr, "Script files bigger than 16MB not allowed\n"); return 1; } QByteArray scriptData = scriptFile.readAll(); scriptFile.close(); if (scriptData.isEmpty()) { fprintf(stderr, "Failed to read script file or file is empty\n"); return 1; } QString outputFilename = nativeToQString(argv[2]); if (outputFilename == "-") { outFile = stdout; } else { #ifdef _WIN32 outFile = _wfopen(outputFilename.toStdWString().c_str(), L"wb"); #else outFile = fopen(outputFilename.toLocal8Bit(), "wb"); #endif if (!outFile) { fprintf(stderr, "Failed to open output for writing\n"); return 1; } } for (int arg = 3; arg < argc; arg++) { QString argString = nativeToQString(argv[arg]); if (argString == "-y4m") { y4m = true; } else if (argString == "-info") { showInfo = true; } else if (argString == "-index") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No index number specified"); return 1; } QString numString = nativeToQString(argv[arg+1]); outputIndex = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else if (argString == "-requests") { bool ok = false; if (argc <= arg + 1) { fprintf(stderr, "No request number specified"); return 1; } QString numString = nativeToQString(argv[arg+1]); requests = numString.toInt(&ok); if (!ok) { fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData()); return 1; } arg++; } else { fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData()); return 1; } } if (!vseval_init()) { fprintf(stderr, "Failed to initialize VapourSynth environment\n"); return 1; } vsapi = vseval_getVSApi(); if (!vsapi) { fprintf(stderr, "Failed to get VapourSynth API pointer\n"); vseval_finalize(); return 1; } if (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) { fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se)); vseval_freeScript(se); vseval_finalize(); return 1; } node = vseval_getOutput(se, outputIndex); if (!node) { fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n"); vseval_freeScript(se); vseval_finalize(); return 1; } bool error = false; const VSVideoInfo *vi = vsapi->getVideoInfo(node); if (showInfo) { fprintf(outFile, "Width: %d\n", vi->width); fprintf(outFile, "Height: %d\n", vi->height); fprintf(outFile, "Frames: %d\n", vi->numFrames); fprintf(outFile, "FPS: %d/%d\n", vi->fpsNum, vi->fpsDen); if (vi->format) { fprintf(outFile, "Format Name: %s\n", vi->format->name); fprintf(outFile, "Color Family: %s\n", colorFamilyToString(vi->format->colorFamily)); fprintf(outFile, "Bits: %d\n", vi->format->bitsPerSample); fprintf(outFile, "SubSampling W: %d\n", vi->format->subSamplingW); fprintf(outFile, "SubSampling H: %d\n", vi->format->subSamplingH); } else { fprintf(outFile, "Format Name: Variable\n"); } } else { if (!isConstantFormat(vi) || vi->numFrames == 0) { fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n"); vseval_freeScript(se); vseval_finalize(); return 1; } error = outputNode(); } fflush(outFile); vseval_freeScript(se); vseval_finalize(); return error; } <|endoftext|>
<commit_before><commit_msg>Enable staking for p2sh-p2wkh.<commit_after><|endoftext|>
<commit_before>#include "GPIO.hh" // STL #include <iostream> #include <chrono> #include <unistd.h> // usleep() using namespace std::chrono; high_resolution_clock::time_point beg; duration<double, std::micro> accum; class Handler { public: void handle(GPIO::Value val) { const high_resolution_clock::time_point end = high_resolution_clock::now(); const auto time_span = end - beg; accum += time_span; std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl; } }; void myisr(GPIO::Value val) { const high_resolution_clock::time_point end = high_resolution_clock::now(); const auto time_span = end - beg; accum += time_span; std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl; } int main() { Handler h; accum = std::chrono::duration<double, std::micro>(0.0); // Member functions do not take any longer to call than global functions std::function<void(GPIO::Value)> global(myisr); std::function<void(GPIO::Value)> handleisr = std::bind(&Handler::handle, &h, std::placeholders::_1); { // Short GPIO 15 (input) to GPIO 27 (output) for the following latency test GPIO gpio1(27, GPIO::Direction::OUT); GPIO gpio2(15, GPIO::Edge::RISING, handleisr); // will be destroyed first, // so no spurious call to handleisr upon // destruction of GPIO 27 usleep(125000); const unsigned int nIterations = 50; for(unsigned int i=0;i<nIterations;++i) { beg = high_resolution_clock::now(); gpio1.setValue(GPIO::Value::HIGH); usleep(31250); gpio1.setValue(GPIO::Value::LOW); usleep(31250); } std::cout << "Average: " << accum.count()/nIterations << " microseconds " << std::endl; } } <commit_msg>Ensure printed units are microseconds<commit_after>#include "GPIO.hh" // STL #include <iostream> #include <chrono> #include <unistd.h> // usleep() using namespace std::chrono; high_resolution_clock::time_point beg; duration<double, std::micro> accum; class Handler { public: void handle(GPIO::Value val) { const high_resolution_clock::time_point end = high_resolution_clock::now(); const auto time_span = duration_cast<microseconds>(end - beg); accum += time_span; std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl; } }; void myisr(GPIO::Value val) { const high_resolution_clock::time_point end = high_resolution_clock::now(); const auto time_span = end - beg; accum += time_span; std::cout << "Latency: " << time_span.count() << " microseconds" << std::endl; } int main() { Handler h; accum = std::chrono::duration<double, std::micro>(0.0); // Member functions do not take any longer to call than global functions std::function<void(GPIO::Value)> global(myisr); std::function<void(GPIO::Value)> handleisr = std::bind(&Handler::handle, &h, std::placeholders::_1); { // Short GPIO 15 (input) to GPIO 27 (output) for the following latency test GPIO gpio1(27, GPIO::Direction::OUT); GPIO gpio2(15, GPIO::Edge::RISING, handleisr); // will be destroyed first, // so no spurious call to handleisr upon // destruction of GPIO 27 usleep(125000); const unsigned int nIterations = 50; for(unsigned int i=0;i<nIterations;++i) { beg = high_resolution_clock::now(); gpio1.setValue(GPIO::Value::HIGH); usleep(31250); gpio1.setValue(GPIO::Value::LOW); usleep(31250); } std::cout << "Average: " << accum.count()/nIterations << " microseconds " << std::endl; } } <|endoftext|>
<commit_before>/* * Copyright 2014 Cloudius Systems */ #include "database.hh" #include "core/app-template.hh" #include "core/distributed.hh" #include "thrift/server.hh" #include "transport/server.hh" namespace bpo = boost::program_options; int main(int ac, char** av) { app_template app; app.add_options() ("cql-port", bpo::value<uint16_t>()->default_value(9042), "CQL port") ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port") ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory"); auto server = std::make_unique<distributed<thrift_server>>();; distributed<database> db; return app.run(ac, av, [&] { auto&& config = app.configuration(); uint16_t thrift_port = config["thrift-port"].as<uint16_t>(); uint16_t cql_port = config["cql-port"].as<uint16_t>(); sstring datadir = config["datadir"].as<std::string>(); return db.start().then([datadir, &db] { return db.invoke_on_all(&database::init_from_data_directory, datadir); }).then([&db, cql_port, thrift_port] { auto cserver = new distributed<cql_server>; cserver->start(std::ref(db)).then([server = std::move(cserver), cql_port] () mutable { server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port}); }).then([cql_port] { std::cout << "CQL server listening on port " << cql_port << " ...\n"; }); auto tserver = new distributed<thrift_server>; tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable { server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port}); }).then([thrift_port] { std::cout << "Thrift server listening on port " << thrift_port << " ...\n"; }); }).or_terminate(); }); } <commit_msg>Avoid crash on ctrl-C<commit_after>/* * Copyright 2014 Cloudius Systems */ #include "database.hh" #include "core/app-template.hh" #include "core/distributed.hh" #include "thrift/server.hh" #include "transport/server.hh" namespace bpo = boost::program_options; int main(int ac, char** av) { app_template app; app.add_options() ("cql-port", bpo::value<uint16_t>()->default_value(9042), "CQL port") ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port") ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory"); auto server = std::make_unique<distributed<thrift_server>>();; distributed<database> db; return app.run(ac, av, [&] { auto&& config = app.configuration(); uint16_t thrift_port = config["thrift-port"].as<uint16_t>(); uint16_t cql_port = config["cql-port"].as<uint16_t>(); sstring datadir = config["datadir"].as<std::string>(); return db.start().then([datadir, &db] { engine().at_exit([&db] { return db.stop(); }); return db.invoke_on_all(&database::init_from_data_directory, datadir); }).then([&db, cql_port, thrift_port] { auto cserver = new distributed<cql_server>; cserver->start(std::ref(db)).then([server = std::move(cserver), cql_port] () mutable { server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port}); }).then([cql_port] { std::cout << "CQL server listening on port " << cql_port << " ...\n"; }); auto tserver = new distributed<thrift_server>; tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable { server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port}); }).then([thrift_port] { std::cout << "Thrift server listening on port " << thrift_port << " ...\n"; }); }).or_terminate(); }); } <|endoftext|>
<commit_before>#ifndef SIMPLE_IO #define SIMPLE_IO #include <string> #include <iostream> #include <fstream> #include <memory> #ifndef NO_ZLIB #include "zlib.h" #endif class FileInputType { public: virtual bool getline(std::string &line) = 0; virtual ~FileInputType() { }; }; class IFStreamInput : public FileInputType { public: IFStreamInput(std::string filename) { ifstr.open(filename, std::ios_base::in); }; ~IFStreamInput() { ifstr.close(); } bool getline(std::string &line) { return std::getline(ifstr, line); } private: std::ifstream ifstr; }; #ifndef NO_ZLIB class GZipFileInput : public FileInputType { public: GZipFileInput(std::string filename); ~GZipFileInput(); bool getline(std::string &line); private: gzFile gzf; }; #endif class SimpleFileInput { public: SimpleFileInput(std::string filename); ~SimpleFileInput() { }; bool getline(std::string &line) { return infs->getline(line); } private: bool ends_with(std::string const &filename, std::string const &suffix) { if (filename.length() < suffix.length()) return false; return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix)); } std::unique_ptr<FileInputType> infs; }; class FileOutputType { public: virtual void close() = 0; virtual FileOutputType& operator<<(const std::string &str) = 0; virtual FileOutputType& operator<<(int) = 0; virtual FileOutputType& operator<<(long int) = 0; virtual FileOutputType& operator<<(unsigned int) = 0; virtual FileOutputType& operator<<(long unsigned int) = 0; virtual FileOutputType& operator<<(float) = 0; virtual FileOutputType& operator<<(double) = 0; virtual ~FileOutputType() { }; }; class OFStream: public FileOutputType { public: OFStream(std::string filename); ~OFStream(); void close(); OFStream& operator<<(const std::string &str); OFStream& operator<<(int); OFStream& operator<<(long int); OFStream& operator<<(unsigned int); OFStream& operator<<(long unsigned int); OFStream& operator<<(float); OFStream& operator<<(double); private: std::ofstream ofstr; }; #ifndef NO_ZLIB class GZipFileOutput: public FileOutputType { public: GZipFileOutput(std::string filename); ~GZipFileOutput(); void close(); GZipFileOutput& operator<<(const std::string &str); GZipFileOutput& operator<<(int); GZipFileOutput& operator<<(long int); GZipFileOutput& operator<<(unsigned int); GZipFileOutput& operator<<(long unsigned int); GZipFileOutput& operator<<(float); GZipFileOutput& operator<<(double); private: gzFile gzf; bool open; }; #endif class SimpleFileOutput { public: SimpleFileOutput(std::string filename); ~SimpleFileOutput(); void close(); SimpleFileOutput& operator<<(const std::string &str); SimpleFileOutput& operator<<(int); SimpleFileOutput& operator<<(long int); SimpleFileOutput& operator<<(unsigned int); SimpleFileOutput& operator<<(long unsigned int); SimpleFileOutput& operator<<(float); SimpleFileOutput& operator<<(double); private: bool ends_with(std::string const &filename, std::string const &suffix) { if (filename.length() < suffix.length()) return false; return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix)); } std::unique_ptr<FileOutputType> outfs; }; #endif <commit_msg>Explicit bool conversion for compatibility.<commit_after>#ifndef SIMPLE_IO #define SIMPLE_IO #include <string> #include <iostream> #include <fstream> #include <memory> #ifndef NO_ZLIB #include "zlib.h" #endif class FileInputType { public: virtual bool getline(std::string &line) = 0; virtual ~FileInputType() { }; }; class IFStreamInput : public FileInputType { public: IFStreamInput(std::string filename) { ifstr.open(filename, std::ios_base::in); }; ~IFStreamInput() { ifstr.close(); } bool getline(std::string &line) { return (bool)std::getline(ifstr, line); } private: std::ifstream ifstr; }; #ifndef NO_ZLIB class GZipFileInput : public FileInputType { public: GZipFileInput(std::string filename); ~GZipFileInput(); bool getline(std::string &line); private: gzFile gzf; }; #endif class SimpleFileInput { public: SimpleFileInput(std::string filename); ~SimpleFileInput() { }; bool getline(std::string &line) { return infs->getline(line); } private: bool ends_with(std::string const &filename, std::string const &suffix) { if (filename.length() < suffix.length()) return false; return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix)); } std::unique_ptr<FileInputType> infs; }; class FileOutputType { public: virtual void close() = 0; virtual FileOutputType& operator<<(const std::string &str) = 0; virtual FileOutputType& operator<<(int) = 0; virtual FileOutputType& operator<<(long int) = 0; virtual FileOutputType& operator<<(unsigned int) = 0; virtual FileOutputType& operator<<(long unsigned int) = 0; virtual FileOutputType& operator<<(float) = 0; virtual FileOutputType& operator<<(double) = 0; virtual ~FileOutputType() { }; }; class OFStream: public FileOutputType { public: OFStream(std::string filename); ~OFStream(); void close(); OFStream& operator<<(const std::string &str); OFStream& operator<<(int); OFStream& operator<<(long int); OFStream& operator<<(unsigned int); OFStream& operator<<(long unsigned int); OFStream& operator<<(float); OFStream& operator<<(double); private: std::ofstream ofstr; }; #ifndef NO_ZLIB class GZipFileOutput: public FileOutputType { public: GZipFileOutput(std::string filename); ~GZipFileOutput(); void close(); GZipFileOutput& operator<<(const std::string &str); GZipFileOutput& operator<<(int); GZipFileOutput& operator<<(long int); GZipFileOutput& operator<<(unsigned int); GZipFileOutput& operator<<(long unsigned int); GZipFileOutput& operator<<(float); GZipFileOutput& operator<<(double); private: gzFile gzf; bool open; }; #endif class SimpleFileOutput { public: SimpleFileOutput(std::string filename); ~SimpleFileOutput(); void close(); SimpleFileOutput& operator<<(const std::string &str); SimpleFileOutput& operator<<(int); SimpleFileOutput& operator<<(long int); SimpleFileOutput& operator<<(unsigned int); SimpleFileOutput& operator<<(long unsigned int); SimpleFileOutput& operator<<(float); SimpleFileOutput& operator<<(double); private: bool ends_with(std::string const &filename, std::string const &suffix) { if (filename.length() < suffix.length()) return false; return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix)); } std::unique_ptr<FileOutputType> outfs; }; #endif <|endoftext|>
<commit_before>#include <string> #include <fstream> #include <iostream> #include "map.h" using namespace std; Map::Map() {} Map::~Map() {} void Map::LoadMap(string MapFileName){ string Temp; fstream MapFile; int X = 0; int Y = 0; MapFile.open (MapFileName, fstream::in); while ( MapFile >> Temp ){ cout << Temp; mapArray[X][Y] = (unsigned short int)stoi(Temp); X++; if (X > MaxX){X = 0; Y++;} } MapFile.close(); } int Map::Point(int X, int Y){ return (int)mapArray[X][Y]; } bool Map::Passable(int X, int Y){ return (mapArray[X][Y] < PassableThreshhold); } string Map::GetPlot(int X, int Y){ //Returns a 20x20 chunk of the map string RetVal; string Temp; for (int i = X; i < X + 20; i++){ for (int j = Y; j < Y + 20; j++){ if (i <= MaxX && i > -1 && j <= MaxY && j > -1){ Temp = to_string(mapArray[i][j]); if (Temp.length() == 1) { RetVal += "0";} RetVal += Temp; } else { RetVal += "-1"; } } } return RetVal; }<commit_msg>Work in progress<commit_after>#include <string> #include <fstream> #include <iostream> #include "map.h" using namespace std; Map::Map() {} Map::~Map() {} void Map::LoadMap(string MapFileName){ string Temp; fstream MapFile; int X = 0; int Y = 0; int F = 0; MapFile.open (MapFileName, fstream::in); while ( MapFile >> Temp ){ for (int i = 0; i < Temp.length(); i++){ if (Temp[i] == ","){ mapArray[X][Y] = (unsigned short int)stoi(Temp.substr(F,i-F)); F = i+1; cout << mapArray[X][Y]; } X++; if (X > MaxX){X = 0; Y++;} } MapFile.close(); } int Map::Point(int X, int Y){ return (int)mapArray[X][Y]; } bool Map::Passable(int X, int Y){ return (mapArray[X][Y] < PassableThreshhold); } string Map::GetPlot(int X, int Y){ //Returns a 20x20 chunk of the map string RetVal; string Temp; for (int i = X; i < X + 20; i++){ for (int j = Y; j < Y + 20; j++){ if (i <= MaxX && i > -1 && j <= MaxY && j > -1){ Temp = to_string(mapArray[i][j]); if (Temp.length() == 1) { RetVal += "0";} RetVal += Temp; } else { RetVal += "-1"; } } } return RetVal; }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsystemdeviceinfo.h" #include "qsysteminfocommon_p.h" #include <QMetaType> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate) #ifdef QT_SIMULATOR QSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); } #endif // device /*! \class QSystemDeviceInfo \ingroup systeminfo \inmodule QtSystemInfo \brief The QSystemDeviceInfo class provides access to device information from the system. \fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent) Constructs a QSystemDeviceInfo with the given \a parent. */ /*! \enum QSystemDisplayInfo::DisplayOrientation This enum describes the current orientation of the display. \value Unknown Orientation could not be determined. \value Landscape Orientation is in landscape. \value Portrait Orientation is in portrait. \value InvertedLandscape Orientation is landscape inverted. \value InvertedPortrait Orientation is portrait inverted. */ /*! \fn void QSystemDeviceInfo::batteryLevelChanged(int level) This signal is emitted when battery level has changed. \a level is the new level. */ /*! \fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status) This signal is emitted when battery status has changed. \a status is the new status. */ /*! \fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state) This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall. \a state is the new power state. */ /*! \fn void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile) This signal is emitted whenever the users active profile changes, specified by \a profile. */ /*! \enum QSystemDeviceInfo::BatteryStatus This enum describes the status of the main battery. \value NoBatteryLevel Battery level undetermined. \value BatteryCritical Battery level is critical 3% or less. \value BatteryVeryLow Battery level is very low, 10% or less. \value BatteryLow Battery level is low 40% or less. \value BatteryNormal Battery level is above 40%. */ /*! \enum QSystemDeviceInfo::PowerState This enum describes the power state: \value UnknownPower Power error. \value BatteryPower On battery power. \value WallPower On wall power. \value WallPowerChargingBattery On wall power and charging main battery. */ /*! \enum QSystemDeviceInfo::Profile This enum describes the current operating profile of the device or computer. \value UnknownProfile Profile unknown or error. \value SilentProfile Silent profile. \value NormalProfile Normal profile. \value LoudProfile Loud profile. \value VibProfile Vibrate profile. \value OfflineProfile Offline profile. \value PowersaveProfile Powersave profile. \value CustomProfile Custom profile. */ /*! \enum QSystemDeviceInfo::SimStatus This enum describes the status is the sim card or cards. \value SimNotAvailable SIM is not available on this device. \value SingleSimAvailable One SIM card is available on this. \value DualSimAvailable Two SIM cards are available on this device. \value SimLocked Device has SIM lock enabled. */ /*! \enum QSystemDeviceInfo::InputMethod This enum describes the device method of user input. \value Keys Device has key/buttons. \value Keypad Device has keypad (1,2,3, etc). \value Keyboard Device has qwerty keyboard. \value SingleTouch Device has single touch screen. \value MultiTouch Device has muti touch screen. \value Mouse Device has a mouse. */ /*! \fn void QSystemDeviceInfo::bluetoothStateChanged(bool on) This signal is emitted whenever bluetooth state changes, specified by \a on. */ QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent) : QObject(parent), d(deviceInfoPrivate()) { qRegisterMetaType<QSystemDeviceInfo::BatteryStatus>("QSystemDeviceInfo::BatteryStatus"); qRegisterMetaType<QSystemDeviceInfo::PowerState>("QSystemDeviceInfo::PowerState"); qRegisterMetaType<QSystemDeviceInfo::SimStatus>("QSystemDeviceInfo::SimStatus"); qRegisterMetaType<QSystemDeviceInfo::Profile>("QSystemDeviceInfo::Profile"); qRegisterMetaType<QSystemDeviceInfo::InputMethodFlags>("QSystemDeviceInfo::InputMethodFlags"); connect(d,SIGNAL(batteryLevelChanged(int)), this,SIGNAL(batteryLevelChanged(int))); connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)), this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))); connect(d,SIGNAL(bluetoothStateChanged(bool)), this,SIGNAL(bluetoothStateChanged(bool))); connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)), this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile))); connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)), this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState))); } /*! Destroys the QSystemDeviceInfo object. */ QSystemDeviceInfo::~QSystemDeviceInfo() { } /*! \internal This function is called when the client connects to signals. \sa connectNotify() */ void QSystemDeviceInfo::connectNotify(const char *signal) { Q_UNUSED(signal); } /*! \internal This function is called when the client disconnects from the signals. \sa connectNotify() */ void QSystemDeviceInfo::disconnectNotify(const char *signal) { if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( batteryLevelChanged(int))))) { disconnect(d,SIGNAL(batteryLevelChanged(int)), this,SIGNAL(batteryLevelChanged(int))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) { disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)), this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( bluetoothStateChanged(bool))))) { disconnect(d,SIGNAL(bluetoothStateChanged(bool)), this,SIGNAL(bluetoothStateChanged(bool))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( currentProfileChanged(QSystemDeviceInfo::Profile))))) { disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)), this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( powerStateChanged(QSystemDeviceInfo::PowerState))))) { disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)), this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState))); } } /*! \property QSystemDeviceInfo::inputMethodType \brief The supported inputmethods. Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses. */ QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType() { return deviceInfoPrivate()->inputMethodType(); } /*! \property QSystemDeviceInfo::imei \brief The IMEI. Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none. */ QString QSystemDeviceInfo::imei() { return deviceInfoPrivate()->imei(); } /*! \property QSystemDeviceInfo::imsi \brief The IMSI. Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none. */ QString QSystemDeviceInfo::imsi() { return deviceInfoPrivate()->imsi(); } /*! \property QSystemDeviceInfo::manufacturer \brief The manufacture's name. Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor of the motherboard. */ QString QSystemDeviceInfo::manufacturer() { return deviceInfoPrivate()->manufacturer(); } /*! \property QSystemDeviceInfo::model \brief The model name. Returns the model information of the device. In the case of desktops where no model information is present, the CPU architect, such as i686, and machine type, such as Server, Desktop or Laptop. */ QString QSystemDeviceInfo::model() { return deviceInfoPrivate()->model(); } /*! \property QSystemDeviceInfo::productName \brief The product name. Returns the product name of the device. In the case where no product information is available, */ QString QSystemDeviceInfo::productName() { return deviceInfoPrivate()->productName(); } /*! \property QSystemDeviceInfo::batteryLevel \brief The battery level. Returns the battery charge level as percentage 1 - 100 scale. */ int QSystemDeviceInfo::batteryLevel() const { return deviceInfoPrivate()->batteryLevel(); } /*! \property QSystemDeviceInfo::batteryStatus \brief The battery status. Returns the battery charge status. */ QSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus() { int level = batteryLevel(); if(level < 4) { return QSystemDeviceInfo::BatteryCritical; } else if(level < 11) { return QSystemDeviceInfo::BatteryVeryLow; } else if(level < 41) { return QSystemDeviceInfo::BatteryLow; } else if(level > 40) { return QSystemDeviceInfo::BatteryNormal; } return QSystemDeviceInfo::NoBatteryLevel; } /*! \property QSystemDeviceInfo::simStatus \brief the status of the sim card. Returns the QSystemDeviceInfo::simStatus status of SIM card. */ QSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus() { return deviceInfoPrivate()->simStatus(); } /*! \property QSystemDeviceInfo::isDeviceLocked \brief Device lock. Returns true if the device is locked, otherwise false. */ bool QSystemDeviceInfo::isDeviceLocked() { return deviceInfoPrivate()->isDeviceLocked(); } /*! \property QSystemDeviceInfo::currentProfile \brief the device profile Gets the current QSystemDeviceInfo::currentProfile device profile. */ QSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile() { return deviceInfoPrivate()->currentProfile(); } /*! \property QSystemDeviceInfo::currentPowerState \brief the power state. Gets the current QSystemDeviceInfo::currentPowerState state. */ QSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState() { return deviceInfoPrivate()->currentPowerState(); } /*! \property QSystemDeviceInfo::currentBluetoothPowerState \brief bluetooth power state. Gets the current bluetooth power state. */ bool QSystemDeviceInfo::currentBluetoothPowerState() { return deviceInfoPrivate()->currentBluetoothPowerState(); } #include "moc_qsystemdeviceinfo.cpp" QTM_END_NAMESPACE <commit_msg>Minor fix to the documentation<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsystemdeviceinfo.h" #include "qsysteminfocommon_p.h" #include <QMetaType> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate) #ifdef QT_SIMULATOR QSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); } #endif // device /*! \class QSystemDeviceInfo \ingroup systeminfo \inmodule QtSystemInfo \brief The QSystemDeviceInfo class provides access to device information from the system. */ /*! \fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent) Constructs a QSystemDeviceInfo with the given \a parent. */ /*! \enum QSystemDisplayInfo::DisplayOrientation This enum describes the current orientation of the display. \value Unknown Orientation could not be determined. \value Landscape Orientation is in landscape. \value Portrait Orientation is in portrait. \value InvertedLandscape Orientation is landscape inverted. \value InvertedPortrait Orientation is portrait inverted. */ /*! \fn void QSystemDeviceInfo::batteryLevelChanged(int level) This signal is emitted when battery level has changed. \a level is the new level. */ /*! \fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status) This signal is emitted when battery status has changed. \a status is the new status. */ /*! \fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state) This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall. \a state is the new power state. */ /*! \fn void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile) This signal is emitted whenever the users active profile changes, specified by \a profile. */ /*! \enum QSystemDeviceInfo::BatteryStatus This enum describes the status of the main battery. \value NoBatteryLevel Battery level undetermined. \value BatteryCritical Battery level is critical 3% or less. \value BatteryVeryLow Battery level is very low, 10% or less. \value BatteryLow Battery level is low 40% or less. \value BatteryNormal Battery level is above 40%. */ /*! \enum QSystemDeviceInfo::PowerState This enum describes the power state: \value UnknownPower Power error. \value BatteryPower On battery power. \value WallPower On wall power. \value WallPowerChargingBattery On wall power and charging main battery. */ /*! \enum QSystemDeviceInfo::Profile This enum describes the current operating profile of the device or computer. \value UnknownProfile Profile unknown or error. \value SilentProfile Silent profile. \value NormalProfile Normal profile. \value LoudProfile Loud profile. \value VibProfile Vibrate profile. \value OfflineProfile Offline profile. \value PowersaveProfile Powersave profile. \value CustomProfile Custom profile. */ /*! \enum QSystemDeviceInfo::SimStatus This enum describes the status is the sim card or cards. \value SimNotAvailable SIM is not available on this device. \value SingleSimAvailable One SIM card is available on this. \value DualSimAvailable Two SIM cards are available on this device. \value SimLocked Device has SIM lock enabled. */ /*! \enum QSystemDeviceInfo::InputMethod This enum describes the device method of user input. \value Keys Device has key/buttons. \value Keypad Device has keypad (1,2,3, etc). \value Keyboard Device has qwerty keyboard. \value SingleTouch Device has single touch screen. \value MultiTouch Device has muti touch screen. \value Mouse Device has a mouse. */ /*! \fn void QSystemDeviceInfo::bluetoothStateChanged(bool on) This signal is emitted whenever bluetooth state changes, specified by \a on. */ QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent) : QObject(parent), d(deviceInfoPrivate()) { qRegisterMetaType<QSystemDeviceInfo::BatteryStatus>("QSystemDeviceInfo::BatteryStatus"); qRegisterMetaType<QSystemDeviceInfo::PowerState>("QSystemDeviceInfo::PowerState"); qRegisterMetaType<QSystemDeviceInfo::SimStatus>("QSystemDeviceInfo::SimStatus"); qRegisterMetaType<QSystemDeviceInfo::Profile>("QSystemDeviceInfo::Profile"); qRegisterMetaType<QSystemDeviceInfo::InputMethodFlags>("QSystemDeviceInfo::InputMethodFlags"); connect(d,SIGNAL(batteryLevelChanged(int)), this,SIGNAL(batteryLevelChanged(int))); connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)), this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))); connect(d,SIGNAL(bluetoothStateChanged(bool)), this,SIGNAL(bluetoothStateChanged(bool))); connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)), this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile))); connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)), this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState))); } /*! Destroys the QSystemDeviceInfo object. */ QSystemDeviceInfo::~QSystemDeviceInfo() { } /*! \internal This function is called when the client connects to signals. \sa connectNotify() */ void QSystemDeviceInfo::connectNotify(const char *signal) { Q_UNUSED(signal); } /*! \internal This function is called when the client disconnects from the signals. \sa connectNotify() */ void QSystemDeviceInfo::disconnectNotify(const char *signal) { if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( batteryLevelChanged(int))))) { disconnect(d,SIGNAL(batteryLevelChanged(int)), this,SIGNAL(batteryLevelChanged(int))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) { disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)), this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( bluetoothStateChanged(bool))))) { disconnect(d,SIGNAL(bluetoothStateChanged(bool)), this,SIGNAL(bluetoothStateChanged(bool))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( currentProfileChanged(QSystemDeviceInfo::Profile))))) { disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)), this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile))); } if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL( powerStateChanged(QSystemDeviceInfo::PowerState))))) { disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)), this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState))); } } /*! \property QSystemDeviceInfo::inputMethodType \brief The supported inputmethods. Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses. */ QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType() { return deviceInfoPrivate()->inputMethodType(); } /*! \property QSystemDeviceInfo::imei \brief The IMEI. Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none. */ QString QSystemDeviceInfo::imei() { return deviceInfoPrivate()->imei(); } /*! \property QSystemDeviceInfo::imsi \brief The IMSI. Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none. */ QString QSystemDeviceInfo::imsi() { return deviceInfoPrivate()->imsi(); } /*! \property QSystemDeviceInfo::manufacturer \brief The manufacture's name. Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor of the motherboard. */ QString QSystemDeviceInfo::manufacturer() { return deviceInfoPrivate()->manufacturer(); } /*! \property QSystemDeviceInfo::model \brief The model name. Returns the model information of the device. In the case of desktops where no model information is present, the CPU architect, such as i686, and machine type, such as Server, Desktop or Laptop. */ QString QSystemDeviceInfo::model() { return deviceInfoPrivate()->model(); } /*! \property QSystemDeviceInfo::productName \brief The product name. Returns the product name of the device. In the case where no product information is available, */ QString QSystemDeviceInfo::productName() { return deviceInfoPrivate()->productName(); } /*! \property QSystemDeviceInfo::batteryLevel \brief The battery level. Returns the battery charge level as percentage 1 - 100 scale. */ int QSystemDeviceInfo::batteryLevel() const { return deviceInfoPrivate()->batteryLevel(); } /*! \property QSystemDeviceInfo::batteryStatus \brief The battery status. Returns the battery charge status. */ QSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus() { int level = batteryLevel(); if(level < 4) { return QSystemDeviceInfo::BatteryCritical; } else if(level < 11) { return QSystemDeviceInfo::BatteryVeryLow; } else if(level < 41) { return QSystemDeviceInfo::BatteryLow; } else if(level > 40) { return QSystemDeviceInfo::BatteryNormal; } return QSystemDeviceInfo::NoBatteryLevel; } /*! \property QSystemDeviceInfo::simStatus \brief the status of the sim card. Returns the QSystemDeviceInfo::simStatus status of SIM card. */ QSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus() { return deviceInfoPrivate()->simStatus(); } /*! \property QSystemDeviceInfo::isDeviceLocked \brief Device lock. Returns true if the device is locked, otherwise false. */ bool QSystemDeviceInfo::isDeviceLocked() { return deviceInfoPrivate()->isDeviceLocked(); } /*! \property QSystemDeviceInfo::currentProfile \brief the device profile Gets the current QSystemDeviceInfo::currentProfile device profile. */ QSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile() { return deviceInfoPrivate()->currentProfile(); } /*! \property QSystemDeviceInfo::currentPowerState \brief the power state. Gets the current QSystemDeviceInfo::currentPowerState state. */ QSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState() { return deviceInfoPrivate()->currentPowerState(); } /*! \property QSystemDeviceInfo::currentBluetoothPowerState \brief bluetooth power state. Gets the current bluetooth power state. */ bool QSystemDeviceInfo::currentBluetoothPowerState() { return deviceInfoPrivate()->currentBluetoothPowerState(); } #include "moc_qsystemdeviceinfo.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>#include <mtp/metadata/Library.h> #include <mtp/ptp/Session.h> #include <mtp/log.h> #include <unordered_map> namespace mtp { namespace { const std::string UknownArtist ("UknownArtist"); const std::string UknownAlbum ("UknownAlbum"); const std::string VariousArtists ("VariousArtists"); } Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId) { NameToObjectIdMap list; auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId); list.reserve(folders.ObjectHandles.size()); for(auto id : folders.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); list.insert(std::make_pair(name, id)); } return list; } ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name) { auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId); for (auto id : objects.ObjectHandles) { auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); if (name == oname) return id; } return _session->CreateDirectory(name, parentId, _storage).ObjectId; } Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session) { auto storages = _session->GetStorageIDs(); if (storages.StorageIDs.empty()) throw std::runtime_error("no storages found"); u64 progress = 0, total = 0; if (reporter) reporter(State::Initialising, progress, total); _artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist); { auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum); _albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end(); } _storage = storages.StorageIDs[0]; //picking up first storage. //zune fails to create artist/album without storage id { msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root); for (auto id : rootFolders.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); if (name == "Artists") _artistsFolder = id; else if (name == "Albums") _albumsFolder = id; else if (name == "Music") _musicFolder = id; } } if (_artistSupported && _artistsFolder == ObjectId()) _artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId; if (_albumsFolder == ObjectId()) _albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId; if (_musicFolder == ObjectId()) _musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId; debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0); debug("albums folder: ", _albumsFolder.Id); debug("music folder: ", _musicFolder.Id); auto musicFolders = ListAssociations(_musicFolder); using namespace mtp; msg::ObjectHandles artists; if (_artistSupported) { debug("getting artists..."); if (reporter) reporter(State::QueryingArtists, progress, total); artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device); total += artists.ObjectHandles.size(); if (reporter) reporter(State::LoadingArtists, progress, total); } if (_artistSupported) { for (auto id : artists.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name); debug("artist: ", name, "\t", id.Id); auto artist = std::make_shared<Artist>(); artist->Id = id; artist->Name = name; auto it = musicFolders.find(name); if (it != musicFolders.end()) artist->MusicFolderId = it->second; else artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId; _artists.insert(std::make_pair(name, artist)); if (reporter) reporter(State::LoadingArtists, ++progress, total); } } std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders; { debug("getting albums..."); if (reporter) reporter(State::QueryingAlbums, progress, total); auto albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device); total += albums.ObjectHandles.size(); if (reporter) reporter(State::LoadingAlbums, progress, total); for (auto id : albums.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name); auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist); std::string albumDate; if (_albumDateAuthoredSupported) albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored); auto artist = GetArtist(artistName); if (!artist) artist = CreateArtist(artistName); debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate); auto album = std::make_shared<Album>(); album->Name = name; album->Artist = artist; album->Id = id; album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0; if (albumFolders.find(artist) == albumFolders.end()) { albumFolders[artist] = ListAssociations(artist->MusicFolderId); } auto it = albumFolders.find(artist); if (it == albumFolders.end()) throw std::runtime_error("no iterator after insert, internal error"); { auto refs = _session->GetObjectReferences(id).ObjectHandles; std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin())); for(auto trackId : refs) { auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name); auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track); debug("[", index, "]: ", name); album->Tracks.insert(std::make_pair(name, index)); } } const auto & albums = it->second; auto alit = albums.find(name); if (alit != albums.end()) album->MusicFolderId = alit->second; else album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); if (reporter) reporter(State::LoadingAlbums, ++progress, total); } } if (reporter) reporter(State::Loaded, progress, total); } Library::~Library() { } Library::ArtistPtr Library::GetArtist(std::string name) { if (name.empty()) name = UknownArtist; auto it = _artists.find(name); return it != _artists.end()? it->second: ArtistPtr(); } Library::ArtistPtr Library::CreateArtist(std::string name) { if (name.empty()) name = UknownArtist; auto artist = std::make_shared<Artist>(); artist->Name = name; artist->MusicFolderId = GetOrCreate(_musicFolder, name); if (_artistSupported) { ByteArray propList; OutputStream os(propList); os.Write32(2); //number of props os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name + ".art"); auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList); artist->Id = response.ObjectId; } _artists.insert(std::make_pair(name, artist)); return artist; } Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name) { if (name.empty()) name = UknownAlbum; auto it = _albums.find(std::make_pair(artist, name)); return it != _albums.end()? it->second: AlbumPtr(); } Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year) { if (!artist) throw std::runtime_error("artists is required"); if (name.empty()) name = UknownAlbum; ByteArray propList; OutputStream os(propList); bool sendYear = year != 0 && _albumDateAuthoredSupported; os.Write32(3 + (sendYear? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name + "--" + name + ".alb"); if (sendYear) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::DateAuthored)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(ConvertYear(year)); } auto album = std::make_shared<Album>(); album->Artist = artist; album->Name = name; album->Year = year; album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name); auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList); album->Id = response.ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); return album; } bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex) { if (!album) return false; auto & tracks = album->Tracks; auto range = tracks.equal_range(name); for(auto i = range.first; i != range.second; ++i) { if (i->second == trackIndex) return true; } return false; } Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist, const AlbumPtr & album, ObjectFormat type, std::string name, const std::string & genre, int trackIndex, const std::string &filename, size_t size) { ByteArray propList; OutputStream os(propList); os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); if (trackIndex) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Track)); os.Write16(static_cast<u16>(DataTypeCode::Uint16)); os.Write16(trackIndex); } if (!genre.empty()) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Genre)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(genre); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(filename); auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList); NewTrackInfo ti; ti.Id = response.ObjectId; ti.Name = name; ti.Index = trackIndex; return ti; } void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti) { if (!album) return; auto & refs = album->Refs; auto & tracks = album->Tracks; msg::ObjectHandles handles; std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles)); handles.ObjectHandles.push_back(ti.Id); _session->SetObjectReferences(album->Id, handles); refs.insert(ti.Id); tracks.insert(std::make_pair(ti.Name, ti.Index)); } bool Library::Supported(const mtp::SessionPtr & session) { auto & gdi = session->GetDeviceInfo(); return gdi.Supports(OperationCode::SendObjectPropList) && gdi.Supports(OperationCode::SetObjectReferences) && gdi.Supports(ObjectFormat::AbstractAudioAlbum); ; } } <commit_msg>load object refs at the beginning, providing consistent total<commit_after>#include <mtp/metadata/Library.h> #include <mtp/ptp/Session.h> #include <mtp/log.h> #include <unordered_map> namespace mtp { namespace { const std::string UknownArtist ("UknownArtist"); const std::string UknownAlbum ("UknownAlbum"); const std::string VariousArtists ("VariousArtists"); } Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId) { NameToObjectIdMap list; auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId); list.reserve(folders.ObjectHandles.size()); for(auto id : folders.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); list.insert(std::make_pair(name, id)); } return list; } ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name) { auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId); for (auto id : objects.ObjectHandles) { auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); if (name == oname) return id; } return _session->CreateDirectory(name, parentId, _storage).ObjectId; } Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session) { auto storages = _session->GetStorageIDs(); if (storages.StorageIDs.empty()) throw std::runtime_error("no storages found"); u64 progress = 0, total = 0; if (reporter) reporter(State::Initialising, progress, total); _artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist); { auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum); _albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end(); } _storage = storages.StorageIDs[0]; //picking up first storage. //zune fails to create artist/album without storage id { msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root); for (auto id : rootFolders.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename); if (name == "Artists") _artistsFolder = id; else if (name == "Albums") _albumsFolder = id; else if (name == "Music") _musicFolder = id; } } if (_artistSupported && _artistsFolder == ObjectId()) _artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId; if (_albumsFolder == ObjectId()) _albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId; if (_musicFolder == ObjectId()) _musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId; debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0); debug("albums folder: ", _albumsFolder.Id); debug("music folder: ", _musicFolder.Id); auto musicFolders = ListAssociations(_musicFolder); using namespace mtp; msg::ObjectHandles artists, albums; if (_artistSupported) { debug("getting artists..."); if (reporter) reporter(State::QueryingArtists, progress, total); artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device); total += artists.ObjectHandles.size(); if (reporter) reporter(State::LoadingArtists, progress, total); } { debug("getting albums..."); if (reporter) reporter(State::QueryingAlbums, progress, total); albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device); total += albums.ObjectHandles.size(); if (reporter) reporter(State::LoadingAlbums, progress, total); } if (_artistSupported) { for (auto id : artists.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name); debug("artist: ", name, "\t", id.Id); auto artist = std::make_shared<Artist>(); artist->Id = id; artist->Name = name; auto it = musicFolders.find(name); if (it != musicFolders.end()) artist->MusicFolderId = it->second; else artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId; _artists.insert(std::make_pair(name, artist)); if (reporter) reporter(State::LoadingArtists, ++progress, total); } } std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders; for (auto id : albums.ObjectHandles) { auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name); auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist); std::string albumDate; if (_albumDateAuthoredSupported) albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored); auto artist = GetArtist(artistName); if (!artist) artist = CreateArtist(artistName); debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate); auto album = std::make_shared<Album>(); album->Name = name; album->Artist = artist; album->Id = id; album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0; if (albumFolders.find(artist) == albumFolders.end()) { albumFolders[artist] = ListAssociations(artist->MusicFolderId); } auto it = albumFolders.find(artist); if (it == albumFolders.end()) throw std::runtime_error("no iterator after insert, internal error"); { auto refs = _session->GetObjectReferences(id).ObjectHandles; std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin())); for(auto trackId : refs) { auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name); auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track); debug("[", index, "]: ", name); album->Tracks.insert(std::make_pair(name, index)); } } const auto & albums = it->second; auto alit = albums.find(name); if (alit != albums.end()) album->MusicFolderId = alit->second; else album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); if (reporter) reporter(State::LoadingAlbums, ++progress, total); } if (reporter) reporter(State::Loaded, progress, total); } Library::~Library() { } Library::ArtistPtr Library::GetArtist(std::string name) { if (name.empty()) name = UknownArtist; auto it = _artists.find(name); return it != _artists.end()? it->second: ArtistPtr(); } Library::ArtistPtr Library::CreateArtist(std::string name) { if (name.empty()) name = UknownArtist; auto artist = std::make_shared<Artist>(); artist->Name = name; artist->MusicFolderId = GetOrCreate(_musicFolder, name); if (_artistSupported) { ByteArray propList; OutputStream os(propList); os.Write32(2); //number of props os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name + ".art"); auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList); artist->Id = response.ObjectId; } _artists.insert(std::make_pair(name, artist)); return artist; } Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name) { if (name.empty()) name = UknownAlbum; auto it = _albums.find(std::make_pair(artist, name)); return it != _albums.end()? it->second: AlbumPtr(); } Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year) { if (!artist) throw std::runtime_error("artists is required"); if (name.empty()) name = UknownAlbum; ByteArray propList; OutputStream os(propList); bool sendYear = year != 0 && _albumDateAuthoredSupported; os.Write32(3 + (sendYear? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name + "--" + name + ".alb"); if (sendYear) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::DateAuthored)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(ConvertYear(year)); } auto album = std::make_shared<Album>(); album->Artist = artist; album->Name = name; album->Year = year; album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name); auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList); album->Id = response.ObjectId; _albums.insert(std::make_pair(std::make_pair(artist, name), album)); return album; } bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex) { if (!album) return false; auto & tracks = album->Tracks; auto range = tracks.equal_range(name); for(auto i = range.first; i != range.second; ++i) { if (i->second == trackIndex) return true; } return false; } Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist, const AlbumPtr & album, ObjectFormat type, std::string name, const std::string & genre, int trackIndex, const std::string &filename, size_t size) { ByteArray propList; OutputStream os(propList); os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props if (_artistSupported) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ArtistId)); os.Write16(static_cast<u16>(DataTypeCode::Uint32)); os.Write32(artist->Id.Id); } else { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Artist)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(artist->Name); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Name)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(name); if (trackIndex) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Track)); os.Write16(static_cast<u16>(DataTypeCode::Uint16)); os.Write16(trackIndex); } if (!genre.empty()) { os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::Genre)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(genre); } os.Write32(0); //object handle os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename)); os.Write16(static_cast<u16>(DataTypeCode::String)); os.WriteString(filename); auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList); NewTrackInfo ti; ti.Id = response.ObjectId; ti.Name = name; ti.Index = trackIndex; return ti; } void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti) { if (!album) return; auto & refs = album->Refs; auto & tracks = album->Tracks; msg::ObjectHandles handles; std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles)); handles.ObjectHandles.push_back(ti.Id); _session->SetObjectReferences(album->Id, handles); refs.insert(ti.Id); tracks.insert(std::make_pair(ti.Name, ti.Index)); } bool Library::Supported(const mtp::SessionPtr & session) { auto & gdi = session->GetDeviceInfo(); return gdi.Supports(OperationCode::SendObjectPropList) && gdi.Supports(OperationCode::SetObjectReferences) && gdi.Supports(ObjectFormat::AbstractAudioAlbum); ; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OOXMLStreamImpl.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2008-03-05 17:06:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_OOXML_STREAM_IMPL_HXX #define INCLUDED_OOXML_STREAM_IMPL_HXX #ifndef INCLUDED_OOXML_DOCUMENT_HXX #include <ooxml/OOXMLDocument.hxx> #endif #ifndef _COMPHELPER_STORAGEHELPER_HXX #include <comphelper/storagehelper.hxx> #endif #ifndef _COM_SUN_STAR_EMBED_XRELATIONSHIPACCESS_HPP_ #include <com/sun/star/embed/XRelationshipAccess.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_ #include <com/sun/star/io/XStream.hpp> #endif namespace writerfilter { namespace ooxml { using namespace com::sun::star; class OOXMLStreamImpl : public OOXMLStream { void init(); uno::Reference<uno::XComponentContext> mxContext; uno::Reference<embed::XStorage> mxStorage; uno::Reference<io::XInputStream> mxInputStream; uno::Reference<embed::XRelationshipAccess> mxRelationshipAccess; uno::Reference<io::XStream> mxDocumentStream; uno::Reference<xml::sax::XFastParser> mxFastParser; uno::Reference<xml::sax::XFastTokenHandler> mxFastTokenHandler; StreamType_t mnStreamType; rtl::OUString msId; rtl::OUString msPath; bool getTarget(uno::Reference<embed::XRelationshipAccess> xRelationshipAccess, StreamType_t nStreamType, const ::rtl::OUString & rId, ::rtl::OUString & rDocumentTarget); public: typedef boost::shared_ptr<OOXMLStreamImpl> Pointer_t; OOXMLStreamImpl (OOXMLStreamImpl & rStream, StreamType_t nType); OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<embed::XStorage> xStorage, StreamType_t nType); OOXMLStreamImpl(OOXMLStreamImpl & rStream, const rtl::OUString & rId); OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<embed::XStorage> xStorage, const rtl::OUString & rId); virtual ~OOXMLStreamImpl(); virtual uno::Reference<xml::sax::XParser> getParser(); virtual uno::Reference<xml::sax::XFastParser> getFastParser(); virtual uno::Reference<io::XInputStream> getDocumentStream(); virtual uno::Reference<io::XInputStream> getInputStream(); virtual uno::Reference<uno::XComponentContext> getContext(); ::rtl::OUString getTargetForId(const ::rtl::OUString & rId); virtual uno::Reference<xml::sax::XFastTokenHandler> getFastTokenHandler(uno::Reference<uno::XComponentContext> rContext); void setInputStream(uno::Reference<io::XInputStream> rxInputStream); }; }} #endif // INCLUDED_OOXML_STREAM_IMPL_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.4); FILE MERGED 2008/04/01 16:06:46 thb 1.6.4.3: #i85898# Stripping all external header guards 2008/04/01 13:02:32 thb 1.6.4.2: #i85898# Stripping all external header guards 2008/03/28 15:53:03 rt 1.6.4.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OOXMLStreamImpl.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_OOXML_STREAM_IMPL_HXX #define INCLUDED_OOXML_STREAM_IMPL_HXX #include <ooxml/OOXMLDocument.hxx> #include <comphelper/storagehelper.hxx> #include <com/sun/star/embed/XRelationshipAccess.hpp> #include <com/sun/star/io/XStream.hpp> namespace writerfilter { namespace ooxml { using namespace com::sun::star; class OOXMLStreamImpl : public OOXMLStream { void init(); uno::Reference<uno::XComponentContext> mxContext; uno::Reference<embed::XStorage> mxStorage; uno::Reference<io::XInputStream> mxInputStream; uno::Reference<embed::XRelationshipAccess> mxRelationshipAccess; uno::Reference<io::XStream> mxDocumentStream; uno::Reference<xml::sax::XFastParser> mxFastParser; uno::Reference<xml::sax::XFastTokenHandler> mxFastTokenHandler; StreamType_t mnStreamType; rtl::OUString msId; rtl::OUString msPath; bool getTarget(uno::Reference<embed::XRelationshipAccess> xRelationshipAccess, StreamType_t nStreamType, const ::rtl::OUString & rId, ::rtl::OUString & rDocumentTarget); public: typedef boost::shared_ptr<OOXMLStreamImpl> Pointer_t; OOXMLStreamImpl (OOXMLStreamImpl & rStream, StreamType_t nType); OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<embed::XStorage> xStorage, StreamType_t nType); OOXMLStreamImpl(OOXMLStreamImpl & rStream, const rtl::OUString & rId); OOXMLStreamImpl (uno::Reference<uno::XComponentContext> xContext, uno::Reference<embed::XStorage> xStorage, const rtl::OUString & rId); virtual ~OOXMLStreamImpl(); virtual uno::Reference<xml::sax::XParser> getParser(); virtual uno::Reference<xml::sax::XFastParser> getFastParser(); virtual uno::Reference<io::XInputStream> getDocumentStream(); virtual uno::Reference<io::XInputStream> getInputStream(); virtual uno::Reference<uno::XComponentContext> getContext(); ::rtl::OUString getTargetForId(const ::rtl::OUString & rId); virtual uno::Reference<xml::sax::XFastTokenHandler> getFastTokenHandler(uno::Reference<uno::XComponentContext> rContext); void setInputStream(uno::Reference<io::XInputStream> rxInputStream); }; }} #endif // INCLUDED_OOXML_STREAM_IMPL_HXX <|endoftext|>
<commit_before><commit_msg>Create 1542 - Reading Books.cpp<commit_after><|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "history_sql.h" namespace history { const float HistoryDatabase::kLatestSchema = 1.0; const float HistoryDatabase::kLatestSupportedSchema = 1.0; const unsigned HistoryDatabase::kLatestSchemaRevision = 1; const std::string HistoryDatabase::kFqrnKey = "fqrn"; /** * This method creates a new database file and initializes the database schema. */ bool HistoryDatabase::CreateEmptyDatabase() { assert (read_write()); return sqlite::Sql(sqlite_db(), "CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, " " timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, " " CONSTRAINT pk_tags PRIMARY KEY (name))").Execute(); } bool HistoryDatabase::InsertInitialValues(const std::string &repository_name) { assert (read_write()); return this->SetProperty(kFqrnKey, repository_name); } bool HistoryDatabase::CheckSchemaCompatibility() { return ! ((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) || (schema_version() > kLatestSchema + kSchemaEpsilon)); } bool HistoryDatabase::LiveSchemaUpgradeIfNecessary() { assert (read_write()); if (schema_revision() == 0) { LogCvmfs(kLogHistory, kLogDebug, "upgrading schema revision"); sqlite::Sql sql_upgrade(sqlite_db(), "ALTER TABLE tags ADD size INTEGER;"); if (!sql_upgrade.Execute()) { LogCvmfs(kLogHistory, kLogDebug, "failed to upgrade tags table"); return false; } set_schema_revision(1); if (! StoreSchemaRevision()) { LogCvmfs(kLogHistory, kLogDebug, "failed tp upgrade schema revision"); return false; } } return true; } //------------------------------------------------------------------------------ const std::string SqlRetrieveTag::tag_database_fields = "name, hash, revision, timestamp, channel, description, size"; const std::string& SqlRetrieveTag::GetDatabaseFields() const { return SqlRetrieveTag::tag_database_fields; } History::Tag SqlRetrieveTag::RetrieveTag() const { History::Tag result; result.name = RetrieveString(0); result.root_hash = shash::MkFromHexPtr(shash::HexPtr(RetrieveString(1))); result.revision = RetrieveInt64(2); result.timestamp = RetrieveInt64(3); result.channel = static_cast<History::UpdateChannel>(RetrieveInt64(4)); result.description = RetrieveString(5); result.size = RetrieveInt64(6); return result; } //------------------------------------------------------------------------------ SqlInsertTag::SqlInsertTag(const HistoryDatabase *database) { const std::string stmt = "INSERT INTO tags (" + GetDatabaseFields() + ")" "VALUES (" + GetDatabasePlaceholders() + ");"; Init(database->sqlite_db(), stmt); } const std::string SqlInsertTag::tag_database_placeholders = ":name, :hash, :revision, :timestamp, :channel, :description, :size"; const std::string& SqlInsertTag::GetDatabasePlaceholders() const { return SqlInsertTag::tag_database_placeholders; } bool SqlInsertTag::BindTag(const History::Tag &tag) { return ( BindText (1, tag.name) && BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString BindInt64 (3, tag.revision) && BindInt64 (4, tag.timestamp) && BindInt64 (5, tag.channel) && BindText (6, tag.description) && BindInt64 (7, tag.size) ); } SqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) { const std::string stmt = "DELETE FROM tags WHERE name = :name;"; const bool success = Init(database->sqlite_db(), stmt); assert (success); } bool SqlRemoveTag::BindName(const std::string &name) { return BindText(1, name); } SqlFindTag::SqlFindTag(const HistoryDatabase *database) { const std::string stmt = "SELECT " + GetDatabaseFields() + " FROM tags " "WHERE name = :name LIMIT 1;"; Init(database->sqlite_db(), stmt); } bool SqlFindTag::BindName(const std::string &name) { return BindText(1, name); } SqlCountTags::SqlCountTags(const HistoryDatabase *database) { Init(database->sqlite_db(), "SELECT count(*) FROM tags;"); } int SqlCountTags::RetrieveCount() const { return RetrieveInt64(0); } SqlListTags::SqlListTags(const HistoryDatabase *database) { Init(database->sqlite_db(), "SELECT " + GetDatabaseFields() + " FROM tags " "ORDER BY revision DESC;"); } bool SqlTag::BindTag(const History::Tag &tag) { return ( BindText(1, tag.name) && BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString BindInt64(3, tag.revision) && BindInt64(4, tag.timestamp) && BindInt64(5, tag.channel) && BindText(6, tag.description) && BindInt64(7, tag.size) ); } History::Tag SqlTag::RetrieveTag() { History::Tag result; result.name = std::string(reinterpret_cast<const char *>(RetrieveText(0))); const std::string hash_str(reinterpret_cast<const char *>(RetrieveText(1))); result.root_hash = shash::MkFromHexPtr(shash::HexPtr(hash_str)); result.revision = RetrieveInt64(2); result.timestamp = RetrieveInt64(3); result.channel = static_cast<History::UpdateChannel>(RetrieveInt64(4)); result.description = std::string(reinterpret_cast<const char *>(RetrieveText(5))); result.size = RetrieveInt64(6); return result; } }; /* namespace history */ <commit_msg>assert success of `Sql::Init()`<commit_after>/** * This file is part of the CernVM File System. */ #include "history_sql.h" namespace history { const float HistoryDatabase::kLatestSchema = 1.0; const float HistoryDatabase::kLatestSupportedSchema = 1.0; const unsigned HistoryDatabase::kLatestSchemaRevision = 1; const std::string HistoryDatabase::kFqrnKey = "fqrn"; /** * This method creates a new database file and initializes the database schema. */ bool HistoryDatabase::CreateEmptyDatabase() { assert (read_write()); return sqlite::Sql(sqlite_db(), "CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, " " timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, " " CONSTRAINT pk_tags PRIMARY KEY (name))").Execute(); } bool HistoryDatabase::InsertInitialValues(const std::string &repository_name) { assert (read_write()); return this->SetProperty(kFqrnKey, repository_name); } bool HistoryDatabase::CheckSchemaCompatibility() { return ! ((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) || (schema_version() > kLatestSchema + kSchemaEpsilon)); } bool HistoryDatabase::LiveSchemaUpgradeIfNecessary() { assert (read_write()); if (schema_revision() == 0) { LogCvmfs(kLogHistory, kLogDebug, "upgrading schema revision"); sqlite::Sql sql_upgrade(sqlite_db(), "ALTER TABLE tags ADD size INTEGER;"); if (!sql_upgrade.Execute()) { LogCvmfs(kLogHistory, kLogDebug, "failed to upgrade tags table"); return false; } set_schema_revision(1); if (! StoreSchemaRevision()) { LogCvmfs(kLogHistory, kLogDebug, "failed tp upgrade schema revision"); return false; } } return true; } //------------------------------------------------------------------------------ const std::string SqlRetrieveTag::tag_database_fields = "name, hash, revision, timestamp, channel, description, size"; const std::string& SqlRetrieveTag::GetDatabaseFields() const { return SqlRetrieveTag::tag_database_fields; } History::Tag SqlRetrieveTag::RetrieveTag() const { History::Tag result; result.name = RetrieveString(0); result.root_hash = shash::MkFromHexPtr(shash::HexPtr(RetrieveString(1))); result.revision = RetrieveInt64(2); result.timestamp = RetrieveInt64(3); result.channel = static_cast<History::UpdateChannel>(RetrieveInt64(4)); result.description = RetrieveString(5); result.size = RetrieveInt64(6); return result; } //------------------------------------------------------------------------------ SqlInsertTag::SqlInsertTag(const HistoryDatabase *database) { const std::string stmt = "INSERT INTO tags (" + GetDatabaseFields() + ")" "VALUES (" + GetDatabasePlaceholders() + ");"; const bool success = Init(database->sqlite_db(), stmt); assert (success); } const std::string SqlInsertTag::tag_database_placeholders = ":name, :hash, :revision, :timestamp, :channel, :description, :size"; const std::string& SqlInsertTag::GetDatabasePlaceholders() const { return SqlInsertTag::tag_database_placeholders; } bool SqlInsertTag::BindTag(const History::Tag &tag) { return ( BindText (1, tag.name) && BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString BindInt64 (3, tag.revision) && BindInt64 (4, tag.timestamp) && BindInt64 (5, tag.channel) && BindText (6, tag.description) && BindInt64 (7, tag.size) ); } SqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) { const std::string stmt = "DELETE FROM tags WHERE name = :name;"; const bool success = Init(database->sqlite_db(), stmt); assert (success); } bool SqlRemoveTag::BindName(const std::string &name) { return BindText(1, name); } SqlFindTag::SqlFindTag(const HistoryDatabase *database) { const std::string stmt = "SELECT " + GetDatabaseFields() + " FROM tags " "WHERE name = :name LIMIT 1;"; const bool success = Init(database->sqlite_db(), stmt); assert (success); } bool SqlFindTag::BindName(const std::string &name) { return BindText(1, name); } SqlCountTags::SqlCountTags(const HistoryDatabase *database) { const bool success = Init(database->sqlite_db(), "SELECT count(*) FROM tags;"); assert (success); } int SqlCountTags::RetrieveCount() const { return RetrieveInt64(0); } SqlListTags::SqlListTags(const HistoryDatabase *database) { const bool success = Init(database->sqlite_db(), "SELECT " + GetDatabaseFields() + " FROM tags " "ORDER BY revision DESC;"); assert (success); } bool SqlTag::BindTag(const History::Tag &tag) { return ( BindText(1, tag.name) && BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString BindInt64(3, tag.revision) && BindInt64(4, tag.timestamp) && BindInt64(5, tag.channel) && BindText(6, tag.description) && BindInt64(7, tag.size) ); } History::Tag SqlTag::RetrieveTag() { History::Tag result; result.name = std::string(reinterpret_cast<const char *>(RetrieveText(0))); const std::string hash_str(reinterpret_cast<const char *>(RetrieveText(1))); result.root_hash = shash::MkFromHexPtr(shash::HexPtr(hash_str)); result.revision = RetrieveInt64(2); result.timestamp = RetrieveInt64(3); result.channel = static_cast<History::UpdateChannel>(RetrieveInt64(4)); result.description = std::string(reinterpret_cast<const char *>(RetrieveText(5))); result.size = RetrieveInt64(6); return result; } }; /* namespace history */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accessiblemenubasecomponent.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2008-01-28 14:13:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX #define ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_AWT_POINT_HPP_ #include <com/sun/star/awt/Point.hpp> #endif #ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX #include <comphelper/accessiblecomponenthelper.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX #include <cppuhelper/implbase2.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif #include <vector> class Menu; class VclSimpleEvent; class VclMenuEvent; class VCLExternalSolarLock; namespace utl { class AccessibleStateSetHelper; } // ---------------------------------------------------- // class OAccessibleMenuBaseComponent // ---------------------------------------------------- typedef ::comphelper::OAccessibleExtendedComponentHelper AccessibleExtendedComponentHelper_BASE; typedef ::cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessible, ::com::sun::star::lang::XServiceInfo > OAccessibleMenuBaseComponent_BASE; class OAccessibleMenuBaseComponent : public AccessibleExtendedComponentHelper_BASE, public OAccessibleMenuBaseComponent_BASE { friend class OAccessibleMenuItemComponent; friend class VCLXAccessibleMenuItem; friend class VCLXAccessibleMenu; private: VCLExternalSolarLock* m_pExternalLock; protected: typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren; AccessibleChildren m_aAccessibleChildren; Menu* m_pMenu; sal_Bool m_bEnabled; sal_Bool m_bFocused; sal_Bool m_bVisible; sal_Bool m_bSelected; sal_Bool m_bChecked; Menu* GetMenu() { return m_pMenu; } virtual sal_Bool IsEnabled(); virtual sal_Bool IsFocused(); virtual sal_Bool IsVisible(); virtual sal_Bool IsSelected(); virtual sal_Bool IsChecked(); void SetEnabled( sal_Bool bEnabled ); void SetFocused( sal_Bool bFocused ); void SetVisible( sal_Bool bVisible ); void SetSelected( sal_Bool bSelected ); void SetChecked( sal_Bool bChecked ); void UpdateEnabled( sal_Int32 i, sal_Bool bEnabled ); void UpdateFocused( sal_Int32 i, sal_Bool bFocused ); void UpdateVisible(); void UpdateSelected( sal_Int32 i, sal_Bool bSelected ); void UpdateChecked( sal_Int32 i, sal_Bool bChecked ); void UpdateAccessibleName( sal_Int32 i ); void UpdateItemText( sal_Int32 i ); sal_Int32 GetChildCount(); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChild( sal_Int32 i ); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChildAt( const ::com::sun::star::awt::Point& rPoint ); void InsertChild( sal_Int32 i ); void RemoveChild( sal_Int32 i ); virtual sal_Bool IsHighlighted(); sal_Bool IsChildHighlighted(); void SelectChild( sal_Int32 i ); void DeSelectAll(); sal_Bool IsChildSelected( sal_Int32 i ); virtual void Select(); virtual void DeSelect(); virtual void Click(); virtual sal_Bool IsPopupMenuOpen(); DECL_LINK( MenuEventListener, VclSimpleEvent* ); virtual void ProcessMenuEvent( const VclMenuEvent& rVclMenuEvent ); virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ) = 0; // XComponent virtual void SAL_CALL disposing(); public: OAccessibleMenuBaseComponent( Menu* pMenu ); virtual ~OAccessibleMenuBaseComponent(); void SetStates(); // XInterface DECLARE_XINTERFACE() // XTypeProvider DECLARE_XTYPEPROVIDER() // XServiceInfo virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException); // XAccessible virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleContext virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException); }; #endif // ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.10); FILE MERGED 2008/04/01 14:58:49 thb 1.3.10.3: #i85898# Stripping all external header guards 2008/04/01 10:45:13 thb 1.3.10.2: #i85898# Stripping all external header guards 2008/03/28 15:57:43 rt 1.3.10.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accessiblemenubasecomponent.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX #define ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX #include <com/sun/star/accessibility/XAccessible.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/awt/Point.hpp> #include <comphelper/accessiblecomponenthelper.hxx> #ifndef _CPPUHELPER_IMPLBASE2_HXX #include <cppuhelper/implbase2.hxx> #endif #include <tools/link.hxx> #include <vector> class Menu; class VclSimpleEvent; class VclMenuEvent; class VCLExternalSolarLock; namespace utl { class AccessibleStateSetHelper; } // ---------------------------------------------------- // class OAccessibleMenuBaseComponent // ---------------------------------------------------- typedef ::comphelper::OAccessibleExtendedComponentHelper AccessibleExtendedComponentHelper_BASE; typedef ::cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessible, ::com::sun::star::lang::XServiceInfo > OAccessibleMenuBaseComponent_BASE; class OAccessibleMenuBaseComponent : public AccessibleExtendedComponentHelper_BASE, public OAccessibleMenuBaseComponent_BASE { friend class OAccessibleMenuItemComponent; friend class VCLXAccessibleMenuItem; friend class VCLXAccessibleMenu; private: VCLExternalSolarLock* m_pExternalLock; protected: typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren; AccessibleChildren m_aAccessibleChildren; Menu* m_pMenu; sal_Bool m_bEnabled; sal_Bool m_bFocused; sal_Bool m_bVisible; sal_Bool m_bSelected; sal_Bool m_bChecked; Menu* GetMenu() { return m_pMenu; } virtual sal_Bool IsEnabled(); virtual sal_Bool IsFocused(); virtual sal_Bool IsVisible(); virtual sal_Bool IsSelected(); virtual sal_Bool IsChecked(); void SetEnabled( sal_Bool bEnabled ); void SetFocused( sal_Bool bFocused ); void SetVisible( sal_Bool bVisible ); void SetSelected( sal_Bool bSelected ); void SetChecked( sal_Bool bChecked ); void UpdateEnabled( sal_Int32 i, sal_Bool bEnabled ); void UpdateFocused( sal_Int32 i, sal_Bool bFocused ); void UpdateVisible(); void UpdateSelected( sal_Int32 i, sal_Bool bSelected ); void UpdateChecked( sal_Int32 i, sal_Bool bChecked ); void UpdateAccessibleName( sal_Int32 i ); void UpdateItemText( sal_Int32 i ); sal_Int32 GetChildCount(); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChild( sal_Int32 i ); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChildAt( const ::com::sun::star::awt::Point& rPoint ); void InsertChild( sal_Int32 i ); void RemoveChild( sal_Int32 i ); virtual sal_Bool IsHighlighted(); sal_Bool IsChildHighlighted(); void SelectChild( sal_Int32 i ); void DeSelectAll(); sal_Bool IsChildSelected( sal_Int32 i ); virtual void Select(); virtual void DeSelect(); virtual void Click(); virtual sal_Bool IsPopupMenuOpen(); DECL_LINK( MenuEventListener, VclSimpleEvent* ); virtual void ProcessMenuEvent( const VclMenuEvent& rVclMenuEvent ); virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ) = 0; // XComponent virtual void SAL_CALL disposing(); public: OAccessibleMenuBaseComponent( Menu* pMenu ); virtual ~OAccessibleMenuBaseComponent(); void SetStates(); // XInterface DECLARE_XINTERFACE() // XTypeProvider DECLARE_XTYPEPROVIDER() // XServiceInfo virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException); // XAccessible virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException); // XAccessibleContext virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException); }; #endif // ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tdoc_services.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-20 05:32:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "com/sun/star/lang/XMultiServiceFactory.hpp" #include "com/sun/star/lang/XSingleServiceFactory.hpp" #include "com/sun/star/registry/XRegistryKey.hpp" #include "tdoc_provider.hxx" #include "tdoc_documentcontentfactory.hxx" using namespace com::sun::star; using namespace tdoc_ucp; //========================================================================= static sal_Bool writeInfo( void * pRegistryKey, const rtl::OUString & rImplementationName, uno::Sequence< rtl::OUString > const & rServiceNames ) { rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) ); aKeyName += rImplementationName; aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" ); uno::Reference< registry::XRegistryKey > xKey; try { xKey = static_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( aKeyName ); } catch ( registry::InvalidRegistryException const & ) { } if ( !xKey.is() ) return sal_False; sal_Bool bSuccess = sal_True; for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n ) { try { xKey->createKey( rServiceNames[ n ] ); } catch ( registry::InvalidRegistryException const & ) { bSuccess = sal_False; break; } } return bSuccess; } //========================================================================= extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //========================================================================= extern "C" sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey ) { return pRegistryKey && ////////////////////////////////////////////////////////////////////// // Transient Documents Content Provider. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, ContentProvider::getImplementationName_Static(), ContentProvider::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // Transient Documents Document Content Factory. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, DocumentContentFactory::getImplementationName_Static(), DocumentContentFactory::getSupportedServiceNames_Static() ); } //========================================================================= extern "C" void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ ) { void * pRet = 0; uno::Reference< lang::XMultiServiceFactory > xSMgr( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; ////////////////////////////////////////////////////////////////////// // Transient Documents Content Provider. ////////////////////////////////////////////////////////////////////// if ( ContentProvider::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = ContentProvider::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // Transient Documents Document Content Factory. ////////////////////////////////////////////////////////////////////// else if ( DocumentContentFactory::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = DocumentContentFactory::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } <commit_msg>INTEGRATION: CWS pchfix02 (1.4.20); FILE MERGED 2006/09/01 17:55:52 kaib 1.4.20.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tdoc_services.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 14:03:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucb.hxx" #include "com/sun/star/lang/XMultiServiceFactory.hpp" #include "com/sun/star/lang/XSingleServiceFactory.hpp" #include "com/sun/star/registry/XRegistryKey.hpp" #include "tdoc_provider.hxx" #include "tdoc_documentcontentfactory.hxx" using namespace com::sun::star; using namespace tdoc_ucp; //========================================================================= static sal_Bool writeInfo( void * pRegistryKey, const rtl::OUString & rImplementationName, uno::Sequence< rtl::OUString > const & rServiceNames ) { rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) ); aKeyName += rImplementationName; aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" ); uno::Reference< registry::XRegistryKey > xKey; try { xKey = static_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( aKeyName ); } catch ( registry::InvalidRegistryException const & ) { } if ( !xKey.is() ) return sal_False; sal_Bool bSuccess = sal_True; for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n ) { try { xKey->createKey( rServiceNames[ n ] ); } catch ( registry::InvalidRegistryException const & ) { bSuccess = sal_False; break; } } return bSuccess; } //========================================================================= extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //========================================================================= extern "C" sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey ) { return pRegistryKey && ////////////////////////////////////////////////////////////////////// // Transient Documents Content Provider. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, ContentProvider::getImplementationName_Static(), ContentProvider::getSupportedServiceNames_Static() ) && ////////////////////////////////////////////////////////////////////// // Transient Documents Document Content Factory. ////////////////////////////////////////////////////////////////////// writeInfo( pRegistryKey, DocumentContentFactory::getImplementationName_Static(), DocumentContentFactory::getSupportedServiceNames_Static() ); } //========================================================================= extern "C" void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ ) { void * pRet = 0; uno::Reference< lang::XMultiServiceFactory > xSMgr( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; ////////////////////////////////////////////////////////////////////// // Transient Documents Content Provider. ////////////////////////////////////////////////////////////////////// if ( ContentProvider::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = ContentProvider::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// // Transient Documents Document Content Factory. ////////////////////////////////////////////////////////////////////// else if ( DocumentContentFactory::getImplementationName_Static(). compareToAscii( pImplName ) == 0 ) { xFactory = DocumentContentFactory::createServiceFactory( xSMgr ); } ////////////////////////////////////////////////////////////////////// if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } <|endoftext|>
<commit_before>#include <Python.h> #include <fstream> #include <boost/python/tuple.hpp> #include <boost/test/unit_test.hpp> #include <ackward/logging/LogRecord.hpp> using namespace ackward::logging; BOOST_AUTO_TEST_SUITE( logging ) BOOST_AUTO_TEST_SUITE( logRecord ) BOOST_AUTO_TEST_CASE( constructor ) { LogRecord(L"foo", DEBUG(), L"/some/path/name", 101, L"Message", boost::python::tuple()); LogRecord(L"foo", DEBUG(), L"/some/path/name", 101, L"Message", boost::python::tuple(), boost::python::make_tuple( boost::python::object(), boost::python::object(), boost::python::object())); } BOOST_AUTO_TEST_CASE( getMessage ) { LogRecord r(L"foo", DEBUG(), L"/some/path/name", 101, L"Message", boost::python::tuple()); BOOST_CHECK(r.getMessage() == L"Message"); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() <commit_msg>disabled tests that don't work right now.<commit_after>#include <Python.h> #include <fstream> #include <boost/python/tuple.hpp> #include <boost/test/unit_test.hpp> #include <ackward/logging/LogRecord.hpp> using namespace ackward::logging; namespace { struct Fixture { Fixture() : rec (L"foo", DEBUG(), L"/some/path/name", 101, L"Message", boost::python::tuple()) {} LogRecord rec; }; } BOOST_AUTO_TEST_SUITE( logging ) BOOST_FIXTURE_TEST_SUITE( logRecord, Fixture ) BOOST_AUTO_TEST_CASE( constructor ) { LogRecord(L"foo", DEBUG(), L"/some/path/name", 101, L"Message", boost::python::tuple(), boost::python::make_tuple( boost::python::object(), boost::python::object(), boost::python::object())); } BOOST_AUTO_TEST_CASE( getMessage ) { BOOST_CHECK(rec.getMessage() == L"Message"); } BOOST_AUTO_TEST_CASE( args ) { boost::python::tuple args = rec.args; } // BOOST_AUTO_TEST_CASE( asctime ) // { // std::wstring at = rec.asctime; // } BOOST_AUTO_TEST_CASE( created ) { float c = rec.created; } // BOOST_AUTO_TEST_CASE( exc_info ) // { // boost::python::tuple ei = rec.exc_info; // } BOOST_AUTO_TEST_CASE( filename ) { std::wstring fn = rec.filename; } // BOOST_AUTO_TEST_CASE( funcName ) // { // std::wstring fn = rec.funcName; // } BOOST_AUTO_TEST_CASE( levelname ) { std::wstring ln = rec.levelname; } BOOST_AUTO_TEST_CASE( levelno ) { int ln = rec.levelno; } BOOST_AUTO_TEST_CASE( lineno ) { int ln = rec.lineno; } BOOST_AUTO_TEST_CASE( module ) { std::wstring m = rec.module; } BOOST_AUTO_TEST_CASE( msecs ) { float ms = rec.msecs; } // BOOST_AUTO_TEST_CASE( message ) // { // std::wstring m = rec.message; // } BOOST_AUTO_TEST_CASE( msg ) { std::wstring m = rec.msg; } BOOST_AUTO_TEST_CASE( name ) { std::wstring n = rec.name; } BOOST_AUTO_TEST_CASE( pathname ) { std::wstring pn = rec.pathname; } BOOST_AUTO_TEST_CASE( process ) { int p = rec.process; } BOOST_AUTO_TEST_CASE( processName ) { std::wstring pn = rec.processName; } BOOST_AUTO_TEST_CASE( relateveCreated ) { float rc = rec.relativeCreated; } BOOST_AUTO_TEST_CASE( stack_info ) { boost::python::object si = rec.stack_info; } BOOST_AUTO_TEST_CASE( thread ) { unsigned long t = rec.thread; } BOOST_AUTO_TEST_CASE( threadName ) { std::wstring tn = rec.threadName; } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// @(#)root/meta:$Id: TGWin32InterpreterProxy.cxx 38517 2011-03-18 20:20:16Z pcanal $ // Author: Valeriy Onuchin 15/11/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGWin32InterpreterProxy // // // // This class defines thread-safe interface to a command line // // interpreter (CINT). // // // ////////////////////////////////////////////////////////////////////////// #include "TGWin32ProxyDefs.h" #include "TGWin32InterpreterProxy.h" #include "TROOT.h" #include "TGWin32.h" //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TInterpreter *TGWin32InterpreterProxy::RealObject() { // returns TCint object return gROOT->GetInterpreter(); } RETURN_PROXY_OBJECT(Interpreter) VOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1) RETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname) VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) VOID_METHOD_ARG0(Interpreter,ClearStack,1) VOID_METHOD_ARG0(Interpreter,EndOfLineAction,1) VOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1) RETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries) RETURN_METHOD_ARG3(Interpreter,Int_t,GenerateDictionary,const char*,classes,const char*,headers,const char*,options); RETURN_METHOD_ARG0(Interpreter,char*,GetPrompt) RETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs) RETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath) RETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system) RETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile) RETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap) RETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps) RETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps) RETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library) VOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG0(Interpreter,PrintIntro,1) typedef char* (*GetlineFunc_t)(const char* prompt); typedef void (*HistaddFunc_t)(char* line); VOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\ HistaddFunc_t, histaddFunc, 1) VOID_METHOD_ARG0(Interpreter,Reset,1) VOID_METHOD_ARG0(Interpreter,ResetAll,1) VOID_METHOD_ARG0(Interpreter,ResetGlobals,1) VOID_METHOD_ARG1(Interpreter,ResetGlobalVar,void*,obj) VOID_METHOD_ARG0(Interpreter,RewindDictionary,1) RETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj) VOID_METHOD_ARG0(Interpreter,SaveContext,1) VOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes) VOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload) RETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload) RETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m) VOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s) RETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s) RETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full) VOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable) VOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1) RETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s) //Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); } <commit_msg>Add missing parameter<commit_after>// @(#)root/meta:$Id: TGWin32InterpreterProxy.cxx 38517 2011-03-18 20:20:16Z pcanal $ // Author: Valeriy Onuchin 15/11/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGWin32InterpreterProxy // // // // This class defines thread-safe interface to a command line // // interpreter (CINT). // // // ////////////////////////////////////////////////////////////////////////// #include "TGWin32ProxyDefs.h" #include "TGWin32InterpreterProxy.h" #include "TROOT.h" #include "TGWin32.h" //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TInterpreter *TGWin32InterpreterProxy::RealObject() { // returns TCint object return gROOT->GetInterpreter(); } RETURN_PROXY_OBJECT(Interpreter) VOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1) RETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname) VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) VOID_METHOD_ARG0(Interpreter,ClearStack,1) VOID_METHOD_ARG0(Interpreter,EndOfLineAction,1) VOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1) RETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries) RETURN_METHOD_ARG3(Interpreter,Int_t,GenerateDictionary,const char*,classes,const char*,headers,const char*,options); RETURN_METHOD_ARG0(Interpreter,char*,GetPrompt) RETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs) RETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath) RETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system) RETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile) RETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap) RETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps) RETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps) RETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library) VOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG0(Interpreter,PrintIntro,1) typedef char* (*GetlineFunc_t)(const char* prompt); typedef void (*HistaddFunc_t)(char* line); VOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\ HistaddFunc_t, histaddFunc, 1) VOID_METHOD_ARG0(Interpreter,Reset,1) VOID_METHOD_ARG0(Interpreter,ResetAll,1) VOID_METHOD_ARG0(Interpreter,ResetGlobals,1) VOID_METHOD_ARG1(Interpreter,ResetGlobalVar,void*,obj,1) VOID_METHOD_ARG0(Interpreter,RewindDictionary,1) RETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj) VOID_METHOD_ARG0(Interpreter,SaveContext,1) VOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes) VOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload) RETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload) RETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m) VOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s) RETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s) RETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full) VOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable) VOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1) RETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s) //Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the Campcaster project. http://campcaster.campware.org/ To report bugs, send an e-mail to bugs@campware.org Campcaster is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Campcaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Campcaster; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author$ Version : $Revision$ Location : $URL$ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #define DEBUG_PREFIX "GstreamerPlayer" #include "LiveSupport/Core/Debug.h" #include "LiveSupport/Core/TimeConversion.h" #include "GstreamerPlayer.h" using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::PlaylistExecutor; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /** * The name of the config element for this class */ const std::string GstreamerPlayer::configElementNameStr = "gstreamerPlayer"; /** * The name of the audio device attribute. */ static const std::string audioDeviceName = "audioDevice"; /* =============================================== local function prototypes */ /* ============================================================= module code */ static gboolean my_bus_callback (GstBus *bus, GstMessage *message, gpointer data) { GstreamerPlayer* const player = (GstreamerPlayer*) data; switch (GST_MESSAGE_TYPE (message)) { case GST_MESSAGE_EOS: if(player->playNextSmil()){ break; } player->close(); // Important: We *must* use an idle function call here, so that the signal handler returns // before fireOnStopEvent() is executed. g_idle_add(GstreamerPlayer::fireOnStopEvent, data); break; case GST_MESSAGE_ERROR: // We make sure that we don't send multiple error messages in a row to the GUI if (!player->m_errorWasRaised) { GError *gerror; gchar *debug; gst_message_parse_error (message, &gerror, &debug); player->m_errorMessage.reset(new const Glib::ustring(gerror->message)); player->m_errorWasRaised = true; std::cerr << "gstreamer error: " << gerror->message << std::endl; g_error_free (gerror); g_free (debug); // Important: We *must* use an idle function call here, so that the signal handler returns // before fireOnStopEvent() is executed. g_idle_add(GstreamerPlayer::fireOnStopEvent, data); } break; } } /*------------------------------------------------------------------------------ * Configure the Audio Player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { DEBUG_FUNC_INFO if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } const xmlpp::Attribute * attribute = 0; if ((attribute = element.get_attribute(audioDeviceName))) { m_audioDevice = attribute->get_value(); } } /*------------------------------------------------------------------------------ * Initialize the Audio Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: initialize(void) throw (std::exception) { DEBUG_FUNC_INFO if (m_initialized) { return; } // initialize the gstreamer library if (!gst_init_check(0, 0, 0)) { throw std::runtime_error("couldn't initialize the gstreamer library"); } m_playContext = new GstreamerPlayContext(); m_playContext->setParentData(this); // set up other variables m_initialized = true; } /*------------------------------------------------------------------------------ * De-initialize the Gstreamer Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: deInitialize(void) throw () { DEBUG_FUNC_INFO if (m_initialized) { m_playContext->closeContext(); delete m_playContext; m_playContext = NULL; m_initialized = false; } } /*------------------------------------------------------------------------------ * Attach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener) throw () { m_listeners.push_back(eventListener); } /*------------------------------------------------------------------------------ * Detach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener) throw (std::invalid_argument) { ListenerVector::iterator it = m_listeners.begin(); ListenerVector::iterator end = m_listeners.end(); while (it != end) { if (*it == eventListener) { m_listeners.erase(it); return; } ++it; } throw std::invalid_argument("supplied event listener not found"); } /*------------------------------------------------------------------------------ * Send the onStop event to all attached listeners. *----------------------------------------------------------------------------*/ gboolean GstreamerPlayer :: fireOnStopEvent(gpointer self) throw () { DEBUG_BLOCK GstreamerPlayer* const player = (GstreamerPlayer*) self; ListenerVector::iterator it = player->m_listeners.begin(); ListenerVector::iterator end = player->m_listeners.end(); while (it != end) { (*it)->onStop(player->m_errorMessage); ++it; } player->m_errorMessage.reset(); // false == Don't call this idle function again return false; } /*------------------------------------------------------------------------------ * Preload a file, to speed up the subsequent open() call. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: preload(const std::string fileUrl) throw (std::invalid_argument, std::runtime_error) { DEBUG_BLOCK //According to the Gstreamer documentation, stream buffering happens //automatically when the pipeline is set to GST_STATE_PAUSED. //As this state is now set automatically in the open function, //we no longer have a need for preloading. } /*------------------------------------------------------------------------------ * Specify which file to play *----------------------------------------------------------------------------*/ void GstreamerPlayer :: open(const std::string fileUri) throw (std::invalid_argument, std::runtime_error) { DEBUG_BLOCK if (isOpen()) { close(); } m_smilOffset = 0L; debug() << "Opening URL: " << fileUri << endl; debug() << "Timestamp: " << *TimeConversion::now() << endl; m_errorMessage.reset(); m_errorWasRaised = false; m_playContext->setAudioDevice(m_audioDevice); if (fileUri.find(std::string(".smil")) != std::string::npos) { m_smilHandler = new SmilHandler(); m_smilHandler->openSmilFile(fileUri.c_str()); AudioDescription *audioDescription = m_smilHandler->getNext(); m_open=m_playContext->openSource(audioDescription); }else{ m_open=m_playContext->openSource(fileUri.c_str()); } if(!m_open){ m_errorMessage.reset(new const Glib::ustring("GstreamerPlayer :: open failed! Please consult console output for details.")); m_errorWasRaised = true; fireOnStopEvent(this); } } bool GstreamerPlayer :: playNextSmil(void) throw () { DEBUG_BLOCK m_currentPlayLength = m_playContext->getPosition();//this gets the length of the stream that just completed m_playContext->closeContext(); if(m_smilHandler == NULL){ return false; } AudioDescription *audioDescription = m_smilHandler->getNext(); if(audioDescription == NULL){//no more audio entries to play delete m_smilHandler; m_smilHandler = NULL; return false; } if(!m_playContext->openSource(audioDescription)){ return false; } m_smilOffset += m_currentPlayLength; m_playContext->playContext(); } /*------------------------------------------------------------------------------ * Tell if we've been opened. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isOpen(void) throw () { return m_open; } /*------------------------------------------------------------------------------ * Get the length of the current audio clip. * Currently not used by the Studio, but may be used later on. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPlaylength(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("player not open"); } Ptr<time_duration>::Ref length; gint64 ns = m_playContext->getPlayLength(); length.reset(new time_duration(microsec(ns / 1000LL))); debug() << length << endl; return length; } /*------------------------------------------------------------------------------ * Get the current position of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPosition(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; if (!isOpen()) { throw std::logic_error("player not open"); } gint64 ns = m_playContext->getPosition(); length.reset(new time_duration(microseconds((m_smilOffset + ns) / 1000LL))); return length; } /*------------------------------------------------------------------------------ * Start playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: start(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (!isPlaying()) { m_playContext->playContext(); }else{ error() << "Already playing!" << endl; } } /*------------------------------------------------------------------------------ * Pause the player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: pause(void) throw (std::logic_error) { DEBUG_BLOCK if (isPlaying()) { m_playContext->pauseContext(); } } /*------------------------------------------------------------------------------ * Tell if we're playing *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isPlaying(void) throw () { return m_playContext->isPlaying(); } /*------------------------------------------------------------------------------ * Stop playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: stop(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (isPlaying()) { m_playContext->stopContext(); } } /*------------------------------------------------------------------------------ * Close the currently opened audio file. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: close(void) throw (std::logic_error) { DEBUG_BLOCK m_playContext->stopContext(); m_playContext->closeContext(); if(m_smilHandler != NULL){ delete m_smilHandler; m_smilHandler = NULL; } m_open = false; } /*------------------------------------------------------------------------------ * Get the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ unsigned int GstreamerPlayer :: getVolume(void) throw () { return 0; } /*------------------------------------------------------------------------------ * Set the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: setVolume(unsigned int volume) throw () {} /*------------------------------------------------------------------------------ * Set the audio device. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: setAudioDevice(const std::string &deviceName) throw () { DEBUG_BLOCK debug() << "Using device: " << deviceName << endl; if (deviceName.size() == 0) { return false; } m_playContext->setAudioDevice(deviceName); return true; } <commit_msg>Fixing ticket #2292<commit_after>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the Campcaster project. http://campcaster.campware.org/ To report bugs, send an e-mail to bugs@campware.org Campcaster is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Campcaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Campcaster; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author$ Version : $Revision$ Location : $URL$ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #define DEBUG_PREFIX "GstreamerPlayer" #include "LiveSupport/Core/Debug.h" #include "LiveSupport/Core/TimeConversion.h" #include "GstreamerPlayer.h" using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::PlaylistExecutor; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /** * The name of the config element for this class */ const std::string GstreamerPlayer::configElementNameStr = "gstreamerPlayer"; /** * The name of the audio device attribute. */ static const std::string audioDeviceName = "audioDevice"; /* =============================================== local function prototypes */ /* ============================================================= module code */ static gboolean my_bus_callback (GstBus *bus, GstMessage *message, gpointer data) { GstreamerPlayer* const player = (GstreamerPlayer*) data; switch (GST_MESSAGE_TYPE (message)) { case GST_MESSAGE_EOS: if(player->playNextSmil()){ break; } player->close(); // Important: We *must* use an idle function call here, so that the signal handler returns // before fireOnStopEvent() is executed. g_idle_add(GstreamerPlayer::fireOnStopEvent, data); break; case GST_MESSAGE_ERROR: // We make sure that we don't send multiple error messages in a row to the GUI if (!player->m_errorWasRaised) { GError *gerror; gchar *debug; gst_message_parse_error (message, &gerror, &debug); player->m_errorMessage.reset(new const Glib::ustring(gerror->message)); player->m_errorWasRaised = true; std::cerr << "gstreamer error: " << gerror->message << std::endl; g_error_free (gerror); g_free (debug); // Important: We *must* use an idle function call here, so that the signal handler returns // before fireOnStopEvent() is executed. g_idle_add(GstreamerPlayer::fireOnStopEvent, data); } break; } } /*------------------------------------------------------------------------------ * Configure the Audio Player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { DEBUG_FUNC_INFO if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } const xmlpp::Attribute * attribute = 0; if ((attribute = element.get_attribute(audioDeviceName))) { m_audioDevice = attribute->get_value(); } } /*------------------------------------------------------------------------------ * Initialize the Audio Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: initialize(void) throw (std::exception) { DEBUG_FUNC_INFO if (m_initialized) { return; } // initialize the gstreamer library if (!gst_init_check(0, 0, 0)) { throw std::runtime_error("couldn't initialize the gstreamer library"); } m_playContext = new GstreamerPlayContext(); m_playContext->setParentData(this); // set up other variables m_initialized = true; } /*------------------------------------------------------------------------------ * De-initialize the Gstreamer Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: deInitialize(void) throw () { DEBUG_FUNC_INFO if (m_initialized) { m_playContext->closeContext(); delete m_playContext; m_playContext = NULL; m_initialized = false; } } /*------------------------------------------------------------------------------ * Attach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener) throw () { m_listeners.push_back(eventListener); } /*------------------------------------------------------------------------------ * Detach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener) throw (std::invalid_argument) { ListenerVector::iterator it = m_listeners.begin(); ListenerVector::iterator end = m_listeners.end(); while (it != end) { if (*it == eventListener) { m_listeners.erase(it); return; } ++it; } throw std::invalid_argument("supplied event listener not found"); } /*------------------------------------------------------------------------------ * Send the onStop event to all attached listeners. *----------------------------------------------------------------------------*/ gboolean GstreamerPlayer :: fireOnStopEvent(gpointer self) throw () { DEBUG_BLOCK GstreamerPlayer* const player = (GstreamerPlayer*) self; ListenerVector::iterator it = player->m_listeners.begin(); ListenerVector::iterator end = player->m_listeners.end(); while (it != end) { (*it)->onStop(player->m_errorMessage); ++it; } player->m_errorMessage.reset(); // false == Don't call this idle function again return false; } /*------------------------------------------------------------------------------ * Preload a file, to speed up the subsequent open() call. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: preload(const std::string fileUrl) throw (std::invalid_argument, std::runtime_error) { DEBUG_BLOCK //According to the Gstreamer documentation, stream buffering happens //automatically when the pipeline is set to GST_STATE_PAUSED. //As this state is now set automatically in the open function, //we no longer have a need for preloading. } /*------------------------------------------------------------------------------ * Specify which file to play *----------------------------------------------------------------------------*/ void GstreamerPlayer :: open(const std::string fileUri) throw (std::invalid_argument, std::runtime_error) { DEBUG_BLOCK if (isOpen()) { close(); } m_smilOffset = 0L; debug() << "Opening URL: " << fileUri << endl; debug() << "Timestamp: " << *TimeConversion::now() << endl; m_errorMessage.reset(); m_errorWasRaised = false; m_playContext->setAudioDevice(m_audioDevice); if (fileUri.find(std::string(".smil")) != std::string::npos) { m_smilHandler = new SmilHandler(); m_smilHandler->openSmilFile(fileUri.c_str()); AudioDescription *audioDescription = m_smilHandler->getNext(); m_open=m_playContext->openSource(audioDescription); }else{ m_open=m_playContext->openSource(fileUri.c_str()); } if(!m_open){ m_errorMessage.reset(new const Glib::ustring("GstreamerPlayer :: open failed! Please consult console output for details.")); m_errorWasRaised = true; fireOnStopEvent(this); } } bool GstreamerPlayer :: playNextSmil(void) throw () { DEBUG_BLOCK m_currentPlayLength = m_playContext->getPosition();//this gets the length of the stream that just completed m_playContext->closeContext(); if(m_smilHandler == NULL){ return false; } AudioDescription *audioDescription = m_smilHandler->getNext(); if(audioDescription == NULL){//no more audio entries to play delete m_smilHandler; m_smilHandler = NULL; return false; } if(!m_playContext->openSource(audioDescription)){ return false; } m_smilOffset += m_currentPlayLength; m_playContext->playContext(); } /*------------------------------------------------------------------------------ * Tell if we've been opened. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isOpen(void) throw () { return m_open; } /*------------------------------------------------------------------------------ * Get the length of the current audio clip. * Currently not used by the Studio, but may be used later on. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPlaylength(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("player not open"); } Ptr<time_duration>::Ref length; gint64 ns = m_playContext->getPlayLength(); length.reset(new time_duration(microsec(ns / 1000LL))); debug() << "playlength is: " << *length << endl; return length; } /*------------------------------------------------------------------------------ * Get the current position of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPosition(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; if (!isOpen()) { throw std::logic_error("player not open"); } gint64 ns = m_playContext->getPosition(); length.reset(new time_duration(microseconds((m_smilOffset + ns) / 1000LL))); return length; } /*------------------------------------------------------------------------------ * Start playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: start(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (!isPlaying()) { m_playContext->playContext(); }else{ error() << "Already playing!" << endl; } } /*------------------------------------------------------------------------------ * Pause the player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: pause(void) throw (std::logic_error) { DEBUG_BLOCK if (isPlaying()) { m_playContext->pauseContext(); } } /*------------------------------------------------------------------------------ * Tell if we're playing *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isPlaying(void) throw () { return m_playContext->isPlaying(); } /*------------------------------------------------------------------------------ * Stop playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: stop(void) throw (std::logic_error) { DEBUG_BLOCK if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (isPlaying()) { m_playContext->stopContext(); } } /*------------------------------------------------------------------------------ * Close the currently opened audio file. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: close(void) throw (std::logic_error) { DEBUG_BLOCK m_playContext->stopContext(); m_playContext->closeContext(); if(m_smilHandler != NULL){ delete m_smilHandler; m_smilHandler = NULL; } m_open = false; } /*------------------------------------------------------------------------------ * Get the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ unsigned int GstreamerPlayer :: getVolume(void) throw () { return 0; } /*------------------------------------------------------------------------------ * Set the volume of the player. *Unimplemented*: Feature is currently not used. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: setVolume(unsigned int volume) throw () {} /*------------------------------------------------------------------------------ * Set the audio device. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: setAudioDevice(const std::string &deviceName) throw () { DEBUG_BLOCK debug() << "Using device: " << deviceName << endl; if (deviceName.size() == 0) { return false; } m_playContext->setAudioDevice(deviceName); return true; } <|endoftext|>
<commit_before>// bslmt_semaphoreimpl_darwin.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bslmt_semaphoreimpl_darwin.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bslmt_semaphoreimpl_darwin_cpp,"$Id$ $CSID$") #ifdef BSLS_PLATFORM_OS_DARWIN #include <bslmt_lockguard.h> // for testing only #include <bslmt_mutex.h> // for testing only #include <bslmt_threadutil.h> // for testing only #include <bsl_string.h> #include <bsl_sstream.h> #include <bsl_iomanip.h> #include <bsl_ios.h> #include <bsl_c_errno.h> #include <bsls_types.h> #include <stdio.h> // 'snprintf' #include <unistd.h> #include <sys/stat.h> #include <sys/time.h> // needed before sys/posix_sem.h to define // 'itimerval' #include <sys/posix_sem.h> // 'PSEMNAMLEN' #ifndef SEM_NAME_LEN #define SEM_NAME_LEN PSEMNAMLEN #endif namespace BloombergLP { // ---------------------------------------------- // class SemaphoreImpl<Platform::DarwinSemaphore> // ---------------------------------------------- const char * bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::s_semaphorePrefix = "bslmt_semaphore_"; namespace { void makeUniqueName(char *buffer, const char *prefix, bsls::Types::UintPtr suffix) // Create a sufficiently unique name for a semaphore object. Note that the // name of the semaphore shouldn't exceed SEM_NAME_LEN characters (31). { snprintf(buffer, SEM_NAME_LEN, "%s%04x_%04x", prefix, (getpid() & 0xffff), (suffix & 0xffff)); } } // close unnamed namespace // CREATORS bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::SemaphoreImpl( int count) { char semaphoreName[SEM_NAME_LEN + 1]; makeUniqueName(semaphoreName, s_semaphorePrefix, reinterpret_cast<bsls::Types::UintPtr>(this)); do { // create a named semaphore with exclusive access d_sem_p = ::sem_open(semaphoreName, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, count); } while (d_sem_p == SEM_FAILED && (errno == EEXIST || errno == EINTR)); BSLS_ASSERT(d_sem_p != SEM_FAILED); // At this point the current thread is the sole owner of the semaphore with // this name. No other thread can create a semaphore with the same name // until we disassociate the name from the semaphore handle. Note that // even though the name is unlinked from the semaphore, we still try to use // sufficiently unique names because if the process is killed before it // unlinks the name, no other process can create a semaphore with that // name. int result = ::sem_unlink(semaphoreName); (void) result; BSLS_ASSERT(result == 0); } // MANIPULATORS void bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::post(int number) { for (int i = 0; i < number; i++) { post(); } } void bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::wait() { sem_t * sem_p = d_sem_p; int result = 0; do { result = ::sem_wait(sem_p); } while (result != 0 && errno == EINTR); BSLS_ASSERT(result == 0); } } // close enterprise namespace #endif // BSLS_PLATFORM_OS_DARWIN // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>add cast to suppress warning<commit_after>// bslmt_semaphoreimpl_darwin.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bslmt_semaphoreimpl_darwin.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bslmt_semaphoreimpl_darwin_cpp,"$Id$ $CSID$") #ifdef BSLS_PLATFORM_OS_DARWIN #include <bslmt_lockguard.h> // for testing only #include <bslmt_mutex.h> // for testing only #include <bslmt_threadutil.h> // for testing only #include <bsl_string.h> #include <bsl_sstream.h> #include <bsl_iomanip.h> #include <bsl_ios.h> #include <bsl_c_errno.h> #include <bsls_types.h> #include <stdio.h> // 'snprintf' #include <unistd.h> #include <sys/stat.h> #include <sys/time.h> // needed before sys/posix_sem.h to define // 'itimerval' #include <sys/posix_sem.h> // 'PSEMNAMLEN' #ifndef SEM_NAME_LEN #define SEM_NAME_LEN PSEMNAMLEN #endif namespace BloombergLP { // ---------------------------------------------- // class SemaphoreImpl<Platform::DarwinSemaphore> // ---------------------------------------------- const char * bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::s_semaphorePrefix = "bslmt_semaphore_"; namespace { void makeUniqueName(char *buffer, const char *prefix, bsls::Types::UintPtr suffix) // Create a sufficiently unique name for a semaphore object. Note that the // name of the semaphore shouldn't exceed SEM_NAME_LEN characters (31). { snprintf(buffer, SEM_NAME_LEN, "%s%04x_%04x", prefix, (getpid() & 0xffff), static_cast<unsigned>(suffix & 0xffff)); } } // close unnamed namespace // CREATORS bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::SemaphoreImpl( int count) { char semaphoreName[SEM_NAME_LEN + 1]; makeUniqueName(semaphoreName, s_semaphorePrefix, reinterpret_cast<bsls::Types::UintPtr>(this)); do { // create a named semaphore with exclusive access d_sem_p = ::sem_open(semaphoreName, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, count); } while (d_sem_p == SEM_FAILED && (errno == EEXIST || errno == EINTR)); BSLS_ASSERT(d_sem_p != SEM_FAILED); // At this point the current thread is the sole owner of the semaphore with // this name. No other thread can create a semaphore with the same name // until we disassociate the name from the semaphore handle. Note that // even though the name is unlinked from the semaphore, we still try to use // sufficiently unique names because if the process is killed before it // unlinks the name, no other process can create a semaphore with that // name. int result = ::sem_unlink(semaphoreName); (void) result; BSLS_ASSERT(result == 0); } // MANIPULATORS void bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::post(int number) { for (int i = 0; i < number; i++) { post(); } } void bslmt::SemaphoreImpl<bslmt::Platform::DarwinSemaphore>::wait() { sem_t * sem_p = d_sem_p; int result = 0; do { result = ::sem_wait(sem_p); } while (result != 0 && errno == EINTR); BSLS_ASSERT(result == 0); } } // close enterprise namespace #endif // BSLS_PLATFORM_OS_DARWIN // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>/// This file contains the implementation of VNS #include "header/vns-priv.hpp" using namespace std; namespace pcp { Solution bestSolution; Solution origSolution; bool checkValid(Solution* s); /// Some constants const int NUM_VNS = 1; const int SHAKE_START = 1; /// Implementation of VNS, see vns.hpp Solution vnsRun(Solution& best, Solution& orig, int unsuccessfulShake, int shakeStart, int shakeIncrement, int maxTime) { /// Backup the starting solutions bestSolution = new Solution(best); origSolution = new Solution(orig); cout<<"Best solution uses "<<bestSolution.colorsUsed<<" colors"<<endl; cout<<"Full solution uses "<<origSolution.colorsUsed<<" colors"<<endl; /// Define the neighborhoods to use VNS_Unit **neighbors = new VNS_Unit*[NUM_VNS]; changeColor *ts = new changeColor; neighbors[0] = ts; time_t startTime = time(NULL); int no_imp_runs = 0; int curNeighbor = 0; int shakeSteps = shakeStart - shakeIncrement; Solution *toImprove = new Solution(&best); Solution *curBest = &best; /// Run as long as shaking still produces usefull solution while (true) { /// Run all possible neighborhood while (curNeighbor < NUM_VNS) { /// Select the new neighborhood VNS_Unit *neigh = neighbors[curNeighbor]; cout<<"Running: "<< neigh->name() <<endl; /// Compute the minimum for this neighborhood Solution *improved = neigh->findLocalMin(best, orig); cout<<"Valid solution: "<<((checkValid(improved)) ? "true" : "false"); cout<<endl; /// Replace the existing solution with the new solution if it is an /// improvement if (improved->colorsUsed < toImprove->colorsUsed) { delete toImprove; toImprove = improved; cout<<"Improvement found with "<<neigh->name()<<endl; /// Restart neighborhoods curNeighbor = curNeighbor == 0 ? 1 : 0; } /// Step to next neighborhood, no improvement found else { cout<<"No improvement found"<<endl; delete improved; curNeighbor++; cout<<"Test next neighborhood"<<endl; } } // end while neighborhood /// Local minimum of neighborhoods is better than current best /// solution if (toImprove->colorsUsed < best.colorsUsed) { cout<<"Improvement to global best solution found"<<endl; best = toImprove; toImprove = new Solution(curBest); no_imp_runs = 0; shakeSteps = shakeStart - shakeIncrement; } /// Reset local best solution to global best Solution else { toImprove = curBest; no_imp_runs++; /// Stopping condition, quit VNS if (no_imp_runs > unsuccessfulShake) { break; } } int shakeNeighbor = rand() % NUM_VNS; VNS_Unit *shaker = neighbors[shakeNeighbor]; toImprove = shaker->shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement)); /// No time left, abort main loop if (startTime + maxTime < time(NULL)) { cout<<"Time's up"<<endl; break; } } return new Solution(curBest); } bool checkValid(Solution* s) { pair<VertexIter, VertexIter> vIter; int parts[s->numParts]; typedef boost::graph_traits<Graph>::adjacency_iterator AdjIter; VertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g); bool valid = true; for (int i = 0; i < s->numParts; i++) { parts[i] = 0; } for (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) { parts[vParts[*vIter.first]] = 1; pair<AdjIter, AdjIter> aIter; for (aIter = adjacent_vertices(*vIter.first, *s->g); aIter.first != aIter.second; aIter.first++) { if (s->partition[vParts[*aIter.first]] == s->partition[vParts[*vIter.first]]) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"Adjacent vertices "<<*aIter.first<<" and "<<*vIter.first; cerr<<" have same color "<<s->partition[vParts[*vIter.first]]; cerr<<endl; } } } for (int i = 0; i < s->numParts; i++) { if (parts[i] == 0) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"partition "<<i<<" seems to be missing"<<endl; } } return valid; } } <commit_msg>Fixed intentation in vns-loop<commit_after>/// This file contains the implementation of VNS #include "header/vns-priv.hpp" using namespace std; namespace pcp { Solution bestSolution; Solution origSolution; bool checkValid(Solution* s); /// Some constants const int NUM_VNS = 1; const int SHAKE_START = 1; /// Implementation of VNS, see vns.hpp Solution vnsRun(Solution& best, Solution& orig, int unsuccessfulShake, int shakeStart, int shakeIncrement, int maxTime) { /// Backup the starting solutions bestSolution = new Solution(best); origSolution = new Solution(orig); cout<<"Best solution uses "<<bestSolution.colorsUsed<<" colors"<<endl; cout<<"Full solution uses "<<origSolution.colorsUsed<<" colors"<<endl; /// Define the neighborhoods to use VNS_Unit **neighbors = new VNS_Unit*[NUM_VNS]; changeColor *ts = new changeColor; neighbors[0] = ts; time_t startTime = time(NULL); int no_imp_runs = 0; int curNeighbor = 0; int shakeSteps = shakeStart - shakeIncrement; Solution *toImprove = new Solution(&best); Solution *curBest = &best; /// Run as long as shaking still produces usefull solution while (true) { /// Run all possible neighborhood while (curNeighbor < NUM_VNS) { /// Select the new neighborhood VNS_Unit *neigh = neighbors[curNeighbor]; cout<<"Running: "<< neigh->name() <<endl; /// Compute the minimum for this neighborhood Solution *improved = neigh->findLocalMin(best, orig); cout<<"Valid solution: "<<((checkValid(improved)) ? "true" : "false"); cout<<endl; /// Replace the existing solution with the new solution if it is an /// improvement if (improved->colorsUsed < toImprove->colorsUsed) { delete toImprove; toImprove = improved; cout<<"Improvement found with "<<neigh->name()<<endl; /// Restart neighborhoods curNeighbor = curNeighbor == 0 ? 1 : 0; } /// Step to next neighborhood, no improvement found else { cout<<"No improvement found"<<endl; delete improved; curNeighbor++; cout<<"Test next neighborhood"<<endl; } } // end while neighborhood /// Local minimum of neighborhoods is better than current best /// solution if (toImprove->colorsUsed < best.colorsUsed) { cout<<"Improvement to global best solution found"<<endl; best = toImprove; toImprove = new Solution(curBest); no_imp_runs = 0; shakeSteps = shakeStart - shakeIncrement; } /// Reset local best solution to global best Solution else { toImprove = curBest; no_imp_runs++; /// Stopping condition, quit VNS if (no_imp_runs > unsuccessfulShake) { break; } } int shakeNeighbor = rand() % NUM_VNS; VNS_Unit *shaker = neighbors[shakeNeighbor]; toImprove = shaker->shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement)); /// No time left, abort main loop if (startTime + maxTime < time(NULL)) { cout<<"Time's up"<<endl; break; } } return new Solution(curBest); } bool checkValid(Solution* s) { pair<VertexIter, VertexIter> vIter; int parts[s->numParts]; typedef boost::graph_traits<Graph>::adjacency_iterator AdjIter; VertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g); bool valid = true; for (int i = 0; i < s->numParts; i++) { parts[i] = 0; } for (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) { parts[vParts[*vIter.first]] = 1; pair<AdjIter, AdjIter> aIter; for (aIter = adjacent_vertices(*vIter.first, *s->g); aIter.first != aIter.second; aIter.first++) { if (s->partition[vParts[*aIter.first]] == s->partition[vParts[*vIter.first]]) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"Adjacent vertices "<<*aIter.first<<" and "<<*vIter.first; cerr<<" have same color "<<s->partition[vParts[*vIter.first]]; cerr<<endl; } } } for (int i = 0; i < s->numParts; i++) { if (parts[i] == 0) { valid = false; cerr<<"Solution is invalid"<<endl; cerr<<"partition "<<i<<" seems to be missing"<<endl; } } return valid; } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/menu_config.h" #include "build/build_config.h" namespace views { static MenuConfig* config_instance = NULL; MenuConfig::MenuConfig() : text_color(SK_ColorBLACK), item_top_margin(3), item_bottom_margin(4), item_no_icon_top_margin(1), item_no_icon_bottom_margin(3), item_left_margin(4), label_to_arrow_padding(10), arrow_to_edge_padding(5), icon_to_label_padding(8), gutter_to_label(5), check_width(16), check_height(16), radio_width(16), radio_height(16), arrow_height(9), arrow_width(9), gutter_width(0), separator_height(6), render_gutter(false), show_mnemonics(false), scroll_arrow_height(3), label_to_accelerator_padding(10), show_accelerators(true) { } MenuConfig::~MenuConfig() {} void MenuConfig::Reset() { delete config_instance; config_instance = NULL; } // static const MenuConfig& MenuConfig::instance() { if (!config_instance) config_instance = Create(); return *config_instance; } } // namespace views <commit_msg>Make menu items 40px tall when touch-optimized-ui is set.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/menu_config.h" #include "base/command_line.h" #include "build/build_config.h" #include "ui/base/ui_base_switches.h" namespace views { static MenuConfig* config_instance = NULL; MenuConfig::MenuConfig() : text_color(SK_ColorBLACK), item_top_margin(3), item_bottom_margin(4), item_no_icon_top_margin(1), item_no_icon_bottom_margin(3), item_left_margin(4), label_to_arrow_padding(10), arrow_to_edge_padding(5), icon_to_label_padding(8), gutter_to_label(5), check_width(16), check_height(16), radio_width(16), radio_height(16), arrow_height(9), arrow_width(9), gutter_width(0), separator_height(6), render_gutter(false), show_mnemonics(false), scroll_arrow_height(3), label_to_accelerator_padding(10), show_accelerators(true) { // Use 40px tall menu items when running in touch optimized mode. if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kTouchOptimizedUI)) { item_top_margin = item_no_icon_top_margin = 12; item_bottom_margin = item_no_icon_bottom_margin = 13; } } MenuConfig::~MenuConfig() {} void MenuConfig::Reset() { delete config_instance; config_instance = NULL; } // static const MenuConfig& MenuConfig::instance() { if (!config_instance) config_instance = Create(); return *config_instance; } } // namespace views <|endoftext|>
<commit_before>#ifndef ITER_ZIP_HPP_ #define ITER_ZIP_HPP_ #include "iterbase.hpp" #include <iterator> #include <tuple> #include <utility> namespace iter { template <typename... RestContainers> class Zipped; template <typename... Containers> Zipped<Containers...> zip(Containers&&...); // specialization for at least 1 template argument template <typename Container, typename... RestContainers> class Zipped <Container, RestContainers...> { using ZipIterDeref = std::tuple<iterator_deref<Container>, iterator_deref<RestContainers>...>; friend Zipped zip<Container, RestContainers...>( Container&&, RestContainers&&...); template <typename... RC> friend class Zipped; private: Container container; Zipped<RestContainers...> rest_zipped; Zipped(Container container, RestContainers&&... rest) : container(std::forward<Container>(container)), rest_zipped{std::forward<RestContainers>(rest)...} { } public: class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref> { private: using RestIter = typename Zipped<RestContainers...>::Iterator; iterator_type<Container> iter; RestIter rest_iter; public: constexpr static const bool is_base_iter = false; Iterator(iterator_type<Container> it, const RestIter& rest) : iter{it}, rest_iter{rest} { } Iterator& operator++() { ++this->iter; ++this->rest_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->iter != other.iter && (RestIter::is_base_iter || this->rest_iter != other.rest_iter); } auto operator*() -> decltype(std::tuple_cat( std::tuple<iterator_deref<Container>>{ *this->iter}, *this->rest_iter)) { return std::tuple_cat( std::tuple<iterator_deref<Container>>{ *this->iter}, *this->rest_iter); } }; Iterator begin() { return {std::begin(this->container), std::begin(this->rest_zipped)}; } Iterator end() { return {std::end(this->container), std::end(this->rest_zipped)}; } }; template <> class Zipped<> { public: class Iterator : public std::iterator<std::input_iterator_tag, std::tuple<>> { public: constexpr static const bool is_base_iter = true; Iterator() { } Iterator(const Iterator&) { } Iterator& operator=(const Iterator&) { return *this; } Iterator& operator++() { return *this; } Iterator operator++(int) { return *this; } // if this were to return true, there would be no need // for the is_base_iter static class attribute. // However, returning false causes an empty zip() call // to reach the "end" immediately. Returning true here // instead results in an infinite loop in the zip() case bool operator!=(const Iterator&) const { return false; } std::tuple<> operator*() { return std::tuple<>{}; } }; Iterator begin() { return {}; } Iterator end() { return {}; } }; template <typename... Containers> Zipped<Containers...> zip(Containers&&... containers) { return {std::forward<Containers>(containers)...}; } } #endif // #ifndef ITER_ZIP_HPP_ <commit_msg>adds zip ==<commit_after>#ifndef ITER_ZIP_HPP_ #define ITER_ZIP_HPP_ #include "iterbase.hpp" #include <iterator> #include <tuple> #include <utility> namespace iter { template <typename... RestContainers> class Zipped; template <typename... Containers> Zipped<Containers...> zip(Containers&&...); // specialization for at least 1 template argument template <typename Container, typename... RestContainers> class Zipped <Container, RestContainers...> { using ZipIterDeref = std::tuple<iterator_deref<Container>, iterator_deref<RestContainers>...>; friend Zipped zip<Container, RestContainers...>( Container&&, RestContainers&&...); template <typename... RC> friend class Zipped; private: Container container; Zipped<RestContainers...> rest_zipped; Zipped(Container container, RestContainers&&... rest) : container(std::forward<Container>(container)), rest_zipped{std::forward<RestContainers>(rest)...} { } public: class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref> { private: using RestIter = typename Zipped<RestContainers...>::Iterator; iterator_type<Container> iter; RestIter rest_iter; public: constexpr static const bool is_base_iter = false; Iterator(iterator_type<Container> it, const RestIter& rest) : iter{it}, rest_iter{rest} { } Iterator& operator++() { ++this->iter; ++this->rest_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->iter != other.iter && (RestIter::is_base_iter || this->rest_iter != other.rest_iter); } bool operator==(const Iterator& other) const { return !(*this == other); } auto operator*() -> decltype(std::tuple_cat( std::tuple<iterator_deref<Container>>{ *this->iter}, *this->rest_iter)) { return std::tuple_cat( std::tuple<iterator_deref<Container>>{ *this->iter}, *this->rest_iter); } }; Iterator begin() { return {std::begin(this->container), std::begin(this->rest_zipped)}; } Iterator end() { return {std::end(this->container), std::end(this->rest_zipped)}; } }; template <> class Zipped<> { public: class Iterator : public std::iterator<std::input_iterator_tag, std::tuple<>> { public: constexpr static const bool is_base_iter = true; Iterator() { } Iterator(const Iterator&) { } Iterator& operator=(const Iterator&) { return *this; } Iterator& operator++() { return *this; } Iterator operator++(int) { return *this; } // if this were to return true, there would be no need // for the is_base_iter static class attribute. // However, returning false causes an empty zip() call // to reach the "end" immediately. Returning true here // instead results in an infinite loop in the zip() case bool operator!=(const Iterator&) const { return false; } bool operator==(const Iterator& other) const { return !(*this != other); } std::tuple<> operator*() { return std::tuple<>{}; } }; Iterator begin() { return {}; } Iterator end() { return {}; } }; template <typename... Containers> Zipped<Containers...> zip(Containers&&... containers) { return {std::forward<Containers>(containers)...}; } } #endif // #ifndef ITER_ZIP_HPP_ <|endoftext|>
<commit_before>#include <ros/ros.h> #include <vector> #include <string> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include "moveit_recorder/utils.h" #include "moveit_recorder/experiment_utils.h" #include "moveit_recorder/trajectory_video_lookup.h" int main(int argc, char** argv) { ros::init(argc, argv, "split_screen_creator"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(1); spinner.start(); boost::program_options::options_description desc; desc.add_options() ("help", "Show help message") ("regex", boost::program_options::value<std::string>(), "Regex of named videos to make 4x4 split screen with") ("save_dir",boost::program_options::value<std::string>(), "Directory for videos"); boost::program_options::variables_map vm; boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc); boost::program_options::store(po, vm); boost::program_options::notify(vm); if (vm.count("help") || argc == 1) // show help if no parameters passed { std::cout << desc << std::endl; return 1; } try { std::string save_dir = utils::get_option(vm, "save_dir", ""); boost::regex vid_regex(utils::get_option(vm, "regex", "view.")); boost::filesystem::path save_directory(save_dir); // read the bag file to get the file names ROS_INFO("Opening bag at %s", save_directory.string().c_str()); TrajectoryVideoLookup video_lookup_table; video_lookup_table.loadFromBag( save_directory.string() ); // create split screen from regex matched videos TrajectoryVideoLookup::iterator traj_it = video_lookup_table.begin(); for(; traj_it!=video_lookup_table.end();++traj_it) { std::vector<std::string> videos; TrajectoryVideoLookupEntry::iterator video_it = traj_it->second.begin(); for(int v=0; v<4; v++) { boost::cmatch matches; if(boost::regex_match( video_it->name.c_str(), matches, vid_regex )) { videos.push_back( video_it->file ); video_it++; } if(video_it==traj_it->second.end()) video_it=traj_it->second.begin(); } if(videos.size()!=4) ROS_WARN("No videos matching the regex, unable to create split screen video for trajectory id=\"%s\"",traj_it->first.c_str()); else { std::string combined = (save_directory / boost::str(boost::format("%s_%s.%s") % traj_it->first % "split" % "ogv")).string(); std::string combine_command = boost::str(boost::format("ffmpeg -i %s -i %s -i %s -i %s -filter_complex \'[0:v]scale=iw/2:ih/2[rescale1];[1:v]scale=iw/2:ih/2[rescale2];[2:v]scale=iw/2:ih/2[rescale3];[3:v]scale=iw/2:ih/2[rescale4];[rescale1]pad=2*iw:2*ih[topleft];[topleft][rescale2]overlay=W/2:0[topright];[topright][rescale3]overlay=0:H/2[bottomleft];[bottomleft][rescale4]overlay=W/2:H/2[final]\' -map [final] -b 10000k %s") %videos[0] %videos[1] %videos[2] %videos[3] %combined); std::string response = utils::system::runCommand(combine_command); video_lookup_table.putVideoFile(traj_it->first, "split", combined); } } video_lookup_table.saveToBag( save_directory.string() ); } catch(...) { std::cout << "Failure!" << std::endl; } ROS_INFO("Finished creating splitscreen videos."); ros::shutdown(); return 0; } <commit_msg>added name prefix argument to node to specify name for resulting video<commit_after>#include <ros/ros.h> #include <vector> #include <string> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include "moveit_recorder/utils.h" #include "moveit_recorder/experiment_utils.h" #include "moveit_recorder/trajectory_video_lookup.h" int main(int argc, char** argv) { ros::init(argc, argv, "split_screen_creator"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(1); spinner.start(); boost::program_options::options_description desc; desc.add_options() ("help", "Show help message") ("prefix", boost::program_options::value<std::string>(), "Prefix of 2x2 merged video") ("regex", boost::program_options::value<std::string>(), "Regex of named videos to make 2x2 split screen with") ("save_dir",boost::program_options::value<std::string>(), "Directory for videos"); boost::program_options::variables_map vm; boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc); boost::program_options::store(po, vm); boost::program_options::notify(vm); if (vm.count("help") || argc == 1) // show help if no parameters passed { std::cout << desc << std::endl; return 1; } try { std::string splitscreen_prefix = utils::get_option(vm, "prefix", "split"); std::string save_dir = utils::get_option(vm, "save_dir", ""); boost::regex vid_regex(utils::get_option(vm, "regex", "view.")); boost::filesystem::path save_directory(save_dir); // read the bag file to get the file names ROS_INFO("Opening bag at %s", save_directory.string().c_str()); TrajectoryVideoLookup video_lookup_table; video_lookup_table.loadFromBag( save_directory.string() ); // create split screen from regex matched videos TrajectoryVideoLookup::iterator traj_it = video_lookup_table.begin(); for(; traj_it!=video_lookup_table.end();++traj_it) { std::vector<std::string> videos; TrajectoryVideoLookupEntry::iterator video_it = traj_it->second.begin(); for(; video_it!=traj_it->second.end(); ++video_it) { boost::cmatch matches; if(boost::regex_match( video_it->name.c_str(), matches, vid_regex )) videos.push_back( video_it->file ); } if(videos.size()!=4) ROS_WARN("No videos matching the regex, unable to create split screen video for trajectory id=\"%s\"",traj_it->first.c_str()); else { std::string combined = (save_directory / boost::str(boost::format("%s-%s.%s") % traj_it->first % splitscreen_prefix % "ogv")).string(); std::string combine_command = boost::str(boost::format("ffmpeg -i %s -i %s -i %s -i %s -filter_complex \'[0:v]scale=iw/2:ih/2[rescale1];[1:v]scale=iw/2:ih/2[rescale2];[2:v]scale=iw/2:ih/2[rescale3];[3:v]scale=iw/2:ih/2[rescale4];[rescale1]pad=2*iw:2*ih[topleft];[topleft][rescale2]overlay=W/2:0[topright];[topright][rescale3]overlay=0:H/2[bottomleft];[bottomleft][rescale4]overlay=W/2:H/2[final]\' -map [final] -b 10000k %s") %videos[0] %videos[1] %videos[2] %videos[3] %combined); std::string response = utils::system::runCommand(combine_command); video_lookup_table.putVideoFile(traj_it->first, splitscreen_prefix, combined); } } video_lookup_table.saveToBag( save_directory.string() ); } catch(...) { std::cout << "Failure!" << std::endl; } ROS_INFO("Finished creating splitscreen videos."); ros::shutdown(); return 0; } <|endoftext|>
<commit_before>#include "SkCGUtils.h" #include "SkBitmap.h" #include "SkColorPriv.h" static void SkBitmap_ReleaseInfo(void* info, const void* pixelData, size_t size) { SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(info); delete bitmap; } #define HAS_ARGB_SHIFTS(a, r, g, b) \ (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \ && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b)) static SkBitmap* prepareForImageRef(const SkBitmap& bm, size_t* bitsPerComponent, CGBitmapInfo* info) { bool upscaleTo32 = false; switch (bm.config()) { case SkBitmap::kRGB_565_Config: upscaleTo32 = true; // fall through case SkBitmap::kARGB_8888_Config: *bitsPerComponent = 8; #if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 0, 8, 16) \ || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(0, 24, 16, 8) *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast; #elif defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) \ || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) // Matches the CGBitmapInfo that Apple recommends for best // performance, used by google chrome. *info = kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst; #else // ...add more formats as required... #warning Cannot convert SkBitmap to CGImageRef with these shiftmasks. \ This will probably not work. // Legacy behavior. Perhaps turn this into an error at some // point. *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast; #endif break; #if 0 case SkBitmap::kRGB_565_Config: // doesn't see quite right. Are they thinking 1555? *bitsPerComponent = 5; *info = kCGBitmapByteOrder16Little; break; #endif case SkBitmap::kARGB_4444_Config: *bitsPerComponent = 4; *info = kCGBitmapByteOrder16Little | kCGImageAlphaPremultipliedLast; break; default: return NULL; } SkBitmap* copy; if (upscaleTo32) { copy = new SkBitmap; // here we make a ceep copy of the pixels, since CG won't take our // 565 directly bm.copyTo(copy, SkBitmap::kARGB_8888_Config); } else { copy = new SkBitmap(bm); } return copy; } #undef HAS_ARGB_SHIFTS CGImageRef SkCreateCGImageRefWithColorspace(const SkBitmap& bm, CGColorSpaceRef colorSpace) { size_t bitsPerComponent SK_INIT_TO_AVOID_WARNING; CGBitmapInfo info SK_INIT_TO_AVOID_WARNING; SkBitmap* bitmap = prepareForImageRef(bm, &bitsPerComponent, &info); if (NULL == bitmap) { return NULL; } const int w = bitmap->width(); const int h = bitmap->height(); const size_t s = bitmap->getSize(); // our provider "owns" the bitmap*, and will take care of deleting it // we initially lock it, so we can access the pixels. The bitmap will be deleted in the release // proc, which will in turn unlock the pixels bitmap->lockPixels(); CGDataProviderRef dataRef = CGDataProviderCreateWithData(bitmap, bitmap->getPixels(), s, SkBitmap_ReleaseInfo); bool releaseColorSpace = false; if (NULL == colorSpace) { colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); releaseColorSpace = true; } CGImageRef ref = CGImageCreate(w, h, bitsPerComponent, bitmap->bytesPerPixel() * 8, bitmap->rowBytes(), colorSpace, info, dataRef, NULL, false, kCGRenderingIntentDefault); if (releaseColorSpace) { CGColorSpaceRelease(colorSpace); } CGDataProviderRelease(dataRef); return ref; } void SkCGDrawBitmap(CGContextRef cg, const SkBitmap& bm, float x, float y) { CGImageRef img = SkCreateCGImageRef(bm); if (img) { CGRect r = CGRectMake(0, 0, bm.width(), bm.height()); CGContextSaveGState(cg); CGContextTranslateCTM(cg, x, r.size.height + y); CGContextScaleCTM(cg, 1, -1); CGContextDrawImage(cg, r, img); CGContextRestoreGState(cg); CGImageRelease(img); } } <commit_msg>revert to DeviceRGB colorspace by default, which was changed accidentially in rev. 637<commit_after>#include "SkCGUtils.h" #include "SkBitmap.h" #include "SkColorPriv.h" static void SkBitmap_ReleaseInfo(void* info, const void* pixelData, size_t size) { SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(info); delete bitmap; } #define HAS_ARGB_SHIFTS(a, r, g, b) \ (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \ && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b)) static SkBitmap* prepareForImageRef(const SkBitmap& bm, size_t* bitsPerComponent, CGBitmapInfo* info) { bool upscaleTo32 = false; switch (bm.config()) { case SkBitmap::kRGB_565_Config: upscaleTo32 = true; // fall through case SkBitmap::kARGB_8888_Config: *bitsPerComponent = 8; #if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 0, 8, 16) \ || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(0, 24, 16, 8) *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast; #elif defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) \ || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) // Matches the CGBitmapInfo that Apple recommends for best // performance, used by google chrome. *info = kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst; #else // ...add more formats as required... #warning Cannot convert SkBitmap to CGImageRef with these shiftmasks. \ This will probably not work. // Legacy behavior. Perhaps turn this into an error at some // point. *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast; #endif break; #if 0 case SkBitmap::kRGB_565_Config: // doesn't see quite right. Are they thinking 1555? *bitsPerComponent = 5; *info = kCGBitmapByteOrder16Little; break; #endif case SkBitmap::kARGB_4444_Config: *bitsPerComponent = 4; *info = kCGBitmapByteOrder16Little | kCGImageAlphaPremultipliedLast; break; default: return NULL; } SkBitmap* copy; if (upscaleTo32) { copy = new SkBitmap; // here we make a ceep copy of the pixels, since CG won't take our // 565 directly bm.copyTo(copy, SkBitmap::kARGB_8888_Config); } else { copy = new SkBitmap(bm); } return copy; } #undef HAS_ARGB_SHIFTS CGImageRef SkCreateCGImageRefWithColorspace(const SkBitmap& bm, CGColorSpaceRef colorSpace) { size_t bitsPerComponent SK_INIT_TO_AVOID_WARNING; CGBitmapInfo info SK_INIT_TO_AVOID_WARNING; SkBitmap* bitmap = prepareForImageRef(bm, &bitsPerComponent, &info); if (NULL == bitmap) { return NULL; } const int w = bitmap->width(); const int h = bitmap->height(); const size_t s = bitmap->getSize(); // our provider "owns" the bitmap*, and will take care of deleting it // we initially lock it, so we can access the pixels. The bitmap will be deleted in the release // proc, which will in turn unlock the pixels bitmap->lockPixels(); CGDataProviderRef dataRef = CGDataProviderCreateWithData(bitmap, bitmap->getPixels(), s, SkBitmap_ReleaseInfo); bool releaseColorSpace = false; if (NULL == colorSpace) { colorSpace = CGColorSpaceCreateDeviceRGB(); releaseColorSpace = true; } CGImageRef ref = CGImageCreate(w, h, bitsPerComponent, bitmap->bytesPerPixel() * 8, bitmap->rowBytes(), colorSpace, info, dataRef, NULL, false, kCGRenderingIntentDefault); if (releaseColorSpace) { CGColorSpaceRelease(colorSpace); } CGDataProviderRelease(dataRef); return ref; } void SkCGDrawBitmap(CGContextRef cg, const SkBitmap& bm, float x, float y) { CGImageRef img = SkCreateCGImageRef(bm); if (img) { CGRect r = CGRectMake(0, 0, bm.width(), bm.height()); CGContextSaveGState(cg); CGContextTranslateCTM(cg, x, r.size.height + y); CGContextScaleCTM(cg, 1, -1); CGContextDrawImage(cg, r, img); CGContextRestoreGState(cg); CGImageRelease(img); } } <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _WIN32 #include "iceoryx_utils/internal/posix_wrapper/access_control.hpp" #include "iceoryx_utils/platform/pwd.hpp" #include "iceoryx_utils/platform/stat.hpp" #include "test.hpp" #include <stdlib.h> using namespace ::testing; using namespace iox::posix; constexpr const char* TestFileName = "/tmp/AclTestFile.tmp"; class AccessController_test : public Test { public: AccessController_test() { } void SetUp() { internal::CaptureStderr(); m_fileStream = fopen(TestFileName, "w"); m_fileDescriptor = fileno(m_fileStream); } void TearDown() { fclose(m_fileStream); std::remove(TestFileName); std::string output = internal::GetCapturedStderr(); if (Test::HasFailure()) { std::cout << output << std::endl; } } ~AccessController_test() { } iox::posix::AccessController m_accessController; FILE* m_fileStream; int m_fileDescriptor; }; TEST_F(AccessController_test, writeStandardPermissions) { // should fail beacuse no access rights have been specified yet bool result = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_FALSE(result); m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); // should fail because group and others is missing result = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_FALSE(result); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::NONE); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::READ); // should succeed now result = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(result); acl_t fileACL = acl_get_fd(m_fileDescriptor); acl_t localACL = acl_from_text("u::rw,g::-,o::r"); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, writeSpecialUserPermissions) { bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE); // no name specified EXPECT_FALSE(entryAdded); std::string currentUserName(getpwuid(geteuid())->pw_name); entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserName); EXPECT_TRUE(entryAdded); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); // standard permissions not yet defined EXPECT_FALSE(entriesWrittenToFile); // add standard permissions m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(entriesWrittenToFile); acl_t fileACL = acl_get_fd(m_fileDescriptor); std::string localACLShortText = "u:" + currentUserName + ":rw,u::rw,g::r,o::-,m::rw"; acl_t localACL = acl_from_text(localACLShortText.c_str()); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, writeSpecialGroupPermissions) { bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE); // no name specified EXPECT_FALSE(entryAdded); std::string groupName = "root"; entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName); EXPECT_TRUE(entryAdded); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); // standard permissions not yet defined EXPECT_FALSE(entriesWrittenToFile); // add standard permissions m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(entriesWrittenToFile); acl_t fileACL = acl_get_fd(m_fileDescriptor); acl_t localACL = acl_from_text("g:root:rw,u::rw,g::r,o::-,m::rw"); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, writeSpecialPermissionsWithID) { std::string currentUserName(getpwuid(geteuid())->pw_name); uid_t currentUserId(getpwuid(geteuid())->pw_uid); gid_t groupId = 0; // root bool entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserId); EXPECT_TRUE(entryAdded); entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupId); EXPECT_TRUE(entryAdded); m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(entriesWrittenToFile); acl_t fileACL = acl_get_fd(m_fileDescriptor); std::string localACLShortText = "u:" + currentUserName + ":rw,u::rw,g:root:rw,g::r,o::-,m::rw"; acl_t localACL = acl_from_text(localACLShortText.c_str()); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, addNameInWrongPlace) { std::string currentUserName(getpwuid(geteuid())->pw_name); // this is not allowed as the default user should not be named explicitly m_accessController.addPermissionEntry( AccessController::Category::USER, AccessController::Permission::READWRITE, currentUserName); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); bool writtenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_FALSE(writtenToFile); } TEST_F(AccessController_test, addManyPermissions) { std::string groupName = "root"; bool entryAdded; for (int i = 0; i < AccessController::MaxNumOfPermissions; ++i) { entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName); ASSERT_TRUE(entryAdded); } entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName); EXPECT_FALSE(entryAdded); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); // the same specific group has been entered several times EXPECT_FALSE(entriesWrittenToFile); } TEST_F(AccessController_test, addStrangeNames) { bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, "VeryUnlikelyThatThisUserExistsOnThisMachine123456"); // non-existing user name specified EXPECT_FALSE(entryAdded); entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, "NeverEverEverSuchAGroupNameExisted"); // non-existing group name specified EXPECT_FALSE(entryAdded); } #endif <commit_msg>iox-#32 disabling acl tests since they are not supported<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if !defined(_WIN32) && !defined(__APPLE__) #include "iceoryx_utils/internal/posix_wrapper/access_control.hpp" #include "iceoryx_utils/platform/pwd.hpp" #include "iceoryx_utils/platform/stat.hpp" #include "test.hpp" #include <stdlib.h> using namespace ::testing; using namespace iox::posix; constexpr const char* TestFileName = "/tmp/AclTestFile.tmp"; class AccessController_test : public Test { public: AccessController_test() { } void SetUp() { internal::CaptureStderr(); m_fileStream = fopen(TestFileName, "w"); m_fileDescriptor = fileno(m_fileStream); } void TearDown() { fclose(m_fileStream); std::remove(TestFileName); std::string output = internal::GetCapturedStderr(); if (Test::HasFailure()) { std::cout << output << std::endl; } } ~AccessController_test() { } iox::posix::AccessController m_accessController; FILE* m_fileStream; int m_fileDescriptor; }; TEST_F(AccessController_test, writeStandardPermissions) { // should fail beacuse no access rights have been specified yet bool result = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_FALSE(result); m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); // should fail because group and others is missing result = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_FALSE(result); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::NONE); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::READ); // should succeed now result = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(result); acl_t fileACL = acl_get_fd(m_fileDescriptor); acl_t localACL = acl_from_text("u::rw,g::-,o::r"); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, writeSpecialUserPermissions) { bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE); // no name specified EXPECT_FALSE(entryAdded); std::string currentUserName(getpwuid(geteuid())->pw_name); entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserName); EXPECT_TRUE(entryAdded); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); // standard permissions not yet defined EXPECT_FALSE(entriesWrittenToFile); // add standard permissions m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(entriesWrittenToFile); acl_t fileACL = acl_get_fd(m_fileDescriptor); std::string localACLShortText = "u:" + currentUserName + ":rw,u::rw,g::r,o::-,m::rw"; acl_t localACL = acl_from_text(localACLShortText.c_str()); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, writeSpecialGroupPermissions) { bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE); // no name specified EXPECT_FALSE(entryAdded); std::string groupName = "root"; entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName); EXPECT_TRUE(entryAdded); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); // standard permissions not yet defined EXPECT_FALSE(entriesWrittenToFile); // add standard permissions m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(entriesWrittenToFile); acl_t fileACL = acl_get_fd(m_fileDescriptor); acl_t localACL = acl_from_text("g:root:rw,u::rw,g::r,o::-,m::rw"); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, writeSpecialPermissionsWithID) { std::string currentUserName(getpwuid(geteuid())->pw_name); uid_t currentUserId(getpwuid(geteuid())->pw_uid); gid_t groupId = 0; // root bool entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserId); EXPECT_TRUE(entryAdded); entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupId); EXPECT_TRUE(entryAdded); m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_TRUE(entriesWrittenToFile); acl_t fileACL = acl_get_fd(m_fileDescriptor); std::string localACLShortText = "u:" + currentUserName + ":rw,u::rw,g:root:rw,g::r,o::-,m::rw"; acl_t localACL = acl_from_text(localACLShortText.c_str()); std::string fileACLText(acl_to_text(fileACL, nullptr)); std::string localACLText(acl_to_text(localACL, nullptr)); EXPECT_EQ(fileACLText, localACLText); acl_free(fileACL); acl_free(localACL); } TEST_F(AccessController_test, addNameInWrongPlace) { std::string currentUserName(getpwuid(geteuid())->pw_name); // this is not allowed as the default user should not be named explicitly m_accessController.addPermissionEntry( AccessController::Category::USER, AccessController::Permission::READWRITE, currentUserName); m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ); m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); bool writtenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); EXPECT_FALSE(writtenToFile); } TEST_F(AccessController_test, addManyPermissions) { std::string groupName = "root"; bool entryAdded; for (int i = 0; i < AccessController::MaxNumOfPermissions; ++i) { entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName); ASSERT_TRUE(entryAdded); } entryAdded = m_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName); EXPECT_FALSE(entryAdded); bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor); // the same specific group has been entered several times EXPECT_FALSE(entriesWrittenToFile); } TEST_F(AccessController_test, addStrangeNames) { bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, "VeryUnlikelyThatThisUserExistsOnThisMachine123456"); // non-existing user name specified EXPECT_FALSE(entryAdded); entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, "NeverEverEverSuchAGroupNameExisted"); // non-existing group name specified EXPECT_FALSE(entryAdded); } #endif <|endoftext|>
<commit_before>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__ #define __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__ #include "vector_tile.pb.h" namespace mapnik { namespace vector_tile_impl { class Geometry { public: inline explicit Geometry(vector_tile::Tile_Feature const& f, double tile_x, double tile_y, double scale_x, double scale_y); enum command : uint8_t { end = 0, move_to = 1, line_to = 2, close = 7 }; inline command next(double& rx, double& ry); private: vector_tile::Tile_Feature const& f_; double scale_x_; double scale_y_; uint32_t k; uint32_t geoms_; uint8_t cmd; uint32_t length; double x, y; double ox, oy; }; Geometry::Geometry(vector_tile::Tile_Feature const& f, double tile_x, double tile_y, double scale_x, double scale_y) : f_(f), scale_x_(scale_x), scale_y_(scale_y), k(0), geoms_(f_.geometry_size()), cmd(1), length(0), x(tile_x), y(tile_y), ox(0), oy(0) {} Geometry::command Geometry::next(double& rx, double& ry) { if (k < geoms_) { if (length == 0) { uint32_t cmd_length = static_cast<uint32_t>(f_.geometry(k++)); cmd = cmd_length & 0x7; length = cmd_length >> 3; } --length; if (cmd == move_to || cmd == line_to) { int32_t dx = f_.geometry(k++); int32_t dy = f_.geometry(k++); dx = ((dx >> 1) ^ (-(dx & 1))); dy = ((dy >> 1) ^ (-(dy & 1))); x += (static_cast<double>(dx) / scale_x_); y += (static_cast<double>(dy) / scale_y_); rx = x; ry = y; if (cmd == move_to) { ox = x; oy = y; return move_to; } else { return line_to; } } else if (cmd == close) { rx = ox; ry = oy; return close; } else { fprintf(stderr, "unknown command: %d\n", cmd); return end; } } else { return end; } } inline mapnik::geometry::geometry decode_geometry(vector_tile::Tile_Feature const& f, double tile_x, double tile_y, double scale_x, double scale_y) { Geometry::command cmd; Geometry geoms(f,tile_x,tile_y,scale_x,scale_y); double x1, y1; switch (f.type()) { case vector_tile::Tile_GeomType_POINT: { mapnik::geometry::multi_point mp; while ((cmd = geoms.next(x1, y1)) != Geometry::end) { mp.emplace_back(mapnik::geometry::point(x1,y1)); } std::size_t num_points = mp.size(); if (num_points == 1) { // return the single point return mapnik::geometry::geometry(std::move(mp[0]));; } else if (num_points > 1) { // return multipoint return mapnik::geometry::geometry(std::move(mp));; } break; } case vector_tile::Tile_GeomType_LINESTRING: { mapnik::geometry::multi_line_string mp; mp.emplace_back(); bool first = true; while ((cmd = geoms.next(x1, y1)) != Geometry::end) { if (cmd == Geometry::move_to) { if (first) { first = false; } else { mp.emplace_back(); } } mp.back().add_coord(x1,y1); } std::size_t num_lines = mp.size(); if (num_lines == 1) { // return the single line return mapnik::geometry::geometry(std::move(mp[0]));; } else if (num_lines > 1) { // return multiline return mapnik::geometry::geometry(std::move(mp));; } break; } case vector_tile::Tile_GeomType_POLYGON: { // TODO - support for multipolygons //mapnik::geometry::multi_polygon; mapnik::geometry::polygon poly; std::vector<mapnik::geometry::linear_ring> rings; rings.emplace_back(); double x2,y2; bool first = true; while ((cmd = geoms.next(x1, y1)) != Geometry::end) { if (cmd == Geometry::move_to) { x2 = x1; y2 = y1; if (first) { first = false; } else { rings.emplace_back(); } } else if (cmd == Geometry::close) { rings.back().add_coord(x2,y2); continue; } rings.back().add_coord(x1,y1); } std::size_t num_rings = rings.size(); if (num_rings == 1) { // return the single polygon mapnik::geometry::polygon poly; poly.set_exterior_ring(std::move(rings[0])); return mapnik::geometry::geometry(std::move(poly)); } for (unsigned i = 0; i < num_rings;++i) { mapnik::geometry::polygon poly; if (i == 0) { poly.set_exterior_ring(std::move(rings[i])); } else { poly.add_hole(std::move(rings[i])); } return mapnik::geometry::geometry(std::move(poly)); } return poly; break; } case vector_tile::Tile_GeomType_UNKNOWN: default: { throw std::runtime_error("unhandled geometry type during decoding"); break; } } return mapnik::geometry::geometry(); } }} // end ns #endif // __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__ <commit_msg>fix polygon decoder to deal with multiple polygons encoded as multiple paths<commit_after>#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__ #define __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__ #include "vector_tile.pb.h" #include <mapnik/util/is_clockwise.hpp> namespace mapnik { namespace vector_tile_impl { class Geometry { public: inline explicit Geometry(vector_tile::Tile_Feature const& f, double tile_x, double tile_y, double scale_x, double scale_y); enum command : uint8_t { end = 0, move_to = 1, line_to = 2, close = 7 }; inline command next(double& rx, double& ry); private: vector_tile::Tile_Feature const& f_; double scale_x_; double scale_y_; uint32_t k; uint32_t geoms_; uint8_t cmd; uint32_t length; double x, y; double ox, oy; }; Geometry::Geometry(vector_tile::Tile_Feature const& f, double tile_x, double tile_y, double scale_x, double scale_y) : f_(f), scale_x_(scale_x), scale_y_(scale_y), k(0), geoms_(f_.geometry_size()), cmd(1), length(0), x(tile_x), y(tile_y), ox(0), oy(0) {} Geometry::command Geometry::next(double& rx, double& ry) { if (k < geoms_) { if (length == 0) { uint32_t cmd_length = static_cast<uint32_t>(f_.geometry(k++)); cmd = cmd_length & 0x7; length = cmd_length >> 3; } --length; if (cmd == move_to || cmd == line_to) { int32_t dx = f_.geometry(k++); int32_t dy = f_.geometry(k++); dx = ((dx >> 1) ^ (-(dx & 1))); dy = ((dy >> 1) ^ (-(dy & 1))); x += (static_cast<double>(dx) / scale_x_); y += (static_cast<double>(dy) / scale_y_); rx = x; ry = y; if (cmd == move_to) { ox = x; oy = y; return move_to; } else { return line_to; } } else if (cmd == close) { rx = ox; ry = oy; return close; } else { fprintf(stderr, "unknown command: %d\n", cmd); return end; } } else { return end; } } inline mapnik::geometry::geometry decode_geometry(vector_tile::Tile_Feature const& f, double tile_x, double tile_y, double scale_x, double scale_y) { Geometry::command cmd; Geometry geoms(f,tile_x,tile_y,scale_x,scale_y); double x1, y1; switch (f.type()) { case vector_tile::Tile_GeomType_POINT: { mapnik::geometry::multi_point mp; while ((cmd = geoms.next(x1, y1)) != Geometry::end) { mp.emplace_back(mapnik::geometry::point(x1,y1)); } std::size_t num_points = mp.size(); if (num_points == 1) { // return the single point return mapnik::geometry::geometry(std::move(mp[0]));; } else if (num_points > 1) { // return multipoint return mapnik::geometry::geometry(std::move(mp));; } break; } case vector_tile::Tile_GeomType_LINESTRING: { mapnik::geometry::multi_line_string mp; mp.emplace_back(); bool first = true; while ((cmd = geoms.next(x1, y1)) != Geometry::end) { if (cmd == Geometry::move_to) { if (first) { first = false; } else { mp.emplace_back(); } } mp.back().add_coord(x1,y1); } std::size_t num_lines = mp.size(); if (num_lines == 1) { // return the single line return mapnik::geometry::geometry(std::move(mp[0]));; } else if (num_lines > 1) { // return multiline return mapnik::geometry::geometry(std::move(mp));; } break; } case vector_tile::Tile_GeomType_POLYGON: { // TODO - support for multipolygons //mapnik::geometry::multi_polygon; mapnik::geometry::polygon poly; std::vector<mapnik::geometry::linear_ring> rings; rings.emplace_back(); double x2,y2; bool first = true; while ((cmd = geoms.next(x1, y1)) != Geometry::end) { if (cmd == Geometry::move_to) { x2 = x1; y2 = y1; if (first) { first = false; } else { rings.emplace_back(); } } else if (cmd == Geometry::close) { rings.back().add_coord(x2,y2); continue; } rings.back().add_coord(x1,y1); } auto rings_itr = std::make_move_iterator(rings.begin()); auto rings_end = std::make_move_iterator(rings.end()); std::size_t num_rings = rings.size(); if (num_rings == 1) { // return the single polygon without interior rings mapnik::geometry::polygon poly; poly.set_exterior_ring(std::move(*rings_itr)); return mapnik::geometry::geometry(std::move(poly)); } mapnik::geometry::multi_polygon multi_poly; multi_poly.emplace_back(); first = true; for (; rings_itr != rings_end; ++rings_itr) { if (first) { // first ring always exterior multi_poly.back().set_exterior_ring(std::move(*rings_itr)); first = false; } else if (!mapnik::util::is_clockwise(*rings_itr)) // no-move --> const& { multi_poly.emplace_back(); // start new polygon multi_poly.back().set_exterior_ring(std::move(*rings_itr)); } else { multi_poly.back().add_hole(std::move(*rings_itr)); } } if (multi_poly.size() == 1) { auto itr = std::make_move_iterator(multi_poly.begin()); return mapnik::geometry::geometry(std::move(*itr)); } else { return mapnik::geometry::geometry(std::move(multi_poly)); } break; } case vector_tile::Tile_GeomType_UNKNOWN: default: { throw std::runtime_error("unhandled geometry type during decoding"); break; } } return mapnik::geometry::geometry(); } }} // end ns #endif // __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__ <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "Step8.h" #include "QmitkStdMultiWidget.h" #include "mitkGlobalInteraction.h" #include "mitkRenderingManager.h" #include <QHBoxLayout> #include <QVBoxLayout> //##Documentation //## @brief As Step6, but with QmitkStdMultiWidget as widget Step8::Step8(int argc, char* argv[], QWidget *parent) : Step6(argc, argv, parent) { } void Step8::SetupWidgets() { //************************************************************************* // Part I: Create windows and pass the tree to it //************************************************************************* // Create toplevel widget with vertical layout QVBoxLayout* vlayout = new QVBoxLayout(this); vlayout->setMargin(0); vlayout->setSpacing(2); // Create viewParent widget with horizontal layout QWidget* viewParent = new QWidget(this); vlayout->addWidget(viewParent); QHBoxLayout* hlayout = new QHBoxLayout(viewParent); hlayout->setMargin(0); //************************************************************************* // Part Ia: create and initialize QmitkStdMultiWidget //************************************************************************* QmitkStdMultiWidget* multiWidget = new QmitkStdMultiWidget(viewParent); hlayout->addWidget(multiWidget); // Tell the multiWidget which DataStorage to render multiWidget->SetDataStorage(m_DataStorage); // Initialize views as transversal, sagittal, coronar (from // top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = m_DataStorage->ComputeBoundingGeometry3D( m_DataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view multiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D); // Enable standard handler for levelwindow-slider multiWidget->EnableStandardLevelWindow(); // Add the displayed views to the DataStorage to see their positions in 2D and 3D multiWidget->AddDisplayPlaneSubTree(); multiWidget->AddPlanesToDataStorage(); multiWidget->SetWidgetPlanesVisibility(true); //************************************************************************* // Part II: Setup standard interaction with the mouse //************************************************************************* // Moving the cut-planes to click-point multiWidget->EnableNavigationControllerEventListening(); // Zooming and panning mitk::GlobalInteraction::GetInstance()->AddListener( multiWidget->GetMoveAndZoomInteractor()); } /** \example Step8.cpp */ <commit_msg>Remove obsolete code<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "Step8.h" #include "QmitkStdMultiWidget.h" #include "mitkGlobalInteraction.h" #include "mitkRenderingManager.h" #include <QHBoxLayout> #include <QVBoxLayout> //##Documentation //## @brief As Step6, but with QmitkStdMultiWidget as widget Step8::Step8(int argc, char* argv[], QWidget *parent) : Step6(argc, argv, parent) { } void Step8::SetupWidgets() { //************************************************************************* // Part I: Create windows and pass the tree to it //************************************************************************* // Create toplevel widget with vertical layout QVBoxLayout* vlayout = new QVBoxLayout(this); vlayout->setMargin(0); vlayout->setSpacing(2); // Create viewParent widget with horizontal layout QWidget* viewParent = new QWidget(this); vlayout->addWidget(viewParent); QHBoxLayout* hlayout = new QHBoxLayout(viewParent); hlayout->setMargin(0); //************************************************************************* // Part Ia: create and initialize QmitkStdMultiWidget //************************************************************************* QmitkStdMultiWidget* multiWidget = new QmitkStdMultiWidget(viewParent); hlayout->addWidget(multiWidget); // Tell the multiWidget which DataStorage to render multiWidget->SetDataStorage(m_DataStorage); // Initialize views as transversal, sagittal, coronar (from // top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = m_DataStorage->ComputeBoundingGeometry3D( m_DataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view multiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D); // Enable standard handler for levelwindow-slider multiWidget->EnableStandardLevelWindow(); // Add the displayed views to the DataStorage to see their positions in 2D and 3D multiWidget->AddDisplayPlaneSubTree(); multiWidget->AddPlanesToDataStorage(); multiWidget->SetWidgetPlanesVisibility(true); //************************************************************************* // Part II: Setup standard interaction with the mouse //************************************************************************* // Moving the cut-planes to click-point multiWidget->EnableNavigationControllerEventListening(); } /** \example Step8.cpp */ <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author : Moritz Dannhauer Last modification : March 16 2014 (ported from SCIRun4) TODO: Nrrd aoutput */ #include <Core/Algorithms/Legacy/Fields/Mapping/MapFieldDataFromElemToNode.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <Core/GeometryPrimitives/Vector.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Core/Datatypes/Legacy/Field/VMesh.h> using namespace SCIRun::Core::Algorithms::Fields; using namespace SCIRun::Core::Geometry; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Utility; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Logging; using namespace SCIRun; template <class DATA> bool MapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo, FieldHandle& input, FieldHandle& output); template <class DATA> bool MapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo, FieldHandle& input, FieldHandle& output) { std::string method = algo->get_option(MapFieldDataFromElemToNodeAlgo::Method); VField *ifield = input->vfield(); VField *ofield = output->vfield(); /// Make sure that the data vector has the same length ofield->resize_fdata(); VMesh* mesh = input->vmesh(); VMesh::Elem::array_type elems; VMesh::Node::iterator it, eit; VMesh::Node::size_type sz; mesh->synchronize(SCIRun::Mesh::NODE_NEIGHBORS_E); mesh->begin(it); mesh->end(eit); mesh->size(sz); index_type cnt = 0, c = 0; if (method == "Interpolation") { algo->remark("Interpolation of piecewise constant data is done by averaging adjoining values"); } if ((method == "Interpolation")||(method == "Average")) { while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); DATA val(0); DATA tval; for (size_t p = 0; p < nsize; p++) { ifield->get_value(tval,elems[p]); val += tval; } val = static_cast<DATA>(val*(1.0/static_cast<double>(nsize))); ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method == "Max") { while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); DATA val(0); DATA tval(0); if (nsize > 0) { ifield->get_value(val,elems[0]); for (size_t p = 1; p < nsize; p++) { ifield->get_value(tval,elems[p]); if (tval > val) val = tval; } } ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method == "Min") { while (it != eit) { mesh->get_elems(elems, *it); size_t nsize = elems.size(); DATA val(0); DATA tval(0); if (nsize > 0) { ifield->get_value(val,elems[0]); for (size_t p = 1; p < nsize; p++) { ifield->value(tval,elems[p]); if (tval < val) val = tval; } } ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method=="Sum") { while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); DATA val(0); DATA tval(0); for (size_t p = 0; p < nsize; p++) { ifield->get_value(tval,elems[p]); val += tval; } ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method == "Median") { std::vector<DATA> valarray; while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); valarray.resize(nsize); for (size_t p = 0; p < nsize; p++) { ifield->get_value(valarray[p],elems[p]); } sort(valarray.begin(),valarray.end()); int idx = static_cast<int>((valarray.size()/2)); ofield->set_value(valarray[idx],*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else { algo->remark("Method is not implemented!"); return false; } return true; } MapFieldDataFromElemToNodeAlgo::MapFieldDataFromElemToNodeAlgo() { add_option(Method,"Interpolation","Interpolation|Average|Min|Max|Sum|Median|None"); } AlgorithmParameterName MapFieldDataFromElemToNodeAlgo::Method("Method"); AlgorithmOutput MapFieldDataFromElemToNodeAlgo::run_generic(const AlgorithmInput& input) const { auto input_field = input.get<Field>(Variables::InputField); FieldHandle output_field; output_field = run(input_field); AlgorithmOutput output; output[Variables::OutputField] = output_field; return output; } /// Function call to convert data from Field into Matrix data FieldHandle MapFieldDataFromElemToNodeAlgo::run(FieldHandle input_field) const { FieldHandle output; if (!input_field) { THROW_ALGORITHM_INPUT_ERROR("Input field is not allocated"); } FieldInformation fi(input_field); FieldInformation fo(input_field); if (fi.is_lineardata()) { THROW_ALGORITHM_INPUT_ERROR("Data is already located at nodes"); } if (!(fi.is_constantdata())) { THROW_ALGORITHM_INPUT_ERROR("The input data needs to be located at the elements"); } fo.make_lineardata(); output = CreateField(fo,input_field->mesh()); if (!output) { THROW_ALGORITHM_INPUT_ERROR("output field cannot be allocated"); } if (input_field->vfield()->is_signed_integer()) { if(!MapFieldDataFromElemToNodeT<int>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output int field cannot be allocated"); } } else if (input_field->vfield()->is_unsigned_integer()) { if(!MapFieldDataFromElemToNodeT<unsigned int>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output uint field cannot be allocated"); } } else if (input_field->vfield()->is_scalar()) { if (!MapFieldDataFromElemToNodeT<double>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output scalar field cannot be allocated"); } } else if (input_field->vfield()->is_vector()) { if (!MapFieldDataFromElemToNodeT<Vector>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output vector field cannot be allocated"); } } else if (input_field->vfield()->is_tensor()) { if (!MapFieldDataFromElemToNodeT<Tensor>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output tensor field cannot be allocated"); } } else { THROW_ALGORITHM_INPUT_ERROR(" Unknown field data type "); } return output; } <commit_msg>Reformat. Fixes #582<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author : Moritz Dannhauer Last modification : March 16 2014 (ported from SCIRun4) TODO: Nrrd aoutput */ #include <Core/Algorithms/Legacy/Fields/Mapping/MapFieldDataFromElemToNode.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <Core/GeometryPrimitives/Vector.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Core/Datatypes/Legacy/Field/VMesh.h> using namespace SCIRun::Core::Algorithms::Fields; using namespace SCIRun::Core::Geometry; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Utility; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Logging; using namespace SCIRun; template <class DATA> bool MapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo, FieldHandle& input, FieldHandle& output); template <class DATA> bool MapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo, FieldHandle& input, FieldHandle& output) { std::string method = algo->get_option(MapFieldDataFromElemToNodeAlgo::Method); VField *ifield = input->vfield(); VField *ofield = output->vfield(); /// Make sure that the data vector has the same length ofield->resize_fdata(); VMesh* mesh = input->vmesh(); VMesh::Elem::array_type elems; VMesh::Node::iterator it, eit; VMesh::Node::size_type sz; mesh->synchronize(SCIRun::Mesh::NODE_NEIGHBORS_E); mesh->begin(it); mesh->end(eit); mesh->size(sz); index_type cnt = 0, c = 0; if (method == "Interpolation") { algo->remark("Interpolation of piecewise constant data is done by averaging adjoining values"); } if ((method == "Interpolation")||(method == "Average")) { while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); DATA val(0); DATA tval; for (size_t p = 0; p < nsize; p++) { ifield->get_value(tval,elems[p]); val += tval; } val = static_cast<DATA>(val*(1.0/static_cast<double>(nsize))); ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method == "Max") { while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); DATA val(0); DATA tval(0); if (nsize > 0) { ifield->get_value(val,elems[0]); for (size_t p = 1; p < nsize; p++) { ifield->get_value(tval,elems[p]); if (tval > val) val = tval; } } ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method == "Min") { while (it != eit) { mesh->get_elems(elems, *it); size_t nsize = elems.size(); DATA val(0); DATA tval(0); if (nsize > 0) { ifield->get_value(val,elems[0]); for (size_t p = 1; p < nsize; p++) { ifield->value(tval,elems[p]); if (tval < val) val = tval; } } ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method=="Sum") { while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); DATA val(0); DATA tval(0); for (size_t p = 0; p < nsize; p++) { ifield->get_value(tval,elems[p]); val += tval; } ofield->set_value(val,*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else if (method == "Median") { std::vector<DATA> valarray; while (it != eit) { mesh->get_elems(elems, *(it)); size_t nsize = elems.size(); valarray.resize(nsize); for (size_t p = 0; p < nsize; p++) { ifield->get_value(valarray[p],elems[p]); } sort(valarray.begin(),valarray.end()); int idx = static_cast<int>((valarray.size()/2)); ofield->set_value(valarray[idx],*(it)); ++it; cnt++; if (cnt==1000) { cnt=0; c+=1000; algo->update_progress(c/sz); } } } else { algo->remark("Method is not implemented!"); return false; } return true; } MapFieldDataFromElemToNodeAlgo::MapFieldDataFromElemToNodeAlgo() { add_option(Method,"Interpolation","Interpolation|Average|Min|Max|Sum|Median|None"); } AlgorithmParameterName MapFieldDataFromElemToNodeAlgo::Method("Method"); AlgorithmOutput MapFieldDataFromElemToNodeAlgo::run_generic(const AlgorithmInput& input) const { auto input_field = input.get<Field>(Variables::InputField); FieldHandle output_field; output_field = run(input_field); AlgorithmOutput output; output[Variables::OutputField] = output_field; return output; } /// Function call to convert data from Field into Matrix data FieldHandle MapFieldDataFromElemToNodeAlgo::run(FieldHandle input_field) const { FieldHandle output; if (!input_field) { THROW_ALGORITHM_INPUT_ERROR("Input field is not allocated"); } FieldInformation fi(input_field); FieldInformation fo(input_field); if (fi.is_lineardata()) { THROW_ALGORITHM_INPUT_ERROR("Data is already located at nodes"); } if (!(fi.is_constantdata())) { THROW_ALGORITHM_INPUT_ERROR("The input data needs to be located at the elements"); } fo.make_lineardata(); output = CreateField(fo,input_field->mesh()); if (!output) { THROW_ALGORITHM_INPUT_ERROR("output field cannot be allocated"); } if (input_field->vfield()->is_signed_integer()) { if(!MapFieldDataFromElemToNodeT<int>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output int field cannot be allocated"); } } else if (input_field->vfield()->is_unsigned_integer()) { if(!MapFieldDataFromElemToNodeT<unsigned int>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output uint field cannot be allocated"); } } else if (input_field->vfield()->is_scalar()) { if (!MapFieldDataFromElemToNodeT<double>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output scalar field cannot be allocated"); } } else if (input_field->vfield()->is_vector()) { if (!MapFieldDataFromElemToNodeT<Vector>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output vector field cannot be allocated"); } } else if (input_field->vfield()->is_tensor()) { if (!MapFieldDataFromElemToNodeT<Tensor>(this,input_field,output)) { THROW_ALGORITHM_INPUT_ERROR("output tensor field cannot be allocated"); } } else { THROW_ALGORITHM_INPUT_ERROR(" Unknown field data type "); } return output; } <|endoftext|>
<commit_before>#include "Archs/SuperH/CShInstruction.h" #include "Archs/SuperH/SuperH.h" #include "Archs/SuperH/ShOpcodes.h" #include "Archs/SuperH/ShParser.h" #include "Core/Common.h" #include "Core/FileManager.h" #include "Core/Misc.h" CShInstruction::CShInstruction(ShOpcodeData& opcode, ShImmediateData& immediate, ShRegisterData& registers) { this->opcodeData = opcode; this->immediateData = immediate; this->registerData = registers; } CShInstruction::~CShInstruction() { } int getImmediateBits(ShImmediateType type) { switch (type) { case ShImmediateType::Immediate4: return 4; case ShImmediateType::Immediate8: return 8; case ShImmediateType::Immediate12: return 12; default: return 0; } } bool CShInstruction::Validate(const ValidateState &state) { //bool Result = false; //bool previousNop = addNop; //addNop = false; RamPos = g_fileManager->getVirtualAddress(); if (RamPos % 2) { Logger::queueError(Logger::Error, "opcode not aligned to word boundary"); return false; } // check immediates if (immediateData.primary.type != ShImmediateType::None) { if (immediateData.primary.expression.isLoaded()) { if (!immediateData.primary.expression.evaluateInteger(immediateData.primary.value)) { Logger::queueError(Logger::Error, "Invalid immediate expression"); return false; } immediateData.primary.originalValue = immediateData.primary.value; } if (opcodeData.opcode.flags & SH_MUSTBEALIGNED) // immediate must be aligned { if ((opcodeData.opcode.flags & SH_IMM16) && (immediateData.primary.value % 2)) { Logger::queueError(Logger::Error, "Immediate must be 2-byte aligned"); return false; } if ((opcodeData.opcode.flags & SH_IMM32) && (immediateData.primary.value % 4)) { Logger::queueError(Logger::Error, "Immediate must be 4-byte aligned"); return false; } } int immediateBits = getImmediateBits(immediateData.primary.type); int maxImmediate = ((1 << immediateBits) - 1); if (opcodeData.opcode.flags & SH_IMMREL) // relative { int ldSize = (opcodeData.opcode.flags & SH_IMM32) ? 4 : 2; int rPos = (opcodeData.opcode.flags & SH_IMM32) ? ((RamPos+4) & 0xFFFFFFFFFFFFFFFC) : (RamPos+4); int range = maxImmediate*ldSize; int hiRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? (range/2) : range; int lowRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? -(range/2) : 0; int num = (int) (immediateData.primary.value-rPos); if (num > hiRange || num < lowRange) { Logger::queueError(Logger::Error, "Branch/move target %08X out of range", immediateData.primary.value); return false; } immediateData.primary.value = num; } if (opcodeData.opcode.flags & SH_IMM16) immediateData.primary.value = immediateData.primary.value >> 1; else if (opcodeData.opcode.flags & SH_IMM32) immediateData.primary.value = immediateData.primary.value >> 2; unsigned int mask = (0xFFFFFFFF << (32-immediateBits)) >> (32-immediateBits); int digits = (immediateBits+3) / 4; if ((unsigned int)std::abs(immediateData.primary.value) > mask) { Logger::queueError(Logger::Error, "Immediate value 0x%0*X out of range",digits,immediateData.primary.value); return false; } immediateData.primary.value &= mask; } #if 0 // check load delay if (Sh.hasLoadDelay() && Sh.GetLoadDelay() && !IgnoreLoadDelay) { bool fix = false; if (registerData.grd.num != -1 && registerData.grd.num == Sh.GetLoadDelayRegister()) { Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grd.name); fix = true; } else if (registerData.grs.num != -1 && registerData.grs.num == Sh.GetLoadDelayRegister()) { Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grs.name); fix = true; } else if (registerData.grt.num != -1 && registerData.grt.num == Sh.GetLoadDelayRegister() && !(opcodeData.opcode.flags & MO_IGNORERTD)) { Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grt.name); fix = true; } if (Sh.GetFixLoadDelay() && fix) { addNop = true; Logger::queueError(Logger::Notice, "added nop to ensure correct behavior"); } } if ((opcodeData.opcode.flags & MO_NODELAYSLOT) && Sh.GetDelaySlot() && !IgnoreLoadDelay) { Logger::queueError(Logger::Error, "This instruction can't be in a delay slot"); } Sh.SetDelaySlot((opcodeData.opcode.flags & MO_DELAY) != 0); // now check if this opcode causes a load delay if (Sh.hasLoadDelay()) Sh.SetLoadDelay((opcodeData.opcode.flags & MO_DELAYRT) != 0,registerData.grt.num); if (previousNop != addNop) Result = true; #endif g_fileManager->advanceMemory(2); //addNop ? 4 : 2 return false; } void CShInstruction::Encode() const { //if (addNop) // g_fileManager->writeU32(0); uint16_t encoding = opcodeData.opcode.base; switch (opcodeData.opcode.format) { case SHFMT_0: // xxxx xxxx xxxx xxxx break; case SHFMT_N: // xxxx nnnn xxxx xxxx encoding |= (registerData.grt.num & 0xF) << 8; break; case SHFMT_M: // xxxx mmmm xxxx xxxx encoding |= (registerData.grs.num & 0xF) << 8; break; case SHFMT_NM: // xxxx nnnn mmmm xxxx encoding |= (registerData.grt.num & 0xF) << 8; encoding |= (registerData.grs.num & 0xF) << 4; break; case SHFMT_MD: // xxxx xxxx mmmm dddd encoding |= (registerData.grs.num & 0xF) << 4; encoding |= immediateData.primary.value; break; case SHFMT_ND4: // xxxx xxxx nnnn dddd encoding |= (registerData.grt.num & 0xF) << 4; encoding |= immediateData.primary.value; break; case SHFMT_NMD: // xxxx nnnn mmmm dddd encoding |= (registerData.grt.num & 0xF) << 8; encoding |= (registerData.grs.num & 0xF) << 4; encoding |= immediateData.primary.value; break; case SHFMT_D: // xxxx xxxx dddd dddd case SHFMT_D12: // xxxx dddd dddd dddd encoding |= immediateData.primary.value; break; case SHFMT_ND8: // xxxx nnnn dddd dddd encoding |= (registerData.grt.num & 0xF) << 8; encoding |= immediateData.primary.value; break; case SHFMT_I: // xxxx xxxx iiii iiii encoding |= immediateData.primary.value; break; case SHFMT_NI: // xxxx nnnn iiii iiii encoding |= (registerData.grt.num & 0xF) << 8; encoding |= immediateData.primary.value; break; } g_fileManager->writeU16((uint16_t)encoding); } void CShInstruction::writeTempData(TempData& tempData) const { ShOpcodeFormatter formatter; tempData.writeLine(RamPos, formatter.formatOpcode(opcodeData,registerData,immediateData)); } <commit_msg>Add a comment regarding delayed instructions in SuperH<commit_after>#include "Archs/SuperH/CShInstruction.h" #include "Archs/SuperH/SuperH.h" #include "Archs/SuperH/ShOpcodes.h" #include "Archs/SuperH/ShParser.h" #include "Core/Common.h" #include "Core/FileManager.h" #include "Core/Misc.h" CShInstruction::CShInstruction(ShOpcodeData& opcode, ShImmediateData& immediate, ShRegisterData& registers) { this->opcodeData = opcode; this->immediateData = immediate; this->registerData = registers; } CShInstruction::~CShInstruction() { } int getImmediateBits(ShImmediateType type) { switch (type) { case ShImmediateType::Immediate4: return 4; case ShImmediateType::Immediate8: return 8; case ShImmediateType::Immediate12: return 12; default: return 0; } } bool CShInstruction::Validate(const ValidateState &state) { //bool Result = false; //bool previousNop = addNop; //addNop = false; RamPos = g_fileManager->getVirtualAddress(); if (RamPos % 2) { Logger::queueError(Logger::Error, "opcode not aligned to word boundary"); return false; } // check immediates if (immediateData.primary.type != ShImmediateType::None) { if (immediateData.primary.expression.isLoaded()) { if (!immediateData.primary.expression.evaluateInteger(immediateData.primary.value)) { Logger::queueError(Logger::Error, "Invalid immediate expression"); return false; } immediateData.primary.originalValue = immediateData.primary.value; } if (opcodeData.opcode.flags & SH_MUSTBEALIGNED) // immediate must be aligned { if ((opcodeData.opcode.flags & SH_IMM16) && (immediateData.primary.value % 2)) { Logger::queueError(Logger::Error, "Immediate must be 2-byte aligned"); return false; } if ((opcodeData.opcode.flags & SH_IMM32) && (immediateData.primary.value % 4)) { Logger::queueError(Logger::Error, "Immediate must be 4-byte aligned"); return false; } } int immediateBits = getImmediateBits(immediateData.primary.type); int maxImmediate = ((1 << immediateBits) - 1); if (opcodeData.opcode.flags & SH_IMMREL) // relative { int ldSize = (opcodeData.opcode.flags & SH_IMM32) ? 4 : 2; int rPos = (opcodeData.opcode.flags & SH_IMM32) ? ((RamPos+4) & 0xFFFFFFFFFFFFFFFC) : (RamPos+4); int range = maxImmediate*ldSize; int hiRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? (range/2) : range; int lowRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? -(range/2) : 0; int num = (int) (immediateData.primary.value-rPos); if (num > hiRange || num < lowRange) { Logger::queueError(Logger::Error, "Branch/move target %08X out of range", immediateData.primary.value); return false; } immediateData.primary.value = num; } if (opcodeData.opcode.flags & SH_IMM16) immediateData.primary.value = immediateData.primary.value >> 1; else if (opcodeData.opcode.flags & SH_IMM32) immediateData.primary.value = immediateData.primary.value >> 2; unsigned int mask = (0xFFFFFFFF << (32-immediateBits)) >> (32-immediateBits); int digits = (immediateBits+3) / 4; if ((unsigned int)std::abs(immediateData.primary.value) > mask) { Logger::queueError(Logger::Error, "Immediate value 0x%0*X out of range",digits,immediateData.primary.value); return false; } immediateData.primary.value &= mask; } // // NOTE: SuperH *does* have delayed instructions, but // I'm not entirely sure how they work exactly yet, // so leaving this functionality off. // #if 0 // check load delay if (Sh.hasLoadDelay() && Sh.GetLoadDelay() && !IgnoreLoadDelay) { bool fix = false; if (registerData.grd.num != -1 && registerData.grd.num == Sh.GetLoadDelayRegister()) { Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grd.name); fix = true; } else if (registerData.grs.num != -1 && registerData.grs.num == Sh.GetLoadDelayRegister()) { Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grs.name); fix = true; } else if (registerData.grt.num != -1 && registerData.grt.num == Sh.GetLoadDelayRegister() && !(opcodeData.opcode.flags & MO_IGNORERTD)) { Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grt.name); fix = true; } if (Sh.GetFixLoadDelay() && fix) { addNop = true; Logger::queueError(Logger::Notice, "added nop to ensure correct behavior"); } } if ((opcodeData.opcode.flags & MO_NODELAYSLOT) && Sh.GetDelaySlot() && !IgnoreLoadDelay) { Logger::queueError(Logger::Error, "This instruction can't be in a delay slot"); } Sh.SetDelaySlot((opcodeData.opcode.flags & MO_DELAY) != 0); // now check if this opcode causes a load delay if (Sh.hasLoadDelay()) Sh.SetLoadDelay((opcodeData.opcode.flags & MO_DELAYRT) != 0,registerData.grt.num); if (previousNop != addNop) Result = true; #endif g_fileManager->advanceMemory(2); //addNop ? 4 : 2 return false; } void CShInstruction::Encode() const { //if (addNop) // g_fileManager->writeU32(0); uint16_t encoding = opcodeData.opcode.base; switch (opcodeData.opcode.format) { case SHFMT_0: // xxxx xxxx xxxx xxxx break; case SHFMT_N: // xxxx nnnn xxxx xxxx encoding |= (registerData.grt.num & 0xF) << 8; break; case SHFMT_M: // xxxx mmmm xxxx xxxx encoding |= (registerData.grs.num & 0xF) << 8; break; case SHFMT_NM: // xxxx nnnn mmmm xxxx encoding |= (registerData.grt.num & 0xF) << 8; encoding |= (registerData.grs.num & 0xF) << 4; break; case SHFMT_MD: // xxxx xxxx mmmm dddd encoding |= (registerData.grs.num & 0xF) << 4; encoding |= immediateData.primary.value; break; case SHFMT_ND4: // xxxx xxxx nnnn dddd encoding |= (registerData.grt.num & 0xF) << 4; encoding |= immediateData.primary.value; break; case SHFMT_NMD: // xxxx nnnn mmmm dddd encoding |= (registerData.grt.num & 0xF) << 8; encoding |= (registerData.grs.num & 0xF) << 4; encoding |= immediateData.primary.value; break; case SHFMT_D: // xxxx xxxx dddd dddd case SHFMT_D12: // xxxx dddd dddd dddd encoding |= immediateData.primary.value; break; case SHFMT_ND8: // xxxx nnnn dddd dddd encoding |= (registerData.grt.num & 0xF) << 8; encoding |= immediateData.primary.value; break; case SHFMT_I: // xxxx xxxx iiii iiii encoding |= immediateData.primary.value; break; case SHFMT_NI: // xxxx nnnn iiii iiii encoding |= (registerData.grt.num & 0xF) << 8; encoding |= immediateData.primary.value; break; } g_fileManager->writeU16((uint16_t)encoding); } void CShInstruction::writeTempData(TempData& tempData) const { ShOpcodeFormatter formatter; tempData.writeLine(RamPos, formatter.formatOpcode(opcodeData,registerData,immediateData)); } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2018, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // written by Roman Dementiev // Austen Ott // Jim Harris (FreeBSD) #include <sys/types.h> #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #ifndef _MSC_VER #include <unistd.h> #endif #include "types.h" #include "msr.h" #include <assert.h> #ifdef _MSC_VER #include <windows.h> #include "utils.h" #include "Winmsrdriver\win7\msrstruct.h" #include "winring0/OlsApiInitExt.h" #endif #if defined(__FreeBSD__) || defined(__DragonFly__) #include <sys/ioccom.h> #include <sys/cpuctl.h> #endif #include <mutex> namespace pcm { #ifdef _MSC_VER extern HMODULE hOpenLibSys; // here comes an implementatation for Windows MsrHandle::MsrHandle(uint32 cpu) : cpu_id(cpu) { hDriver = CreateFile(L"\\\\.\\RDMSR", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hDriver == INVALID_HANDLE_VALUE && hOpenLibSys == NULL) throw std::exception(); } MsrHandle::~MsrHandle() { if (hDriver != INVALID_HANDLE_VALUE) CloseHandle(hDriver); } int32 MsrHandle::write(uint64 msr_number, uint64 value) { if (hDriver != INVALID_HANDLE_VALUE) { MSR_Request req; ULONG64 result; DWORD reslength = 0; req.core_id = cpu_id; req.msr_address = msr_number; req.write_value = value; BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_WRITE, &req, sizeof(MSR_Request), &result, sizeof(uint64), &reslength, NULL); assert(status && "Error in DeviceIoControl"); return status ? sizeof(uint64) : 0; } cvt_ds cvt; cvt.ui64 = value; ThreadGroupTempAffinity affinity(cpu_id); DWORD status = Wrmsr((DWORD)msr_number, cvt.ui32.low, cvt.ui32.high); return status ? sizeof(uint64) : 0; } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { if (hDriver != INVALID_HANDLE_VALUE) { MSR_Request req; // ULONG64 result; DWORD reslength = 0; req.core_id = cpu_id; req.msr_address = msr_number; BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_READ, &req, sizeof(MSR_Request), value, sizeof(uint64), &reslength, NULL); assert(status && "Error in DeviceIoControl"); return (int32)reslength; } cvt_ds cvt; cvt.ui64 = 0; ThreadGroupTempAffinity affinity(cpu_id); DWORD status = Rdmsr((DWORD)msr_number, &(cvt.ui32.low), &(cvt.ui32.high)); if (status) *value = cvt.ui64; return status ? sizeof(uint64) : 0; } #elif __APPLE__ // OSX Version MSRAccessor * MsrHandle::driver = NULL; int MsrHandle::num_handles = 0; MsrHandle::MsrHandle(uint32 cpu) { cpu_id = cpu; if (!driver) { driver = new MSRAccessor(); MsrHandle::num_handles = 1; } else { MsrHandle::num_handles++; } } MsrHandle::~MsrHandle() { MsrHandle::num_handles--; if (MsrHandle::num_handles == 0) { delete driver; driver = NULL; } } int32 MsrHandle::write(uint64 msr_number, uint64 value) { return driver->write(cpu_id, msr_number, value); } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { return driver->read(cpu_id, msr_number, value); } int32 MsrHandle::buildTopology(uint32 num_cores, void * ptr) { return driver->buildTopology(num_cores, ptr); } uint32 MsrHandle::getNumInstances() { return driver->getNumInstances(); } uint32 MsrHandle::incrementNumInstances() { return driver->incrementNumInstances(); } uint32 MsrHandle::decrementNumInstances() { return driver->decrementNumInstances(); } #elif defined(__FreeBSD__) || defined(__DragonFly__) MsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu) { char path[200]; snprintf(path, 200, "/dev/cpuctl%d", cpu); int handle = ::open(path, O_RDWR); if (handle < 0) throw std::exception(); fd = handle; } MsrHandle::~MsrHandle() { if (fd >= 0) ::close(fd); } int32 MsrHandle::write(uint64 msr_number, uint64 value) { cpuctl_msr_args_t args; int ret; args.msr = msr_number; args.data = value; ret = ::ioctl(fd, CPUCTL_WRMSR, &args); if (ret) return ret; return sizeof(value); } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { cpuctl_msr_args_t args; int32 ret; args.msr = msr_number; ret = ::ioctl(fd, CPUCTL_RDMSR, &args); if (ret) return ret; *value = args.data; return sizeof(*value); } #else // here comes a Linux version MsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu) { char * path = new char[200]; snprintf(path, 200, "/dev/cpu/%d/msr", cpu); int handle = ::open(path, O_RDWR); if (handle < 0) { // try Android msr device path snprintf(path, 200, "/dev/msr%d", cpu); handle = ::open(path, O_RDWR); } delete[] path; if (handle < 0) { std::cerr << "PCM Error: can't open MSR handle for core " << cpu << "\n"; throw std::exception(); } fd = handle; } MsrHandle::~MsrHandle() { if (fd >= 0) ::close(fd); } int32 MsrHandle::write(uint64 msr_number, uint64 value) { #if 0 static std::mutex m; std::lock_guard<std::mutex> g(m); std::cout << "DEBUG: writing MSR 0x" << std::hex << msr_number << " value 0x" << value << " on cpu " << std::dec << cpu_id << std::endl; #endif return ::pwrite(fd, (const void *)&value, sizeof(uint64), msr_number); } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { return ::pread(fd, (void *)value, sizeof(uint64), msr_number); } #endif } // namespace pcm <commit_msg>allow writes for Linux MSR driver<commit_after>/* Copyright (c) 2009-2018, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // written by Roman Dementiev // Austen Ott // Jim Harris (FreeBSD) #include <sys/types.h> #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #ifndef _MSC_VER #include <unistd.h> #endif #include "types.h" #include "msr.h" #include "utils.h" #include <assert.h> #ifdef _MSC_VER #include <windows.h> #include "utils.h" #include "Winmsrdriver\win7\msrstruct.h" #include "winring0/OlsApiInitExt.h" #endif #if defined(__FreeBSD__) || defined(__DragonFly__) #include <sys/ioccom.h> #include <sys/cpuctl.h> #endif #include <mutex> namespace pcm { #ifdef _MSC_VER extern HMODULE hOpenLibSys; // here comes an implementatation for Windows MsrHandle::MsrHandle(uint32 cpu) : cpu_id(cpu) { hDriver = CreateFile(L"\\\\.\\RDMSR", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hDriver == INVALID_HANDLE_VALUE && hOpenLibSys == NULL) throw std::exception(); } MsrHandle::~MsrHandle() { if (hDriver != INVALID_HANDLE_VALUE) CloseHandle(hDriver); } int32 MsrHandle::write(uint64 msr_number, uint64 value) { if (hDriver != INVALID_HANDLE_VALUE) { MSR_Request req; ULONG64 result; DWORD reslength = 0; req.core_id = cpu_id; req.msr_address = msr_number; req.write_value = value; BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_WRITE, &req, sizeof(MSR_Request), &result, sizeof(uint64), &reslength, NULL); assert(status && "Error in DeviceIoControl"); return status ? sizeof(uint64) : 0; } cvt_ds cvt; cvt.ui64 = value; ThreadGroupTempAffinity affinity(cpu_id); DWORD status = Wrmsr((DWORD)msr_number, cvt.ui32.low, cvt.ui32.high); return status ? sizeof(uint64) : 0; } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { if (hDriver != INVALID_HANDLE_VALUE) { MSR_Request req; // ULONG64 result; DWORD reslength = 0; req.core_id = cpu_id; req.msr_address = msr_number; BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_READ, &req, sizeof(MSR_Request), value, sizeof(uint64), &reslength, NULL); assert(status && "Error in DeviceIoControl"); return (int32)reslength; } cvt_ds cvt; cvt.ui64 = 0; ThreadGroupTempAffinity affinity(cpu_id); DWORD status = Rdmsr((DWORD)msr_number, &(cvt.ui32.low), &(cvt.ui32.high)); if (status) *value = cvt.ui64; return status ? sizeof(uint64) : 0; } #elif __APPLE__ // OSX Version MSRAccessor * MsrHandle::driver = NULL; int MsrHandle::num_handles = 0; MsrHandle::MsrHandle(uint32 cpu) { cpu_id = cpu; if (!driver) { driver = new MSRAccessor(); MsrHandle::num_handles = 1; } else { MsrHandle::num_handles++; } } MsrHandle::~MsrHandle() { MsrHandle::num_handles--; if (MsrHandle::num_handles == 0) { delete driver; driver = NULL; } } int32 MsrHandle::write(uint64 msr_number, uint64 value) { return driver->write(cpu_id, msr_number, value); } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { return driver->read(cpu_id, msr_number, value); } int32 MsrHandle::buildTopology(uint32 num_cores, void * ptr) { return driver->buildTopology(num_cores, ptr); } uint32 MsrHandle::getNumInstances() { return driver->getNumInstances(); } uint32 MsrHandle::incrementNumInstances() { return driver->incrementNumInstances(); } uint32 MsrHandle::decrementNumInstances() { return driver->decrementNumInstances(); } #elif defined(__FreeBSD__) || defined(__DragonFly__) MsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu) { char path[200]; snprintf(path, 200, "/dev/cpuctl%d", cpu); int handle = ::open(path, O_RDWR); if (handle < 0) throw std::exception(); fd = handle; } MsrHandle::~MsrHandle() { if (fd >= 0) ::close(fd); } int32 MsrHandle::write(uint64 msr_number, uint64 value) { cpuctl_msr_args_t args; int ret; args.msr = msr_number; args.data = value; ret = ::ioctl(fd, CPUCTL_WRMSR, &args); if (ret) return ret; return sizeof(value); } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { cpuctl_msr_args_t args; int32 ret; args.msr = msr_number; ret = ::ioctl(fd, CPUCTL_RDMSR, &args); if (ret) return ret; *value = args.data; return sizeof(*value); } #else // here comes a Linux version MsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu) { constexpr auto allowWritesPath = "/sys/module/msr/parameters/allow_writes"; static bool writesEnabled = false; if (writesEnabled == false) { if (readSysFS(allowWritesPath, true).length() > 0) { writeSysFS(allowWritesPath, "on", false); } writesEnabled = true; } char * path = new char[200]; snprintf(path, 200, "/dev/cpu/%d/msr", cpu); int handle = ::open(path, O_RDWR); if (handle < 0) { // try Android msr device path snprintf(path, 200, "/dev/msr%d", cpu); handle = ::open(path, O_RDWR); } delete[] path; if (handle < 0) { std::cerr << "PCM Error: can't open MSR handle for core " << cpu << "\n"; throw std::exception(); } fd = handle; } MsrHandle::~MsrHandle() { if (fd >= 0) ::close(fd); } int32 MsrHandle::write(uint64 msr_number, uint64 value) { #if 0 static std::mutex m; std::lock_guard<std::mutex> g(m); std::cout << "DEBUG: writing MSR 0x" << std::hex << msr_number << " value 0x" << value << " on cpu " << std::dec << cpu_id << std::endl; #endif return ::pwrite(fd, (const void *)&value, sizeof(uint64), msr_number); } int32 MsrHandle::read(uint64 msr_number, uint64 * value) { return ::pread(fd, (void *)value, sizeof(uint64), msr_number); } #endif } // namespace pcm <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <map> #include <iomanip> #include <algorithm> #include <assert.h> #include "lieonn.hh" typedef myfloat num_t; #if ! defined(_FLOAT_BITS_) #define _FLOAT_BITS_ 63 #endif #include <cmath> int main(int argc, char* argv[]) { SimpleMatrix<num_t> A(8 + 1, 6); SimpleVector<num_t> left(A.rows()); SimpleVector<num_t> right(A.rows()); for(int j = 0; j < 8; j ++) { SimpleVector<num_t> work(4); work[0] = num_t(j & 1 ? 1 : 2) / num_t(2); work[1] = num_t((j >> 1) & 1 ? 1 : 2) / num_t(2); work[2] = num_t((j >> 2) & 1 ? 1 : 2) / num_t(2); work[3] = num_t(!((j & 1) && ((j >> 1) & 1)) && ((j >> 2) & 1) ? 2 : 1) / num_t(2); A.row(j) = makeProgramInvariant<num_t>(work).first; assert(A.cols() == A.row(j).size()); left[j] = - (right[j] = sqrt(A.epsilon)); } for(int j = 0; j < A.cols(); j ++) A(8, j) = num_t(4 == j ? 1 : 0); left[8] = sqrt(sqrt(A.epsilon)); right[8] = num_t(1) / sqrt(sqrt(A.epsilon)); const auto in(A.inner(left, right)); std::cout << A * in << std::endl; return 0; } <commit_msg>fix last.<commit_after>#include <cstdio> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <map> #include <iomanip> #include <algorithm> #include <assert.h> #include "lieonn.hh" typedef myfloat num_t; #if ! defined(_FLOAT_BITS_) #define _FLOAT_BITS_ 63 #endif #include <cmath> int main(int argc, char* argv[]) { SimpleMatrix<num_t> A(8 + 1, 6); SimpleVector<num_t> left(A.rows()); SimpleVector<num_t> right(A.rows()); for(int j = 0; j < 8; j ++) { SimpleVector<num_t> work(4); work[0] = num_t(j & 1 ? 1 : 2) / num_t(2); work[1] = num_t((j >> 1) & 1 ? 1 : 2) / num_t(2); work[2] = num_t((j >> 2) & 1 ? 1 : 2) / num_t(2); work[3] = num_t(!((j & 1) && ((j >> 1) & 1)) && ((j >> 2) & 1) ? 2 : 1) / num_t(2); A.row(j) = makeProgramInvariant<num_t>(work).first; assert(A.cols() == A.row(j).size()); left[j] = - (right[j] = sqrt(A.epsilon)); } for(int j = 0; j < A.cols(); j ++) A(8, j) = num_t(3 == j ? 1 : 0); left[8] = sqrt(sqrt(A.epsilon)); right[8] = num_t(1) / sqrt(sqrt(A.epsilon)); const auto in(A.inner(left, right)); std::cout << A * in << std::endl; return 0; } <|endoftext|>
<commit_before>#include <test/unit/math/test_ad.hpp> #include <cmath> #include <complex> #include <vector> #include <type_traits> TEST(mixFun, abs) { auto f = [](const auto& x) { using std::abs; return abs(x); }; stan::test::expect_common_nonzero_unary(f); stan::test::expect_value(f, 0); stan::test::expect_value(f, 0.0); stan::test::expect_ad(f, -3); stan::test::expect_ad(f, -2); stan::test::expect_ad(f, 2); stan::test::expect_ad(f, -17.3); stan::test::expect_ad(f, -0.68); stan::test::expect_ad(f, 0.68); stan::test::expect_ad(f, 2.0); stan::test::expect_ad(f, 4.0); // not differentiable at zero for (double re : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) { for (double im : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) { stan::test::expect_ad(f, std::complex<double>(re, im)); } } } TEST(mixFun, absReturnType) { // validate return types not overpromoted to complex by assignability std::complex<stan::math::var> a = 3; stan::math::var b = abs(a); std::complex<stan::math::fvar<double>> c = 3; stan::math::fvar<double> d = abs(c); SUCCEED(); } TEST(mathMixMatFun, abs_varmat) { using stan::math::vec_concat; using stan::test::expect_ad_vector_matvar; using stan::test::internal::common_nonzero_args; auto f = [](const auto& x1) { using stan::math::abs; return abs(x1); }; std::vector<double> com_args = common_nonzero_args(); std::vector<double> args{0, -3, -2, 2, -17.3, -0.68, 2, 4}; auto all_args = vec_concat(com_args, args); Eigen::VectorXd A(all_args.size()); for (int i = 0; i < all_args.size(); ++i) { A(i) = all_args[i]; } expect_ad_vector_matvar(f, A); } <commit_msg>Don't test abs gradients at 0 cause they don't exist (Issue #2101)<commit_after>#include <test/unit/math/test_ad.hpp> #include <cmath> #include <complex> #include <vector> #include <type_traits> TEST(mixFun, abs) { auto f = [](const auto& x) { using std::abs; return abs(x); }; stan::test::expect_common_nonzero_unary(f); stan::test::expect_value(f, 0); stan::test::expect_value(f, 0.0); stan::test::expect_ad(f, -3); stan::test::expect_ad(f, -2); stan::test::expect_ad(f, 2); stan::test::expect_ad(f, -17.3); stan::test::expect_ad(f, -0.68); stan::test::expect_ad(f, 0.68); stan::test::expect_ad(f, 2.0); stan::test::expect_ad(f, 4.0); // not differentiable at zero for (double re : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) { for (double im : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) { stan::test::expect_ad(f, std::complex<double>(re, im)); } } } TEST(mixFun, absReturnType) { // validate return types not overpromoted to complex by assignability std::complex<stan::math::var> a = 3; stan::math::var b = abs(a); std::complex<stan::math::fvar<double>> c = 3; stan::math::fvar<double> d = abs(c); SUCCEED(); } TEST(mathMixMatFun, abs_varmat) { using stan::math::vec_concat; using stan::test::expect_ad_vector_matvar; using stan::test::internal::common_nonzero_args; auto f = [](const auto& x1) { using stan::math::abs; return abs(x1); }; std::vector<double> com_args = common_nonzero_args(); std::vector<double> args{-3, 2, -0.68, 1}; auto all_args = vec_concat(com_args, args); Eigen::VectorXd A(all_args.size()); for (int i = 0; i < all_args.size(); ++i) { A(i) = all_args[i]; } expect_ad_vector_matvar(f, A); } <|endoftext|>