code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
//****************************************************************************** // MIDIƒV[ƒPƒ“ƒT[ƒ\ƒtƒgw¢ŠEŽ÷x // ƒsƒAƒmƒ[ƒ‹ƒtƒŒ[ƒ€ƒEƒBƒ“ƒhƒEƒNƒ‰ƒX // (C)2002-2012 ‚¨[‚Õ‚ñMIDI‚Õ‚ë‚¶‚¥‚­‚Ɓ^‚­‚¸ //****************************************************************************** /* This library 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. */ /* 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 "winver.h" #include <afxwin.h> #include <afxext.h> #include <afxcmn.h> #include <afxmt.h> #include "common.h" #include "..\\..\\MIDIIO\\MIDIIO.h" #include "..\\..\\MIDIData\\MIDIData.h" #include "..\\..\\MIDIClock\\MIDIClock.h" #include "..\\..\\MIDIStatus\\MIDIStatus.h" #include "..\\..\\MIDIInstrument\\MIDIInstrument.h" #include "resource.h" #include "ColorfulComboBox.h" #include "ColorfulCheckListBox.h" #include "HistoryRecord.h" #include "HistoryUnit.h" #include "SekaijuApp.h" #include "SekaijuDoc.h" #include "SekaijuView.h" #include "SekaijuToolBar.h" #include "MainFrame.h" #include "ChildFrame.h" #include "PianoRollFrame.h" #include "PianoRollPrintView.h" #include "PianoRollScaleView.h" #include "PianoRollTimeScaleView.h" #include "PianoRollKeyScaleView.h" #include "PianoRollKeyTimeView.h" #include "PianoRollVelScaleView.h" #include "PianoRollVelTimeView.h" #include "PropertyNoteDlg.h" // ƒAƒƒP[ƒVƒ‡ƒ“‚ÌŠÄŽ‹ #ifdef _DEBUG #define new DEBUG_NEW #endif // ŽqƒEƒBƒ“ƒhƒE‚̃TƒCƒY #define PIANOROLLFRAME_SCALEHEIGHT 32 #define PIANOROLLFRAME_SCALEWIDTH 64 #define PIANOROLLFRAME_TIMEWIDTH 600 #define PIANOROLLFRAME_KEYHEIGHT 256 #define PIANOROLLFRAME_VELHEIGHT 128 #define PIANOROLLFRAME_SCROLLBARHEIGHT 16 #define PIANOROLLFRAME_SCROLLBARWIDTH 16 #define PIANOROLLFRAME_BORDERWIDTH 2 #define PIANOROLLFRAME_BORDERHEIGHT 2 #define PIANOROLLFRAME_SPLITTERWIDTH 4 #define PIANOROLLFRAME_SPLITTERHEIGHT 4 #define PIANOROLLFRAME_TRACKLISTWIDTH 120 // ŽqƒEƒBƒ“ƒhƒEID‚ð’è‹` #define PIANOROLLFRAME_DUMMYVIEW (AFX_IDW_PANE_FIRST + 0) #define PIANOROLLFRAME_PRINTVIEW (AFX_IDW_PANE_FIRST + 31) #define PIANOROLLFRAME_SCALEVIEW (AFX_IDW_PANE_FIRST + 32) #define PIANOROLLFRAME_TIMESCALEVIEW (AFX_IDW_PANE_FIRST + 33) #define PIANOROLLFRAME_KEYSCALEVIEW (AFX_IDW_PANE_FIRST + 34) #define PIANOROLLFRAME_KEYTIMEVIEW (AFX_IDW_PANE_FIRST + 35) #define PIANOROLLFRAME_VELSCALEVIEW (AFX_IDW_PANE_FIRST + 36) #define PIANOROLLFRAME_VELTIMEVIEW (AFX_IDW_PANE_FIRST + 37) #define PIANOROLLFRAME_TIMESCROLL (AFX_IDW_PANE_FIRST + 48) #define PIANOROLLFRAME_KEYSCROLL (AFX_IDW_PANE_FIRST + 49) #define PIANOROLLFRAME_VELSCROLL (AFX_IDW_PANE_FIRST + 50) #define PIANOROLLFRAME_SIZEBOX (AFX_IDW_PANE_FIRST + 51) #define PIANOROLLFRAME_TIMEZOOMDOWN (AFX_IDW_PANE_FIRST + 52) #define PIANOROLLFRAME_TIMEZOOMUP (AFX_IDW_PANE_FIRST + 53) #define PIANOROLLFRAME_KEYZOOMDOWN (AFX_IDW_PANE_FIRST + 54) #define PIANOROLLFRAME_KEYZOOMUP (AFX_IDW_PANE_FIRST + 55) #define PIANOROLLFRAME_VELZOOMDOWN (AFX_IDW_PANE_FIRST + 56) #define PIANOROLLFRAME_VELZOOMUP (AFX_IDW_PANE_FIRST + 57) #define PIANOROLLFRAME_TRACKLIST (AFX_IDW_PANE_FIRST + 58) #define PIANOROLLFRAME_GRAPHKINDLIST (AFX_IDW_PANE_FIRST + 59) // // ƒsƒAƒmƒ[ƒ‹ƒtƒŒ[ƒ€‚̃Nƒ‰ƒCƒAƒ“ƒg—̈æ‚É”z’u‚³‚ꂽƒIƒuƒWƒFƒNƒg // @@@@@@@@@@@@@@@@@@@@@@@@ @@ m_lScr@„« m_lTrack // „«©m_lScale¨„ © m_lTime @¨„ ©ollBar¨š© ListWidth ¨„« // Width Width @@ Width „« // „Ÿ // ª „¬„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„­ // m_lToolBar1Height„«CToolBar „« // @« „«m_wndToolBar1 „« // „ª „°„ª„ª„ª„ª„ª„ª„¶„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„¶„ª„±„ª„ª„ª„ª„ª„ª„ª„¶„ª„² // ª „«CView* „ CView* @@ „ ª„«CChcekListBox „ ª„« // m_lScaleHeight „«m_pScaleView„ m_pTimeScaleView @@@„¥„Ÿ„·m_wndTrackList„¥„Ÿ„· // « „µ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„©„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„§@„«(With Scroll „ @„« // „Ÿ „«CView*@ „ CView* @@ @ „  š Bar) „  „« // ª „«m_pKeyScale „ m_pKeyTimeView @@ „ @„« „ @„« // „«View „  @@@@@@@@@@@@@„¥„Ÿ„· „ @„« // m_lKeyHeight „«@@@ „  CScrollBar m_wndKeyScroll„ «„« „ @„« // „«@@@ „ @@@@@@@@@@@@@ „¥„Ÿ„· „¥„Ÿ„· // „«@@@ „ @ CButton m_wndKeyZoomDown„ |„« „ «„« // „«@@@ „ @@@@@@@@@@@@@@„¥„Ÿ„·„Ÿ„¦„Ÿ„Ÿ„Ÿ„¦„Ÿ„©„Ÿ„· // « „«@@@ „ @ @ CButton m_wndKeyZoomUp„ {„«©„  @@„ ¨„ @„« // „ªš„ª „°„ª„ª„ª„ª„ª„ª„¹„ª„ª„ª„ªš„ª„ª„ª„ª„ª„ª„ª„ª„ª„¹„ª„´„ª„¸„ªš„ª„¸„ª„¹„ª„² // ª „«CView*@@@„ CView*@@@@@@@@@@@„ ª„«CCheckListBox „ ª„«@ // „«m_pVelScale „ m_pVelTimeView „¥„Ÿ„·m_wndGraph „¥„Ÿ„· // „«View „  @@ „  „«KindList „  „« // „« „  @@ „ @š(With Scroll „ @„« // m_lVelHeight „« „  @@@@@@@@@@@@@„¥„Ÿ„· Bar) „ @„« // „«@@@ „ @ CScrollBar m_wndVelScroll„ «„« „ @„« // „«@@@ „  @@@@@@@@@@@@ „¥„Ÿ„· „ @„« // „«@@@ „  @CButton m_wndVelZoomDown„ |„« „ @„« // « „«@@@ „ @@@@@@@@@@@@@@„¥„Ÿ„· „¥„Ÿ„· // „Ÿ@ „«@@@ „ @@@CButton m_wndVelZoomUp„ {„« „ «„« // ª „µ„Ÿ„¦„Ÿ„Ÿ„Ÿ„Ÿ„¨„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„Ÿ„¦„Ÿ„¦„Ÿ„¦„Ÿ„©„Ÿ„·„Ÿ„¦„Ÿ„Ÿ„Ÿ„¦„Ÿ„©„Ÿ„· //m_lScrollBarHeight„«©„ @@@ @@@@@@@@@„ ¨„ |„ {„ ‡™„«©„  @@„ ¨„ @„«@@ // « „¯„ª„¸„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„ª„¸„ª„¸„ª„¸„ª„¸„ª„³„ª„¸„ª„ª„ª„¸„ª„¸„ª„® // „ª CScrollBar CButton CButton // m_wndTimeScroll m_wndTime m_wndTime // ZoomDown ZoomDown // // (‚ )\\\F’Pƒ‚È‹«ŠEü(0px)B // (‚¢)„ª„ª„ªF‘¾‚­—§‘Ì“I‚È‹«ŠEüBBORDERWIDTH(2px)–”‚ÍBORDERHEIGHT(2px)‚ÅŽ¦‚·•‚ðè—Ì // (‚¤)„ªš„ªFƒXƒvƒŠƒbƒ^[‹«ŠEüB(‚¢)*2+SPRITTERWIDTH(4px)–”‚ÍSPRITTERHEIGHT(4px)‚ÅŽ¦‚·•‚ðè—́B // // ŠÖ”ƒ}ƒNƒ #define PIANOROLLFRAME_RANGE(A,B,C) ((A)>(B)?(A):((B)>(C)?(C):(B))) // ƒƒbƒZ[ƒWƒ}ƒbƒv IMPLEMENT_DYNCREATE(CPianoRollFrame, CChildFrame) BEGIN_MESSAGE_MAP(CPianoRollFrame, CChildFrame) ON_WM_CREATE () ON_WM_DESTROY () ON_WM_SIZE () ON_WM_TIMER () ON_WM_ERASEBKGND () ON_WM_MDIACTIVATE () ON_WM_PAINT () ON_WM_KEYDOWN () ON_WM_LBUTTONDOWN () ON_WM_RBUTTONDOWN () ON_WM_LBUTTONUP () ON_WM_RBUTTONUP () ON_WM_MOUSEMOVE () ON_WM_HSCROLL () ON_WM_VSCROLL () ON_BN_CLICKED (PIANOROLLFRAME_TIMEZOOMDOWN, OnTimeZoomDown) ON_BN_CLICKED (PIANOROLLFRAME_TIMEZOOMUP, OnTimeZoomUp) ON_BN_CLICKED (PIANOROLLFRAME_KEYZOOMDOWN, OnKeyZoomDown) ON_BN_CLICKED (PIANOROLLFRAME_KEYZOOMUP, OnKeyZoomUp) ON_BN_CLICKED (PIANOROLLFRAME_VELZOOMDOWN, OnVelZoomDown) ON_BN_CLICKED (PIANOROLLFRAME_VELZOOMUP, OnVelZoomUp) // ON_WM_CHILDACTIVATE () ON_COMMAND (ID_PIANOROLL_PEN, OnPianoRollPen) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_PEN, OnUpdatePianoRollPenUI) ON_COMMAND (ID_PIANOROLL_LINE, OnPianoRollLine) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_LINE, OnUpdatePianoRollLineUI) ON_COMMAND (ID_PIANOROLL_ERASER, OnPianoRollEraser) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_ERASER, OnUpdatePianoRollEraserUI) ON_COMMAND (ID_PIANOROLL_SELECT, OnPianoRollSelect) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_SELECT, OnUpdatePianoRollSelectUI) ON_COMMAND (ID_PIANOROLL_SPEAKER, OnPianoRollSpeaker) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_SPEAKER, OnUpdatePianoRollSpeakerUI) ON_COMMAND (ID_PIANOROLL_ONLYCURTRACK, OnPianoRollOnlyCurTrack) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_ONLYCURTRACK, OnUpdatePianoRollOnlyCurTrackUI) ON_COMMAND (ID_PIANOROLL_SHOWALLTRACK, OnPianoRollShowAllTrack) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_SHOWALLTRACK, OnUpdatePianoRollShowAllTrackUI) ON_COMMAND (ID_PIANOROLL_ONLYCURGRAPH, OnPianoRollOnlyCurGraph) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_ONLYCURGRAPH, OnUpdatePianoRollOnlyCurGraphUI) ON_COMMAND (ID_PIANOROLL_SHOWALLGRAPH, OnPianoRollShowAllGraph) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_SHOWALLGRAPH, OnUpdatePianoRollShowAllGraphUI) ON_COMMAND (ID_PIANOROLL_AUTOPAGEUPDATE, OnPianoRollAutoPageUpdate) ON_UPDATE_COMMAND_UI (ID_PIANOROLL_AUTOPAGEUPDATE, OnUpdatePianoRollAutoPageUpdateUI) ON_COMMAND (ID_POPUP_TRACKVISIBLEON, OnPopupTrackVisibleOn) ON_UPDATE_COMMAND_UI (ID_POPUP_TRACKVISIBLEON, OnUpdatePopupTrackVisibleOnUI) // 20100429’ljÁ ON_COMMAND (ID_POPUP_TRACKVISIBLEOFF, OnPopupTrackVisibleOff) ON_UPDATE_COMMAND_UI (ID_POPUP_TRACKVISIBLEOFF, OnUpdatePopupTrackVisibleOffUI) // 20100429’ljÁ ON_COMMAND (ID_POPUP_TRACKVISIBLEALL, OnPopupTrackVisibleAll) ON_UPDATE_COMMAND_UI (ID_POPUP_TRACKVISIBLEALL, OnUpdatePopupTrackVisibleAllUI) // 20100429’ljÁ ON_COMMAND (ID_POPUP_EVENTPROPERTY, OnPopupEventProperty) // 20100501’ljÁ ON_UPDATE_COMMAND_UI (ID_POPUP_EVENTPROPERTY, OnUpdatePopupEventPropertyUI) // 20100501’ljÁ ON_CBN_SELENDOK (IDC_TRACKCOMBO, OnTrackComboSelEndOK) ON_CLBN_CHKCHANGE (PIANOROLLFRAME_TRACKLIST, OnTrackListChkChange) ON_LBN_SELCHANGE (PIANOROLLFRAME_TRACKLIST, OnTrackListSelChange) ON_CBN_SELENDOK (IDC_GRAPHKINDCOMBO, OnGraphKindComboSelEndOK) ON_CLBN_CHKCHANGE (PIANOROLLFRAME_GRAPHKINDLIST, OnGraphKindListChkChange) ON_LBN_SELCHANGE (PIANOROLLFRAME_GRAPHKINDLIST, OnGraphKindListSelChange) END_MESSAGE_MAP() //------------------------------------------------------------------------------ // \’z‚Æ”j‰ó //------------------------------------------------------------------------------ // ƒRƒ“ƒXƒgƒ‰ƒNƒ^ CPianoRollFrame::CPianoRollFrame () { long i; CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); m_lKeyHeight = PIANOROLLFRAME_KEYHEIGHT; m_lScaleHeight = PIANOROLLFRAME_SCALEHEIGHT; m_lVelHeight = PIANOROLLFRAME_VELHEIGHT + 16; m_lScaleWidth = PIANOROLLFRAME_SCALEWIDTH; m_lTimeWidth = PIANOROLLFRAME_TIMEWIDTH; //m_lSplitterHeight = PIANOROLLFRAME_SPLITTERHEIGHT; //m_lSplitterWidth = PIANOROLLFRAME_SPLITTERWIDTH; m_lHScrollBarHeight = ::GetSystemMetrics (SM_CYHSCROLL); m_lVScrollBarWidth = ::GetSystemMetrics (SM_CXVSCROLL); m_lTrackListWidth = PIANOROLLFRAME_TRACKLISTWIDTH; m_lVelZoom = pSekaijuApp->m_thePianoRollOption.m_lDefVelZoom; m_lKeyZoom = pSekaijuApp->m_thePianoRollOption.m_lDefKeyZoom; m_lTimeZoom = pSekaijuApp->m_thePianoRollOption.m_lDefTimeZoom; m_lTimeScrollPos = 0; CString strDefaultFontName; VERIFY (strDefaultFontName.LoadString (IDS_DEFAULTFONTNAME)); m_theFont.CreateFont (12, 0, 0, 0, FW_DONTCARE, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, strDefaultFontName); m_lCurTool = ID_PIANOROLL_PEN; // ƒfƒtƒHƒ‹ƒg‚̃c[ƒ‹=ƒyƒ“ m_bAutoPageUpdate = FALSE; // Ž©“®ƒy[ƒWXV=ON m_bOnlyCurTrack = FALSE; // Œ»Ý‚̃gƒ‰ƒbƒN‚̂ݕ\ަ=OFF m_bShowAllTrack = FALSE; // ‚·‚ׂẴgƒ‰ƒbƒN‚ð•\ަ=OFF for (i = 0; i < MAXMIDITRACKNUM; i++) { m_bTrackVisible[i] = TRUE; // ‚·‚ׂẴgƒ‰ƒbƒN‚ð‰ÂŽ‹‚É‚·‚éB } m_bOnlyCurGraph = FALSE; // Œ»Ý‚̃gƒ‰ƒbƒN‚̃Oƒ‰ƒt‚̂ݕ\ަ=OFF m_bShowAllGraph = FALSE; // ‚·‚ׂẴgƒ‰ƒbƒN‚̃Oƒ‰ƒt‚ð•\ަ=OFF for (i = 0; i < 256; i++) { m_bGraphVisible[i] = FALSE; // ‘SƒOƒ‰ƒt‚ð•s‰ÂŽ‹‚É‚·‚éB } m_bGraphVisible[1] = TRUE; // ƒxƒƒVƒeƒB‚̃Oƒ‰ƒt‚¾‚¯‰ÂŽ‹‚É‚·‚éB } // ƒfƒXƒgƒ‰ƒNƒ^ CPianoRollFrame::~CPianoRollFrame () { m_theFont.DeleteObject (); } //------------------------------------------------------------------------------ // ƒIƒyƒŒ[ƒVƒ‡ƒ“ //------------------------------------------------------------------------------ // ƒhƒLƒ…ƒƒ“ƒg‚̎擾 CSekaijuDoc* CPianoRollFrame::GetDocument () { ASSERT (m_pDummyView); return (CSekaijuDoc*)m_pDummyView->GetDocument (); } // ŽžŠÔ•ûŒü‚̃Y[ƒ€”{—¦Žæ“¾ long CPianoRollFrame::GetTimeZoom () { return m_lTimeZoom; } // ƒL[•ûŒü‚̃Y[ƒ€”{—¦Žæ“¾ long CPianoRollFrame::GetKeyZoom () { return m_lKeyZoom; } // ƒxƒƒVƒeƒB•ûŒü‚̃Y[ƒ€”{—¦Žæ“¾ long CPianoRollFrame::GetVelZoom () { return m_lVelZoom; } // yÀ•W‚ðƒm[ƒgƒL[‚ɕϊ· long CPianoRollFrame::YtoKey (long y) { return 127 - (y / GetKeyZoom ()); } // ƒm[ƒgƒL[‚ðyÀ•W‚ɕϊ· long CPianoRollFrame::KeytoY (long lKey) { return (128 - lKey) * GetKeyZoom (); } // yÀ•W‚ðƒxƒƒVƒeƒB‚ɕϊ· long CPianoRollFrame::YtoVel (long y) { return (128 * m_lVelZoom + 8 - y) / m_lVelZoom; } // yÀ•W‚ðƒsƒbƒ`ƒxƒ“ƒh‚ɕϊ· long CPianoRollFrame::YtoPitchBend (long y) { return (128 * m_lVelZoom + 8 - y) * 128 / m_lVelZoom; } // yÀ•W‚ðƒeƒ“ƒ|[BPM]‚ɕϊ· long CPianoRollFrame::YtoTempoBPM (long y) { return (128 * m_lVelZoom + 8 - y) * 2 / m_lVelZoom; } // ƒxƒƒVƒeƒB‚ðyÀ•W‚ɕϊ· long CPianoRollFrame::VeltoY (long lVel) { return (128 - lVel) * m_lVelZoom + 8; } // ƒsƒbƒ`ƒxƒ“ƒh‚ðyÀ•W‚ɕϊ· long CPianoRollFrame::PitchBendtoY (long lPitchBend) { return (16384 - lPitchBend) * m_lVelZoom / 128 + 8; } // ƒeƒ“ƒ|[BPM]‚ðyÀ•W‚ɕϊ· long CPianoRollFrame::TempoBPMtoY (long lTempoBPM) { return (256 - lTempoBPM) * m_lVelZoom / 2 + 8; } // xÀ•W‚©‚çƒ^ƒCƒ€‚ðŽæ“¾ long CPianoRollFrame::XtoTime (long x) { long lTimeResolution = MIDIData_GetTimeResolution (GetDocument ()->m_pMIDIData); return x * lTimeResolution / 4 / m_lTimeZoom; // ’FƒY[ƒ€”{—¦1”{‚̂Ƃ«4•ª‰¹•„‚Ì’·‚³‚ð4ƒsƒNƒZƒ‹‚Æ’è‹`‚µ‚Ä‚¢‚éB } // ƒ^ƒCƒ€‚ðxÀ•W‚ɕϊ· long CPianoRollFrame::TimetoX (long lTime) { long lTimeResolution = MIDIData_GetTimeResolution (GetDocument ()->m_pMIDIData); return lTime * 4 * m_lTimeZoom / lTimeResolution; // ’FƒY[ƒ€”{—¦1”{‚̂Ƃ«4•ª‰¹•„‚Ì’·‚³‚ð4ƒsƒNƒZƒ‹‚Æ’è‹`‚µ‚Ä‚¢‚éB } // ŽžŠÔ•ûŒü‚̃XƒNƒ[ƒ‹ƒ|ƒWƒVƒ‡ƒ“Žæ“¾ long CPianoRollFrame::GetTimeScrollPos () { return m_lTimeScrollPos; } // ƒL[•ûŒü‚̃XƒNƒ[ƒ‹ƒ|ƒWƒVƒ‡ƒ“Žæ“¾ long CPianoRollFrame::GetKeyScrollPos () { return m_lKeyScrollPos; } // ƒxƒƒVƒeƒB•ûŒü‚̃XƒNƒ[ƒ‹ƒ|ƒWƒVƒ‡ƒ“Žæ“¾ long CPianoRollFrame::GetVelScrollPos () { return m_lVelScrollPos; } // ŽžŠÔ•ûŒü‚̃XƒNƒ[ƒ‹ƒ|ƒWƒVƒ‡ƒ“Ý’è long CPianoRollFrame::SetTimeScrollPos (long lTimeScrollPos) { long lOldTimeScrollPos = m_lTimeScrollPos; m_wndTimeScroll.SetScrollPos (lTimeScrollPos); m_lTimeScrollPos = m_wndTimeScroll.GetScrollPos (); long lDeltaTimeScrollPos = m_lTimeScrollPos - lOldTimeScrollPos; m_pTimeScaleView->ScrollWindow (-lDeltaTimeScrollPos, 0); m_pKeyTimeView->ScrollWindow (-lDeltaTimeScrollPos, 0); m_pVelTimeView->ScrollWindow (-lDeltaTimeScrollPos, 0); m_pTimeScaleView->UpdateWindow (); m_pKeyTimeView->UpdateWindow (); m_pVelTimeView->UpdateWindow (); return m_lTimeScrollPos; } // ƒL[•ûŒü‚̃XƒNƒ[ƒ‹ƒ|ƒWƒVƒ‡ƒ“Ý’è long CPianoRollFrame::SetKeyScrollPos (long lKeyScrollPos) { long lOldKeyScrollPos = m_lKeyScrollPos; m_wndKeyScroll.SetScrollPos (lKeyScrollPos); m_lKeyScrollPos = m_wndKeyScroll.GetScrollPos (); long lDeltaKeyScrollPos = m_lKeyScrollPos - lOldKeyScrollPos; m_pKeyScaleView->ScrollWindow (0, -lDeltaKeyScrollPos); m_pKeyTimeView->ScrollWindow (0, -lDeltaKeyScrollPos); m_pKeyScaleView->UpdateWindow (); m_pKeyTimeView->UpdateWindow (); return m_lKeyScrollPos; } // ƒxƒƒVƒeƒB•ûŒü‚̃XƒNƒ[ƒ‹ƒ|ƒWƒVƒ‡ƒ“Ý’è long CPianoRollFrame::SetVelScrollPos (long lVelScrollPos) { long lOldVelScrollPos = m_lVelScrollPos; m_wndVelScroll.SetScrollPos (lVelScrollPos); m_lVelScrollPos = m_wndVelScroll.GetScrollPos (); long lDeltaVelScrollPos = m_lVelScrollPos - lOldVelScrollPos; m_pVelScaleView->ScrollWindow (0, -lDeltaVelScrollPos); m_pVelTimeView->ScrollWindow (0, -lDeltaVelScrollPos); m_pVelScaleView->UpdateWindow (); m_pVelTimeView->UpdateWindow (); return m_lVelScrollPos; } // •\ަ‚³‚ê‚Ä‚¢‚éƒ^ƒCƒ€‚̍¶’[‚ð‹‚ß‚é long CPianoRollFrame::GetVisibleLeftTime () { long lTimeResolution = MIDIData_GetTimeResolution (GetDocument ()->m_pMIDIData); return m_lTimeScrollPos * lTimeResolution / 4 / m_lTimeZoom; // ’FƒY[ƒ€”{—¦1”{‚̂Ƃ«4•ª‰¹•„‚Ì’·‚³‚ð4ƒsƒNƒZƒ‹‚Æ’è‹`‚µ‚Ä‚¢‚éB } // •\ަ‚³‚ê‚Ä‚¢‚éƒ^ƒCƒ€‚̉E’[‚ð‹‚ß‚é long CPianoRollFrame::GetVisibleRightTime () { CRect rcClient; m_pTimeScaleView->GetClientRect (&rcClient); long lTimeResolution = MIDIData_GetTimeResolution (GetDocument ()->m_pMIDIData); return (m_lTimeScrollPos + rcClient.Width ()) * lTimeResolution / 4 / m_lTimeZoom; // ’FƒY[ƒ€”{—¦1”{‚̂Ƃ«4•ª‰¹•„‚Ì’·‚³‚ð4ƒsƒNƒZƒ‹‚Æ’è‹`‚µ‚Ä‚¢‚éB } // •\ަ‚³‚ê‚Ä‚¢‚éƒL[‚̏ãŒÀ‚ðŒvŽZ long CPianoRollFrame::GetVisibleTopKey () { return 127 - (m_lKeyScrollPos / m_lKeyZoom); } // •\ަ‚³‚ê‚Ä‚¢‚éƒL[‚̉ºŒÀ‚ðŒvŽZ long CPianoRollFrame::GetVisibleBottomKey () { CRect rcClient; m_pKeyScaleView->GetClientRect (&rcClient); return 127 - (m_lKeyScrollPos + rcClient.Height ()) / m_lKeyZoom; } // •\ަ‚³‚ê‚Ä‚¢‚éƒxƒƒVƒeƒB‚̏ãŒÀ‚ðŒvŽZ long CPianoRollFrame::GetVisibleTopVel() { return 127 - (m_lVelScrollPos / m_lVelZoom); } // •\ަ‚³‚ê‚Ä‚¢‚éƒxƒƒVƒeƒB‚̉ºŒÀ‚ðŒvŽZ long CPianoRollFrame::GetVisibleBottomVel () { CRect rcClient; m_pVelScaleView->GetClientRect (&rcClient); return 127 - (m_lVelScrollPos + rcClient.Height ()) / m_lVelZoom; } // ƒXƒvƒŠƒbƒ^[ƒLƒƒƒvƒ^[‚Ì•`‰æ void CPianoRollFrame::DrawSplitterCaptor (CDC* pDC, CPoint pt) { CRect rcClient; GetClientRect (&rcClient); CPen pen; CPen* pOldPen; pen.CreatePen (PS_SOLID, 4, ::GetSysColor(COLOR_BTNSHADOW)); pDC->SetROP2 (R2_XORPEN); pOldPen = pDC->SelectObject (&pen); if (m_bSplitterMovingH) { pDC->MoveTo (0, pt.y); pDC->LineTo (rcClient.Width (), pt.y); } if (m_bSplitterMovingV) { pDC->MoveTo (pt.x, 0); pDC->LineTo (pt.x, rcClient.Height ()); } pDC->SelectObject (pOldPen); } // Œ»Ý‚̃gƒ‰ƒbƒN‚̃Cƒ“ƒfƒbƒNƒX‚ðŽæ“¾ long CPianoRollFrame::GetCurTrackIndex () { return m_wndTrackList.GetCurSel (); } // Œ»Ý‚̃`ƒƒƒ“ƒlƒ‹‚ðŽæ“¾ long CPianoRollFrame::GetCurChannel () { return m_wndChannelCombo.GetCurSel (); } // Œ»Ý‚̃Xƒiƒbƒv[ƒeƒBƒbƒN]‚ðŽæ“¾ long CPianoRollFrame::GetCurSnap () { CString strText; m_wndSnapCombo.GetWindowText (strText); return _ttol (strText); } // Œ»Ý‚̃xƒƒVƒeƒB‚ðŽæ“¾ long CPianoRollFrame::GetCurVelocity () { CString strText; m_wndVelocityCombo.GetWindowText (strText); return _ttol (strText); } // Œ»Ý‚Ì(‰¹•„‚Ì)’·‚³[ƒeƒBƒbƒN]‚ðŽæ“¾ long CPianoRollFrame::GetCurDuration () { CString strText; m_wndDurationCombo.GetWindowText (strText); return _ttol (strText); } // Œ»Ý‚̃Oƒ‰ƒt‚ÌŽí—Þ‚ðŽæ“¾ long CPianoRollFrame::GetCurGraphKind () { return m_wndGraphKindList.GetCurSel (); } // Œ»Ý‚̃Oƒ‰ƒt‚̃Xƒiƒbƒv[ƒeƒBƒbƒN]‚ðŽæ“¾ long CPianoRollFrame::GetCurGraphSnap () { CString strText; m_wndGraphSnapCombo.GetWindowText (strText); return _ttol (strText); } // Œ»Ý‚̃gƒ‰ƒbƒN‚̃Cƒ“ƒfƒbƒNƒX‚ðÝ’è BOOL CPianoRollFrame::SetCurTrackIndex (long lCurTrackIndex) { ASSERT (0 <= lCurTrackIndex && lCurTrackIndex < MAXMIDITRACKNUM); CSekaijuDoc* pSekaijuDoc = GetDocument (); m_wndTrackCombo.SetCurSel (lCurTrackIndex); m_wndTrackList.SetCurSel (lCurTrackIndex); //m_pCurTrack = pSekaijuDoc->GetTrack (lCurTrackIndex); if (m_bOnlyCurTrack) { long lCount = m_wndTrackList.GetCount (); for (long i = 0; i < lCount; i++) { m_wndTrackList.SetCheck (i, (i == lCurTrackIndex ? 1 : 0)); } m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); } return TRUE; } // Œ»Ý‚̃`ƒƒƒ“ƒlƒ‹‚ðÝ’è BOOL CPianoRollFrame::SetCurChannel (long lCurChannel) { ASSERT (0 <= lCurChannel && lCurChannel < 16); m_wndChannelCombo.SetCurSel (lCurChannel); return TRUE; } // Œ»Ý‚̃Xƒiƒbƒv[ƒeƒBƒbƒN]‚ðÝ’è BOOL CPianoRollFrame::SetCurSnap (long lCurSnap) { ASSERT (1 <= lCurSnap); CString strText; strText.Format (_T("%d"), lCurSnap); m_wndSnapCombo.SetWindowText (strText); return TRUE; } // Œ»Ý‚̃xƒƒVƒeƒB‚ðÝ’è BOOL CPianoRollFrame::SetCurVelocity (long lCurVelocity) { ASSERT (0 <= lCurVelocity && lCurVelocity <= 127); CString strText; strText.Format (_T("%d"), lCurVelocity); m_wndVelocityCombo.SetWindowText (strText); return TRUE; } // Œ»Ý‚Ì(‰¹•„‚Ì)’·‚³[ƒeƒBƒbƒN]‚ðÝ’è BOOL CPianoRollFrame::SetCurDuration (long lCurDuration) { ASSERT (0 <= lCurDuration); CString strText; strText.Format (_T("%d"), lCurDuration); m_wndDurationCombo.SetWindowText (strText); return TRUE; } // Œ»Ý‚̃Oƒ‰ƒt‚ÌŽí—Þ‚ðÝ’è BOOL CPianoRollFrame::SetCurGraphKind (long lCurGraphKind) { ASSERT (0 <= lCurGraphKind && lCurGraphKind < 256); m_wndGraphKindCombo.SetCurSel (lCurGraphKind); m_wndGraphKindList.SetCurSel (lCurGraphKind); if (m_bOnlyCurGraph) { long lCount = m_wndGraphKindList.GetCount (); for (long i = 0; i < lCount; i++) { m_wndGraphKindList.SetCheck (i, (i == lCurGraphKind ? 1 : 0)); } m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); m_pVelScaleView->Invalidate (); } return TRUE; } // Œ»Ý‚̃Oƒ‰ƒtƒXƒiƒbƒv[ƒeƒBƒbƒN]‚ðÝ’è BOOL CPianoRollFrame::SetCurGraphSnap (long lCurSnap) { ASSERT (1 <= lCurSnap); CString strText; strText.Format (_T("%d"), lCurSnap); m_wndGraphSnapCombo.SetWindowText (strText); return TRUE; } // Žw’èƒCƒ“ƒfƒbƒNƒX‚̃gƒ‰ƒbƒN‚ª•\ަó‘Ô‚©’²‚ׂé BOOL CPianoRollFrame::IsTrackVisible (long lTrackIndex) { // (1)Œ»Ý‚̃gƒ‰ƒbƒN‚̂ݕ\ަ‚ªON‚̂Ƃ«‚́AŒ»Ý‚̃gƒ‰ƒbƒN‚݂̂ªVisibleA‘¼‚ÍUnVisibleB // (2)‚·‚ׂẴgƒ‰ƒbƒN‚ð•\ަ‚ªON‚̂Ƃ«‚́A‘S‚Ẵgƒ‰ƒbƒN‚ªVisibleB // (3)‚»‚Ì‘¼‚̏ꍇ(’ʏ펞)‚́Am_bTrackVisible[MAXMIDITRACKNUM]‚Ì’l‚ɏ]‚¤B ASSERT (0 <= lTrackIndex && lTrackIndex < MAXMIDITRACKNUM); if (m_bOnlyCurTrack == TRUE && GetCurTrackIndex () == lTrackIndex || m_bShowAllTrack == TRUE || m_bShowAllTrack == FALSE && m_bOnlyCurTrack == FALSE && m_bTrackVisible[lTrackIndex] == TRUE) { return TRUE; } return FALSE; } // Žw’èƒCƒ“ƒfƒbƒNƒX‚̃gƒ‰ƒbƒN‚ð•\ަó‘Ô‚É‚·‚é BOOL CPianoRollFrame::SetTrackVisible (long lTrackIndex) { // (1)Œ»Ý‚̃gƒ‰ƒbƒN‚̂ݕ\ަ‚ªON‚̂Ƃ«‚́AŒ»Ý‚̃gƒ‰ƒbƒN‚ðŽw’èƒgƒ‰ƒbƒN‚ɕύX‚·‚é // (2)‚·‚ׂẴgƒ‰ƒbƒN‚ð•\ަ‚ªON‚̂Ƃ«‚́A‰½‚à‚µ‚È‚¢B // (3)‚»‚Ì‘¼‚̏ꍇ(’ʏ펞)‚́Am_bTrackVisible[lTrackIndex]‚ðƒ`ƒFƒbƒNE‰ÂŽ‹‰»‚·‚éB ASSERT (0 <= lTrackIndex && lTrackIndex < MAXMIDITRACKNUM); if (m_bOnlyCurTrack == TRUE) { m_wndTrackCombo.SetCurSel (lTrackIndex); m_wndTrackList.SetCurSel (lTrackIndex); } else if (m_bShowAllTrack == TRUE) { ; } else { m_wndTrackList.SetCheck (lTrackIndex, TRUE); m_bTrackVisible[lTrackIndex] = TRUE; } return TRUE; } // Žw’èŽí—ނ̃Oƒ‰ƒt‚ª•\ަó‘Ô‚©’²‚ׂé BOOL CPianoRollFrame::IsGraphVisible (long lGraphKind) { // (1)Œ»Ý‚̃Oƒ‰ƒt‚̂ݕ\ަ‚ªON‚̂Ƃ«‚́AŒ»Ý‚̃Oƒ‰ƒt‚݂̂ªVisibleA‘¼‚ÍUnVisibleB // (2)‚·‚ׂẴOƒ‰ƒt‚ð•\ަ‚ªON‚̂Ƃ«‚́A‘S‚ẴOƒ‰ƒt‚ªVisibleB // (3)‚»‚Ì‘¼‚̏ꍇ(’ʏ펞)‚́Am_bGraphVisible[MAXMIDITRACKNUM]‚Ì’l‚ɏ]‚¤B ASSERT (0 <= lGraphKind && lGraphKind < 256); if (m_bOnlyCurGraph == TRUE && GetCurGraphKind () == lGraphKind || m_bShowAllGraph == TRUE || m_bShowAllGraph == FALSE && m_bOnlyCurGraph == FALSE && m_bGraphVisible[lGraphKind] == TRUE) { return TRUE; } return FALSE; } // Žw’èŽí—ނ̃Oƒ‰ƒt‚ð•\ަó‘Ô‚É‚·‚é BOOL CPianoRollFrame::SetGraphVisible (long lGraphKind) { // (1)Œ»Ý‚̃Oƒ‰ƒt‚̂ݕ\ަ‚ªON‚̂Ƃ«‚́AŒ»Ý‚̃gƒ‰ƒbƒN‚ðŽw’èƒgƒ‰ƒbƒN‚ɕύX‚·‚é // (2)‚·‚ׂẴOƒ‰ƒt‚ð•\ަ‚ªON‚̂Ƃ«‚́A‰½‚à‚µ‚È‚¢B // (3)‚»‚Ì‘¼‚̏ꍇ(’ʏ펞)‚́Am_bGraphKindVisible[lGraphKind]‚ðƒ`ƒFƒbƒNE‰ÂŽ‹‰»‚·‚éB ASSERT (0 <= lGraphKind && lGraphKind < m_wndGraphKindList.GetCount ()); if (m_bOnlyCurGraph == TRUE) { m_wndGraphKindCombo.SetCurSel (lGraphKind); m_wndGraphKindList.SetCurSel (lGraphKind); } else if (m_bShowAllGraph == TRUE) { ; } else { m_wndGraphKindList.SetCheck (lGraphKind, TRUE); m_bGraphVisible[lGraphKind] = TRUE; } return TRUE; } // ƒgƒ‰ƒbƒNƒRƒ“ƒ{‚̍XV BOOL CPianoRollFrame::UpdateTrackCombo () { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); CSekaijuDoc* pSekaijuDoc = GetDocument (); //pSekaijuDoc->m_theCriticalSection.Lock (); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; MIDITrack* pMIDITrack = NULL; BOOL bTrackZeroOrigin = pSekaijuApp->m_theGeneralOption.m_bTrackZeroOrigin; // ‹Œó‘Ԃ̕ێ static MIDITrack* pOldMIDITrack[MAXMIDITRACKNUM]; BOOL bOldTrackVisible[MAXMIDITRACKNUM]; memcpy (bOldTrackVisible, m_bTrackVisible, sizeof (BOOL) * MAXMIDITRACKNUM); long lOldCurSel = m_wndTrackCombo.GetCurSel (); long lOldCount = m_wndTrackCombo.GetCount (); MIDITrack* pOldCurTrack = NULL; if (0 <= lOldCurSel && lOldCurSel < __min (lOldCount, MAXMIDITRACKNUM)) { pOldCurTrack = pOldMIDITrack[lOldCurSel]; } // ƒRƒ“ƒ{‚̏‰Šú‰» //m_wndTrackCombo.ResetContent (); m_wndTrackCombo.RemoveAllItem (); // ƒRƒ“ƒ{‚ɍ€–Ú‚ð’ljÁ long i = 0; long j = 0; TCHAR szTrackName1[1024]; TCHAR szTrackName2[1024]; CString strText; forEachTrack (pMIDIData, pMIDITrack) { if (i >= MAXMIDITRACKNUM) { break; } memset (szTrackName1, 0, sizeof (szTrackName1)); memset (szTrackName2, 0, sizeof (szTrackName2)); MIDITrack_GetName (pMIDITrack, szTrackName1, sizeof (szTrackName1) - 1); codestr2str (szTrackName1, TCSLEN (szTrackName1), szTrackName2, TSIZEOF (szTrackName2) - 1); strText.Format (_T("%d-%s"), i + (bTrackZeroOrigin ? 0 : 1), szTrackName2); long lForeColor = MIDITrack_GetForeColor (pMIDITrack); long lBackColor = ::GetSysColor (COLOR_WINDOW); m_wndTrackCombo.AddItem (strText, lForeColor, lBackColor); // Œ»Ý‚̃gƒ‰ƒbƒN‚Å‚ ‚éê‡‘I‘ð if (pMIDITrack == pOldCurTrack) { m_wndTrackCombo.SetCurSel (i); } i++; } // Œ»Ý‘I‘ð‚µ‚Ä‚¢‚é‚à‚Ì‚ª‚È‚¢ê‡‚Í‹­§‘I‘ð long lNewCount = m_wndTrackCombo.GetCount (); long lNewCurSel = m_wndTrackCombo.GetCurSel (); if (m_wndTrackCombo.GetCurSel () == CB_ERR) { if (0 <= lOldCurSel && lOldCurSel < lNewCount) { m_wndTrackCombo.SetCurSel (lOldCurSel); } else if (lNewCount >= 2) { m_wndTrackCombo.SetCurSel (1); } else { m_wndTrackCombo.SetCurSel (0); } } // ŽŸ‰ñ‚̃Aƒbƒvƒf[ƒgŒÄ‚яo‚µ‚É”õ‚¦‚ÄŒ»ó‚ð•ÛŽ‚·‚éB i = 0; memset (pOldMIDITrack, 0, sizeof (MIDITrack*) * MAXMIDITRACKNUM); forEachTrack (pMIDIData, pMIDITrack) { if (i >= MAXMIDITRACKNUM) { break; } pOldMIDITrack[i] = pMIDITrack; i++; } //pSekaijuDoc->m_theCriticalSection.Unlock (); return TRUE; } // ƒOƒ‰ƒt‚ÌŽí—ÞƒRƒ“ƒ{‚̍XV BOOL CPianoRollFrame::UpdateGraphKindCombo () { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); CString strText; m_wndGraphKindCombo.ResetContent (); VERIFY (strText.LoadString (IDS_TEMPO)); m_wndGraphKindCombo.AddString (strText); VERIFY (strText.LoadString (IDS_VELOCITY)); m_wndGraphKindCombo.AddString (strText); VERIFY (strText.LoadString (IDS_CHANNELAFTERTOUCH)); m_wndGraphKindCombo.AddString (strText); VERIFY (strText.LoadString (IDS_PITCHBEND)); m_wndGraphKindCombo.AddString (strText); TCHAR szName[1024]; long lTrackIndex = GetCurTrackIndex (); MIDITrack* pMIDITrack = pSekaijuDoc->GetTrack (lTrackIndex); long lPortNumber = MIDITrack_GetOutputPort (pMIDITrack); MIDIInstrumentDefinition* pMIDIInstDefNorm = NULL; MIDIControllerNameTable* pMIDIControllerNameTable = NULL; if (0 <= lPortNumber && lPortNumber < MAXMIDIOUTDEVICENUM) { pMIDIInstDefNorm = ((CSekaijuApp*)AfxGetApp())->m_pMIDIInstDefNorm[lPortNumber]; if (pMIDIInstDefNorm) { pMIDIControllerNameTable = MIDIInstrumentDefinition_GetControllerNameTable (pMIDIInstDefNorm); } } for (long i = 0; i < 128; i++) { memset (szName, 0, sizeof (szName)); if (pMIDIControllerNameTable) { MIDIControllerNameTable_GetName (pMIDIControllerNameTable, i, szName, TSIZEOF (szName) - 1); } CString strFormat; VERIFY (strFormat.LoadString (IDS_CC_D_S)); strText.Format (strFormat, i, szName); m_wndGraphKindCombo.AddString (strText); } pSekaijuDoc->m_theCriticalSection.Unlock (); return TRUE; } // ƒgƒ‰ƒbƒNƒŠƒXƒgƒ{ƒbƒNƒX‚̍XV BOOL CPianoRollFrame::UpdateTrackList () { CSekaijuDoc* pSekaijuDoc = GetDocument (); CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); //pSekaijuDoc->m_theCriticalSection.Lock (); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; MIDITrack* pMIDITrack = NULL; BOOL bTrackZeroOrigin = pSekaijuApp->m_theGeneralOption.m_bTrackZeroOrigin; // ‹Œó‘Ԃ̕ێ static MIDITrack* pOldMIDITrack[MAXMIDITRACKNUM]; BOOL bOldTrackVisible[MAXMIDITRACKNUM]; memcpy (bOldTrackVisible, m_bTrackVisible, sizeof (BOOL) * MAXMIDITRACKNUM); long lOldCurSel = m_wndTrackList.GetCurSel (); long lOldCount = m_wndTrackList.GetCount (); MIDITrack* pOldCurTrack = NULL; if (0 <= lOldCurSel && lOldCurSel < __min (lOldCount, MAXMIDITRACKNUM)) { pOldCurTrack = pOldMIDITrack[lOldCurSel]; } // ƒŠƒXƒg‚̏‰Šú‰» //m_wndTrackList.ResetContent (); m_wndTrackList.RemoveAllItem (); // ƒŠƒXƒg‚̍XV long i = 0; long j = 0; TCHAR szTrackName1[1024]; TCHAR szTrackName2[1024]; CString strText; forEachTrack (pMIDIData, pMIDITrack) { if (i >= MAXMIDITRACKNUM) { break; } memset (szTrackName1, 0, sizeof (szTrackName1)); memset (szTrackName2, 0, sizeof (szTrackName2)); MIDITrack_GetName (pMIDITrack, szTrackName1, sizeof (szTrackName1) - 1); codestr2str (szTrackName1, TCSLEN (szTrackName1), szTrackName2, TSIZEOF (szTrackName2) - 1); strText.Format (_T("%d-%s"), i + (bTrackZeroOrigin ? 0 : 1), szTrackName2); long lForeColor = MIDITrack_GetForeColor (pMIDITrack); long lBackColor = ::GetSysColor (COLOR_WINDOW); m_wndTrackList.AddItem (strText, lForeColor, lBackColor); // ƒ`ƒFƒbƒNó‘ԕϐ”‚̍XV m_bTrackVisible[i] = 1; for (j = 0; j < MAXMIDITRACKNUM; j++) { if (pOldMIDITrack[j] == NULL) { break; } if (pOldMIDITrack[j] == pMIDITrack) { m_bTrackVisible[i] = bOldTrackVisible[j]; break; } } // Œ»Ý‚̃gƒ‰ƒbƒN‚Å‚ ‚éê‡‘I‘ð if (pMIDITrack == pOldCurTrack) { m_wndTrackList.SetCurSel (i); } i++; } // Œ»Ý‘I‘ð‚µ‚Ä‚¢‚é‚à‚Ì‚ª‚È‚¢ê‡‚Í‹­§‘I‘ð long lNewCount = m_wndTrackList.GetCount (); long lNewCurSel = m_wndTrackList.GetCurSel (); if (m_wndTrackList.GetCurSel () == LB_ERR) { if (0 <= lOldCurSel && lOldCurSel < lNewCount) { m_wndTrackList.SetCurSel (lOldCurSel); } else if (lNewCount >= 2) { m_wndTrackList.SetCurSel (1); } else { m_wndTrackList.SetCurSel (0); } lNewCurSel = m_wndTrackList.GetCurSel (); } // ƒ`ƒFƒbƒNƒ{ƒbƒNƒX‚ÌŠ®‘SXV if (m_bShowAllTrack) { for (i = 0; i < lNewCount; i++) { m_wndTrackList.SetCheck (i, 1); } } else if (m_bOnlyCurTrack) { for (i = 0; i < lNewCount; i++) { m_wndTrackList.SetCheck (i, 0); } if (0 <= lNewCurSel && lNewCurSel < lNewCount) { m_wndTrackList.SetCheck (lNewCurSel, 1); } } else { for (i = 0; i < lNewCount; i++) { m_wndTrackList.SetCheck (i, m_bTrackVisible[i]); } } // ŽŸ‰ñ‚̃Aƒbƒvƒf[ƒgŒÄ‚яo‚µ‚É”õ‚¦‚ÄŒ»ó‚ð•ÛŽ‚·‚éB i = 0; memset (pOldMIDITrack, 0, sizeof (MIDITrack*) * MAXMIDITRACKNUM); forEachTrack (pMIDIData, pMIDITrack) { if (i >= MAXMIDITRACKNUM) { break; } pOldMIDITrack[i] = pMIDITrack; i++; } //pSekaijuDoc->m_theCriticalSection.Unlock (); return TRUE; } // ƒOƒ‰ƒt‚ÌŽí—ÞƒŠƒXƒg‚̍XV BOOL CPianoRollFrame::UpdateGraphKindList () { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); CString strText; m_wndGraphKindList.ResetContent (); VERIFY (strText.LoadString (IDS_TEMPO)); m_wndGraphKindList.AddString (strText); VERIFY (strText.LoadString (IDS_VELOCITY)); m_wndGraphKindList.AddString (strText); VERIFY (strText.LoadString (IDS_CHANNELAFTERTOUCH)); m_wndGraphKindList.AddString (strText); VERIFY (strText.LoadString (IDS_PITCHBEND)); m_wndGraphKindList.AddString (strText); TCHAR szName[1024]; long lTrackIndex = GetCurTrackIndex (); MIDITrack* pMIDITrack = pSekaijuDoc->GetTrack (lTrackIndex); long lPortNumber = MIDITrack_GetOutputPort (pMIDITrack); MIDIInstrumentDefinition* pMIDIInstDefNorm = NULL; MIDIControllerNameTable* pMIDIControllerNameTable = NULL; if (0 <= lPortNumber && lPortNumber < MAXMIDIOUTDEVICENUM) { pMIDIInstDefNorm = ((CSekaijuApp*)AfxGetApp())->m_pMIDIInstDefNorm[lPortNumber]; if (pMIDIInstDefNorm) { pMIDIControllerNameTable = MIDIInstrumentDefinition_GetControllerNameTable (pMIDIInstDefNorm); } } for (long i = 0; i < 128; i++) { memset (szName, 0, sizeof (szName)); if (pMIDIControllerNameTable) { MIDIControllerNameTable_GetName (pMIDIControllerNameTable, i, szName, TSIZEOF (szName) - 1); } CString strFormat; VERIFY (strFormat.LoadString (IDS_CC_D_S)); strText.Format (strFormat, i, szName); m_wndGraphKindList.AddString (strText); } pSekaijuDoc->m_theCriticalSection.Unlock (); return TRUE; } // ƒXƒiƒbƒvƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̍XV BOOL CPianoRollFrame::UpdateSnapCombo () { CString strText; CSekaijuDoc* pSekaijuDoc = (CSekaijuDoc*)GetDocument (); long lTimeResolution = MIDIData_GetTimeResolution (pSekaijuDoc->m_pMIDIData); long lCurSel = m_wndSnapCombo.GetCurSel (); m_wndSnapCombo.ResetContent (); // ƒXƒiƒbƒvƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̏[–ž CString strFormat; VERIFY (strFormat.LoadString (IDS_D_4DIVNOTE)); // %d-4•ª‰¹•„ strText.Format (strFormat, lTimeResolution * 1); m_wndSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_8DIVNOTE)); // %d-8•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 2); m_wndSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_12DIVNOTE)); // %d-3˜A8•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 3); m_wndSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_16DIVNOTE)); // %d-16•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 4); m_wndSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_24DIVNOTE)); // %d-3˜A16•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 6); m_wndSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_32DIVNOTE)); // %d-32•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 8); m_wndSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_48DIVNOTE)); // %d-3˜A32•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 12); m_wndSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_FREE)); // %d-Ž©—R strText.Format (strFormat, 1); m_wndSnapCombo.AddString (strText); // ƒJƒŒƒ“ƒgƒZƒ‹Ý’è if (lCurSel >= 0) { m_wndSnapCombo.SetCurSel (lCurSel); } return TRUE; } // ƒxƒƒVƒeƒBƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̍XV BOOL CPianoRollFrame::UpdateVelocityCombo () { long i; CString strText; long lCurSel = m_wndVelocityCombo.GetCurSel (); m_wndVelocityCombo.ResetContent (); // ƒxƒƒVƒeƒBƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̏[–ž for (i = 127; i >= 1; i--) { if (i == 127 || (i % 5) == 0) { strText.Format (_T("%d"), i); m_wndVelocityCombo.AddString (strText); } } // ƒJƒŒƒ“ƒgƒZƒ‹Ý’è if (lCurSel >= 0) { m_wndVelocityCombo.SetCurSel (lCurSel); } return TRUE; } // ’·‚³ƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̍XV BOOL CPianoRollFrame::UpdateDurationCombo () { CString strText; CSekaijuDoc* pSekaijuDoc = (CSekaijuDoc*)GetDocument (); long lTimeResolution = MIDIData_GetTimeResolution (pSekaijuDoc->m_pMIDIData); //long lCurSel = m_wndDurationCombo.GetCurSel (); // 20100328”pŽ~ CString strCurText; m_wndDurationCombo.GetWindowText (strCurText); // 20100328’ljÁ long i = 0; long lCurSel = -1; // 20100328’ljÁ for (i = 0; i < m_wndDurationCombo.GetCount (); i++) { // 20100328’ljÁ CString strLBText; // 20100328’ljÁ m_wndDurationCombo.GetLBText (i, strLBText); // 20100328’ljÁ if (strLBText == strCurText) { // 20100328’ljÁ lCurSel = i; // 20100328’ljÁ break; // 20100328’ljÁ } // 20100328’ljÁ } // 20100328’ljÁ m_wndDurationCombo.ResetContent (); // ’·‚³ƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̏[–ž strText.Format (_T("%d"), lTimeResolution * 4); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution * 3); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution * 2); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution * 1); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution / 2); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution / 3); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution / 4); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution / 6); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution / 8); m_wndDurationCombo.AddString (strText); strText.Format (_T("%d"), lTimeResolution / 12); m_wndDurationCombo.AddString (strText); // ƒJƒŒƒ“ƒgƒZƒ‹‚̐ݒè if (lCurSel >= 0) { m_wndDurationCombo.SetCurSel (lCurSel); } else { // 20100328’ljÁ m_wndDurationCombo.SetWindowText (strCurText); // 20100328’ljÁ } return TRUE; } // ƒOƒ‰ƒtƒXƒiƒbƒvƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̍XV BOOL CPianoRollFrame::UpdateGraphSnapCombo () { CString strText; CSekaijuDoc* pSekaijuDoc = (CSekaijuDoc*)GetDocument (); long lTimeResolution = MIDIData_GetTimeResolution (pSekaijuDoc->m_pMIDIData); long lCurSel = m_wndGraphSnapCombo.GetCurSel (); m_wndGraphSnapCombo.ResetContent (); // ƒXƒiƒbƒvƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̏[–ž CString strFormat; VERIFY (strFormat.LoadString (IDS_D_4DIVNOTE)); // %d-4•ª‰¹•„ strText.Format (strFormat, lTimeResolution * 1); m_wndGraphSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_8DIVNOTE)); // %d-8•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 2); m_wndGraphSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_12DIVNOTE)); // %d-3˜A8•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 3); m_wndGraphSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_16DIVNOTE)); // %d-16•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 4); m_wndGraphSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_24DIVNOTE)); // %d-3˜A16•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 6); m_wndGraphSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_32DIVNOTE)); // %d-32•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 8); m_wndGraphSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_48DIVNOTE)); // %d-3˜A32•ª‰¹•„ strText.Format (strFormat, lTimeResolution / 12); m_wndGraphSnapCombo.AddString (strText); VERIFY (strFormat.LoadString (IDS_D_FREE)); // %d-Ž©—R strText.Format (strFormat, 1); m_wndGraphSnapCombo.AddString (strText); // ƒJƒŒƒ“ƒgƒZƒ‹Ý’è if (lCurSel >= 0) { m_wndGraphSnapCombo.SetCurSel (lCurSel); } return TRUE; } // ƒL[ƒXƒNƒ[ƒ‹ƒo[(c)‚̃fƒUƒCƒ“Ý’è void CPianoRollFrame::RecalcKeyScrollInfo () { SCROLLINFO si; si.fMask = SIF_RANGE | SIF_PAGE; si.nMin = 0; si.nMax = 128 * m_lKeyZoom; si.nPage = m_lKeyHeight; m_wndKeyScroll.SetScrollInfo (&si, TRUE); m_lKeyScrollPos = m_wndKeyScroll.GetScrollPos (); } // ƒ”ƒFƒƒVƒeƒBƒXƒNƒ[ƒ‹ƒo[(c)‚̃fƒUƒCƒ“Ý’è void CPianoRollFrame::RecalcVelScrollInfo () { SCROLLINFO si; si.fMask = SIF_RANGE | SIF_PAGE; si.nMin = 0; si.nMax = PIANOROLLFRAME_VELHEIGHT * m_lVelZoom + 16; si.nPage = m_lVelHeight; m_wndVelScroll.SetScrollInfo (&si, TRUE); m_lVelScrollPos = m_wndVelScroll.GetScrollPos (); } // ƒ^ƒCƒ€ƒXƒNƒ[ƒ‹ƒo[(‰¡)‚̃fƒUƒCƒ“Ý’è void CPianoRollFrame::RecalcTimeScrollInfo () { CSekaijuDoc* pSekaijuDoc = GetDocument (); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; long lTimeResolution = 120; long lEndTime = 0; if (pMIDIData) { lTimeResolution = MIDIData_GetTimeResolution (pMIDIData); lEndTime = MIDIData_GetEndTime (pMIDIData); } long lFeedTime = lTimeResolution * 4 * 120; SCROLLINFO si; si.fMask = SIF_RANGE | SIF_PAGE; si.nMin = 0; si.nMax = (lEndTime + lFeedTime) * m_lTimeZoom * 4 / lTimeResolution; si.nPage = m_lTimeWidth; m_wndTimeScroll.SetScrollInfo (&si, TRUE); m_lTimeScrollPos = m_wndTimeScroll.GetScrollPos (); // ’FƒY[ƒ€”{—¦1”{‚̂Ƃ«4•ª‰¹•„‚Ì’·‚³‚ð4ƒsƒNƒZƒ‹‚Æ’è‹`‚µ‚Ä‚¢‚éB } //------------------------------------------------------------------------------ // ƒI[ƒo[ƒ‰ƒCƒh //------------------------------------------------------------------------------ // ƒEƒBƒ“ƒhƒE¶¬’¼‘O‚̍\‘¢‘̐ݒè BOOL CPianoRollFrame::PreCreateWindow (CREATESTRUCT& cs) { return (CWnd::PreCreateWindow(cs)); } // ƒEƒBƒ“ƒhƒEƒ^ƒCƒgƒ‹‚ÌŽ©“®Ý’è(CMDIChildWnd::OnUpdateFrameTitle‚̃I[ƒo[ƒ‰ƒCƒh) void CPianoRollFrame::OnUpdateFrameTitle (BOOL bAddToTitle) { // update our parent window first GetMDIFrame()->OnUpdateFrameTitle (bAddToTitle); if ((GetStyle() & FWS_ADDTOTITLE) == 0) { return; // leave child window alone! } CDocument* pDocument = GetActiveDocument(); if (bAddToTitle && pDocument != NULL) { CString strPianoRoll; strPianoRoll.LoadString (IDS_PIANOROLL); CString strTitle; if (m_nWindow > 0) { strTitle.Format (_T("%s:%d(%s)"), pDocument->GetTitle (), m_nWindow, strPianoRoll); } else { strTitle.Format (_T("%s(%s)"), pDocument->GetTitle (), strPianoRoll); } this->SetWindowText (strTitle); } } // Ä”z’u—pŠÖ”(CFrameWnd::RecalcLayout‚̃I[ƒo[ƒ‰ƒCƒh) void CPianoRollFrame::RecalcLayout (BOOL bNotify) { CRect rcClient; GetClientRect (&rcClient); // Šî–{ƒNƒ‰ƒX‚̊֐”‚ðˆ— CFrameWnd::RecalcLayout (bNotify); // ƒAƒCƒRƒ“‰»Žž‚ɂ͊eƒRƒ“ƒgƒ[ƒ‹‚̃TƒCƒY‚ðÄŒvŽZ‚µ‚È‚¢B if (rcClient.Width () == 0 || rcClient.Height () == 0) { return; } // ƒc[ƒ‹ƒo[1‚̍‚‚³Žæ“¾ CRect rcToolBar1; m_wndToolBar1.GetWindowRect (&rcToolBar1); m_lToolBar1Height = rcToolBar1.Height (); // ‚‚³•ûŒü‚̈ʒuŒvŽZ if (rcClient.Height () - m_lToolBar1Height < PIANOROLLFRAME_SCALEHEIGHT + m_lHScrollBarHeight + PIANOROLLFRAME_BORDERHEIGHT * 4 + PIANOROLLFRAME_SPLITTERHEIGHT) { m_lScaleHeight = rcClient.Height () - m_lHScrollBarHeight - PIANOROLLFRAME_BORDERHEIGHT * 4 - PIANOROLLFRAME_SPLITTERHEIGHT; m_lKeyHeight = 0; m_lVelHeight = 0; } else if (rcClient.Height () - m_lToolBar1Height < m_lVelHeight + PIANOROLLFRAME_SCALEHEIGHT + m_lHScrollBarHeight + PIANOROLLFRAME_BORDERHEIGHT * 4 + PIANOROLLFRAME_SPLITTERHEIGHT) { m_lScaleHeight = PIANOROLLFRAME_SCALEHEIGHT; m_lKeyHeight = 0; m_lVelHeight = rcClient.Height () - m_lToolBar1Height - m_lScaleHeight - m_lHScrollBarHeight - PIANOROLLFRAME_BORDERHEIGHT * 4 - PIANOROLLFRAME_SPLITTERHEIGHT; } else { m_lScaleHeight = PIANOROLLFRAME_SCALEHEIGHT; m_lKeyHeight = rcClient.Height () - m_lToolBar1Height - m_lScaleHeight - m_lVelHeight - m_lHScrollBarHeight - PIANOROLLFRAME_BORDERHEIGHT * 4 - PIANOROLLFRAME_SPLITTERHEIGHT; m_lVelHeight = m_lVelHeight; } //m_lVelHeight = __min (m_lVelHeight, 128); // ••ûŒü‚̈ʒuŒvŽZ if (rcClient.Width () < PIANOROLLFRAME_SCALEWIDTH + m_lVScrollBarWidth + PIANOROLLFRAME_BORDERWIDTH * 4) { m_lScaleWidth = rcClient.Width () - m_lVScrollBarWidth - PIANOROLLFRAME_BORDERWIDTH * 4; m_lTimeWidth = 0; m_lTrackListWidth = 0; } else if (rcClient.Width () < PIANOROLLFRAME_SCALEWIDTH + m_lVScrollBarWidth + PIANOROLLFRAME_BORDERWIDTH * 4 + PIANOROLLFRAME_SPLITTERWIDTH + m_lTrackListWidth) { //m_lScaleWidth = rcClient.Width () - // m_lVScrollBarWidth - PIANOROLLFRAME_BORDERWIDTH * 2; m_lScaleWidth = PIANOROLLFRAME_SCALEWIDTH; m_lTimeWidth = 0; m_lTrackListWidth = rcClient.Width () - m_lScaleWidth - m_lVScrollBarWidth - PIANOROLLFRAME_BORDERWIDTH * 4 - PIANOROLLFRAME_SPLITTERWIDTH; } else { m_lScaleWidth = PIANOROLLFRAME_SCALEWIDTH; m_lTimeWidth = rcClient.Width () - m_lScaleWidth - m_lVScrollBarWidth - PIANOROLLFRAME_BORDERWIDTH * 4 - PIANOROLLFRAME_SPLITTERWIDTH - m_lTrackListWidth; m_lTrackListWidth = m_lTrackListWidth; } // ƒrƒ…[‚̐®—ñ if (m_pScaleView) { m_pScaleView->MoveWindow (PIANOROLLFRAME_BORDERWIDTH, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT, m_lScaleWidth, m_lScaleHeight); } if (m_pTimeScaleView) { m_pTimeScaleView->MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT, m_lTimeWidth, m_lScaleHeight); } if (m_pKeyScaleView) { m_pKeyScaleView->MoveWindow (PIANOROLLFRAME_BORDERWIDTH, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT + m_lScaleHeight, m_lScaleWidth, m_lKeyHeight); } if (m_pKeyTimeView) { m_pKeyTimeView->MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT + m_lScaleHeight, m_lTimeWidth, m_lKeyHeight); } if (m_pVelScaleView) { m_pVelScaleView->MoveWindow (PIANOROLLFRAME_BORDERWIDTH, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT, m_lScaleWidth, m_lVelHeight); } if (m_pVelTimeView) { m_pVelTimeView->MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT, m_lTimeWidth, m_lVelHeight); } // ƒXƒNƒ[ƒ‹ƒo[‚̐®—ñ m_wndTimeScroll.MoveWindow (PIANOROLLFRAME_BORDERWIDTH, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT + m_lVelHeight, m_lScaleWidth + m_lTimeWidth - m_lVScrollBarWidth * 2, m_lHScrollBarHeight); m_wndKeyScroll.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT, m_lVScrollBarWidth, m_lScaleHeight + m_lKeyHeight - m_lVScrollBarWidth * 2); m_wndVelScroll.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT, m_lVScrollBarWidth, m_lVelHeight - m_lVScrollBarWidth * 2); m_wndSizeScroll.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT + m_lVelHeight, m_lVScrollBarWidth, m_lHScrollBarHeight); // ƒY[ƒ€ƒ{ƒ^ƒ“‚̐®—ñ m_wndTimeZoomDown.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth - m_lVScrollBarWidth * 2, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT + m_lVelHeight, m_lVScrollBarWidth, m_lHScrollBarHeight); m_wndTimeZoomUp.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth - m_lVScrollBarWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT + m_lVelHeight, m_lVScrollBarWidth, m_lHScrollBarHeight); m_wndKeyZoomDown.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT + m_lScaleHeight + m_lKeyHeight - m_lVScrollBarWidth * 2, m_lVScrollBarWidth, m_lHScrollBarHeight); m_wndKeyZoomUp.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT + m_lScaleHeight + m_lKeyHeight - m_lVScrollBarWidth, m_lVScrollBarWidth, m_lHScrollBarHeight); m_wndVelZoomDown.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT + m_lVelHeight - m_lVScrollBarWidth * 2, m_lVScrollBarWidth, m_lHScrollBarHeight); m_wndVelZoomUp.MoveWindow (PIANOROLLFRAME_BORDERWIDTH + m_lScaleWidth + m_lTimeWidth, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT + m_lVelHeight - m_lVScrollBarWidth, m_lVScrollBarWidth, m_lVScrollBarWidth, m_lHScrollBarHeight); // ƒŠƒXƒg‚̐®—ñ m_wndTrackList.MoveWindow (PIANOROLLFRAME_BORDERWIDTH * 3 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth + PIANOROLLFRAME_SPLITTERWIDTH, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT, m_lTrackListWidth, m_lScaleHeight + m_lKeyHeight); m_wndGraphKindList.MoveWindow (PIANOROLLFRAME_BORDERWIDTH * 3 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth + PIANOROLLFRAME_SPLITTERWIDTH, m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 3 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT, m_lTrackListWidth, m_lVelHeight + m_lHScrollBarHeight); // ƒXƒNƒ[ƒ‹ƒo[‚̃TƒCƒY‚ª•ω»‚µ‚½‚̂ŁAƒo[‚̃fƒUƒCƒ“‚ðÄ’²®‚·‚éB RecalcKeyScrollInfo (); RecalcVelScrollInfo (); RecalcTimeScrollInfo (); } // ƒNƒ‰ƒCƒAƒ“ƒg—̈æ‚̐¶¬(CFrameWnd::OnCreateClient‚̃I[ƒo[ƒ‰ƒCƒh) BOOL CPianoRollFrame::OnCreateClient (LPCREATESTRUCT lpcs, CCreateContext* pContext) { // ƒTƒCƒY’²®—p‚̃_ƒ~[ƒrƒ…[¶¬(Visible = FALSE) CWnd* pWnd = NULL; m_pDummyView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_DUMMYVIEW); if (m_pDummyView == NULL) { return FALSE; } m_pDummyView->ShowWindow (SW_HIDE); // ˆóü—p‚̃rƒ…[¶¬(Visible = FALSE) pContext->m_pNewViewClass = RUNTIME_CLASS (CPianoRollPrintView); m_pPrintView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_PRINTVIEW); if (m_pPrintView == NULL) { return FALSE; } m_pPrintView->ShowWindow (SW_HIDE); // ƒrƒ…[1‚̐¶¬ pContext->m_pNewViewClass = RUNTIME_CLASS (CPianoRollScaleView); m_pScaleView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_SCALEVIEW); if (m_pScaleView == NULL) { return FALSE; } m_pScaleView->ModifyStyleEx (WS_EX_CLIENTEDGE, 0); // ƒrƒ…[2‚̐¶¬ pContext->m_pNewViewClass = RUNTIME_CLASS (CPianoRollTimeScaleView); m_pTimeScaleView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_TIMESCALEVIEW); if (m_pTimeScaleView == NULL) { return FALSE; } m_pTimeScaleView->ModifyStyleEx (WS_EX_CLIENTEDGE, 0); // ƒrƒ…[3‚̐¶¬ pContext->m_pNewViewClass = RUNTIME_CLASS (CPianoRollKeyScaleView); m_pKeyScaleView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_KEYSCALEVIEW); if (m_pKeyScaleView == NULL) { return FALSE; } m_pKeyScaleView->ModifyStyleEx (WS_EX_CLIENTEDGE, 0); // ƒrƒ…[4‚̐¶¬ pContext->m_pNewViewClass = RUNTIME_CLASS (CPianoRollKeyTimeView); m_pKeyTimeView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_KEYTIMEVIEW); if (m_pKeyTimeView == NULL) { return FALSE; } m_pKeyTimeView->ModifyStyleEx (WS_EX_CLIENTEDGE, 0); // ƒrƒ…[5‚̐¶¬ pContext->m_pNewViewClass = RUNTIME_CLASS (CPianoRollVelScaleView); m_pVelScaleView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_VELSCALEVIEW); if (m_pVelScaleView == NULL) { return FALSE; } m_pVelScaleView->ModifyStyleEx (WS_EX_CLIENTEDGE, 0); // ƒrƒ…[6‚̐¶¬ pContext->m_pNewViewClass = RUNTIME_CLASS (CPianoRollVelTimeView); m_pVelTimeView = (CView*)CFrameWnd::CreateView (pContext, PIANOROLLFRAME_VELTIMEVIEW); if (m_pVelTimeView == NULL) { return FALSE; } m_pVelTimeView->ModifyStyleEx (WS_EX_CLIENTEDGE, 0); // ƒXƒNƒ[ƒ‹ƒo[‚̐¶¬ m_wndTimeScroll.Create (WS_CHILD|WS_VISIBLE|SBS_HORZ, CRect(0,0,0,0), this, PIANOROLLFRAME_TIMESCROLL); m_wndKeyScroll.Create (WS_CHILD|WS_VISIBLE|SBS_VERT, CRect(0,0,0,0), this, PIANOROLLFRAME_KEYSCROLL); m_wndVelScroll.Create (WS_CHILD|WS_VISIBLE|SBS_VERT, CRect(0,0,0,0), this, PIANOROLLFRAME_VELSCROLL); m_wndSizeScroll.Create (WS_CHILD|WS_VISIBLE|SBS_SIZEBOX, CRect(0,0,0,0), this, PIANOROLLFRAME_SIZEBOX); // ƒY[ƒ€ƒ{ƒ^ƒ“—ނ̐¶¬ m_wndTimeZoomDown.Create (_T("-"), WS_CHILD|WS_VISIBLE, CRect(0,0,0,0), this, PIANOROLLFRAME_TIMEZOOMDOWN); m_wndTimeZoomUp.Create (_T("+"), WS_CHILD|WS_VISIBLE, CRect(0,0,0,0), this, PIANOROLLFRAME_TIMEZOOMUP); m_wndKeyZoomDown.Create (_T("-"), WS_CHILD|WS_VISIBLE, CRect(0,0,0,0), this, PIANOROLLFRAME_KEYZOOMDOWN); m_wndKeyZoomUp.Create (_T("+"), WS_CHILD|WS_VISIBLE, CRect(0,0,0,0), this, PIANOROLLFRAME_KEYZOOMUP); m_wndVelZoomDown.Create (_T("-"), WS_CHILD|WS_VISIBLE, CRect(0,0,0,0), this, PIANOROLLFRAME_VELZOOMDOWN); m_wndVelZoomUp.Create (_T("+"), WS_CHILD|WS_VISIBLE, CRect(0,0,0,0), this, PIANOROLLFRAME_VELZOOMUP); // ƒgƒ‰ƒbƒNƒŠƒXƒg‚̍쐬 m_wndTrackList.Create (WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_HSCROLL| LBS_NOTIFY|LBS_DISABLENOSCROLL|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT, CRect(0,0,0,0), this, PIANOROLLFRAME_TRACKLIST); // ƒRƒ“ƒgƒ[ƒ‰‚ÌŽí—ÞƒŠƒXƒg‚̍쐬 m_wndGraphKindList.Create (WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_HSCROLL| LBS_NOTIFY|LBS_DISABLENOSCROLL|LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT, CRect(0,0,0,0), this, PIANOROLLFRAME_GRAPHKINDLIST); // ƒRƒ“ƒgƒ[ƒ‹‚̈ʒu‡‚킹‚ÍWM_SIZE‚Ȃǂɂæ‚éRecalcLaoyout‚É”C‚¹‚éB return TRUE; } // ˆóü—p‚̃Rƒ}ƒ“ƒh‚ðƒgƒ‰ƒbƒv(CFrameWnd::OnCmdMsg‚̃I[ƒo[ƒ‰ƒCƒh) BOOL CPianoRollFrame::OnCmdMsg (UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); // ˆóü—p‚̃Rƒ}ƒ“ƒh‚̏ꍇA‹­§“I‚ÉCPianoRollPrintView‚É“n‚·B if ((nID == ID_FILE_PRINT || nID == ID_FILE_PRINT_DIRECT || nID == ID_FILE_PRINT_PREVIEW) && pSekaijuApp->m_bRecording == FALSE) { if (m_pPrintView) { return ((CPianoRollPrintView*)m_pPrintView)->OnCmdMsg (nID, nCode, pExtra, pHandlerInfo); } return FALSE; } // ‚»‚Ì‘¼‚̃Rƒ}ƒ“ƒh‚̓fƒtƒHƒ‹ƒg‚̏ˆ—‚Æ‚·‚éB return CFrameWnd::OnCmdMsg (nID, nCode, pExtra, pHandlerInfo); } //------------------------------------------------------------------------------ // ƒƒbƒZ[ƒWƒ}ƒbƒv //------------------------------------------------------------------------------ // ƒEƒBƒ“ƒhƒE¶¬Žž int CPianoRollFrame::OnCreate (LPCREATESTRUCT lpCreateStruct) { CRect rcTemp; // ƒc[ƒ‹ƒo[1‚̍쐬 if (!m_wndToolBar1.Create (this) || !m_wndToolBar1.LoadToolBar (IDR_PIANOROLL1)) { TRACE0 ("Failed to create toolbar\n"); return -1; } m_wndToolBar1.SetBarStyle (m_wndToolBar1.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); //m_wndToolBar1.EnableDocking (CBRS_ALIGN_ANY); //EnableDocking (CBRS_ALIGN_ANY); //DockControlBar (&m_wndToolBar1); LoadAccelTable (MAKEINTRESOURCE (IDR_PIANOROLL)); // ƒgƒ‰ƒbƒNƒRƒ“ƒ{‚̍쐬 m_wndToolBar1.SetButtonInfo (6, IDC_TRACKCOMBO, TBBS_SEPARATOR, 80); m_wndToolBar1.GetItemRect (6, &rcTemp); rcTemp.top = 2; rcTemp.bottom = 120; if (!m_wndTrackCombo.CreateEx ( WS_EX_CLIENTEDGE, _T("COMBOBOX"), NULL, WS_BORDER | WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_VSCROLL | CBS_DROPDOWNLIST, rcTemp.left, rcTemp.top, rcTemp.Width (), rcTemp.Height (), m_wndToolBar1.GetSafeHwnd (), (HMENU)IDC_TRACKCOMBO)) { TRACE0 ("Failed to create edit box\n"); return -1; } m_wndTrackCombo.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); // ƒ`ƒƒƒ“ƒlƒ‹ƒRƒ“ƒ{‚̍쐬 m_wndToolBar1.SetButtonInfo (8, IDC_CHANNELCOMBO, TBBS_SEPARATOR, 40); m_wndToolBar1.GetItemRect (8, &rcTemp); rcTemp.top = 2; rcTemp.bottom = 120; if (!m_wndChannelCombo.CreateEx ( WS_EX_CLIENTEDGE, _T("COMBOBOX"), NULL, WS_BORDER | WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_VSCROLL | CBS_DROPDOWNLIST, rcTemp.left, rcTemp.top, rcTemp.Width (), rcTemp.Height (), m_wndToolBar1.GetSafeHwnd (), (HMENU)IDC_CHANNELCOMBO)) { TRACE0 ("Failed to create edit box\n"); return -1; } m_wndChannelCombo.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); // ƒXƒiƒbƒvƒRƒ“ƒ{‚̍쐬 m_wndToolBar1.SetButtonInfo (10, IDC_SNAPCOMBO, TBBS_SEPARATOR, 100); m_wndToolBar1.GetItemRect (10, &rcTemp); rcTemp.top = 2; rcTemp.bottom = 120; if (!m_wndSnapCombo.CreateEx ( WS_EX_CLIENTEDGE, _T("COMBOBOX"), NULL, WS_BORDER | WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_VSCROLL | CBS_DROPDOWNLIST, rcTemp.left, rcTemp.top, rcTemp.Width (), rcTemp.Height (), m_wndToolBar1.GetSafeHwnd (), (HMENU)IDC_SNAPCOMBO)) { TRACE0 ("Failed to create edit box\n"); return -1; } m_wndSnapCombo.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); // ƒxƒƒVƒeƒBƒRƒ“ƒ{‚̍쐬 m_wndToolBar1.SetButtonInfo (12, IDC_VELOCITYCOMBO, TBBS_SEPARATOR, 50); m_wndToolBar1.GetItemRect (12, &rcTemp); rcTemp.top = 2; rcTemp.bottom = 120; if (!m_wndVelocityCombo.CreateEx ( WS_EX_CLIENTEDGE, _T("COMBOBOX"), NULL, WS_BORDER | WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_VSCROLL | CBS_DROPDOWN, rcTemp.left, rcTemp.top, rcTemp.Width (), rcTemp.Height (), m_wndToolBar1.GetSafeHwnd (), (HMENU)IDC_VELOCITYCOMBO)) { TRACE0 ("Failed to create edit box\n"); return -1; } m_wndVelocityCombo.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); // ƒXƒsƒ“‚̍쐬(ƒeƒXƒg) //m_wndVelocitySpin.Create ( // WS_VISIBLE | WS_TABSTOP | WS_CHILD | UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_AUTOBUDDY | UDS_ALIGNRIGHT, // rcTemp, &m_wndToolBar1, IDC_VELOCITYSPIN); // ’·‚³ƒRƒ“ƒ{‚̍쐬 m_wndToolBar1.SetButtonInfo (14, IDC_DURATIONCOMBO, TBBS_SEPARATOR, 50); m_wndToolBar1.GetItemRect (14, &rcTemp); rcTemp.top = 2; rcTemp.bottom = 120; if (!m_wndDurationCombo.CreateEx ( WS_EX_CLIENTEDGE, _T("COMBOBOX"), NULL, WS_BORDER | WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_VSCROLL | CBS_DROPDOWN, rcTemp.left, rcTemp.top, rcTemp.Width (), rcTemp.Height (), m_wndToolBar1.GetSafeHwnd (), (HMENU)IDC_DURATIONCOMBO)) { TRACE0 ("Failed to create edit box\n"); return -1; } m_wndDurationCombo.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); // ƒOƒ‰ƒt‚ÌŽí—ÞƒRƒ“ƒ{‚̍쐬 m_wndToolBar1.SetButtonInfo (16, IDC_GRAPHKINDCOMBO, TBBS_SEPARATOR, 120); m_wndToolBar1.GetItemRect (16, &rcTemp); rcTemp.top = 2; rcTemp.bottom = 120; if (!m_wndGraphKindCombo.CreateEx ( WS_EX_CLIENTEDGE, _T("COMBOBOX"), NULL, WS_BORDER | WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_VSCROLL | CBS_DROPDOWNLIST, rcTemp.left, rcTemp.top, rcTemp.Width (), rcTemp.Height (), m_wndToolBar1.GetSafeHwnd (), (HMENU)IDC_GRAPHKINDCOMBO)) { TRACE0 ("Failed to create edit box\n"); return -1; } m_wndGraphKindCombo.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); // ƒOƒ‰ƒt‚̃XƒiƒbƒvƒRƒ“ƒ{‚̍쐬 m_wndToolBar1.SetButtonInfo (18, IDC_GRAPHSNAPCOMBO, TBBS_SEPARATOR, 100); m_wndToolBar1.GetItemRect (18, &rcTemp); rcTemp.top = 2; rcTemp.bottom = 120; if (!m_wndGraphSnapCombo.CreateEx ( WS_EX_CLIENTEDGE, _T("COMBOBOX"), NULL, WS_BORDER | WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_VSCROLL | CBS_DROPDOWNLIST, rcTemp.left, rcTemp.top, rcTemp.Width (), rcTemp.Height (), m_wndToolBar1.GetSafeHwnd (), (HMENU)IDC_GRAPHSNAPCOMBO)) { TRACE0 ("Failed to create edit box\n"); return -1; } m_wndGraphSnapCombo.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); // eƒNƒ‰ƒX‚̊֐”ŒÄ‚яo‚µ int nRet = CChildFrame::OnCreate (lpCreateStruct); // ƒXƒNƒ[ƒ‹ƒ|ƒWƒVƒ‡ƒ“‚̈ʒu‚ ‚킹 SetKeyScrollPos (64 * m_lKeyZoom - m_lKeyHeight / 2); CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; MIDITrack* pMIDITrack = NULL; // ƒgƒ‰ƒbƒNƒRƒ“ƒ{ƒ{ƒbƒNƒX‚̏[–ž UpdateTrackCombo (); // ƒ`ƒƒƒ“ƒlƒ‹ƒRƒ“ƒ{‚̏[–ž int i; CString strText; for (i = 0; i < 16; i++) { strText.Format (_T("%d"), i + 1); m_wndChannelCombo.AddString (strText); } m_wndChannelCombo.SetCurSel (0); // ƒJƒŒƒ“ƒgƒ`ƒƒƒ“ƒlƒ‹‚ÌŽ©“®‘I‘ð if (pSekaijuDoc->m_pTempTrack) { long lOutputChannel = MIDITrack_GetOutputChannel (pSekaijuDoc->m_pTempTrack); if (0 <= lOutputChannel && lOutputChannel <= 15) { SetCurChannel (lOutputChannel); } } // ƒXƒiƒbƒvƒRƒ“ƒ{‚̏[–ž UpdateSnapCombo (); m_wndSnapCombo.SetCurSel (3); // ƒxƒƒVƒeƒBƒRƒ“ƒ{‚̏[–ž UpdateVelocityCombo (); m_wndVelocityCombo.SetCurSel (6); // ’·‚³ƒRƒ“ƒ{‚̏[–ž UpdateDurationCombo (); m_wndDurationCombo.SetCurSel (3); // ƒOƒ‰ƒtƒXƒiƒbƒvƒRƒ“ƒ{‚̏[–ž UpdateGraphSnapCombo (); m_wndGraphSnapCombo.SetCurSel (7); // ƒgƒ‰ƒbƒNƒŠƒXƒg‚̏[–ž UpdateTrackList (); m_wndTrackList.SetCurSel (0); m_wndTrackList.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); long lCount = m_wndTrackList.GetCount (); i = 0; if (pSekaijuDoc->m_pTempTrack) { forEachTrack (pMIDIData, pMIDITrack) { if (0 <= i && i < lCount) { m_wndTrackList.SetCheck (i, pMIDITrack == pSekaijuDoc->m_pTempTrack ? TRUE : FALSE); m_bTrackVisible[i] = (pMIDITrack == pSekaijuDoc->m_pTempTrack ? TRUE : FALSE); } i++; } } else { forEachTrack (pMIDIData, pMIDITrack) { if (0 <= i && i < lCount) { m_wndTrackList.SetCheck (i, TRUE); m_bTrackVisible[i] = (TRUE); } i++; } } m_bOnlyCurTrack = FALSE; m_bShowAllTrack = FALSE; // ƒJƒŒƒ“ƒgƒgƒ‰ƒbƒN‚ƃJƒŒƒ“ƒgƒ`ƒƒƒ“ƒlƒ‹‚ðXV long lTrackIndex = 0; if (pSekaijuDoc->m_pTempTrack) { lTrackIndex = pSekaijuDoc->GetTrackIndex (pSekaijuDoc->m_pTempTrack); } else if (MIDIData_GetFormat (pMIDIData) == 1 && lCount >= 2) { lTrackIndex = 1; } ASSERT (0 <= lTrackIndex && lTrackIndex < lCount); if (m_bTrackVisible[lTrackIndex]) { SetCurTrackIndex (lTrackIndex); pMIDITrack = pSekaijuDoc->GetTrack (lTrackIndex); if (pMIDITrack) { long lOutputChannel = MIDITrack_GetOutputChannel (pMIDITrack); if (0 <= lOutputChannel && lOutputChannel <= 15) { SetCurChannel (lOutputChannel); } } } // ƒOƒ‰ƒt‚ÌŽí—ÞƒRƒ“ƒ{‚̏[–ž(æ‚Ƀgƒ‰ƒbƒNƒŠƒXƒg‚ðŠ®¬‚³‚¹GetCurTrackIndex‚ðŒø‚©‚¹‚邱‚Æ) UpdateGraphKindCombo (); m_wndGraphKindCombo.SetCurSel (1); // ƒOƒ‰ƒt‚ÌŽí—ÞƒŠƒXƒg‚̏[–ž UpdateGraphKindList (); m_wndGraphKindList.SetCurSel (1); m_wndGraphKindList.SetFont (CFont::FromHandle ((HFONT)::GetStockObject (DEFAULT_GUI_FONT))); lCount = m_wndGraphKindList.GetCount (); for (i = 0; i < lCount; i++) { m_wndGraphKindList.SetCheck (i, IsGraphVisible (i) ? 1 : 0); } // Ž©“®ƒy[ƒWXV‚̐ݒè if (pSekaijuApp->m_theGeneralOption.m_bEnableAutoPageUpdate) { m_bAutoPageUpdate = TRUE; } SetActiveView (m_pKeyTimeView, FALSE); m_pKeyTimeView->SetFocus (); pSekaijuDoc->m_theCriticalSection.Unlock (); return nRet; } // ƒEƒBƒ“ƒhƒE”jŠüŽž void CPianoRollFrame::OnDestroy () { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); //KillTimer (0x11); CChildFrame::OnDestroy (); pSekaijuDoc->m_theCriticalSection.Unlock (); } // ƒEƒBƒ“ƒhƒEƒTƒCƒY•ύXŽž void CPianoRollFrame::OnSize (UINT nType, int cx, int cy) { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); // Šî–{ƒNƒ‰ƒX‚̊֐”ŒÄ‚яo‚µ CChildFrame::OnSize (nType, cx, cy); pSekaijuDoc->m_theCriticalSection.Unlock (); } // ƒ^ƒCƒ}[ŒÄ‚яo‚µŽž void CPianoRollFrame::OnTimer (UINT nIDEvent) { //if (nIDEvent == 0x11) { // m_pKeyTimeView->SendMessage (WM_TIMER, 11, NULL); // m_pVelTimeView->SendMessage (WM_TIMER, 11, NULL); //} } // ”wŒiÁ‹Ž(CFrameWnd::OnEraseBkgnd‚̃I[ƒo[ƒ‰ƒCƒh) BOOL CPianoRollFrame::OnEraseBkgnd (CDC* pDC) { return 0; } // ƒEƒBƒ“ƒhƒE‚ªƒAƒNƒeƒBƒu‚ɂȂÁ‚½‚Æ‚« void CPianoRollFrame::OnMDIActivate (BOOL bActivate, CWnd* pActivateWnd, CWnd* pDeactivateWnd) { CChildFrame::OnMDIActivate (bActivate, pActivateWnd, pDeactivateWnd); } // •`‰æ‚·‚邯‚« void CPianoRollFrame::OnPaint () { CPaintDC dc (this); CRect rcClient; GetClientRect (&rcClient); // ¶ã‘¤—̈æ‚Ì‚­‚Ú‚Ý•`‰æ CRect rcClient1 (rcClient); rcClient1.top = m_lToolBar1Height; rcClient1.bottom = m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 2 + m_lScaleHeight + m_lKeyHeight; rcClient1.right = PIANOROLLFRAME_BORDERWIDTH * 2 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth; dc.Draw3dRect (&rcClient1, RGB (128, 128, 128), RGB (255, 255, 255)); rcClient1.InflateRect (-1, -1); dc.Draw3dRect (&rcClient1, RGB (0, 0, 0), RGB (192, 192, 192)); // ¶‰º‘¤—̈æ‚Ì‚­‚Ú‚Ý•`‰æ CRect rcClient2 (rcClient); rcClient2.top = m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 2 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT; rcClient2.right = PIANOROLLFRAME_BORDERWIDTH * 2 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth; dc.Draw3dRect (&rcClient2, RGB (128, 128, 128), RGB (255, 255, 255)); rcClient2.InflateRect (-1, -1); dc.Draw3dRect (&rcClient2, RGB (0, 0, 0), RGB (192, 192, 192)); // ‰Eã‘¤—̈æ‚Ì‚­‚Ú‚Ý•`‰æ CRect rcClient3 (rcClient); rcClient3.top = m_lToolBar1Height; rcClient3.bottom = m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 2 + m_lScaleHeight + m_lKeyHeight; rcClient3.left = PIANOROLLFRAME_BORDERWIDTH * 2 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth + PIANOROLLFRAME_SPLITTERWIDTH; dc.Draw3dRect (&rcClient3, RGB (128, 128, 128), RGB (255, 255, 255)); rcClient3.InflateRect (-1, -1); dc.Draw3dRect (&rcClient3, RGB (0, 0, 0), RGB (192, 192, 192)); // ‰E‰º‘¤—̈æ‚Ì‚­‚Ú‚Ý•`‰æ CRect rcClient4 (rcClient); rcClient4.top = m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 2 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT; rcClient4.left = PIANOROLLFRAME_BORDERWIDTH * 2 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth + PIANOROLLFRAME_SPLITTERWIDTH; dc.Draw3dRect (&rcClient4, RGB (128, 128, 128), RGB (255, 255, 255)); rcClient4.InflateRect (-1, -1); dc.Draw3dRect (&rcClient4, RGB (0, 0, 0), RGB (192, 192, 192)); // ‰¡‹«ŠE•”•ª‚Ì•`‰æ CBrush brush; brush.CreateSolidBrush (::GetSysColor (COLOR_3DFACE)); CRect rcClient5 (rcClient); rcClient5.top = rcClient1.bottom + 1; rcClient5.bottom = rcClient2.top - 1; dc.FillRect (&rcClient5, &brush); // c‹«ŠE•”•ª‚Ì•`‰æ CRect rcClient6 (rcClient); rcClient6.left = rcClient1.right + 1; rcClient6.right = rcClient3.left - 1; dc.FillRect (&rcClient6, &brush); } // ƒL[‚ª‰Ÿ‚³‚ê‚½Žž void CPianoRollFrame::OnKeyDown (UINT nChar, UINT nRepCnt, UINT nFlags) { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); CSekaijuDoc* pSekaijuDoc = GetDocument (); switch (nChar) { // D(•`‰æ)P(ƒyƒ“) case 'D': case 'P': if (GetCapture () == NULL) { this->PostMessage (WM_COMMAND, ID_PIANOROLL_PEN, 0); } break; // L(ü) case 'L': if (GetCapture () == NULL) { this->PostMessage (WM_COMMAND, ID_PIANOROLL_LINE, 0); } break; // E(Á‚µƒSƒ€) case 'E': if (GetCapture () == NULL) { this->PostMessage (WM_COMMAND, ID_PIANOROLL_ERASER, 0); } break; // S(‘I‘ð) case 'S': if (GetCapture () == NULL) { this->PostMessage (WM_COMMAND, ID_PIANOROLL_SELECT, 0); } break; // B(ƒXƒNƒ‰ƒu) case 'B': if (GetCapture () == NULL) { this->PostMessage (WM_COMMAND, ID_PIANOROLL_SPEAKER, 0); } break; } return; } // ƒ}ƒEƒX¶ƒ{ƒ^ƒ“‰Ÿ‚³‚ê‚½Žž void CPianoRollFrame::OnLButtonDown (UINT nFlags, CPoint point) { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); // ã”¼•ª(ƒsƒAƒmƒ[ƒ‹)‚Ɖº”¼•ª(ƒRƒ“ƒgƒ[ƒ‰[)‚Ì‹«ŠEüã‚ðƒhƒ‰ƒbƒO‚·‚邯A‹«ŠEü‚ªã‰º‚Ɉړ® if (m_bSplitterMovingH || m_bSplitterMovingV) { SetCapture (); m_ptMouseDown = m_ptMouseMoveOld = point; CDC* pDC = GetDC (); DrawSplitterCaptor (pDC, point); ReleaseDC (pDC); if (m_bSplitterMovingH && m_bSplitterMovingV) { ::SetCursor (pSekaijuApp->m_hCursorResizeAll); } else if (m_bSplitterMovingH) { ::SetCursor (pSekaijuApp->m_hCursorResizeNS); } else if (m_bSplitterMovingV) { ::SetCursor (pSekaijuApp->m_hCursorResizeWE); } } } // ƒ}ƒEƒX‰Eƒ{ƒ^ƒ“‰Ÿ‚³‚ê‚½Žž void CPianoRollFrame::OnRButtonDown (UINT nFlags, CPoint point) { } // ƒ}ƒEƒX¶ƒ{ƒ^ƒ“—£‚³‚ꂽ‚Æ‚« void CPianoRollFrame::OnLButtonUp (UINT nFlags, CPoint point) { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); if (GetCapture () == this) { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); CDC* pDC = GetDC (); DrawSplitterCaptor (pDC, m_ptMouseMoveOld); ReleaseDC (pDC); ReleaseCapture (); ::SetCursor (pSekaijuApp->m_hCursorArrow); CPoint ptDelta = point - m_ptMouseDown; if (m_bSplitterMovingH) { m_lVelHeight = CLIP (0, (m_lVelHeight - ptDelta.y), PIANOROLLFRAME_VELHEIGHT * m_lVelZoom + 16); } if (m_bSplitterMovingV) { m_lTrackListWidth = CLIP (0, (m_lTrackListWidth - ptDelta.x), 1600); } m_bSplitterMovingH = FALSE; m_bSplitterMovingV = FALSE; RecalcLayout (); Invalidate (); pSekaijuDoc->m_theCriticalSection.Unlock (); } } // ƒ}ƒEƒX‰Eƒ{ƒ^ƒ“—£‚³‚ꂽ‚Æ‚« void CPianoRollFrame::OnRButtonUp (UINT nFlags, CPoint point) { } // ƒ}ƒEƒX‚ª“®‚©‚³‚ꂽ‚Æ‚« void CPianoRollFrame::OnMouseMove (UINT nFlags, CPoint point) { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); // ƒLƒƒƒvƒ^[’† if (GetCapture () == this) { CRect rcClient; GetClientRect (&rcClient); CDC* pDC = GetDC (); DrawSplitterCaptor (pDC, m_ptMouseMoveOld); DrawSplitterCaptor (pDC, point); ReleaseDC (pDC); m_ptMouseMoveOld = point; } // ”ñƒLƒƒƒvƒ^[’† else { // ƒJ[ƒ\ƒ‹‚ª…•½ƒXƒvƒŠƒbƒ^[ã‚É‚ ‚é‚© m_bSplitterMovingH = m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 2 + m_lScaleHeight + m_lKeyHeight <= point.y && point.y < m_lToolBar1Height + PIANOROLLFRAME_BORDERHEIGHT * 2 + m_lScaleHeight + m_lKeyHeight + PIANOROLLFRAME_SPLITTERHEIGHT; // ƒJ[ƒ\ƒ‹‚ª‚’¼ƒXƒvƒŠƒbƒ^[ã‚É‚ ‚é‚© m_bSplitterMovingV = PIANOROLLFRAME_BORDERWIDTH * 2 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth <= point.x && point.x < PIANOROLLFRAME_BORDERWIDTH * 2 + m_lScaleWidth + m_lTimeWidth + m_lVScrollBarWidth + PIANOROLLFRAME_SPLITTERWIDTH; // ƒJ[ƒ\ƒ‹‚ª…•½ƒXƒvƒŠƒbƒ^[‚Ɛ‚’¼ƒXƒvƒŠƒbƒ^[‚ÌŒð·•”‚É‚ ‚éê‡ if (m_bSplitterMovingH && m_bSplitterMovingV) { ::SetCursor (pSekaijuApp->m_hCursorResizeAll); } // ƒJ[ƒ\ƒ‹‚ª…•½ƒXƒvƒŠƒbƒ^[ã‚É‚ ‚éê‡ else if (m_bSplitterMovingH) { ::SetCursor (pSekaijuApp->m_hCursorResizeNS); } // ƒJ[ƒ\ƒ‹‚ª‚’¼ƒXƒvƒŠƒbƒ^[ã‚É‚ ‚éê‡ else if (m_bSplitterMovingV) { ::SetCursor (pSekaijuApp->m_hCursorResizeWE); } // ƒJ[ƒ\ƒ‹‚ªƒXƒvƒŠƒbƒ^[‚ɂȂ¢ê‡ else { ::SetCursor (pSekaijuApp->m_hCursorArrow); } } } // ŽžŠÔ•ûŒüƒY[ƒ€ƒ_ƒEƒ“(20091220:¶’[ˆÊ’u•ÛŽ‹@”\’ljÁAŽ©“®ƒy[ƒWXVŽ©“®ƒIƒt’ljÁ) void CPianoRollFrame::OnTimeZoomDown () { CSekaijuDoc* pSekaijuDoc = GetDocument (); long lOldTimeZoom = m_lTimeZoom; long lOldTimePos = m_wndTimeScroll.GetScrollPos (); long lNewTimeZoom = CLIP (1, m_lTimeZoom - 1, 16); long lNewTimePos = lOldTimePos * lNewTimeZoom / lOldTimeZoom; pSekaijuDoc->m_theCriticalSection.Lock (); m_bAutoPageUpdate = FALSE; m_lTimeZoom = lNewTimeZoom; RecalcTimeScrollInfo (); m_wndTimeScroll.SetScrollPos (lNewTimePos); m_lTimeScrollPos = m_wndTimeScroll.GetScrollPos (); m_pTimeScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); //m_bAutoPageUpdate = TRUE; pSekaijuDoc->m_theCriticalSection.Unlock (); } // ŽžŠÔ•ûŒüƒY[ƒ€ƒAƒbƒv(20091220:¶’[ˆÊ’u•ÛŽ‹@”\’ljÁAŽ©“®ƒy[ƒWXVŽ©“®ƒIƒt’ljÁ) void CPianoRollFrame::OnTimeZoomUp () { CSekaijuDoc* pSekaijuDoc = GetDocument (); long lOldTimeZoom = m_lTimeZoom; long lOldTimePos = m_wndTimeScroll.GetScrollPos (); long lNewTimeZoom = CLIP (1, m_lTimeZoom + 1, 16); long lNewTimePos = lOldTimePos * lNewTimeZoom / lOldTimeZoom; pSekaijuDoc->m_theCriticalSection.Lock (); m_bAutoPageUpdate = FALSE; m_lTimeZoom = lNewTimeZoom; RecalcTimeScrollInfo (); m_wndTimeScroll.SetScrollPos (lNewTimePos); m_lTimeScrollPos = m_wndTimeScroll.GetScrollPos (); m_pTimeScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); //m_bAutoPageUpdate = TRUE; pSekaijuDoc->m_theCriticalSection.Unlock (); } // ƒL[•ûŒüƒY[ƒ€ƒ_ƒEƒ“(20091220:ã’[ˆÊ’u•ÛŽ‹@”\’ljÁ) void CPianoRollFrame::OnKeyZoomDown () { CSekaijuDoc* pSekaijuDoc = GetDocument (); long lOldKeyZoom = m_lKeyZoom; long lOldKeyPos = m_wndKeyScroll.GetScrollPos (); long lNewKeyZoom = CLIP (4, m_lKeyZoom - 1, 16); long lNewKeyPos = lOldKeyPos * lNewKeyZoom / lOldKeyZoom; pSekaijuDoc->m_theCriticalSection.Lock (); m_lKeyZoom = lNewKeyZoom; RecalcKeyScrollInfo (); m_wndKeyScroll.SetScrollPos (lNewKeyPos); m_lKeyScrollPos = m_wndKeyScroll.GetScrollPos (); m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); pSekaijuDoc->m_theCriticalSection.Unlock (); } // ƒL[•ûŒüƒY[ƒ€ƒAƒbƒv(20091220:ã’[ˆÊ’u•ÛŽ‹@”\’ljÁ) void CPianoRollFrame::OnKeyZoomUp () { CSekaijuDoc* pSekaijuDoc = GetDocument (); long lOldKeyZoom = m_lKeyZoom; long lOldKeyPos = m_wndKeyScroll.GetScrollPos (); long lNewKeyZoom = CLIP (4, m_lKeyZoom + 1, 16); long lNewKeyPos = lOldKeyPos * lNewKeyZoom / lOldKeyZoom; pSekaijuDoc->m_theCriticalSection.Lock (); m_lKeyZoom = lNewKeyZoom; RecalcKeyScrollInfo (); m_wndKeyScroll.SetScrollPos (lNewKeyPos); m_lKeyScrollPos = m_wndKeyScroll.GetScrollPos (); m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); pSekaijuDoc->m_theCriticalSection.Unlock (); } // ƒxƒƒVƒeƒB•ûŒüƒY[ƒ€ƒ_ƒEƒ“(20091220:ã’[ˆÊ’u•ÛŽ‹@”\’ljÁ) void CPianoRollFrame::OnVelZoomDown () { CSekaijuDoc* pSekaijuDoc = GetDocument (); long lOldVelZoom = m_lVelZoom; long lOldVelPos = m_wndVelScroll.GetScrollPos (); long lNewVelZoom = CLIP (1, m_lVelZoom - 1, 4); long lNewVelPos = lOldVelPos * lNewVelZoom / lOldVelZoom; pSekaijuDoc->m_theCriticalSection.Lock (); m_lVelZoom = lNewVelZoom; m_lVelHeight = MIN (m_lVelHeight, 128 * m_lVelZoom); RecalcLayout (FALSE); m_wndVelScroll.SetScrollPos (lNewVelPos); m_lVelScrollPos = m_wndVelScroll.GetScrollPos (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); this->Invalidate (); pSekaijuDoc->m_theCriticalSection.Unlock (); } // ƒxƒƒVƒeƒB•ûŒüƒY[ƒ€ƒAƒbƒv(20091220:ã’[ˆÊ’u•ÛŽ‹@”\’ljÁ) void CPianoRollFrame::OnVelZoomUp () { CSekaijuDoc* pSekaijuDoc = GetDocument (); long lOldVelZoom = m_lVelZoom; long lOldVelPos = m_wndVelScroll.GetScrollPos (); long lNewVelZoom = CLIP (1, m_lVelZoom + 1, 4); long lNewVelPos = lOldVelPos * lNewVelZoom / lOldVelZoom; pSekaijuDoc->m_theCriticalSection.Lock (); m_lVelZoom = lNewVelZoom; m_lVelHeight = MIN (m_lVelHeight, 128 * m_lVelZoom); RecalcLayout (FALSE); m_wndVelScroll.SetScrollPos (lNewVelPos); m_lVelScrollPos = m_wndVelScroll.GetScrollPos (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); this->Invalidate (); pSekaijuDoc->m_theCriticalSection.Unlock (); } // …•½ƒXƒNƒ[ƒ‹ void CPianoRollFrame::OnHScroll (UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); if (pScrollBar == &m_wndTimeScroll) { int nMin = 0; int nMax = 0; pScrollBar->GetScrollRange (&nMin, &nMax); long lNewPos = m_lTimeScrollPos; switch (nSBCode) { case SB_LINELEFT: lNewPos = m_lTimeScrollPos - m_lTimeZoom; break; case SB_LINERIGHT: lNewPos = m_lTimeScrollPos + m_lTimeZoom; break; case SB_PAGELEFT: lNewPos = m_lTimeScrollPos - m_lTimeZoom * 4; break; case SB_PAGERIGHT: lNewPos = m_lTimeScrollPos + m_lTimeZoom * 4; break; case SB_LEFT: // 20100206’ljÁ lNewPos = nMin; break; case SB_RIGHT: // 20100206’ljÁ lNewPos = nMax; break; case SB_THUMBTRACK: lNewPos = nPos; break; } SetTimeScrollPos (PIANOROLLFRAME_RANGE (0, lNewPos, 0x7FFFFFFF)); m_bAutoPageUpdate = FALSE; m_pKeyTimeView->SetFocus (); } pSekaijuDoc->m_theCriticalSection.Unlock (); } // ‚’¼ƒXƒNƒ[ƒ‹ void CPianoRollFrame::OnVScroll (UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); if (pScrollBar == &m_wndKeyScroll) { int nMin = 0; int nMax = 0; pScrollBar->GetScrollRange (&nMin, &nMax); long lNewPos = m_lKeyScrollPos; switch (nSBCode) { case SB_LINEUP: lNewPos = m_lKeyScrollPos - m_lKeyZoom; break; case SB_LINEDOWN: lNewPos = m_lKeyScrollPos + m_lKeyZoom; break; case SB_PAGEUP: lNewPos = m_lKeyScrollPos - m_lKeyZoom * 12; break; case SB_PAGEDOWN: lNewPos = m_lKeyScrollPos + m_lKeyZoom * 12; break; case SB_TOP: // 20100206’ljÁ lNewPos = nMin; break; case SB_BOTTOM: // 20100206’ljÁ lNewPos = nMax; break; case SB_THUMBTRACK: lNewPos = nPos; break; } SetKeyScrollPos (PIANOROLLFRAME_RANGE (0, lNewPos, 0x7FFFFFFF)); m_pKeyTimeView->SetFocus (); } else if (pScrollBar == &m_wndVelScroll) { int nMin = 0; int nMax = 0; pScrollBar->GetScrollRange (&nMin, &nMax); long lNewPos = m_lVelScrollPos; switch (nSBCode) { case SB_LINEUP: lNewPos = m_lVelScrollPos - m_lVelZoom * 2; break; case SB_LINEDOWN: lNewPos = m_lVelScrollPos + m_lVelZoom * 2; break; case SB_PAGEUP: lNewPos = m_lVelScrollPos - m_lVelZoom * 20; break; case SB_PAGEDOWN: lNewPos = m_lVelScrollPos + m_lVelZoom * 20; break; case SB_TOP: // 20100206’ljÁ lNewPos = nMin; break; case SB_BOTTOM: // 20100206’ljÁ lNewPos = nMax; break; case SB_THUMBTRACK: lNewPos = nPos; break; } SetVelScrollPos (PIANOROLLFRAME_RANGE (0, lNewPos, 0x7FFFFFFF)); m_pVelTimeView->SetFocus (); } pSekaijuDoc->m_theCriticalSection.Unlock (); } // wƒc[ƒ‹(&T)x-wƒyƒ“(&P)x void CPianoRollFrame::OnPianoRollPen () { m_lCurTool = ID_PIANOROLL_PEN; } // wƒc[ƒ‹(&T)x-wƒyƒ“(&P)x void CPianoRollFrame::OnUpdatePianoRollPenUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_lCurTool == ID_PIANOROLL_PEN); } // wƒc[ƒ‹(&T)x-wü(&L)x void CPianoRollFrame::OnPianoRollLine () { m_lCurTool = ID_PIANOROLL_LINE; } // wƒc[ƒ‹(&T)x-wü(&L)x void CPianoRollFrame::OnUpdatePianoRollLineUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_lCurTool == ID_PIANOROLL_LINE); } // wƒc[ƒ‹(&T)x-wÁ‚µƒSƒ€(&E)x void CPianoRollFrame::OnPianoRollEraser () { m_lCurTool = ID_PIANOROLL_ERASER; } // wƒc[ƒ‹(&T)x-wÁ‚µƒSƒ€(&E)x void CPianoRollFrame::OnUpdatePianoRollEraserUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_lCurTool == ID_PIANOROLL_ERASER); } // wƒc[ƒ‹(&T)x-w‘I‘ð(&S)x void CPianoRollFrame::OnPianoRollSelect () { m_lCurTool = ID_PIANOROLL_SELECT; } // wƒc[ƒ‹(&T)x-w‘I‘ð(&S)x void CPianoRollFrame::OnUpdatePianoRollSelectUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_lCurTool == ID_PIANOROLL_SELECT); } // wƒc[ƒ‹(&T)x-wƒXƒs[ƒJ(&P)x void CPianoRollFrame::OnPianoRollSpeaker () { m_lCurTool = ID_PIANOROLL_SPEAKER; } // wƒc[ƒ‹(&T)x-wƒXƒs[ƒJ(&P)x void CPianoRollFrame::OnUpdatePianoRollSpeakerUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_lCurTool == ID_PIANOROLL_SPEAKER); } // wƒc[ƒ‹(&T)x-wŒ»Ý‚̃gƒ‰ƒbƒN‚̂ݕ\ަ(&C)x void CPianoRollFrame::OnPianoRollOnlyCurTrack () { long lTrackCount = m_wndTrackList.GetCount (); long lTrackCurSel = m_wndTrackList.GetCurSel (); if (m_bOnlyCurTrack) { m_bOnlyCurTrack = FALSE; m_bShowAllTrack = FALSE; } else { m_bOnlyCurTrack = TRUE; m_bShowAllTrack = FALSE; } for (long i = 0; i < lTrackCount; i++) { m_wndTrackList.SetCheck (i, IsTrackVisible (i) ? 1 : 0); } m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); } // wƒc[ƒ‹(&T)x-wŒ»Ý‚̃gƒ‰ƒbƒN‚̂ݕ\ަ(&C)x void CPianoRollFrame::OnUpdatePianoRollOnlyCurTrackUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_bOnlyCurTrack); } // wƒc[ƒ‹(&T)x-w‘S‚Ẵgƒ‰ƒbƒN‚ð•\ަ(&A)x void CPianoRollFrame::OnPianoRollShowAllTrack () { long lTrackCount = m_wndTrackList.GetCount (); long lTrackCurSel = m_wndTrackList.GetCurSel (); if (m_bShowAllTrack) { m_bOnlyCurTrack = FALSE; m_bShowAllTrack = FALSE; } else { m_bOnlyCurTrack = FALSE; m_bShowAllTrack = TRUE; } for (long i = 0; i < lTrackCount; i++) { m_wndTrackList.SetCheck (i, IsTrackVisible (i) ? 1 : 0); } m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); } // wƒc[ƒ‹(&T)x-w‘S‚Ẵgƒ‰ƒbƒN‚ð•\ަ(&A)x void CPianoRollFrame::OnUpdatePianoRollShowAllTrackUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_bShowAllTrack); } // wƒc[ƒ‹(&T)x-wŒ»Ý‚̃Oƒ‰ƒt‚̂ݕ\ަ(&C)x void CPianoRollFrame::OnPianoRollOnlyCurGraph () { long lGraphKindCount = m_wndGraphKindList.GetCount (); long lGraphKindCurSel = m_wndGraphKindList.GetCurSel (); if (m_bOnlyCurGraph) { m_bOnlyCurGraph = FALSE; m_bShowAllGraph = FALSE; } else { m_bOnlyCurGraph = TRUE; m_bShowAllGraph = FALSE; } for (long i = 0; i < lGraphKindCount; i++) { m_wndGraphKindList.SetCheck (i, IsGraphVisible (i) ? 1 : 0); } m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); m_pVelScaleView->Invalidate (); } // wƒc[ƒ‹(&T)x-wŒ»Ý‚̃Oƒ‰ƒt‚̂ݕ\ަ(&C)x void CPianoRollFrame::OnUpdatePianoRollOnlyCurGraphUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_bOnlyCurGraph); } // wƒc[ƒ‹(&T)x-w‘S‚ẴOƒ‰ƒt‚ð•\ަ(&A)x void CPianoRollFrame::OnPianoRollShowAllGraph () { long lGraphKindCount = m_wndGraphKindList.GetCount (); long lGraphKindCurSel = m_wndGraphKindList.GetCurSel (); if (m_bShowAllGraph) { m_bOnlyCurGraph = FALSE; m_bShowAllGraph = FALSE; } else { m_bOnlyCurGraph = FALSE; m_bShowAllGraph = TRUE; } for (long i = 0; i < lGraphKindCount; i++) { m_wndGraphKindList.SetCheck (i, IsGraphVisible (i) ? 1 : 0); } m_pKeyTimeView->Invalidate (); m_pVelTimeView->Invalidate (); m_pVelScaleView->Invalidate (); } // wƒc[ƒ‹(&T)x-w‘S‚ẴOƒ‰ƒt‚ð•\ަ(&A)x void CPianoRollFrame::OnUpdatePianoRollShowAllGraphUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_bShowAllGraph); } // wƒc[ƒ‹(&T)x-wŽ©“®ƒy[ƒWXVx void CPianoRollFrame::OnPianoRollAutoPageUpdate () { m_bAutoPageUpdate = !m_bAutoPageUpdate; } // wƒc[ƒ‹(&T)x-wŽ©“®ƒy[ƒWXVx void CPianoRollFrame::OnUpdatePianoRollAutoPageUpdateUI (CCmdUI* pCmdUI) { pCmdUI->SetCheck (m_bAutoPageUpdate); } // ƒgƒ‰ƒbƒNƒRƒ“ƒ{‚ª‘I‘ð‚³‚êI‚í‚Á‚½Žž void CPianoRollFrame::OnTrackComboSelEndOK () { // ƒJƒŒƒ“ƒgƒgƒ‰ƒbƒN‚ðXV‚·‚é long lCurTrackIndex = m_wndTrackCombo.GetCurSel (); SetCurTrackIndex (lCurTrackIndex); SetTrackVisible (lCurTrackIndex); // ƒJƒŒƒ“ƒgƒ`ƒƒƒ“ƒlƒ‹‚àXV‚·‚é CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); MIDITrack* pMIDITrack = pSekaijuDoc->GetTrack (lCurTrackIndex); if (pMIDITrack) { long lOutputChannel = MIDITrack_GetOutputChannel (pMIDITrack); if (0 <= lOutputChannel && lOutputChannel <= 15) { SetCurChannel (lOutputChannel); } } pSekaijuDoc->m_theCriticalSection.Unlock (); // Ä•`‰æ m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // ƒgƒ‰ƒbƒNƒŠƒXƒg‚̃`ƒFƒbƒNƒ{ƒbƒNƒX‚ª•ω»‚µ‚½‚Æ‚« void CPianoRollFrame::OnTrackListChkChange () { // ƒgƒ‰ƒbƒN‚Ì•\ަ^”ñ•\ަ‚ðƒ`ƒFƒbƒNƒ{ƒbƒNƒX‚̏ó‘Ԃɍ‡‚킹‚é long lCount = m_wndTrackList.GetCount (); long lCurSel = m_wndTrackList.GetCurSel (); if (m_bOnlyCurTrack) { m_bOnlyCurTrack = FALSE; } for (long i = 0; i < lCount; i++) { m_bTrackVisible[i] = m_wndTrackList.GetCheck (i); if (m_bTrackVisible[i] == FALSE) { // TODO m_bShowAllTrack = FALSE; } } m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // ƒgƒ‰ƒbƒNƒŠƒXƒg‚Ì‘I‘ð€–Ú‚ª•ω»‚µ‚½‚Æ‚« void CPianoRollFrame::OnTrackListSelChange () { // ƒJƒŒƒ“ƒgƒgƒ‰ƒbƒN‚ð•ύX‚·‚é long lCurTrackIndex = m_wndTrackList.GetCurSel (); SetCurTrackIndex (lCurTrackIndex); // ƒJƒŒƒ“ƒgƒ`ƒƒƒ“ƒlƒ‹‚àXV‚·‚é CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); MIDITrack* pMIDITrack = pSekaijuDoc->GetTrack (lCurTrackIndex); if (pMIDITrack) { long lOutputChannel = MIDITrack_GetOutputChannel (pMIDITrack); if (0 <= lOutputChannel && lOutputChannel <= 15) { SetCurChannel (lOutputChannel); } } pSekaijuDoc->m_theCriticalSection.Unlock (); // Ä•`‰æ m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // ƒOƒ‰ƒt‚ÌŽí—ÞƒRƒ“ƒ{‚ª‘I‘ð‚³‚êI‚í‚Á‚½Žž void CPianoRollFrame::OnGraphKindComboSelEndOK () { long lCurGraphKind = m_wndGraphKindCombo.GetCurSel (); SetCurGraphKind (lCurGraphKind); SetGraphVisible (lCurGraphKind); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // ƒOƒ‰ƒt‚ÌŽí—ÞƒŠƒXƒg‚̃`ƒFƒbƒNƒ{ƒbƒNƒX‚ª•ω»‚µ‚½‚Æ‚« void CPianoRollFrame::OnGraphKindListChkChange () { // ƒOƒ‰ƒt‚Ì•\ަ^”ñ•\ަ‚ðƒ`ƒFƒbƒNƒ{ƒbƒNƒX‚̏ó‘Ԃɍ‡‚킹‚é long lCount = m_wndGraphKindList.GetCount (); long lCurSel = m_wndGraphKindList.GetCurSel (); if (m_bOnlyCurGraph) { m_bOnlyCurGraph = FALSE; } else { for (long i = 0; i < lCount; i++) { m_bGraphVisible[i] = m_wndGraphKindList.GetCheck (i); if (m_bGraphVisible[i] == FALSE) { m_bShowAllGraph = FALSE; } } } //m_pKeyTimeView->Invalidate (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // ƒOƒ‰ƒt‚ÌŽí—ÞƒŠƒXƒg‚Ì‘I‘ð€–Ú‚ª•ω»‚µ‚½‚Æ‚« void CPianoRollFrame::OnGraphKindListSelChange () { // ƒJƒŒƒ“ƒgƒOƒ‰ƒt‚ð•ύX‚·‚éB long lCurGraphKind = m_wndGraphKindList.GetCurSel (); SetCurGraphKind (lCurGraphKind); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // wƒ|ƒbƒvƒAƒbƒvx-w‚±‚̃gƒ‰ƒbƒN‚̂ݕ\ަONx void CPianoRollFrame::OnPopupTrackVisibleOn () { CSekaijuDoc* pSekaijuDoc = GetDocument (); if (pSekaijuDoc->m_pTempTrack == NULL) { // 20100429’ljÁ return; } pSekaijuDoc->m_theCriticalSection.Lock (); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; MIDITrack* pMIDITrack = NULL; long lCount = m_wndTrackList.GetCount (); long i = 0; forEachTrack (pMIDIData, pMIDITrack) { if (0 <= i && i < lCount) { m_wndTrackList.SetCheck (i, pMIDITrack == pSekaijuDoc->m_pTempTrack ? TRUE : FALSE); m_bTrackVisible[i] = (pMIDITrack == pSekaijuDoc->m_pTempTrack ? TRUE : FALSE); } i++; } m_bOnlyCurTrack = FALSE; m_bShowAllTrack = FALSE; // ƒJƒŒƒ“ƒgƒgƒ‰ƒbƒN‚ƃJƒŒƒ“ƒgƒ`ƒƒƒ“ƒlƒ‹‚ðXV long lTrackIndex = pSekaijuDoc->GetTrackIndex (pSekaijuDoc->m_pTempTrack); ASSERT (0 <= lTrackIndex && lTrackIndex < lCount); if (m_bTrackVisible[lTrackIndex]) { SetCurTrackIndex (lTrackIndex); pMIDITrack = pSekaijuDoc->GetTrack (lTrackIndex); if (pMIDITrack) { long lOutputChannel = MIDITrack_GetOutputChannel (pMIDITrack); if (0 <= lOutputChannel && lOutputChannel <= 15) { SetCurChannel (lOutputChannel); } } } pSekaijuDoc->m_theCriticalSection.Unlock (); // Ä•`‰æ m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // wƒ|ƒbƒvƒAƒbƒvx-w‚±‚̃gƒ‰ƒbƒN‚̂ݕ\ަONx // 20100429’ljÁ void CPianoRollFrame::OnUpdatePopupTrackVisibleOnUI (CCmdUI* pCmdUI) { CSekaijuDoc* pSekaijuDoc = GetDocument (); if (pSekaijuDoc->m_pTempTrack == NULL) { // 20100429’ljÁ pCmdUI->Enable (FALSE); } } // wƒ|ƒbƒvƒAƒbƒvx-w‚±‚̃gƒ‰ƒbƒN‚̂ݕ\ަOFFx void CPianoRollFrame::OnPopupTrackVisibleOff () { CSekaijuDoc* pSekaijuDoc = GetDocument (); if (pSekaijuDoc->m_pTempTrack == NULL) { // 20100429’ljÁ return; } pSekaijuDoc->m_theCriticalSection.Lock (); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; MIDITrack* pMIDITrack = NULL; long lCount = m_wndTrackList.GetCount (); long i = 0; forEachTrack (pMIDIData, pMIDITrack) { if (0 <= i && i < lCount) { m_wndTrackList.SetCheck (i, pMIDITrack == pSekaijuDoc->m_pTempTrack ? FALSE : TRUE); m_bTrackVisible[i] = (pMIDITrack == pSekaijuDoc->m_pTempTrack ? FALSE : TRUE); } i++; } m_bOnlyCurTrack = FALSE; m_bShowAllTrack = FALSE; // ƒJƒŒƒ“ƒgƒgƒ‰ƒbƒN‚ƃJƒŒƒ“ƒgƒ`ƒƒƒ“ƒlƒ‹‚ðXV long lTrackIndex = pSekaijuDoc->GetTrackIndex (pSekaijuDoc->m_pTempTrack); ASSERT (0 <= lTrackIndex && lTrackIndex < lCount); if (m_bTrackVisible[lTrackIndex]) { SetCurTrackIndex (lTrackIndex); pMIDITrack = pSekaijuDoc->GetTrack (lTrackIndex); if (pMIDITrack) { long lOutputChannel = MIDITrack_GetOutputChannel (pMIDITrack); if (0 <= lOutputChannel && lOutputChannel <= 15) { SetCurChannel (lOutputChannel); } } } pSekaijuDoc->m_theCriticalSection.Unlock (); // Ä•`‰æ m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // wƒ|ƒbƒvƒAƒbƒvx-w‚±‚̃gƒ‰ƒbƒN‚̂ݕ\ަOFFx // 20100429’ljÁ void CPianoRollFrame::OnUpdatePopupTrackVisibleOffUI (CCmdUI* pCmdUI) { CSekaijuDoc* pSekaijuDoc = GetDocument (); if (pSekaijuDoc->m_pTempTrack == NULL) { // 20100429’ljÁ pCmdUI->Enable (FALSE); } } // wƒ|ƒbƒvƒAƒbƒvx-w‘Sƒgƒ‰ƒbƒN•\ަONx void CPianoRollFrame::OnPopupTrackVisibleAll () { CSekaijuDoc* pSekaijuDoc = GetDocument (); pSekaijuDoc->m_theCriticalSection.Lock (); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; MIDITrack* pMIDITrack = NULL; long lCount = m_wndTrackList.GetCount (); long i = 0; forEachTrack (pMIDIData, pMIDITrack) { if (0 <= i && i < lCount) { m_wndTrackList.SetCheck (i, 1); m_bTrackVisible[i] = TRUE; } i++; } m_bOnlyCurTrack = FALSE; m_bShowAllTrack = FALSE; // ƒJƒŒƒ“ƒgƒgƒ‰ƒbƒN‚ƃJƒŒƒ“ƒgƒ`ƒƒƒ“ƒlƒ‹‚ðXV // 20100429”pŽ~ //long lTrackIndex = pSekaijuDoc->GetTrackIndex (pSekaijuDoc->m_pTempTrack); //ASSERT (0 <= lTrackIndex && lTrackIndex < lCount); //if (m_bTrackVisible[lTrackIndex]) { // SetCurTrackIndex (lTrackIndex); // pMIDITrack = pSekaijuDoc->GetTrack (lTrackIndex); // if (pMIDITrack) { // long lOutputChannel = MIDITrack_GetOutputChannel (pMIDITrack); // if (0 <= lOutputChannel && lOutputChannel <= 15) { // SetCurChannel (lOutputChannel); // } // } //} pSekaijuDoc->m_theCriticalSection.Unlock (); // Ä•`‰æ m_pKeyScaleView->Invalidate (); m_pKeyTimeView->Invalidate (); m_pVelScaleView->Invalidate (); m_pVelTimeView->Invalidate (); } // wƒ|ƒbƒvƒAƒbƒvx-w‘Sƒgƒ‰ƒbƒN•\ަONx // 20100429’ljÁ void CPianoRollFrame::OnUpdatePopupTrackVisibleAllUI (CCmdUI* pCmdUI) { CSekaijuDoc* pSekaijuDoc = GetDocument (); } // wƒ|ƒbƒvƒAƒbƒvx-w‚±‚̃Cƒxƒ“ƒg‚̃vƒƒpƒeƒB(&R)x// 20110109C³ void CPianoRollFrame::OnPopupEventProperty () { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); CSekaijuDoc* pSekaijuDoc = GetDocument (); if (pSekaijuApp->m_bRecording || pSekaijuApp->m_bInplaceEditing || pSekaijuApp->m_bInplaceListing || pSekaijuApp->m_bValueUpDowning) { return; } if (pSekaijuDoc->m_bEditLocked) { return; } if (pSekaijuDoc->m_pTempEvent == NULL || pSekaijuDoc->m_pTempTrack == NULL) { return; } if (!MIDIEvent_IsNote (pSekaijuDoc->m_pTempEvent)) { return; } MIDIEvent* pNoteOffEvent = pSekaijuDoc->m_pTempEvent->m_pNextCombinedEvent; if (pNoteOffEvent == NULL) { return; } long lTrackIndex = pSekaijuDoc->GetTrackIndex (pSekaijuDoc->m_pTempTrack); long lTime = MIDIEvent_GetTime (pSekaijuDoc->m_pTempEvent); CString strTime; pSekaijuDoc->LongTimeToStringTime (pSekaijuDoc->m_pMIDIData, lTime, &strTime); CPropertyNoteDlg theDlg; theDlg.m_bTrackZeroOrigin = pSekaijuApp->m_theGeneralOption.m_bTrackZeroOrigin; theDlg.m_bNoteOnNoteOn0 = (MIDIEvent_GetKind (pNoteOffEvent) & 0xF0) == 0x80 ? FALSE : TRUE; MIDITrack* pMIDITrack; forEachTrack (pSekaijuDoc->m_pMIDIData, pMIDITrack) { TCHAR szTrackName[256]; memset (szTrackName, 0, sizeof (szTrackName)); MIDITrack_GetName (pMIDITrack, szTrackName, TSIZEOF (szTrackName)); theDlg.m_theTrackNameArray.Add (szTrackName); long lTrackOutputChannel = MIDITrack_GetOutputChannel (pMIDITrack); theDlg.m_theTrackOutputChannelArray.Add ((DWORD)lTrackOutputChannel); } long lKey = 0; for (lKey = 0; lKey < 128; lKey++) { CString strKeyName; strKeyName = pSekaijuDoc->GetKeyName (pSekaijuDoc->m_pTempTrack, lTime, lKey); theDlg.m_theKeyNameArray.Add (strKeyName); } theDlg.m_nTrackIndex = (int)lTrackIndex; theDlg.m_strTime = strTime; theDlg.m_nChannel = (int)MIDIEvent_GetChannel (pSekaijuDoc->m_pTempEvent) + 1; theDlg.m_nKey = (int)MIDIEvent_GetKey (pSekaijuDoc->m_pTempEvent); theDlg.m_nOnVelocity = (int)MIDIEvent_GetVelocity (pSekaijuDoc->m_pTempEvent); theDlg.m_nOffVelocity = (int)MIDIEvent_GetVelocity (pNoteOffEvent); theDlg.m_nDuration = (int)MIDIEvent_GetDuration (pSekaijuDoc->m_pTempEvent); if (theDlg.DoModal () == IDOK) { // ƒgƒ‰ƒbƒN’Šo long lTrackIndex = (long)theDlg.m_nTrackIndex; if (MIDIData_GetFormat (pSekaijuDoc->m_pMIDIData) == 1 && lTrackIndex == 0) { CString strMsg; VERIFY (strMsg.LoadString (IDS_UNABLE_TO_INSERT_NOTEEVENT_TO_THE_FIRST_TRACK_IN_FORMAT1_MIDIDATA)); AfxMessageBox (strMsg, MB_ICONEXCLAMATION); return; } MIDITrack* pNewTrack = pSekaijuDoc->GetTrack (lTrackIndex); if (pNewTrack == NULL) { CString strMsg; AfxMessageBox (strMsg, MB_ICONEXCLAMATION); return; } // ƒ^ƒCƒ€•¶Žš—ñ‚ðlongŒ^‚ɕϊ· long lTime = MIDIEvent_GetTime (pSekaijuDoc->m_pTempEvent); long lErrorID = pSekaijuDoc->StringTimeToLongTime (pSekaijuDoc->m_pMIDIData, theDlg.m_strTime, &lTime); if (lErrorID != 0) { CString strMsg; VERIFY (strMsg.LoadString (lErrorID)); AfxMessageBox (strMsg, MB_ICONEXCLAMATION); return; } BeginWaitCursor (); pSekaijuDoc->m_theCriticalSection.Lock (); MIDIEvent* pNewEvent = NULL; MIDIEvent* pLastEvent = NULL; MIDIEvent* pCloneEvent = NULL; CString strHistoryName; VERIFY (strHistoryName.LoadString (IDS_MODIFY_NOTE)); pSekaijuDoc->AddHistoryUnit (strHistoryName); CHistoryUnit* pCurHistoryUnit = pSekaijuDoc->GetCurHistoryUnit (); // Š‘®ƒgƒ‰ƒbƒN‚ª•ύX‚³‚ê‚È‚¢ê‡ if (pNewTrack == pSekaijuDoc->m_pTempTrack) { // EOT‚Ì—š—ð•ÛŽ(20110109C³) pLastEvent = MIDITrack_GetLastEvent (pNewTrack); if (pLastEvent != NULL) { if (MIDIEvent_IsEndofTrack (pLastEvent)) { VERIFY (pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_REMOVEEVENT, pLastEvent)); VERIFY (pCloneEvent = pSekaijuDoc->ReplaceMIDIEvent (pLastEvent)); } } // ƒCƒxƒ“ƒg‚Ì’uŠ·‚ƕύX pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_REMOVEEVENT, pSekaijuDoc->m_pTempEvent); VERIFY (pNewEvent = pSekaijuDoc->ReplaceMIDIEvent (pSekaijuDoc->m_pTempEvent)); MIDIEvent_SetTime (pNewEvent, lTime); MIDIEvent_SetChannel (pNewEvent, theDlg.m_nChannel - 1); MIDIEvent_SetKey (pNewEvent, theDlg.m_nKey); MIDIEvent_SetVelocity (pNewEvent, theDlg.m_nOnVelocity); MIDIEvent_SetDuration (pNewEvent, theDlg.m_nDuration); if (!theDlg.m_bNoteOnNoteOn0) { MIDIEvent* pNewNoteOffEvent = pNewEvent->m_pNextCombinedEvent; MIDIEvent_SetVelocity (pNewNoteOffEvent, theDlg.m_nOffVelocity); } pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_INSERTEVENT, pNewEvent); // EOT‚Ì—š—ð•ÛŽ(20110109C³) pLastEvent = MIDITrack_GetLastEvent (pNewTrack); if (pLastEvent != NULL) { if (MIDIEvent_IsEndofTrack (pLastEvent)) { VERIFY (pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_INSERTEVENT, pLastEvent)); } } } // Š‘®ƒgƒ‰ƒbƒN‚ª•ύX‚³‚ê‚éê‡ else { // ƒCƒxƒ“ƒg‚Ì’uŠ·‚Əœ‹Ž pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_REMOVEEVENT, pSekaijuDoc->m_pTempEvent); VERIFY (pNewEvent = pSekaijuDoc->ReplaceMIDIEvent (pSekaijuDoc->m_pTempEvent)); VERIFY (MIDITrack_RemoveEvent (pSekaijuDoc->m_pTempTrack, pNewEvent)); // EOT‚Ì—š—ð•ÛŽ(20110109C³) pLastEvent = MIDITrack_GetLastEvent (pNewTrack); if (pLastEvent != NULL) { if (MIDIEvent_IsEndofTrack (pLastEvent)) { VERIFY (pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_REMOVEEVENT, pLastEvent)); VERIFY (pCloneEvent = pSekaijuDoc->ReplaceMIDIEvent (pLastEvent)); } } // ƒCƒxƒ“ƒg‚Ì‘}“ü‚ƕύX VERIFY (MIDITrack_InsertEvent (pNewTrack, pNewEvent)); MIDIEvent_SetTime (pNewEvent, lTime); MIDIEvent_SetChannel (pNewEvent, theDlg.m_nChannel - 1); MIDIEvent_SetKey (pNewEvent, theDlg.m_nKey); MIDIEvent_SetVelocity (pNewEvent, theDlg.m_nOnVelocity); MIDIEvent_SetDuration (pNewEvent, theDlg.m_nDuration); if (!theDlg.m_bNoteOnNoteOn0) { MIDIEvent* pNewNoteOffEvent = pNewEvent->m_pNextCombinedEvent; MIDIEvent_SetVelocity (pNewNoteOffEvent, theDlg.m_nOffVelocity); } pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_INSERTEVENT, pNewEvent); // EOT‚Ì—š—ð•ÛŽ(20110109C³) pLastEvent = MIDITrack_GetLastEvent (pNewTrack); if (pLastEvent != NULL) { if (MIDIEvent_IsEndofTrack (pLastEvent)) { VERIFY (pCurHistoryUnit->AddHistoryRecord (HISTORYRECORD_INSERTEVENT, pLastEvent)); } } } pSekaijuDoc->m_theCriticalSection.Unlock (); EndWaitCursor (); SetTrackVisible (theDlg.m_nTrackIndex); SetCurTrackIndex (theDlg.m_nTrackIndex); SetCurChannel (theDlg.m_nChannel - 1); SetCurVelocity (theDlg.m_nOnVelocity); SetCurDuration (theDlg.m_nDuration); pSekaijuDoc->UpdateAllViews (NULL, SEKAIJUDOC_MIDIEVENTCHANGED); ::Sleep (0); } } // wƒ|ƒbƒvƒAƒbƒvx-w‚±‚̃Cƒxƒ“ƒg‚̃vƒƒpƒeƒB(&R)x void CPianoRollFrame::OnUpdatePopupEventPropertyUI (CCmdUI* pCmdUI) { CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); CSekaijuDoc* pSekaijuDoc = GetDocument (); if (pSekaijuApp->m_bRecording || pSekaijuApp->m_bInplaceEditing || pSekaijuApp->m_bInplaceListing || pSekaijuApp->m_bValueUpDowning) { pCmdUI->Enable (FALSE); return; } if (pSekaijuDoc->m_bEditLocked) { pCmdUI->Enable (FALSE); return; } if (pSekaijuDoc->m_pTempEvent == NULL || pSekaijuDoc->m_pTempTrack == NULL) { pCmdUI->Enable (FALSE); return; } if (!MIDIEvent_IsNote (pSekaijuDoc->m_pTempEvent)) { pCmdUI->Enable (FALSE); return; } MIDIEvent* pNoteOffEvent = pSekaijuDoc->m_pTempEvent->m_pNextCombinedEvent; if (pNoteOffEvent == NULL) { pCmdUI->Enable (FALSE); return; } }
qdotme/Sekaiju
src/PianoRollFrame.cpp
C++
lgpl-2.1
99,912
/** * * $Id:$ * $Copyright:$ * * BUI - a user interface library for the JME 3D engine * Copyright (C) 2005-2006, Michael Bayne, All Rights Reserved * * This library 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. * * 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 * */ package com.jmex.bui.enumeratedConstants; /** * @author timo * @since 27Apr07 */ public enum MessageLayoutOptions { NORTH, SOUTH, CENTER, BUTTONS }
cdrchops/gbui
src/java/com/jmex/bui/enumeratedConstants/MessageLayoutOptions.java
Java
lgpl-2.1
1,054
import ChatAppDispatcher from '../dispatcher/ChatAppDispatcher'; import ChatConstants from '../constants/ChatConstants'; import * as ChatMessageUtils from '../utils/ChatMessageUtils'; import { EventEmitter } from 'events'; import ThreadStore from './ThreadStore'; let ActionTypes = ChatConstants.ActionTypes; let CHANGE_EVENT = 'change'; let _messages = {}; let _feedback = {}; let _showLoading = false; let TTSVoices = []; let _initialisedVoices = false; function _markAllInThreadRead(threadID) { for (let id in _messages) { if (_messages[id].threadID === threadID) { _messages[id].isRead = true; } } } function _addDates(allMsgs){ let msgsWithDates = []; let currDate = null; allMsgs.forEach((message)=>{ if(currDate === null){ let dateMsg = { id: 'd_'+Date.parse(message.date), threadID: 't_1', date: message.date, type: 'date', }; msgsWithDates.push(dateMsg); } else if(currDate.getDate() !== message.date.getDate()){ let dateMsg = { id: 'd_'+Date.parse(message.date), threadID: 't_1', date: message.date, type: 'date', }; msgsWithDates.push(dateMsg); } currDate = message.date; msgsWithDates.push(message); }); return msgsWithDates; } let MessageStore = { ...EventEmitter.prototype, emitChange() { this.emit(CHANGE_EVENT); }, /** * @param {function} callback */ addChangeListener(callback) { this.on(CHANGE_EVENT, callback); }, removeChangeListener(callback) { this.removeListener(CHANGE_EVENT, callback); }, get(id) { return _messages[id]; }, getAll() { return _messages; }, getTTSVoiceList() { return TTSVoices; }, getTTSInitStatus(){ return _initialisedVoices; }, getLoadStatus(){ return _showLoading; }, getFeedback(){ return _feedback; }, /** * @param {string} threadID */ getAllForThread(threadID) { let threadMessages = []; for (let id in _messages) { if (_messages[id].threadID === threadID) { threadMessages.push(_messages[id]); } } threadMessages.sort((a, b) => { if (a.date < b.date) { return -1; } else if (a.date > b.date) { return 1; } return 0; }); return threadMessages; }, getAllForCurrentThread() { return _addDates(this.getAllForThread(ThreadStore.getCurrentID())); }, resetVoiceForThread(threadID) { for (let id in _messages) { if ((_messages[id].threadID === threadID) && (_messages[id].authorName === 'SUSI')) { _messages[id].voice = false; _messages[id].feedback.isRated = true; } } }, resetVoiceForCurrentThread(){ this.resetVoiceForThread(ThreadStore.getCurrentID()); } }; MessageStore.dispatchToken = ChatAppDispatcher.register(action => { switch(action.type) { case ActionTypes.CLICK_THREAD: ChatAppDispatcher.waitFor([ThreadStore.dispatchToken]); _markAllInThreadRead(ThreadStore.getCurrentID()); MessageStore.emitChange(); break; case ActionTypes.CREATE_MESSAGE: { let message = action.message; _messages[message.id] = message; _showLoading = true; MessageStore.emitChange(); break; } case ActionTypes.RECEIVE_RAW_CREATED_MESSAGE: { let { rawMessage, tempMessageID } = action; delete _messages[tempMessageID]; let message = ChatMessageUtils.convertRawMessage(rawMessage); _messages[message.id] = message; MessageStore.emitChange(); break; } case ActionTypes.CREATE_SUSI_MESSAGE: { let message = action.message; MessageStore.resetVoiceForThread(message.threadID); _messages[message.id] = message; _showLoading = false; _feedback = {}; MessageStore.emitChange(); break; } case ActionTypes.STORE_HISTORY_MESSAGE: { let message = action.message; _messages[message.id] = message; MessageStore.emitChange(); break; } case ActionTypes.RESET_MESSAGE_VOICE: { MessageStore.resetVoiceForCurrentThread(); MessageStore.emitChange(); break; } case ActionTypes.FEEDBACK_RECEIVED: { _feedback = action.feedback; MessageStore.emitChange(); break; } case ActionTypes.INIT_TTS_VOICES: { TTSVoices = action.voiceList; _initialisedVoices = true; MessageStore.emitChange(); break; } default: // do nothing } }); export default MessageStore;
madhavrathi/chat.susi.ai
src/stores/MessageStore.js
JavaScript
lgpl-2.1
4,603
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: Button.qml Example File (declarative/positioners/qml/positioners/Button.qml)</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">Button.qml Example File</h1> <span class="small-subtitle">declarative/positioners/qml/positioners/Button.qml</span> <!-- $$$declarative/positioners/qml/positioners/Button.qml-description --> <div class="descr"> <a name="details"></a> <pre class="qml"> <span class="comment">/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** &quot;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 Nokia Corporation and its Subsidiary(-ies) 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 ** &quot;AS IS&quot; 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.&quot; ** $QT_END_LICENSE$ ** ****************************************************************************/</span> import QtQuick 1.0 <span class="type"><a href="qml-rectangle.html">Rectangle</a></span> { <span class="name">id</span>: <span class="name">page</span> property <span class="type">string</span> <span class="name">text</span> property <span class="type">string</span> <span class="name">icon</span> signal <span class="type">clicked</span> <span class="name">border</span>.color: <span class="string">&quot;black&quot;</span>; <span class="name">color</span>: <span class="string">&quot;steelblue&quot;</span>; <span class="name">radius</span>: <span class="number">5</span> <span class="name">width</span>: <span class="name">pix</span>.<span class="name">width</span> <span class="operator">+</span> <span class="name">textelement</span>.<span class="name">width</span> <span class="operator">+</span> <span class="number">13</span> <span class="name">height</span>: <span class="name">pix</span>.<span class="name">height</span> <span class="operator">+</span> <span class="number">10</span> <span class="type"><a href="qml-image.html">Image</a></span> { <span class="name">id</span>: <span class="name">pix</span>; <span class="name">x</span>: <span class="number">5</span>; <span class="name">y</span>:<span class="number">5</span>; <span class="name">source</span>: <span class="name">parent</span>.<span class="name">icon</span> } <span class="type"><a href="qml-text.html">Text</a></span> { <span class="name">id</span>: <span class="name">textelement</span> <span class="name">text</span>: <span class="name">page</span>.<span class="name">text</span>; <span class="name">color</span>: <span class="string">&quot;white&quot;</span> <span class="name">x</span>: <span class="name">pix</span>.<span class="name">width</span> <span class="operator">+</span> <span class="name">pix</span>.<span class="name">x</span> <span class="operator">+</span> <span class="number">3</span> <span class="name">anchors</span>.verticalCenter: <span class="name">pix</span>.<span class="name">verticalCenter</span> } <span class="type"><a href="qml-mousearea.html">MouseArea</a></span> { <span class="name">id</span>: <span class="name">mr</span> <span class="name">anchors</span>.fill: <span class="name">parent</span> <span class="name">onClicked</span>: { <span class="name">parent</span>.<span class="name">focus</span> <span class="operator">=</span> <span class="number">true</span>; <span class="name">page</span>.<span class="name">clicked</span>() } } <span class="name">states</span>: <span class="name">State</span> { <span class="name">name</span>: <span class="string">&quot;pressed&quot;</span>; <span class="name">when</span>: <span class="name">mr</span>.<span class="name">pressed</span> <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">textelement</span>; <span class="name">x</span>: <span class="number">5</span> } <span class="type"><a href="qml-propertychanges.html">PropertyChanges</a></span> { <span class="name">target</span>: <span class="name">pix</span>; <span class="name">x</span>: <span class="name">textelement</span>.<span class="name">x</span> <span class="operator">+</span> <span class="name">textelement</span>.<span class="name">width</span> <span class="operator">+</span> <span class="number">3</span> } } <span class="name">transitions</span>: <span class="name">Transition</span> { <span class="type"><a href="qml-numberanimation.html">NumberAnimation</a></span> { <span class="name">properties</span>: <span class="string">&quot;x,left&quot;</span>; <span class="name">easing</span>.type: <span class="name">Easing</span>.<span class="name">InOutQuad</span>; <span class="name">duration</span>: <span class="number">200</span> } } }</pre> </div> <!-- @@@declarative/positioners/qml/positioners/Button.qml --> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
kobolabs/qt-everywhere-4.8.0
doc/html/declarative-positioners-qml-positioners-button-qml.html
HTML
lgpl-2.1
8,284
#include "key2pho8.h" const static int shift[] = { 9, 7, 3, 0 }; const static int sb[] = { 31, 3, 15, 7 }; const char *ph_pho[] = { /* number of bits */ " ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙ", /* 5 */ " ㄧㄨㄩ", /* 2 */ " ㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦ", /* 4 */ " ˙ˊˇˋ" /* 3 */ }; /* Translate a single phone into a single uint assume phone is a big5 null-terminated string with no spaces */ uint16_t PhoneWc2Uint( const wchar_t *phone ) { int i, j, len = wcslen( phone ); uint16_t result = 0; wchar_t *pc; wchar_t temp; wchar_t *wcPho; for ( i = 0, j = 0; i < len && j < 4; j++ ) { temp = phone[ i ]; wcPho = malloc(sizeof(wchar_t)*22); mbstowcs( wcPho, ph_pho[ j ], 22); pc = wcschr( wcPho, temp ); if ( pc ) { result |= ( ( pc - wcPho ) - 1 ) << shift[ j ]; i++; } free( wcPho ); } return result; } uint16_t Uint2PhoneWc( wchar_t *phone, uint16_t seq ) { int i, j; wchar_t *wcPho; for ( i = 0, j = 0; i < 4; i++) { wcPho = malloc(sizeof(wchar_t)*22); mbstowcs( wcPho, ph_pho[ i ], 22); if ( wcPho[ ((seq >> shift[ i ]) & sb[ i ]) + 1 ] != ' ' ) { phone[ j ] = wcPho[ ((seq >> shift[ i ]) & sb[ i ]) + 1 ]; j++; } free (wcPho); } return j; } //int main(int argc, char *argv[]) //{ // wchar_t phone[100]; // char bphone[100]; // if (argc < 2) // { // fprintf(stderr, "Usage: key2pho <number>\n"); // exit(1); // } // setlocale(LC_CTYPE, "zh_TW.UTF-8"); //// mbstowcs( phone, "ㄊㄡˊ", 3 ); //// printf("ㄊㄡˊ : %d\n", PhoneWc2Uint( phone )); // memset(phone, 0, sizeof(phone)); // Uint2PhoneWc(phone, atoi(argv[1])); // wcstombs( bphone, phone, sizeof(bphone) ); // printf("%d: %s\n",atoi(argv[1]), bphone); // // return 0; //}
chewing/chewing-utils
hash-editor/src/key2pho8.c
C
lgpl-2.1
1,768
#ifndef __STDAIR_STDAIR_RM_TYPES_HPP #define __STDAIR_STDAIR_RM_TYPES_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <string> #include <vector> #include <map> // StdAir #include <stdair/stdair_basic_types.hpp> #include <stdair/stdair_inventory_types.hpp> namespace stdair { // Forward declarations. class BookingClass; // //////// Type definitions ///////// /** Mode of the forecaster. */ typedef std::string ForecasterMode_T; /** Limit of similar flight-dates used in the forecaster. */ typedef short HistoricalDataLimit_T; /** Mode of the forecaster. */ typedef std::string OptimizerMode_T; /** Define the demand for a policy. */ typedef NbOfBookings_T PolicyDemand_T; /** Define the vector of generated demand (for MC integration use). <br> It is a vector of double. */ typedef std::vector<double> GeneratedDemandVector_T; /** Define the holder of the generated demand vectors. */ typedef std::vector<GeneratedDemandVector_T> GeneratedDemandVectorHolder_T; /** Define the sellup probability.*/ typedef double SellupProbability_T; /** Define the vector of historical unconstrained demand. */ typedef std::vector<NbOfRequests_T> UncDemVector_T; /** Define the vector of historical bookings. */ typedef std::vector<NbOfBookings_T> BookingVector_T; /** Define the FRAT5 coefficient. */ typedef double FRAT5_T; /** Define the FRAT5 curve. */ typedef std::map<const DTD_T, FRAT5_T> FRAT5Curve_T; /** Define the fare family disutility curve. */ typedef std::map<const DTD_T, double> FFDisutilityCurve_T; /** Define the sell-up factor curve. */ typedef std::map<const DTD_T, double> SellUpCurve_T; /** Define the dispatching factor curve. */ typedef std::map<const DTD_T, double> DispatchingCurve_T; /** Define the map between class and sell-up factor curve. */ typedef std::map<BookingClass*, SellUpCurve_T> BookingClassSellUpCurveMap_T; /** Define the map between class and dispatching factor curve. */ typedef std::map<BookingClass*, DispatchingCurve_T> BookingClassDispatchingCurveMap_T; /** Define the map between the yield of a class and the demand forecast of this class within a policy. */ typedef std::map<const Yield_T, double> YieldDemandMap_T; /** Define the revenue of a policy */ typedef double Revenue_T; /** Define the number of samples for the generated demand of booking class */ typedef unsigned int NbOfSamples_T; } #endif // __STDAIR_STDAIR_RM_TYPES_HPP
airsim/stdair
stdair/stdair_rm_types.hpp
C++
lgpl-2.1
2,633
/* ********************************************************** * Copyright (c) 2012 Google, Inc. All rights reserved. * **********************************************************/ /* Dr. Memory: the memory debugger * * This library 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; * version 2.1 of the License, and no later version. * 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 * Library 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* Tests Windows Handle Leaks */ #ifndef WINDOWS # error Windows-only #endif #include <windows.h> #include <assert.h> #include <stdio.h> #include <process.h> /* for _beginthreadex */ #include <tchar.h> /* for tchar */ #include <strsafe.h> /* for Str* */ #include <tlhelp32.h> static void test_gdi_handles(bool close) { HDC mydc = GetDC(NULL); assert(mydc != NULL); HDC dupdc = CreateCompatibleDC(mydc); assert(dupdc != NULL); HPEN mypen = CreatePen(PS_SOLID, 0xab,RGB(0xab,0xcd,0xef)); assert(mypen != NULL); HBITMAP mybmA = CreateBitmap(30, 30, 1, 16, NULL); assert(mybmA != NULL); HBITMAP mybmB = CreateCompatibleBitmap(dupdc, 30, 30); assert(mybmB != NULL); if (close) { DeleteObject(mybmB); DeleteObject(mybmA); DeleteObject(mypen); DeleteDC(dupdc); ReleaseDC(NULL, mydc); } } static unsigned int WINAPI thread_func(void *arg) { int i; HANDLE hEvent; for (i = 0; i < 10; i++) { hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (hEvent == NULL) { printf("fail to create event\n"); return 0; } CloseHandle(hEvent); } return 0; } static void test_thread_handles(bool close) { unsigned int tid; HANDLE thread; thread = (HANDLE) _beginthreadex(NULL, 0, thread_func, NULL, 0, &tid); thread_func(NULL); WaitForSingleObject(thread, INFINITE); if (close) CloseHandle(thread); } static void test_file_handles(bool close) { // the files' handles HANDLE hFile, dupFile1, dupFile2; HANDLE hFind; // filenames, the file is not there... TCHAR buf[MAX_PATH]; DWORD size; WIN32_FIND_DATA ffd; bool create_file_tested = false; size = GetCurrentDirectory(MAX_PATH, buf); // check size if (size == 0) { printf("fail to get current directory\n"); return; } // append StringCchCat(buf, MAX_PATH, TEXT("\\*")); // find the first file in the directory. hFind = FindFirstFile(buf, &ffd); if (hFind == INVALID_HANDLE_VALUE) { printf("fail to find the first file\n"); return; } // find all the files in the directory do { bool test_done = false; if (!create_file_tested && !(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { hFile = CreateFile(ffd.cFileName, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); create_file_tested = true; if (hFile == INVALID_HANDLE_VALUE) { printf("fail to open the file %s\n", ffd.cFileName); return; } // test DuplicateHandle DuplicateHandle(GetCurrentProcess(), hFile, GetCurrentProcess(), &dupFile1, 0, FALSE, DUPLICATE_SAME_ACCESS); if (dupFile1 == INVALID_HANDLE_VALUE) { printf("fail to duplicate the file handle\n"); return; } // close the handle using DuplicateHandle DuplicateHandle(GetCurrentProcess(), dupFile1, GetCurrentProcess(), &dupFile2, // NULL would cause another leak 0, FALSE, DUPLICATE_CLOSE_SOURCE); if (dupFile2 == INVALID_HANDLE_VALUE) { printf("fail to duplicate the file handle\n"); return; } CloseHandle(dupFile2); if (close) { // test handle leak on syscall DuplicateHandle(GetCurrentProcess(), hFile, GetCurrentProcess(), NULL, // handle leak 0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(hFile); } test_done = true; } if (test_done) break; } while (FindNextFile(hFind, &ffd) != 0); if (GetLastError() != ERROR_NO_MORE_FILES) { printf("fail to find the next file\n"); return; } if (close) FindClose(hFind); } void test_window_handles(bool close) { HWND hWnd; hWnd = CreateWindowEx(0L, // ExStyle "Button", // class name "Main Window", // window name WS_OVERLAPPEDWINDOW, // style CW_USEDEFAULT, CW_USEDEFAULT, // pos CW_USEDEFAULT, CW_USEDEFAULT, // size (HWND) NULL, // no parent (HMENU) NULL, // calls menu (HINSTANCE) NULL, NULL); if (!hWnd) { printf("fail to create window\n"); return; } if (close) { DestroyWindow(hWnd); } } void test_process_handles(bool close) { HANDLE hSnapshot, hProcess; PROCESSENTRY32 pe; BOOL res; hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0); if (hSnapshot == INVALID_HANDLE_VALUE) { printf("CreateToolhelp32Snapshot failed\n"); return; } pe.dwSize = sizeof(pe); for (res = Process32First(hSnapshot, &pe); res; res = Process32Next(hSnapshot, &pe)) { hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID); if (hProcess == INVALID_HANDLE_VALUE) { printf("OpenProcess failed\n"); return; } #ifdef VERBOSE printf("Process %6u: %s\n", pe.th32ProcessID, pe.szExeFile); #endif if (hProcess != 0 && pe.th32ProcessID != 0) /* skip system process */ break; } if (close) { CloseHandle(hProcess); CloseHandle(hSnapshot); } } int main() { printf("test gdi handles\n"); test_gdi_handles(true); // create and close test_gdi_handles(false); // create but not close, error raised printf("test file handles\n"); test_file_handles(true); test_file_handles(false); printf("test thread handles\n"); test_thread_handles(true); test_thread_handles(false); printf("test window handles\n"); test_window_handles(true); test_window_handles(false); printf("test process handles\n"); test_process_handles(true); test_process_handles(false); return 0; }
rnk/drmemory
tests/handle.cpp
C++
lgpl-2.1
7,714
package fr.toss.FF7itemsa; public class itema145 extends FF7itemsabase { public itema145(int id) { super(id); setUnlocalizedName("itema145"); } }
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/FF7itemsa/itema145.java
Java
lgpl-2.1
159
/******************************************************************************* * CogTool Copyright Notice and Distribution Terms * CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * CogTool 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. * * CogTool 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 CogTool; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * CogTool makes use of several third-party components, with the * following notices: * * Eclipse SWT version 3.448 * Eclipse GEF Draw2D version 3.2.1 * * Unless otherwise indicated, all Content made available by the Eclipse * Foundation is provided to you under the terms and conditions of the Eclipse * Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this * Content and is also available at http://www.eclipse.org/legal/epl-v10.html. * * CLISP version 2.38 * * Copyright (c) Sam Steingold, Bruno Haible 2001-2006 * This software is distributed under the terms of the FSF Gnu Public License. * See COPYRIGHT file in clisp installation folder for more information. * * ACT-R 6.0 * * Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere & * John R Anderson. * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * Apache Jakarta Commons-Lang 2.1 * * This product contains software developed by the Apache Software Foundation * (http://www.apache.org/) * * jopt-simple version 1.0 * * Copyright (c) 2004-2013 Paul R. Holser, Jr. * * 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. * * Mozilla XULRunner 1.9.0.5 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The J2SE(TM) Java Runtime Environment version 5.0 * * Copyright 2009 Sun Microsystems, Inc., 4150 * Network Circle, Santa Clara, California 95054, U.S.A. All * rights reserved. U.S. * See the LICENSE file in the jre folder for more information. ******************************************************************************/ package edu.cmu.cs.hcii.cogtool.model; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.xerces.parsers.DOMParser; import org.eclipse.ecf.core.util.Base64; import org.eclipse.swt.graphics.Image; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import edu.cmu.cs.hcii.cogtool.util.GraphicsUtil; import edu.cmu.cs.hcii.cogtool.util.IAttributed; import edu.cmu.cs.hcii.cogtool.util.L10N; import edu.cmu.cs.hcii.cogtool.util.NamedObjectUtil; import edu.cmu.cs.hcii.cogtool.util.NullSafe; import edu.cmu.cs.hcii.cogtool.util.ObjectLoader; /** * Imports designs and demonstrations from an XML File * @author AlexF * Edited by Brett Harris with Importing from an BMML File */ public class ImportCogToolXML { public static final String CURRENT_VERSION = "1"; public static final String COGTOOL_IMPORT_ELT = "cogtoolimport"; public static final String DESIGN_ELT = "design"; public static final String DEVICE_ELT = "device"; public static final String FRAME_ELT = "frame"; public static final String CONTROLS_ELT = "controls"; public static final String CONTROL_ELT = "control"; public static final String HREF_ELT = "href"; public static final String BALSAMIQ_TEXT_ELT = "text"; public static final String MOCKUP_ELT = "mockup"; public static final String DEMONSTRATION_ELT = "demonstration"; public static final String BKG_IMAGE_PATH_ELT = "backgroundImagePath"; public static final String BKG_IMAGE_DATA_ELT = "backgroundImageData"; public static final String ORIGIN_ELT = "topLeftOrigin"; public static final String SPEAKER_TEXT_ELT = "speakerText"; public static final String LISTEN_TIME_SECS_ELT = "listenTimeSecs"; public static final String WIDGET_ELT = "widget"; public static final String ELTGROUP_ELT = "eltGroup"; public static final String ELTNAME_ELT = "elementName"; public static final String KEYBOARD_TRANSITIONS_ELT = "keyboardTransitions"; public static final String VOICE_TRANSITIONS_ELT = "voiceTransitions"; public static final String DISPLAY_LABEL_ELT = "displayLabel"; public static final String AUX_TEXT_ELT = "auxText"; public static final String EXTENT_ELT = "extent"; public static final String TRANSITION_ELT = "transition"; public static final String ACTION_ELT = "action"; public static final String MOUSE_ACTION_ELT = "mouseAction"; public static final String TOUCHSCREEN_ACTION_ELT = "touchscreenAction"; public static final String GRAFFITI_ACTION_ELT = "graffitiAction"; public static final String KEYBOARD_ACTION_ELT = "keyboardAction"; public static final String VOICE_ACTION_ELT = "voiceAction"; public static final String KBD_MODIFIER_ELT = "modifier"; public static final String GESTURES_ELT = "gestures"; public static final String TEXT_ELT = "text"; public static final String DEMO_STEP_ELT = "demonstrationStep"; public static final String ACTION_STEP_ELT = "actionStep"; public static final String KEYBOARD_STEP_ELT = "keyboardActionStep"; public static final String VOICE_STEP_ELT = "voiceActionStep"; public static final String THINK_STEP_ELT = "thinkStep"; public static final String SYS_DELAY_STEP_ELT = "systemDelayStep"; public static final String LOOK_AT_STEP_ELT = "lookAtWidgetStep"; public static final String START_EYE_LOC_ELT = "startingEyePosition"; public static final String START_MOUSE_LOC_ELT = "startingMousePosition"; public static final String START_LEFT_POS_ELT = "startingLeftHandPosition"; public static final String START_RIGHT_POS_ELT = "startingRightHandPosition"; public static final String TASK_ELT = "task"; public static final String TASK_GROUP_ELT = "taskGroup"; public static final String VERSION_ATTR = "version"; public static final String NAME_ATTR = "name"; public static final String TYPE_ATTR = "type"; public static final String PARENT_ATTR = "parent"; public static final String GROUP_ATTR = "group"; public static final String REMOTE_LABEL_ATTR = "remoteLabel"; public static final String CONTROL_TYPE_ATTR = "controlTypeID"; public static final String CONTROL_ID_ATTR = "controlID"; public static final String TASK_GROUP_ID_ATTR = "taskGroupID"; public static final String X_ATTR = "x"; public static final String Y_ATTR = "y"; public static final String WIDTH_ATTR = "width"; public static final String HEIGHT_ATTR = "height"; public static final String MEASURED_WIDTH_ATTR = "measuredW"; public static final String MEASURED_HEIGHT_ATTR = "measuredH"; public static final String SHAPE_ATTR = "shape"; public static final String DEST_FRAME_NAME_ATTR = "destinationFrameName"; public static final String BUTTON_ATTR = "button"; public static final String ACTION_ATTR = "action"; public static final String IS_CMD_ATTR = "is-command"; public static final String TASK_NAME_ATTR = "taskName"; public static final String START_FRAME_NAME_ATTR = "startFrameName"; public static final String HANDEDNESS_ATTR = "handedness"; public static final String TARGET_WIDGET_NAME_ATTR = "targetWidgetName"; public static final String LOOKAT_WIDGET_NAME_ATTR = "lookAtWidgetName"; public static final String DURATION_ATTR = "durationInSecs"; public static final String THINK_LABEL_ATTR = "thinkLabel"; public static final String DELAY_LABEL_ATTR = "delayLabel"; public static final String GROUP_NATURE_ATTR = "displayedGroupSummary"; // General WidgetAttributes attribute names and values // REMEMBER TO ENTER INTO THE REGISTRIES BELOW!!!! public static final String TRUE_VALUE = "true"; public static final String FALSE_VALUE = "false"; public static final String IS_SELECTED_ATTR = "w-is-selected"; public static final String IS_SELECTED_VALUE = TRUE_VALUE; public static final String NOT_SELECTED_VALUE = FALSE_VALUE; public static final String TOGGLE_VALUE = "toggle"; public static final String IS_TOGGLEABLE_ATTR = "w-is-toggleable"; public static final String IS_STANDARD_ATTR = "w-is-standard"; public static final String SELECTION_ATTR = "w-selected-name"; public static final String IS_RENDERED_ATTR = "w-is-rendered"; public static final String IS_SEPARATOR_ATTR = "w-is-separator"; public static final String APPENDED_TEXT_ATTR = "w-appended-text"; public static final String SUBMENU_ACTION_ATTR = "w-submenu-action"; public static final String TAP_VALUE = "tap"; public static final String CLICK_VALUE = "click"; public static final String HOVER_VALUE = "hover"; public static final String SUBMENU_DELAY_ATTR = "w-submenu-delay"; public static final String PC_DELAY_VALUE = "pc-delay"; public static final String NO_DELAY_VALUE = "no-delay"; public static final String CONTEXT_MENU_ACTION_ATTR = "w-menu-action"; public static final String CTRL_LEFT_VALUE = "ctrl-left-click"; public static final String TAP_HOLD_VALUE = "tap-hold"; public static final String MENU_KEY_VALUE = "menu-key"; public static final String RIGHT_CLICK_VALUE = "right-click"; public static final String KEYBOARD_DEVICE = "keyboard"; public static final String MOUSE_DEVICE = "mouse"; public static final String TOUCHSCREEN_DEVICE = "touchscreen"; public static final String MICROPHONE_DEVICE = "microphone"; public static final String DISPLAY_DEVICE = "display"; public static final String SPEAKER_DEVICE = "speaker"; public static final String BUTTON_WIDGETTYPE = "button"; public static final String LINK_WIDGETTYPE = "link"; public static final String CHECKBOX_WIDGETTYPE = "check box"; public static final String RADIO_WIDGETTYPE = "radio button"; public static final String TEXTBOX_WIDGETTYPE = "text box"; public static final String TEXT_WIDGETTYPE = "text"; public static final String PULLDOWNLIST_WIDGETTYPE = "pull-down list"; public static final String PULLDOWNITEM_WIDGETTYPE = "pull-down item"; public static final String LISTBOXITEM_WIDGETTYPE = "list box item"; public static final String CONTEXTMENU_WIDGETTYPE = "context menu"; public static final String MENUHEADER_WIDGETTYPE = "menu"; public static final String SUBMENU_WIDGETTYPE = "submenu"; public static final String MENUITEM_WIDGETTYPE = "menu item"; public static final String GRAFFITI_WIDGETTYPE = "graffiti"; public static final String NONINTERACTIVE_WIDGETTYPE = "non-interactive"; public static final String RECTANGLE_SHAPE = "rectangle"; public static final String ELLIPSE_SHAPE = "ellipse"; public static final String ROUND_RECT_SHAPE = "rounded rectangle"; public static final String LEFT_BUTTON = "left"; public static final String MIDDLE_BUTTON = "middle"; public static final String RIGHT_BUTTON = "right"; public static final String DOWNUP_ACTION = "downUp"; public static final String TAP_ACTION = "tap"; public static final String PRESS_ACTION = "press"; public static final String DOUBLE_ACTION = "double"; public static final String TRIPLE_ACTION = "triple"; public static final String DOWN_ACTION = "down"; public static final String UP_ACTION = "up"; public static final String HOVER_ACTION = "hover"; public static final String SHIFT_MODIFIER = "SHIFT"; public static final String CTRL_MODIFIER = "CTRL"; public static final String ALT_MODIFIER = "ALT"; public static final String COMMAND_MODIFIER = "COMMAND"; public static final String FUNCTION_MODIFIER = "FUNCTION"; public static final String RIGHT_HAND = "right"; public static final String LEFT_HAND = "left"; public static final String FINAL_FRAME_NAME = "FINAL FRAME"; /** * Thrown when the import cannot complete. */ public static class ImportFailedException extends RuntimeException { public ImportFailedException(String msg, Throwable ex) { super(msg, ex); } public ImportFailedException(String msg) { super(msg); } } private static final Map<String, IAttributed.AttributeDefinition<?>> ATTRIBUTE_REGISTRY = new HashMap<String, IAttributed.AttributeDefinition<?>>(); private static final Map<String, Object> VALUE_REGISTRY = new HashMap<String, Object>(); private static IAttributed.AttributeDefinition<?> getAttrDefn(String attr) { return IAttributed.AttributeRegistry.ONLY.getAttributeDefn(attr); } private static void registerAttributes() { ATTRIBUTE_REGISTRY.put(IS_SELECTED_ATTR, getAttrDefn(WidgetAttributes.IS_SELECTED_ATTR)); ATTRIBUTE_REGISTRY.put(IS_TOGGLEABLE_ATTR, getAttrDefn(WidgetAttributes.IS_TOGGLEABLE_ATTR)); ATTRIBUTE_REGISTRY.put(IS_STANDARD_ATTR, getAttrDefn(WidgetAttributes.IS_STANDARD_ATTR)); ATTRIBUTE_REGISTRY.put(SELECTION_ATTR, getAttrDefn(WidgetAttributes.SELECTION_ATTR)); ATTRIBUTE_REGISTRY.put(IS_RENDERED_ATTR, getAttrDefn(WidgetAttributes.IS_RENDERED_ATTR)); ATTRIBUTE_REGISTRY.put(IS_SEPARATOR_ATTR, getAttrDefn(WidgetAttributes.IS_SEPARATOR_ATTR)); ATTRIBUTE_REGISTRY.put(APPENDED_TEXT_ATTR, getAttrDefn(WidgetAttributes.APPENDED_TEXT_ATTR)); ATTRIBUTE_REGISTRY.put(SUBMENU_ACTION_ATTR, getAttrDefn(WidgetAttributes.SUBMENU_ACTION_ATTR)); ATTRIBUTE_REGISTRY.put(SUBMENU_DELAY_ATTR, getAttrDefn(WidgetAttributes.SUBMENU_DELAY_ATTR)); ATTRIBUTE_REGISTRY.put(CONTEXT_MENU_ACTION_ATTR, getAttrDefn(WidgetAttributes.CONTEXT_MENU_ACTION_ATTR)); VALUE_REGISTRY.put(TRUE_VALUE, Boolean.TRUE); VALUE_REGISTRY.put(FALSE_VALUE, Boolean.FALSE); VALUE_REGISTRY.put(TOGGLE_VALUE, WidgetAttributes.TOGGLE_SELECTION); VALUE_REGISTRY.put(TAP_VALUE, WidgetAttributes.TAP_SUBMENU_ACTION); VALUE_REGISTRY.put(CLICK_VALUE, WidgetAttributes.CLICK_SUBMENU_ACTION); VALUE_REGISTRY.put(HOVER_VALUE, WidgetAttributes.HOVER_SUBMENU_ACTION); VALUE_REGISTRY.put(PC_DELAY_VALUE, WidgetAttributes.PC_SUBMENU_DELAY); VALUE_REGISTRY.put(NO_DELAY_VALUE, WidgetAttributes.NO_SUBMENU_DELAY); VALUE_REGISTRY.put(CTRL_LEFT_VALUE, WidgetAttributes.CTRL_LEFT_CLICK); VALUE_REGISTRY.put(TAP_HOLD_VALUE, WidgetAttributes.TAP_HOLD); VALUE_REGISTRY.put(MENU_KEY_VALUE, WidgetAttributes.MENU_KEY_PRESS); VALUE_REGISTRY.put(RIGHT_CLICK_VALUE, WidgetAttributes.RIGHT_CLICK); } private static boolean notInitialized = true; private static void addAttributes(IAttributed attributed, Node node) { addAttributes(attributed, node, null); } private static void addAttributes(IAttributed attributed, Node node, Map<IAttributed, String> pendingAttrSets) { NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { int numAttributes = attributes.getLength(); if (numAttributes > 0) { if (notInitialized) { registerAttributes(); } for (int i = 0; i < numAttributes; i++) { Node attributeNode = attributes.item(i); // Should never be null; sanity check if (attributeNode != null) { String attribute = attributeNode.getNodeName(); IAttributed.AttributeDefinition<?> attrDefn = ATTRIBUTE_REGISTRY.get(attribute); if (attrDefn != null) { String attrName = attrDefn.attrName; String attrNodeValue = attributeNode.getNodeValue(); if (WidgetAttributes.SELECTION_ATTR.equals(attrName)) { // attrNodeValue is name of the selected widget, // but the widget may not exist yet. pendingAttrSets.put(attributed, attrNodeValue); } else if (VALUE_REGISTRY.containsKey(attrNodeValue)) { Object attrValue = VALUE_REGISTRY.get(attrNodeValue); if (! NullSafe.equals(attrValue, attrDefn.defaultValue)) { attributed.setAttribute(attrName, attrValue); } } else { // Assume string value (eg, APPENDED_TEXT_ATTR) attributed.setAttribute(attrName, attrNodeValue); } } } } } } } private String directoryPath = ""; private ObjectLoader objLoader = new ObjectLoader(); // Maps Design to List of Demonstration private Map<Design, Collection<Demonstration>> designs = new LinkedHashMap<Design, Collection<Demonstration>>(); private Set<AUndertaking> newUndertakings = new LinkedHashSet<AUndertaking>(); private Map<String, TaskGroup> taskGroups = new HashMap<String, TaskGroup>(); private List<String> failedObjectErrors = new ArrayList<String>(); private List<String> failedImages = new ArrayList<String>(); private List<String> klmWarnings = new ArrayList<String>(); private CognitiveModelGenerator modelGenerator = null; private String dtdVersion = "0"; private DefaultModelGeneratorState currentState = null; // Maps name to newly created Task private Map<String, List<Task>> createdTaskRegistry = new HashMap<String, List<Task>>(); // Maps file name to image data (byte[]) private Map<String, byte[]> imageRegistry = new HashMap<String, byte[]>(); private Map<String, SimpleWidgetGroup> groupRegistry = new HashMap<String, SimpleWidgetGroup>(); // Image data cache; maps image name to data (byte[]) private Map<String, byte[]> cachedImages = new HashMap<String, byte[]>(); private static ObjectLoader.IObjectLoader<Design> designLoader = Design.getImportLoader(); private static ObjectLoader.IObjectLoader<Frame> frameLoader = Frame.getImportLoader(); private static ObjectLoader.IObjectLoader<Widget> widgetLoader = Widget.getImportLoader(); private static ObjectLoader.IObjectLoader<FrameElementGroup> groupLoader = FrameElementGroup.getImportLoader(); private static boolean inImportFromXML = false; public boolean importXML(File inputFile, TaskParent parent, CognitiveModelGenerator modelGen) throws IOException, SAXException, SecurityException { InputStream fis = null; fis = new FileInputStream(inputFile); boolean result = false; try { Reader input = new InputStreamReader(fis, "UTF-8"); try { result = importXML(input, inputFile.getParent() + File.separator, parent, modelGen); } finally { input.close(); } } finally { fis.close(); } return result; } public boolean importXML(Reader input, String imageDirPath, TaskParent taskParent, CognitiveModelGenerator modelGen) throws IOException, SAXException { modelGenerator = modelGen; // Create a Xerces DOM Parser DOMParser parser = new DOMParser(); // Set the path for loading images directoryPath = imageDirPath; // Parse the Document and traverse the DOM parser.parse(new InputSource(input)); Document document = parser.getDocument(); parseFile(document, taskParent); if (failedImages.size() > 0) { String failedImageString = "Failed to load the following images:"; Iterator<String> fIter = failedImages.iterator(); while (fIter.hasNext()) { failedImageString += System.getProperty("file.separator") + fIter.next(); } throw new GraphicsUtil.ImageException(failedImageString); } return true; } public Map<Design, Collection<Demonstration>> getDesigns() { return designs; } public Set<AUndertaking> getNewUndertakings() { return newUndertakings; } public List<String> getObjectFailures() { return failedObjectErrors; } public List<String> getGenerationWarnings() { return klmWarnings; } private String getAttributeValue(Node node, String attr) { NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { Node attributeNode = attributes.getNamedItem(attr); if (attributeNode != null) { return attributeNode.getNodeValue(); } } return null; } private String getElementText(Node node) { if (node.getFirstChild() != null) { return node.getFirstChild().getNodeValue().trim(); } return ""; } /** * Imports an XML file containing a design * and possibly a demonstration * @param node */ private void parseFile(Node node, TaskParent taskParent) throws IOException { NodeList children = node.getChildNodes(); if (children != null) { if (node.getNodeName().equalsIgnoreCase(COGTOOL_IMPORT_ELT)) { dtdVersion = getAttributeValue(node, VERSION_ATTR); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(TASK_GROUP_ELT)) { parseTaskGroup(child, null); } else if (nodeName.equalsIgnoreCase(TASK_ELT)) { parseTask(child, taskParent); } } for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(DESIGN_ELT)) { parseDesign(child, taskParent); } } } else { for (int i = 0; i < children.getLength(); i++) { parseFile(children.item(i), taskParent); } } } } private void parseTaskGroup(Node node, TaskParent taskParent) { TaskGroup taskGroup = new TaskGroup(getAttributeValue(node, NAME_ATTR), GroupNature.fromString( getAttributeValue(node, GROUP_NATURE_ATTR))); if (taskParent != null) { taskParent.addUndertaking(taskGroup); } else { newUndertakings.add(taskGroup); } taskGroups.put(getAttributeValue(node, TASK_GROUP_ID_ATTR), taskGroup); NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { Node child = children.item(i); String childName = child.getNodeName(); if (childName.equalsIgnoreCase(TASK_GROUP_ELT)) { parseTaskGroup(child, taskGroup); } else if (childName.equalsIgnoreCase(TASK_ELT)) { parseTask(child, taskGroup); } } } private void parseTask(Node node, TaskParent taskParent) { getTask(getAttributeValue(node, NAME_ATTR), null, taskParent); } /** * Imports a design * @param node */ private void parseDesign(Node node, TaskParent taskParent) throws IOException { NodeList children = node.getChildNodes(); if (children != null) { Design design = designLoader.createObject(); List<Demonstration> demonstrations = new ArrayList<Demonstration>(); designLoader.set(design, Design.nameVAR, getAttributeValue(node, NAME_ATTR)); addAttributes(design, node); @SuppressWarnings("unchecked") Collection<DeviceType> deviceTypes = (Collection<DeviceType>) designLoader.createCollection(design, Design.deviceTypesVAR, 1); Collection<?> frames = designLoader.createCollection(design, Design.framesVAR, 1); ObjectLoader.IAggregateLoader deviceTypesLoader = designLoader.getLoader(Design.deviceTypesVAR); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(DEVICE_ELT)) { String device = getElementText(child); if (device.equalsIgnoreCase(KEYBOARD_DEVICE)) { deviceTypesLoader.addToCollection(objLoader, deviceTypes, DeviceType.Keyboard); } else if (device.equalsIgnoreCase(MOUSE_DEVICE)) { deviceTypesLoader.addToCollection(objLoader, deviceTypes, DeviceType.Mouse); } else if (device.equalsIgnoreCase(TOUCHSCREEN_DEVICE)) { deviceTypesLoader.addToCollection(objLoader, deviceTypes, DeviceType.Touchscreen); } else if (device.equalsIgnoreCase(MICROPHONE_DEVICE)) { deviceTypesLoader.addToCollection(objLoader, deviceTypes, DeviceType.Voice); } else if (device.equalsIgnoreCase(DISPLAY_DEVICE)) { deviceTypesLoader.addToCollection(objLoader, deviceTypes, DeviceType.Display); } else if (device.equalsIgnoreCase(SPEAKER_DEVICE)) { deviceTypesLoader.addToCollection(objLoader, deviceTypes, DeviceType.Speaker); } else { // "unknown device" failedObjectErrors.add("Unknown Design device: " + device); } } else if (nodeName.equalsIgnoreCase(FRAME_ELT)) { parseFrame(design, child); // No need to add frame to the design here; done already! } else if (nodeName.equalsIgnoreCase(DEMONSTRATION_ELT)) { Demonstration demo = parseDemonstration(design, child, taskParent); if (demo != null) { demonstrations.add(demo); } } } if ((design.getName() == null) || (deviceTypes.size() == 0) || (frames.size() == 0)) { throw new ImportFailedException("No design found"); } designs.put(design, demonstrations); } } private byte[] loadImage(String relativePath) throws IOException { byte[] loadedImageData = imageRegistry.get(relativePath); if (loadedImageData == null) { loadedImageData = GraphicsUtil.loadImageFromFile(directoryPath + relativePath); if (loadedImageData != null) { imageRegistry.put(relativePath, loadedImageData); } } return loadedImageData; } /** * Imports a frame * @param node */ private Frame parseFrame(Design design, Node node) throws IOException { NodeList children = node.getChildNodes(); if (children != null) { String frameName = getAttributeValue(node, NAME_ATTR); if ((frameName == null) || frameName.equals("")) { failedObjectErrors.add("Cannot create a frame with an empty name."); return null; } // This adds the created frame to the design Frame frame = getFrame(design, frameName); addAttributes(frame, node); Frame.setFrameDevices(frame, design.getDeviceTypes()); TransitionSource keyboardDevice = frame.getInputDevice(DeviceType.Keyboard); TransitionSource voiceDevice = frame.getInputDevice(DeviceType.Voice); // Some widgets have parents; so as not to require that // all widgets of a frame occur in a particular order, we must // resolve the parent names after all widgets have been parsed. // Maps the child widget to the name of its parent Map<ChildWidget, String> pendingParentSets = new LinkedHashMap<ChildWidget, String>(); // Some attributes refer to widget names; must resolve these // after all widgets have been created. // Currently, the only such attribute that applies to widgets // is WidgetAttributes.SELECTION_ATTR // Maps the attributed object to the widget name that is // the value of the WidgetAttributes.SELECTION_ATTR attribute Map<IAttributed, String> pendingAttrSets = new HashMap<IAttributed, String>(); // Some element groups may be referenced as members of other // groups before being defined; this map will hold them Map<String, FrameElementGroup> pendingGrps = new HashMap<String, FrameElementGroup>(); // Some remote labels may not be defined before they're referenced // so keep track of those cases. Maps the owner object to // the name of the remote label Map<FrameElement, String> pendingRemoteLabels = new HashMap<FrameElement, String>(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(BKG_IMAGE_PATH_ELT)) { String backgroundImagePath = getElementText(child); byte[] image = loadImage(backgroundImagePath); if (image != null) { frameLoader.set(frame, Frame.backgroundVAR, image); frame.setAttribute(WidgetAttributes.IMAGE_PATH_ATTR, backgroundImagePath); } } else if (nodeName.equalsIgnoreCase(BKG_IMAGE_DATA_ELT)) { String backgroundImageData = getElementText(child); String imageName = getAttributeValue(child, NAME_ATTR); byte[] image = null; if (backgroundImageData != "") { image = Base64.decode(backgroundImageData); if ((imageName != null) && ! imageName.equals("")) { cachedImages.put(imageName, image); } } else if ((imageName != null) && ! imageName.equals("")) { // If imageName specified but there is no data, trust and // try to find the last image data associated with that // name in the cache. image = cachedImages.get(imageName); } if (image != null) { frameLoader.set(frame, Frame.backgroundVAR, image); if ((imageName != null) && ! imageName.equals("")) { frame.setAttribute(WidgetAttributes.IMAGE_PATH_ATTR, imageName); } } } else if (nodeName.equalsIgnoreCase(ORIGIN_ELT)) { double x = Double.parseDouble(getAttributeValue(child, X_ATTR)); double y = Double.parseDouble(getAttributeValue(child, Y_ATTR)); DoublePoint origin = new DoublePoint(x, y); frameLoader.set(frame, Frame.originVAR, origin); } else if (nodeName.equalsIgnoreCase(SPEAKER_TEXT_ELT)) { frameLoader.set(frame, Frame.speakerTextVAR, getElementText(child)); } else if (nodeName.equalsIgnoreCase(LISTEN_TIME_SECS_ELT)) { frameLoader.set(frame, Frame.listenTimeVAR, Double.parseDouble(getElementText(child))); } else if (nodeName.equalsIgnoreCase(WIDGET_ELT)) { IWidget w = parseWidget(design, frame, pendingParentSets, pendingAttrSets, pendingRemoteLabels, child); if (w != null) { frame.addWidget(w); } else { w = new Widget(null, WidgetType.Noninteractive); Image wImage = GraphicsUtil.getImageFromResource("edu/cmu/cs/hcii/cogtool/resources/warning.jpg"); //w.setImage(wImage.getBytes()); frame.addWidget(w); } } else if (nodeName.equalsIgnoreCase(ELTGROUP_ELT)) { FrameElementGroup g = parseEltGroup(design, frame, pendingGrps, child); if (g != null) { String eltGrpName = g.getName(); pendingGrps.remove(eltGrpName); eltGrpName = NamedObjectUtil.makeNameUnique(eltGrpName, frame.getEltGroups()); g.setName(eltGrpName); frame.addEltGroup(g); } } else if (nodeName.equalsIgnoreCase(KEYBOARD_TRANSITIONS_ELT)) { if (keyboardDevice != null) { parseTransitions(design, keyboardDevice, child); } else { failedObjectErrors.add("Keyboard transitions require that Design have a Keyboard device"); } } else if (nodeName.equalsIgnoreCase(VOICE_TRANSITIONS_ELT)) { if (voiceDevice != null) { parseTransitions(design, voiceDevice, child); } else { failedObjectErrors.add("Voice transitions require that Design have a Voice device"); } } } if (frame.getName() != null) { // Handle any forward references for remote labels Iterator<Map.Entry<FrameElement, String>> labelRefs = pendingRemoteLabels.entrySet().iterator(); while (labelRefs.hasNext()) { Map.Entry<FrameElement, String> labelRef = labelRefs.next(); setRemoteLabel(frame, labelRef.getValue(), labelRef.getKey(), null); } // If any "pending" element groups still exist, then there // is an error -- an element group that didn't exist! Iterator<FrameElementGroup> missingGrps = pendingGrps.values().iterator(); StringBuilder errorMsg = new StringBuilder(); while (missingGrps.hasNext()) { FrameElementGroup missingGrp = missingGrps.next(); errorMsg.append("Missing widget or group, named: "); errorMsg.append(missingGrp.getName()); errorMsg.append(" as member of the following groups: "); Iterator<FrameElementGroup> inGrps = missingGrp.getEltGroups().iterator(); String separator = ""; while (inGrps.hasNext()) { errorMsg.append(separator + inGrps.next().getName()); separator = ", "; } failedObjectErrors.add(errorMsg.toString()); errorMsg.delete(0, errorMsg.length()); } Iterator<Map.Entry<ChildWidget, String>> childToParentSet = pendingParentSets.entrySet().iterator(); // Now that all widgets have been created, set the parent-child // relationships while (childToParentSet.hasNext()) { Map.Entry<ChildWidget, String> childToParent = childToParentSet.next(); String parentName = childToParent.getValue(); if (! "".equals(parentName)) { ChildWidget child = childToParent.getKey(); AParentWidget parent = (AParentWidget) frame.getWidget(parentName); parent.addItem(child); child.setParent(parent); } } Iterator<Map.Entry<IAttributed, String>> selnAttrToSet = pendingAttrSets.entrySet().iterator(); // Now that all widgets have been created, set the attributes // that used widget names as values. while (selnAttrToSet.hasNext()) { Map.Entry<IAttributed, String> selnAttr = selnAttrToSet.next(); String widgetName = selnAttr.getValue(); IWidget attrValue = "".equals(widgetName) ? null : frame.getWidget(widgetName); // At the moment, all occurrences that use pendingAttrSets // are instances of PullDownHeader for // WidgetAttributes.SELECTION_ATTR selnAttr.getKey().setAttribute(WidgetAttributes.SELECTION_ATTR, attrValue); } return frame; } } return null; } // parseFrame /** Helper function used by parseFrame. * This method is used to return the corresponding Frame object for a * given frame name * * @ param frameName the specified frame name */ private Frame getFrame(Design design, String frameName) { if ((frameName != null) && ! frameName.equals("") && ! frameName.equals(FINAL_FRAME_NAME)) { // Fail-fast -- right now, we have only one implementation of // Frame, so this cannot fail. Frame frame = design.getFrame(frameName); if (frame == null) { frame = frameLoader.createObject(); frame.setName(frameName); design.addFrame(frame); } return frame; } return null; } private WidgetType getWidgetType(String widgetType) { if ((widgetType == null) || // TODO: note error, return null on this case? widgetType.equalsIgnoreCase(BUTTON_WIDGETTYPE)) { return WidgetType.Button; } if (widgetType.equalsIgnoreCase(LINK_WIDGETTYPE)) { return WidgetType.Link; } if (widgetType.equalsIgnoreCase(CHECKBOX_WIDGETTYPE)) { return WidgetType.Check; } if (widgetType.equalsIgnoreCase(RADIO_WIDGETTYPE)) { return WidgetType.Radio; } if (widgetType.equalsIgnoreCase(TEXTBOX_WIDGETTYPE)) { return WidgetType.TextBox; } if (widgetType.equalsIgnoreCase(TEXT_WIDGETTYPE)) { return WidgetType.Text; } if (widgetType.equalsIgnoreCase(PULLDOWNLIST_WIDGETTYPE)) { return WidgetType.PullDownList; } if (widgetType.equalsIgnoreCase(PULLDOWNITEM_WIDGETTYPE)) { return WidgetType.PullDownItem; } if (widgetType.equalsIgnoreCase(LISTBOXITEM_WIDGETTYPE)) { return WidgetType.ListBoxItem; } if (widgetType.equalsIgnoreCase(CONTEXTMENU_WIDGETTYPE)) { return WidgetType.ContextMenu; } if (widgetType.equalsIgnoreCase(MENUHEADER_WIDGETTYPE)) { return WidgetType.Menu; } if (widgetType.equalsIgnoreCase(SUBMENU_WIDGETTYPE)) { return WidgetType.Submenu; } if (widgetType.equalsIgnoreCase(MENUITEM_WIDGETTYPE)) { return WidgetType.MenuItem; } if (widgetType.equalsIgnoreCase(GRAFFITI_WIDGETTYPE)) { return WidgetType.Graffiti; } if (widgetType.equalsIgnoreCase(NONINTERACTIVE_WIDGETTYPE)) { return WidgetType.Noninteractive; } failedObjectErrors.add("Unknown widget type: " + widgetType); return null; } /** * Imports a widget * @param node */ private IWidget parseWidget(Design design, Frame frame, Map<ChildWidget, String> pendingParentSets, Map<IAttributed, String> pendingAttrSets, Map<FrameElement, String> pendingRemoteLabels, Node node) throws IOException { NodeList children = node.getChildNodes(); if (children != null) { String isStandardValue = getAttributeValue(node, IS_STANDARD_ATTR); boolean isStandard; if (isStandardValue != null) { Boolean isStandardAttrValue = (Boolean) VALUE_REGISTRY.get(isStandardValue); if (isStandardAttrValue != null) { isStandard = isStandardAttrValue.booleanValue(); } else { isStandard = false; } } else if (CURRENT_VERSION.equals(dtdVersion)) { isStandard = false; } else { isStandard = true; } WidgetType widgetType = getWidgetType(getAttributeValue(node, TYPE_ATTR)); Widget widget = null; if (widgetType != null) { if (isStandard) { if (widgetType == WidgetType.ContextMenu) { // Using this constructor sets up childItems and // childLocation to the only value currently in use widget = new ContextMenu(ContextMenu.FOR_DUPLICATION); } else if (widgetType == WidgetType.Menu) { // Using this constructor sets up childItems and // childLocation to the only value currently in use widget = new MenuHeader(MenuHeader.FOR_DUPLICATION); // Must also find its "anonymous" parentGroup String grpName = getAttributeValue(node, GROUP_ATTR); if ((grpName != null) && ! "".equals(grpName)) { SimpleWidgetGroup menuHdrGroup = groupRegistry.get(grpName); if (menuHdrGroup == null) { menuHdrGroup = new SimpleWidgetGroup(SimpleWidgetGroup.HORIZONTAL); menuHdrGroup.setName(grpName); groupRegistry.put(grpName, menuHdrGroup); } menuHdrGroup.add(widget); } } else if ((widgetType == WidgetType.Submenu) || (widgetType == WidgetType.MenuItem)) { // Must also assign its parent, which must come earlier String parentName = getAttributeValue(node, PARENT_ATTR); if (parentName != null) { MenuItem menuItem = new MenuItem(); // If a submenu, set up childItems and childLocation menuItem.setSubmenu(widgetType == WidgetType.Submenu); pendingParentSets.put(menuItem, parentName); widget = menuItem; } else { widget = widgetLoader.createObject(); } } else if (widgetType == WidgetType.PullDownList) { // Using this constructor sets up childItems and // childLocation to the only value currently in use widget = new PullDownHeader(PullDownHeader.FOR_DUPLICATION); } else if (widgetType == WidgetType.PullDownItem) { // Must assign its parent, which must come earlier String parentName = getAttributeValue(node, PARENT_ATTR); if (parentName != null) { PullDownItem pullDownItem = new PullDownItem(); pendingParentSets.put(pullDownItem, parentName); widget = pullDownItem; } else { widget = widgetLoader.createObject(); } } else if (widgetType == WidgetType.ListBoxItem) { widget = new ListItem(); // Must also find its "anonymous" parentGroup String grpName = getAttributeValue(node, GROUP_ATTR); if ((grpName != null) && ! "".equals(grpName)) { SimpleWidgetGroup listItemGroup = groupRegistry.get(grpName); if (listItemGroup == null) { listItemGroup = new SimpleWidgetGroup(SimpleWidgetGroup.VERTICAL); listItemGroup.setName(grpName); groupRegistry.put(grpName, listItemGroup); } listItemGroup.add(widget); } } else if ((widgetType == WidgetType.Radio) || (widgetType == WidgetType.Check)) { GridButton gridWidget; if (widgetType == WidgetType.Radio) { gridWidget = new RadioButton(); } else { gridWidget = new CheckBox(); } // Fetch the horizontal/vertical spacing attributes double horizontal = Double.parseDouble(getAttributeValue(node, X_ATTR)); double vertical = Double.parseDouble(getAttributeValue(node, Y_ATTR)); gridWidget.setHorizSpace(horizontal); gridWidget.setVertSpace(vertical); // Must also find its "anonymous" parentGroup String grpName = getAttributeValue(node, GROUP_ATTR); if ((grpName != null) && ! "".equals(grpName)) { SimpleWidgetGroup gridWidgetGrp = groupRegistry.get(grpName); if (gridWidgetGrp == null) { if (widgetType == WidgetType.Radio) { gridWidgetGrp = new RadioButtonGroup(); } else { gridWidgetGrp = new GridButtonGroup(); } gridWidgetGrp.setName(grpName); groupRegistry.put(grpName, gridWidgetGrp); } gridWidgetGrp.add(gridWidget); } widget = gridWidget; } else { widget = widgetLoader.createObject(); } } else { widget = widgetLoader.createObject(); } widgetLoader.set(widget, Widget.widgetTypeVAR, widgetType); } else { widget = widgetLoader.createObject(); } String widgetName = getAttributeValue(node, NAME_ATTR); widget.setName(widgetName); String remoteLabelAttr = getAttributeValue(node, REMOTE_LABEL_ATTR); if ((remoteLabelAttr != null) && ! remoteLabelAttr.equals("")) { FrameElement remoteLabelOwner = widget.getRemoteLabelOwner(); if (remoteLabelOwner == null) { failedObjectErrors.add("Attempting to set a remote label on the wrong widget type for: " + widgetName); } else { IWidget existingLabel = (IWidget) remoteLabelOwner.getAttribute(WidgetAttributes.REMOTE_LABEL_ATTR); if (existingLabel == null) { setRemoteLabel(frame, remoteLabelAttr, remoteLabelOwner, pendingRemoteLabels); } else if (! remoteLabelAttr.equals(existingLabel.getName())) { failedObjectErrors.add("Attempting to set a second remote label for the widget: " + widgetName); } } } // For the case that the widget is a RadioButton that // has an is-selected attribute, the setting of that // attribute in this call will, per the override of setAttribute() // in RadioButton, set the proper selected-widget attribute // on the containing widget group. addAttributes(widget, node, pendingAttrSets); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(DISPLAY_LABEL_ELT)) { widgetLoader.set(widget, Widget.titleVAR, getElementText(child)); } else if (nodeName.equalsIgnoreCase(AUX_TEXT_ELT)) { widgetLoader.set(widget, Widget.auxTextVAR, getElementText(child)); } else if (nodeName.equalsIgnoreCase(EXTENT_ELT)) { double x = Double.parseDouble(getAttributeValue(child, X_ATTR)); double y = Double.parseDouble(getAttributeValue(child, Y_ATTR)); double width = Double.parseDouble(getAttributeValue(child, WIDTH_ATTR)); double height = Double.parseDouble(getAttributeValue(child, HEIGHT_ATTR)); DoubleRectangle extent = new DoubleRectangle(x, y, width, height); AShape widgetShape = null; String shapeType = getAttributeValue(node, SHAPE_ATTR); if ((shapeType == null) || shapeType.equalsIgnoreCase(RECTANGLE_SHAPE)) { widgetShape = new ShapeRectangle(extent); } else if (shapeType.equalsIgnoreCase(ELLIPSE_SHAPE)) { widgetShape = new ShapeOval(extent); } else if (shapeType.equalsIgnoreCase(ROUND_RECT_SHAPE)) { widgetShape = new ShapeRoundedRectangle(extent); } else { failedObjectErrors.add("Unknown shape type: " + shapeType); widgetShape = new ShapeRectangle(extent); } if (widgetShape != null) { widgetLoader.set(widget, Widget.shapeVAR, widgetShape); } } else if (nodeName.equalsIgnoreCase(BKG_IMAGE_PATH_ELT)) { String backgroundImagePath = getElementText(child); byte[] image = loadImage(backgroundImagePath); if (image != null) { widgetLoader.set(widget, Widget.widgetImageVAR, image); widget.setAttribute(WidgetAttributes.IMAGE_PATH_ATTR, backgroundImagePath); } } else if (nodeName.equalsIgnoreCase(BKG_IMAGE_DATA_ELT)) { String backgroundImageData = getElementText(child); if (backgroundImageData != "") { byte[] image = Base64.decode(backgroundImageData); widgetLoader.set(widget, Widget.widgetImageVAR, image); String imageName = getAttributeValue(child, NAME_ATTR); if ((imageName != null) && ! imageName.equals("")) { widget.setAttribute(WidgetAttributes.IMAGE_PATH_ATTR, imageName); } } } else if (nodeName.equalsIgnoreCase(TRANSITION_ELT)) { Transition t = parseTransition(design, widget, child); if (t != null) { // TODO Because of the setting of parents is deferred, // this is executed when there may not be any // parents. This results in the curves not being // assigned to the transitions, and is a bug, // ticket #775. The fix is probably to also defer // adding transitions until later? widget.addTransition(t); } } } if ((widget.getName() != null) && (widget.getWidgetType() != null) && (widget.getShape() != null)) { return widget; } } return null; } // parseWidget private void setRemoteLabel(Frame frame, String remoteLabelName, FrameElement labelOwner, Map<FrameElement, String> pendingRemoteLabels) { IWidget remoteLabel = frame.getWidget(remoteLabelName); if (remoteLabel == null) { if (pendingRemoteLabels == null) { failedObjectErrors.add("Missing remote label widget (" + remoteLabelName + ") for element group: " + labelOwner.getName()); } else { pendingRemoteLabels.put(labelOwner, remoteLabelName); } } else if (! remoteLabel.getWidgetType().canBeARemoteLabel()) { failedObjectErrors.add("Disallowed type for remote label: " + remoteLabelName); } else if (remoteLabel instanceof GridButton) { failedObjectErrors.add("Disallowed class for remote label: " + remoteLabelName); } else { labelOwner.setAttribute(WidgetAttributes.REMOTE_LABEL_ATTR, remoteLabel); remoteLabel.setAttribute(WidgetAttributes.REMOTE_LABEL_OWNER_ATTR, labelOwner); remoteLabel.setAttribute(WidgetAttributes.IS_STANDARD_ATTR, WidgetAttributes.IS_CUSTOM); } } private static final String DEFAULT_GROUP_PREFIX = L10N.get("ICT.GroupNamePrefix", "Group"); private FrameElementGroup parseEltGroup(Design design, Frame frame, Map<String, FrameElementGroup> pendingGrps, Node node) { String nameAttr = getAttributeValue(node, NAME_ATTR); if (nameAttr == null) { nameAttr = DEFAULT_GROUP_PREFIX + " [1]"; } FrameElementGroup eltGroup = pendingGrps.get(nameAttr); if (eltGroup == null) { eltGroup = new FrameElementGroup(); } eltGroup.setName(nameAttr); String remoteLabelAttr = getAttributeValue(node, REMOTE_LABEL_ATTR); if ((remoteLabelAttr != null) && ! remoteLabelAttr.equals("")) { setRemoteLabel(frame, remoteLabelAttr, eltGroup, null); } addAttributes(eltGroup, node); NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(ELTNAME_ELT)) { String eltName = getElementText(child); IWidget widget = frame.getWidget(eltName); FrameElement elt = null; if (widget != null) { elt = widget.getRootElement(); } else { SimpleWidgetGroup anonymousParentGroup = groupRegistry.get(eltName); if (anonymousParentGroup != null) { elt = anonymousParentGroup; } else { FrameElementGroup grp = frame.getEltGroup(eltName); // If not found, assume the group will show up later! if (grp == null) { grp = pendingGrps.get(eltName); if (grp == null) { grp = new FrameElementGroup(); grp.setName(eltName); pendingGrps.put(eltName, grp); } } elt = grp; } } eltGroup.add(elt); } else if (nodeName.equalsIgnoreCase(AUX_TEXT_ELT)) { groupLoader.set(eltGroup, Widget.auxTextVAR, getElementText(child)); } } } return eltGroup; } /** * Imports a transition * @param node */ private void parseTransitions(Design design, TransitionSource source, Node node) { NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeName().equalsIgnoreCase(TRANSITION_ELT)) { Transition t = parseTransition(design, source, child); if (t != null) { source.addTransition(t); } } } } } private Transition parseTransition(Design design, TransitionSource source, Node node) { NodeList children = node.getChildNodes(); if (children != null) { String frameName = getAttributeValue(node, DEST_FRAME_NAME_ATTR); Frame destination = (frameName != null) ? getFrame(design, frameName) : null; if (destination != null) { AAction action = null; for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(ACTION_ELT)) { action = parseAction(child); } } if (action != null) { Transition t = new Transition(source, destination, action); String delayDurationAttr = getAttributeValue(node, DURATION_ATTR); if (delayDurationAttr != null) { t.setDelayInfo(Double.parseDouble(delayDurationAttr), getAttributeValue(node, DELAY_LABEL_ATTR)); } addAttributes(t, node); return t; } } } return null; } // parseTransition /** * Imports an action * @param node */ private AAction parseAction(Node node) { NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(MOUSE_ACTION_ELT)) { return parseMouseAction(child); } if (nodeName.equalsIgnoreCase(TOUCHSCREEN_ACTION_ELT)) { return parseTouchscreenAction(child); } if (nodeName.equalsIgnoreCase(GRAFFITI_ACTION_ELT)) { return parseGraffitiAction(child); } if (nodeName.equalsIgnoreCase(KEYBOARD_ACTION_ELT)) { return parseKeyboardAction(child); } if (nodeName.equalsIgnoreCase(VOICE_ACTION_ELT)) { return parseVoiceAction(child); } } } return null; } private AAction parseMouseAction(Node node) { int modifiers = AAction.NONE; NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeName().equalsIgnoreCase(KBD_MODIFIER_ELT)) { modifiers = addKeyboardModifier(modifiers, getElementText(child)); } } } String buttonAttr = getAttributeValue(node, BUTTON_ATTR); String actionAttr = getAttributeValue(node, ACTION_ATTR); MouseButtonState button = null; MousePressType mouseAction = null; if ((actionAttr == null) || actionAttr.equalsIgnoreCase(DOWNUP_ACTION)) { mouseAction = MousePressType.Click; } else if (actionAttr.equalsIgnoreCase(DOUBLE_ACTION)) { mouseAction = MousePressType.Double; } else if (actionAttr.equalsIgnoreCase(TRIPLE_ACTION)) { mouseAction = MousePressType.Triple; } else if (actionAttr.equalsIgnoreCase(DOWN_ACTION)) { mouseAction = MousePressType.Down; } else if (actionAttr.equalsIgnoreCase(UP_ACTION)) { mouseAction = MousePressType.Up; } else if (actionAttr.equalsIgnoreCase(HOVER_ACTION)) { mouseAction = MousePressType.Hover; } else { failedObjectErrors.add("Unknown button action: " + actionAttr); mouseAction = MousePressType.Click; } if (buttonAttr == null) { if (mouseAction != MousePressType.Hover) { button = MouseButtonState.Left; } } else if (buttonAttr.equalsIgnoreCase(LEFT_BUTTON)) { button = MouseButtonState.Left; } else if (buttonAttr.equalsIgnoreCase(MIDDLE_BUTTON)) { button = MouseButtonState.Middle; } else if (buttonAttr.equalsIgnoreCase(RIGHT_BUTTON)) { button = MouseButtonState.Right; } else { failedObjectErrors.add("Unknown button: " + buttonAttr); button = MouseButtonState.Left; } AAction action = new ButtonAction(button, mouseAction, modifiers); addAttributes(action, node); return action; } private AAction parseTouchscreenAction(Node node) { int modifiers = AAction.NONE; NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeName().equalsIgnoreCase(KBD_MODIFIER_ELT)) { modifiers = addKeyboardModifier(modifiers, getElementText(child)); } } } // TODO: currently, we have no place to put the modifiers; fix TapAction! String actionAttr = getAttributeValue(node, ACTION_ATTR); TapPressType tapAction = null; if ((actionAttr == null) || actionAttr.equalsIgnoreCase(TAP_ACTION) || actionAttr.equalsIgnoreCase(DOWNUP_ACTION)) { tapAction = TapPressType.Tap; } else if (actionAttr.equalsIgnoreCase(DOUBLE_ACTION)) { tapAction = TapPressType.DoubleTap; } else if (actionAttr.equalsIgnoreCase(TRIPLE_ACTION)) { tapAction = TapPressType.TripleTap; } else if (actionAttr.equalsIgnoreCase(DOWN_ACTION)) { tapAction = TapPressType.Down; } else if (actionAttr.equalsIgnoreCase(UP_ACTION)) { tapAction = TapPressType.Up; } else if (actionAttr.equalsIgnoreCase(HOVER_ACTION)) { tapAction = TapPressType.Hover; } else { failedObjectErrors.add("Unknown tap action: " + actionAttr); tapAction = TapPressType.Tap; } AAction action = new TapAction(tapAction); addAttributes(action, node); return action; } private boolean isAttributeTRUE(String isAttr, boolean defaultsTRUE) { if (isAttr == null) { return defaultsTRUE; } return isAttr.equalsIgnoreCase("true") || isAttr.equalsIgnoreCase("t") || isAttr.equals("1"); } private AAction parseGraffitiAction(Node node) { NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeName().equalsIgnoreCase(GESTURES_ELT)) { boolean isCommand = isAttributeTRUE(getAttributeValue(node, IS_CMD_ATTR), true); AAction action = new GraffitiAction(getElementText(child), isCommand); addAttributes(action, node); return action; } } } return null; } private KeyPressType getPressType(String type) { if (type != null) { if (type.equalsIgnoreCase(PRESS_ACTION)) { return KeyPressType.Stroke; } if (type.equalsIgnoreCase(UP_ACTION)) { return KeyPressType.Up; } if (type.equalsIgnoreCase(DOWN_ACTION)) { return KeyPressType.Down; } failedObjectErrors.add("Unknown key press type: " + type); } return KeyPressType.Stroke; } private AAction parseKeyboardAction(Node node) { NodeList children = node.getChildNodes(); if (children != null) { String text = null; int modifiers = AAction.NONE; KeyPressType pressType = getPressType(getAttributeValue(node, TYPE_ATTR)); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(TEXT_ELT)) { text = getElementText(child); } // No need to handle modifiers any more; // SPECIAL CHARACTERS ARE USED INSTEAD } if (text != null) { boolean isCommand = isAttributeTRUE(getAttributeValue(node, IS_CMD_ATTR), true); if ((text.length() == 1) && isCommand) { return new KeyAction(text.charAt(0), pressType, modifiers); } AAction action = new KeyAction(text, isCommand, modifiers); addAttributes(action, node); return action; } } return null; } private int addKeyboardModifier(int modifiers, String addModifier) { if (addModifier != null) { if (addModifier.equalsIgnoreCase(SHIFT_MODIFIER)) { return modifiers | AAction.SHIFT; } if (addModifier.equalsIgnoreCase(CTRL_MODIFIER)) { return modifiers | AAction.CTRL; } if (addModifier.equalsIgnoreCase(ALT_MODIFIER)) { return modifiers | AAction.ALT; } if (addModifier.equalsIgnoreCase(COMMAND_MODIFIER)) { return modifiers | AAction.COMMAND; } if (addModifier.equalsIgnoreCase(FUNCTION_MODIFIER)) { return modifiers | AAction.FUNCTION; } failedObjectErrors.add("Unknown keyboard modifier: " + addModifier); } return modifiers; } private AAction parseVoiceAction(Node node) { NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeName().equalsIgnoreCase(TEXT_ELT)) { boolean isCommand = isAttributeTRUE(getAttributeValue(node, IS_CMD_ATTR), true); AAction action = new VoiceAction(getElementText(child), isCommand); addAttributes(action, node); return action; } } } return null; } private Task getTask(String taskName, String taskGroupID, TaskParent parent) { if (taskName != null) { AUndertaking undertaking = null; if (taskGroupID == null) { undertaking = parent.getUndertaking(taskName); } if (undertaking == null) { List<Task> createdTasks = createdTaskRegistry.get(taskName); if (taskGroupID != null) { parent = taskGroups.get(taskGroupID); } if (createdTasks != null) { for (Task t : createdTasks) { TaskGroup tg = t.getTaskGroup(); if (tg == parent || (tg == null && taskGroupID == null)) { return t; } } } else { createdTasks = new ArrayList<Task>(1); createdTaskRegistry.put(taskName, createdTasks); } Task ct = new Task(taskName); if (parent instanceof TaskGroup) { parent.addUndertaking(ct); } else { newUndertakings.add(ct); } createdTasks.add(ct); return ct; } if (undertaking instanceof Task) { return (Task) undertaking; } } return null; } /** * Imports a demonstration * @param node */ private Demonstration parseDemonstration(Design design, Node node, TaskParent taskParent) { if (design == null) { return null; } NodeList children = node.getChildNodes(); if (children == null) { return null; } Task task = getTask(getAttributeValue(node, TASK_NAME_ATTR), getAttributeValue(node, TASK_GROUP_ID_ATTR), taskParent); if (task == null) { failedObjectErrors.add("Cannot create demonstration without a valid task."); return null; } Frame startFrame = getFrame(design, getAttributeValue(node, START_FRAME_NAME_ATTR)); if (startFrame == null) { failedObjectErrors.add("Cannot create a demonstration without a start frame"); return null; } Frame currentFrame = startFrame; TaskApplication taskApp = new TaskApplication(task, design); Demonstration demo = taskApp.getDemonstration(); demo.setStartFrame(startFrame); demo.setStartFrameChosen(true); Script genScript = new Script(demo, modelGenerator); taskApp.setScript(modelGenerator, genScript); // DemoStateManager.trackEdits, adding new tasks to the project, // etc. are the responsibility of the caller. String handAttr = getAttributeValue(node, HANDEDNESS_ATTR); boolean mouseHand = (handAttr == null) || handAttr.equalsIgnoreCase(RIGHT_HAND); demo.setMouseHand(mouseHand); addAttributes(demo, node); // Call this after setting the mouseHand! currentState = demo.getInitialState(); // Actual location for mouse hand might change via child elements for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(START_RIGHT_POS_ELT)) { // Assume touchscreen is akin to mouse for now if (getElementText(child).equalsIgnoreCase(KEYBOARD_DEVICE)) { currentState.setHandLocation(HandLocation.RIGHT_HAND, HandLocation.OnKeyboard); } else { currentState.setHandLocation(HandLocation.RIGHT_HAND, HandLocation.OnMouse); } } else if (nodeName.equalsIgnoreCase(START_LEFT_POS_ELT)) { // Assume touchscreen is akin to mouse for now if (getElementText(child).equalsIgnoreCase(KEYBOARD_DEVICE)) { currentState.setHandLocation(HandLocation.LEFT_HAND, HandLocation.OnKeyboard); } else { currentState.setHandLocation(HandLocation.LEFT_HAND, HandLocation.OnMouse); } } else if (nodeName.equalsIgnoreCase(START_MOUSE_LOC_ELT)) { String attrValue = getAttributeValue(child, X_ATTR); attrValue = getAttributeValue(child, Y_ATTR); } else if (nodeName.equalsIgnoreCase(START_EYE_LOC_ELT)) { String attrValue = getAttributeValue(child, X_ATTR); attrValue = getAttributeValue(child, Y_ATTR); } else if (nodeName.equalsIgnoreCase(DEMO_STEP_ELT)) { AScriptStep demoStep = parseDemoStep(currentFrame, genScript, child); if (demoStep != null) { addAttributes(demoStep, child); demo.appendStep(demoStep); currentFrame = demoStep.getDestinationFrame(); } } } return demo; } // parseDemonstration private void generateAndAppend(AScriptStep step, Script genScript) { try { inImportFromXML = true; currentState = modelGenerator.generateScriptSteps(step, currentState, klmWarnings, genScript.getStepStates()); } finally { inImportFromXML = false; } } public static boolean isInImportFromXML() { return inImportFromXML; } private AScriptStep buildActionStep(TransitionSource src, AAction action, Node node) { if (action != null) { if (src != null) { Transition transition = src.getTransition(action); if (transition != null) { return new TransitionScriptStep(transition); } } ActionScriptStep step = new ActionScriptStep(action, src); String delayDurationAttr = getAttributeValue(node, DURATION_ATTR); double delayDuration = 0.0; if (delayDurationAttr != null) { delayDuration = Double.parseDouble(delayDurationAttr); } step.setDelay(delayDuration, getAttributeValue(node, DELAY_LABEL_ATTR)); return step; } return null; } private AScriptStep parseActionStep(TransitionSource src, Node child) { AAction action = parseAction(child); return buildActionStep(src, action, child); } private AScriptStep parseDemoStep(Frame currentFrame, Script genScript, Node node) { AScriptStep newStep = null; NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String nodeName = child.getNodeName(); if (nodeName.equalsIgnoreCase(ACTION_STEP_ELT)) { String targetWidgetName = getAttributeValue(child, TARGET_WIDGET_NAME_ATTR); if (targetWidgetName != null) { IWidget actionFocus = currentFrame.getWidget(targetWidgetName); newStep = parseActionStep(actionFocus, child); } else { newStep = parseActionStep(null, child); } } else if (nodeName.equalsIgnoreCase(KEYBOARD_STEP_ELT)) { InputDevice kbDevice = currentFrame.getInputDevice(DeviceType.Keyboard); newStep = buildActionStep(kbDevice, parseKeyboardAction(child), child); } else if (nodeName.equalsIgnoreCase(VOICE_STEP_ELT)) { InputDevice voiceDevice = currentFrame.getInputDevice(DeviceType.Voice); newStep = buildActionStep(voiceDevice, parseVoiceAction(child), child); } else if (nodeName.equalsIgnoreCase(THINK_STEP_ELT)) { String duration = getAttributeValue(child, DURATION_ATTR); String thinkLabel = getAttributeValue(child, THINK_LABEL_ATTR); if (thinkLabel == null) { thinkLabel = ThinkScriptStep.DEFAULT_THINK_LABEL; } if (duration != null) { newStep = new ThinkScriptStep(currentFrame, Double.parseDouble(duration), thinkLabel); } } else if (nodeName.equalsIgnoreCase(SYS_DELAY_STEP_ELT)) { String duration = getAttributeValue(child, DURATION_ATTR); String label = getAttributeValue(child, DELAY_LABEL_ATTR); if (label == null) { label = DelayScriptStep.DEFAULT_DELAY_LABEL; } if (duration != null) { newStep = new DelayScriptStep(currentFrame, Double.parseDouble(duration), label); } } else if (nodeName.equalsIgnoreCase(LOOK_AT_STEP_ELT)) { String widgetName = getAttributeValue(child, LOOKAT_WIDGET_NAME_ATTR); if (widgetName != null) { IWidget widget = currentFrame.getWidget(widgetName); if (widget != null) { newStep = new LookAtScriptStep(widget); } } } if (newStep != null) { generateAndAppend(newStep, genScript); return newStep; } } } return null; } }
cogtool/cogtool
java/edu/cmu/cs/hcii/cogtool/model/ImportCogToolXML.java
Java
lgpl-2.1
89,400
/* * Copyright (C) 2014-2016 Red Hat, Inc. * * This library 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. * * 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, see * <http://www.gnu.org/licenses/>. */ #include <config.h> #include "internal.h" #include "viralloc.h" #include "vircommand.h" #include "vircrypto.h" #include "virmock.h" #include "virnetdev.h" #include "virnetdevip.h" #include "virnetdevtap.h" #include "virnetdevopenvswitch.h" #include "virnuma.h" #include "virrandom.h" #include "virscsi.h" #include "virscsivhost.h" #include "virstring.h" #include "virtpm.h" #include "virutil.h" #include "qemu/qemu_interface.h" #include "qemu/qemu_command.h" #include <time.h> #include <unistd.h> #include <fcntl.h> #define VIR_FROM_THIS VIR_FROM_NONE long virGetSystemPageSize(void) { return 4096; } time_t time(time_t *t) { const time_t ret = 1234567890; if (t) *t = ret; return ret; } bool virNumaIsAvailable(void) { return true; } int virNumaGetMaxNode(void) { return 7; } /* We shouldn't need to mock virNumaNodeIsAvailable() and *definitely* not * virNumaNodesetIsAvailable(), but it seems to be the only way to get * mocking to work with Clang on FreeBSD, so keep these duplicates around * until we figure out a cleaner solution */ bool virNumaNodeIsAvailable(int node) { return node >= 0 && node <= virNumaGetMaxNode(); } bool virNumaNodesetIsAvailable(virBitmapPtr nodeset) { ssize_t bit = -1; if (!nodeset) return true; while ((bit = virBitmapNextSetBit(nodeset, bit)) >= 0) { if (virNumaNodeIsAvailable(bit)) continue; return false; } return true; } char * virTPMCreateCancelPath(const char *devpath) { char *path; (void)devpath; ignore_value(VIR_STRDUP(path, "/sys/class/misc/tpm0/device/cancel")); return path; } /** * Large values for memory would fail on 32 bit systems, despite having * variables that support it. */ unsigned long long virMemoryMaxValue(bool capped ATTRIBUTE_UNUSED) { return LLONG_MAX; } char * virSCSIDeviceGetSgName(const char *sysfs_prefix ATTRIBUTE_UNUSED, const char *adapter ATTRIBUTE_UNUSED, unsigned int bus ATTRIBUTE_UNUSED, unsigned int target ATTRIBUTE_UNUSED, unsigned long long unit ATTRIBUTE_UNUSED) { char *ret; ignore_value(VIR_STRDUP(ret, "sg0")); return ret; } int virSCSIVHostOpenVhostSCSI(int *vhostfd) { *vhostfd = STDERR_FILENO + 1; return 0; } int virNetDevTapCreate(char **ifname, const char *tunpath ATTRIBUTE_UNUSED, int *tapfd, size_t tapfdSize, unsigned int flags ATTRIBUTE_UNUSED) { size_t i; for (i = 0; i < tapfdSize; i++) tapfd[i] = STDERR_FILENO + 1 + i; if (STREQ_NULLABLE(*ifname, "mytap0")) { return 0; } else { VIR_FREE(*ifname); return VIR_STRDUP(*ifname, "vnet0"); } } int virNetDevSetMAC(const char *ifname ATTRIBUTE_UNUSED, const virMacAddr *macaddr ATTRIBUTE_UNUSED) { return 0; } int virNetDevExists(const char *ifname) { return STREQ_NULLABLE(ifname, "mytap0"); } int virNetDevIPAddrAdd(const char *ifname ATTRIBUTE_UNUSED, virSocketAddr *addr ATTRIBUTE_UNUSED, virSocketAddr *peer ATTRIBUTE_UNUSED, unsigned int prefix ATTRIBUTE_UNUSED) { return 0; } int virNetDevSetOnline(const char *ifname ATTRIBUTE_UNUSED, bool online ATTRIBUTE_UNUSED) { return 0; } int virNetDevRunEthernetScript(const char *ifname ATTRIBUTE_UNUSED, const char *script ATTRIBUTE_UNUSED) { return 0; } char * virHostGetDRMRenderNode(void) { char *dst = NULL; ignore_value(VIR_STRDUP(dst, "/dev/dri/foo")); return dst; } static void (*real_virCommandPassFD)(virCommandPtr cmd, int fd, unsigned int flags); static const int testCommandPassSafeFDs[] = { 1730, 1731 }; void virCommandPassFD(virCommandPtr cmd, int fd, unsigned int flags) { size_t i; for (i = 0; i < ARRAY_CARDINALITY(testCommandPassSafeFDs); i++) { if (testCommandPassSafeFDs[i] == fd) { if (!real_virCommandPassFD) VIR_MOCK_REAL_INIT(virCommandPassFD); real_virCommandPassFD(cmd, fd, flags); return; } } } int virNetDevOpenvswitchGetVhostuserIfname(const char *path ATTRIBUTE_UNUSED, char **ifname) { return VIR_STRDUP(*ifname, "vhost-user0"); } int qemuInterfaceOpenVhostNet(virDomainDefPtr def ATTRIBUTE_UNUSED, virDomainNetDefPtr net, int *vhostfd, size_t *vhostfdSize) { size_t i; if (!virDomainNetIsVirtioModel(net)) { *vhostfdSize = 0; return 0; } for (i = 0; i < *vhostfdSize; i++) vhostfd[i] = STDERR_FILENO + 42 + i; return 0; } int qemuOpenChrChardevUNIXSocket(const virDomainChrSourceDef *dev ATTRIBUTE_UNUSED) { /* We need to return an FD number for a UNIX listener socket, * which will be given to QEMU via a CLI arg. We need a fixed * number to get stable tests. This is obviously not a real * FD number, so when virCommand closes the FD in the parent * it will get EINVAL, but that's (hopefully) not going to * be a problem.... */ if (fcntl(1729, F_GETFD) != -1) abort(); return 1729; } int qemuBuildTPMOpenBackendFDs(const char *tpmdev ATTRIBUTE_UNUSED, const char *cancel_path ATTRIBUTE_UNUSED, int *tpmfd, int *cancelfd) { if (fcntl(1730, F_GETFD) != -1 || fcntl(1731, F_GETFD) != -1) abort(); *tpmfd = 1730; *cancelfd = 1731; return 0; }
andreabolognani/libvirt
tests/qemuxml2argvmock.c
C
lgpl-2.1
6,506
package codechicken.lib.render; import codechicken.lib.colour.Colour; import codechicken.lib.colour.ColourRGBA; import codechicken.lib.model.CachedFormat; import codechicken.lib.render.buffer.ISpriteAwareVertexBuilder; import codechicken.lib.render.buffer.TransformingVertexBuilder; import codechicken.lib.render.lighting.LC; import codechicken.lib.render.lighting.LightMatrix; import codechicken.lib.render.lighting.PlanarLightModel; import codechicken.lib.render.pipeline.CCRenderPipeline; import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.render.pipeline.IVertexSource; import codechicken.lib.render.pipeline.VertexAttribute; import codechicken.lib.render.pipeline.attribute.*; import codechicken.lib.vec.Matrix4; import codechicken.lib.vec.Vector3; import codechicken.lib.vec.Vertex5; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockDisplayReader; import net.minecraftforge.fluids.FluidStack; /** * The core of the CodeChickenLib render system. * Where possible assign a local var of CCRenderState to avoid millions of calls to instance(); * Uses a ThreadLocal system to assign each thread their own CCRenderState so we can use it in Multithreaded chunk batching. * TODO, proper piping of BakedQuads and CCBakedQuads. */ public class CCRenderState { private static final ThreadLocal<CCRenderState> instances = ThreadLocal.withInitial(CCRenderState::new); //Each attrib needs to be assigned in this order to have a valid operation index. public final VertexAttribute<Vector3[]> normalAttrib = new NormalAttribute(); public final VertexAttribute<int[]> colourAttrib = new ColourAttribute(); public final VertexAttribute<int[]> lightingAttrib = new LightingAttribute(); public final VertexAttribute<int[]> sideAttrib = new SideAttribute(); public final VertexAttribute<LC[]> lightCoordAttrib = new LightCoordAttribute(); //pipeline state public IVertexSource model; public int firstVertexIndex; public int lastVertexIndex; public int vertexIndex; public CCRenderPipeline pipeline; public IVertexBuilder r; public VertexFormat fmt; public CachedFormat cFmt; //context /** * The base color, multiplied by the {@link ColourAttribute} from the bound model if present otherwise used as-is. */ public int baseColour; /** * An override for the alpha colour component. */ public int alphaOverride; /** * Lets the {@link LightMatrix} or {@link PlanarLightModel} know if this {@link CCRenderState} should compute lighting. */ public boolean computeLighting; /** * A standard {@link LightMatrix} instance to be shared on this pipeline. */ public LightMatrix lightMatrix = new LightMatrix(); //vertex outputs public final Vertex5 vert = new Vertex5(); public final Vector3 normal = new Vector3(); public int colour; public int brightness; public int overlay; //attribute storage public int side; public LC lc = new LC(); public TextureAtlasSprite sprite; private CCRenderState() { pipeline = new CCRenderPipeline(this); } public static CCRenderState instance() { return instances.get(); } /** * Bind this {@link CCRenderState} instance to the {@link Tessellator} buffer * and prepare to start drawing vertices for the given <code>mode</code> and {@link VertexFormat}. * * @param mode The GL integer mode. E.g: GL_QUADS, GL_TRIANGLES, and so on. * @param format The {@link VertexFormat}. * @return The {@link BufferBuilder} instance from {@link Tessellator}. */ public BufferBuilder startDrawing(int mode, VertexFormat format) { BufferBuilder r = Tessellator.getInstance().getBuilder(); r.begin(mode, format); bind(r); return r; } /** * Bind this {@link CCRenderState} instance to the given {@link BufferBuilder} * and prepare to start drawing vertices for the given <code>mode</code> and {@link VertexFormat}. * * @param mode The GL integer mode. E.g: GL_QUADS, GL_TRIANGLES, and so on. * @param format The {@link VertexFormat}. * @param buffer The {@link BufferBuilder} to bind to. * @return The same {@link BufferBuilder} that was passed in. */ public BufferBuilder startDrawing(int mode, VertexFormat format, BufferBuilder buffer) { buffer.begin(mode, format); bind(buffer); return buffer; } /** * Bind this {@link CCRenderState} instance to the given {@link BufferBuilder}. * * @param r The {@link BufferBuilder}. */ public void bind(BufferBuilder r) { bind(r, r.getVertexFormat()); } /** * Bind this {@link CCRenderState} to the given {@link IVertexBuilder} and {@link VertexFormat}. * * @param consumer The {@link IVertexBuilder} to bind to. * @param format The {@link VertexFormat} of the {@link IVertexBuilder}. */ public void bind(IVertexBuilder consumer, VertexFormat format) { r = consumer; fmt = format; cFmt = CachedFormat.lookup(format); } /** * Bind this {@link CCRenderState} to the given {@link RenderType}. * * @param renderType The {@link RenderType} to bind to. * @param getter The {@link IRenderTypeBuffer} instance. */ public void bind(RenderType renderType, IRenderTypeBuffer getter) { bind(getter.getBuffer(renderType), renderType.format()); } /** * Bind this {@link CCRenderState} to the given {@link RenderType}, applying * the given MatrixStack. * * @param renderType The {@link RenderType} to bind to. * @param getter The {@link IRenderTypeBuffer} instance. * @param mStack The {@link MatrixStack} to apply. */ public void bind(RenderType renderType, IRenderTypeBuffer getter, MatrixStack mStack) { bind(new TransformingVertexBuilder(getter.getBuffer(renderType), mStack), renderType.format()); } /** * Bind this {@link CCRenderState} to the given {@link RenderType}, applying * the given MatrixStack. * * @param renderType The {@link RenderType} to bind to. * @param getter The {@link IRenderTypeBuffer} instance. * @param mat The {@link Matrix4} to apply. */ public void bind(RenderType renderType, IRenderTypeBuffer getter, Matrix4 mat) { bind(new TransformingVertexBuilder(getter.getBuffer(renderType), mat), renderType.format()); } /** * Resets this {@link CCRenderState} instance's pipeline and internal state. */ public void reset() { model = null; pipeline.reset(); computeLighting = true; colour = baseColour = alphaOverride = -1; } public void preRenderWorld(IBlockDisplayReader world, BlockPos pos) { this.reset(); this.colour = 0xFFFFFFFF; this.setBrightness(world, pos); } public void setPipeline(IVertexOperation... ops) { pipeline.setPipeline(ops); } public void setPipeline(IVertexSource model, int start, int end, IVertexOperation... ops) { pipeline.reset(); setModel(model, start, end); pipeline.setPipeline(ops); } public void bindModel(IVertexSource model) { if (this.model != model) { this.model = model; pipeline.rebuild(); } } public void setModel(IVertexSource source) { setModel(source, 0, source.getVertices().length); } public void setModel(IVertexSource source, int start, int end) { bindModel(source); setVertexRange(start, end); } public void setVertexRange(int start, int end) { firstVertexIndex = start; lastVertexIndex = end; } public void render(IVertexOperation... ops) { setPipeline(ops); render(); } public void render() { Vertex5[] verts = model.getVertices(); for (vertexIndex = firstVertexIndex; vertexIndex < lastVertexIndex; vertexIndex++) { model.prepareVertex(this); vert.set(verts[vertexIndex]); runPipeline(); writeVert(); } } public void runPipeline() { pipeline.operate(); } public void writeVert() { if (r instanceof ISpriteAwareVertexBuilder) { ((ISpriteAwareVertexBuilder) r).sprite(sprite); } ImmutableList<VertexFormatElement> elements = fmt.getElements(); for (int e = 0; e < elements.size(); e++) { VertexFormatElement fmte = elements.get(e); switch (fmte.getUsage()) { case POSITION: r.vertex(vert.vec.x, vert.vec.y, vert.vec.z); break; case UV: int idx = fmte.getIndex(); switch (idx) { case 0: r.uv((float) vert.uv.u, (float) vert.uv.v); break; case 1: r.overlayCoords(overlay); break; case 2: r.uv2(brightness); break; } break; case COLOR: if (r instanceof BufferBuilder && ((BufferBuilder) r).defaultColorSet) { //-_- Fucking mojang.. ((BufferBuilder) r).nextElement(); } else { r.color(colour >>> 24, colour >> 16 & 0xFF, colour >> 8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF); } break; case NORMAL: r.normal((float) normal.x, (float) normal.y, (float) normal.z); break; case PADDING: break; default: throw new UnsupportedOperationException("Generic vertex format element"); } } r.endVertex(); } @Deprecated public void pushColour() { GlStateManager._color4f((colour >>> 24) / 255F, (colour >> 16 & 0xFF) / 255F, (colour >> 8 & 0xFF) / 255F, (alphaOverride >= 0 ? alphaOverride : colour & 0xFF) / 255F); } public void setBrightness(IBlockDisplayReader world, BlockPos pos) { brightness = WorldRenderer.getLightColor(world, world.getBlockState(pos), pos); } public void setBrightness(Entity entity, float frameDelta) { brightness = Minecraft.getInstance().getEntityRenderDispatcher().getPackedLightCoords(entity, frameDelta); } public void setFluidColour(FluidStack fluidStack) { setFluidColour(fluidStack, 0xFF); } public void setFluidColour(FluidStack fluidStack, int alpha) { this.baseColour = fluidStack.getFluid().getAttributes().getColor(fluidStack) << 8 | alpha; } public void setColour(Colour colour) { this.colour = colour.rgba(); } public ColourRGBA getColour() { return new ColourRGBA(colour); } public IVertexBuilder getConsumer() { return r; } public VertexFormat getVertexFormat() { return fmt; } public void draw() { Tessellator.getInstance().end(); } }
TheCBProject/CodeChickenLib
src/main/java/codechicken/lib/render/CCRenderState.java
Java
lgpl-2.1
11,934
/* * StarPU * Copyright (C) Université Bordeaux 1, CNRS 2008-2010 (see AUTHORS file) * * This program 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. * * 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 Lesser General Public License in COPYING.LGPL for more details. */ #include <errno.h> #include <core/workers.h> #include <common/config.h> #include <starpu.h> #include <starpu_cuda.h> #include <drivers/opencl/opencl.h> #if defined(STARPU_USE_CUDA) || defined(STARPU_USE_OPENCL) struct malloc_pinned_codelet_struct { void **ptr; size_t dim; }; #endif //#ifdef STARPU_USE_OPENCL //static void malloc_pinned_opencl_codelet(void *buffers[] __attribute__((unused)), void *arg) //{ // struct malloc_pinned_codelet_struct *s = arg; // // *(s->ptr) = malloc(s->dim); // _starpu_opencl_allocate_memory((void **)(s->ptr), s->dim, CL_MEM_READ_WRITE|CL_MEM_ALLOC_HOST_PTR); //} //#endif #ifdef STARPU_USE_CUDA static void malloc_pinned_cuda_codelet(void *buffers[] __attribute__((unused)), void *arg) { struct malloc_pinned_codelet_struct *s = arg; cudaError_t cures; cures = cudaHostAlloc((void **)(s->ptr), s->dim, cudaHostAllocPortable); if (STARPU_UNLIKELY(cures)) STARPU_CUDA_REPORT_ERROR(cures); } #endif #if defined(STARPU_USE_CUDA)// || defined(STARPU_USE_OPENCL) static struct starpu_perfmodel_t malloc_pinned_model = { .type = STARPU_HISTORY_BASED, .symbol = "malloc_pinned" }; static starpu_codelet malloc_pinned_cl = { .cuda_func = malloc_pinned_cuda_codelet, //#ifdef STARPU_USE_OPENCL // .opencl_func = malloc_pinned_opencl_codelet, //#endif .nbuffers = 0, .model = &malloc_pinned_model }; #endif int starpu_data_malloc_pinned_if_possible(void **A, size_t dim) { if (STARPU_UNLIKELY(!_starpu_worker_may_perform_blocking_calls())) return -EDEADLK; STARPU_ASSERT(A); if (_starpu_may_submit_cuda_task()) { #ifdef STARPU_USE_CUDA int push_res; struct malloc_pinned_codelet_struct s = { .ptr = A, .dim = dim }; malloc_pinned_cl.where = STARPU_CUDA; struct starpu_task *task = starpu_task_create(); task->callback_func = NULL; task->cl = &malloc_pinned_cl; task->cl_arg = &s; task->synchronous = 1; #ifdef STARPU_USE_FXT _starpu_exclude_task_from_dag(task); #endif push_res = starpu_task_submit(task, NULL); STARPU_ASSERT(push_res != -ENODEV); #endif } // else if (_starpu_may_submit_opencl_task()) // { //#ifdef STARPU_USE_OPENCL // int push_res; // // struct malloc_pinned_codelet_struct s = { // .ptr = A, // .dim = dim // }; // // malloc_pinned_cl.where = STARPU_OPENCL; // struct starpu_task *task = starpu_task_create(); // task->callback_func = NULL; // task->cl = &malloc_pinned_cl; // task->cl_arg = &s; // // task->synchronous = 1; // //#ifdef STARPU_USE_FXT // _starpu_exclude_task_from_dag(task); //#endif // // push_res = starpu_task_submit(task, NULL); // STARPU_ASSERT(push_res != -ENODEV); //#endif // } else { *A = malloc(dim); } STARPU_ASSERT(*A); return 0; } #ifdef STARPU_USE_CUDA static void free_pinned_cuda_codelet(void *buffers[] __attribute__((unused)), void *arg) { cudaError_t cures; cures = cudaFreeHost(arg); if (STARPU_UNLIKELY(cures)) STARPU_CUDA_REPORT_ERROR(cures); } #endif //#ifdef STARPU_USE_OPENCL //static void free_pinned_opencl_codelet(void *buffers[] __attribute__((unused)), void *arg) //{ // // free(arg); // int err = clReleaseMemObject(arg); // if (err != CL_SUCCESS) STARPU_OPENCL_REPORT_ERROR(err); //} //#endif #if defined(STARPU_USE_CUDA) // || defined(STARPU_USE_OPENCL) static struct starpu_perfmodel_t free_pinned_model = { .type = STARPU_HISTORY_BASED, .symbol = "free_pinned" }; static starpu_codelet free_pinned_cl = { .cuda_func = free_pinned_cuda_codelet, //#ifdef STARPU_USE_OPENCL // .opencl_func = free_pinned_opencl_codelet, //#endif .nbuffers = 0, .model = &free_pinned_model }; #endif int starpu_data_free_pinned_if_possible(void *A) { if (STARPU_UNLIKELY(!_starpu_worker_may_perform_blocking_calls())) return -EDEADLK; if (_starpu_may_submit_cuda_task()) { #ifdef STARPU_USE_CUDA int push_res; free_pinned_cl.where = STARPU_CUDA; struct starpu_task *task = starpu_task_create(); task->callback_func = NULL; task->cl = &free_pinned_cl; task->cl_arg = A; task->synchronous = 1; #ifdef STARPU_USE_FXT _starpu_exclude_task_from_dag(task); #endif push_res = starpu_task_submit(task, NULL); STARPU_ASSERT(push_res != -ENODEV); #endif } // else if (_starpu_may_submit_opencl_task()) // { //#ifdef STARPU_USE_OPENCL // int push_res; // // free_pinned_cl.where = STARPU_OPENCL; // struct starpu_task *task = starpu_task_create(); // task->callback_func = NULL; // task->cl = &free_pinned_cl; // task->cl_arg = A; // // task->synchronous = 1; // //#ifdef STARPU_USE_FXT // _starpu_exclude_task_from_dag(task); //#endif // // push_res = starpu_task_submit(task, NULL); // STARPU_ASSERT(push_res != -ENODEV); //#endif // } else { free(A); } return 0; }
alucas/StarPU
src/util/malloc.c
C
lgpl-2.1
5,447
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ // File name: Metadata.php // Required path: /lib/core/FutureLink // // Programmer: Robert Plummer // // Purpose: Generates list of pages which have FutureLink connections to a given page. class FutureLink_MetadataAssembler { public $page; public $lang; public $lastModif; public $href; public $websiteTitle; public $moderatorData; public $authorData; public $raw; public $minimumStatisticsNeeded; public $minimumMathNeeded; public $scientificField; public $categories = []; public $keywords; public $questions; public $datePageOriginated; public $countAll; public $language = ''; public $findDatePageOriginated; static $acceptableKeys = [ 'websiteTitle' => true, 'websiteSubtitle' => true, 'moderator' => true, 'moderatorInstitution' => true, 'moderatorProfession' => true, 'hash' => true, 'author' => true, 'authorInstitution' => true, 'authorProfession' => true, "href" => true, 'answers' => true, 'dateLastUpdated' => true, 'dateOriginated' => true, 'language' => true, 'count' => true, 'keywords' => true, 'categories' => true, 'scientificField' => true, 'minimumMathNeeded' => true, 'minimumStatisticsNeeded' => true, 'text' => true ]; function __construct($page) { global $tikilib, $prefs; $this->page = $page; //TODO: abstract $details = $tikilib->fetchAll("SELECT lang, lastModif FROM tiki_pages WHERE pageName = ?", $page); $detail = end($details); $this->lang = (empty($detail['lang']) ? $prefs['site_language'] : $detail['lang']); $this->lastModif = $detail['lastModif']; $this->websiteTitle = $prefs['browsertitle']; $this->href = TikiLib::tikiUrl() . 'tiki-index.php?page=' . $page; } static function fromRawToMetaData($raw) { $me = new FutureLink_Metadata(); $me->websiteTitle = $raw->websiteTitle; $me->websiteSubtitle = $raw->websiteSubtitle; $me->moderator = $raw->moderator; $me->moderatorInstitution = $raw->moderatorInstitution; $me->moderatorProfession = $raw->moderatorProfession; $me->hash = $raw->hash; $me->author = $raw->author; $me->dateLastUpdated = $raw->dateLastUpdated; $me->authorProfession = $raw->authorProfession; $me->href = $raw->href; $me->answers = $raw->answers; $me->dateLastUpdated = $raw->dateLastUpdated; $me->dateOriginated = $raw->dateOriginated; $me->language = $raw->language; $me->count = $raw->countAll; $me->keywords = $raw->keywords; $me->categories = $raw->categories; $me->scientificField = $raw->scientificField; $me->minimumMathNeeded = $raw->minimumMathNeeded; $me->minimumStatisticsNeeded = $raw->minimumStatisticsNeeded; $me->text = $raw->text; return $me; } static function pagePastLink($page, $data) { $me = new FutureLink_MetadataAssembler($page); $me->raw = new FutureLink_Metadata(); $me->raw->websiteTitle = $me->websiteTitle; $me->raw->websiteSubtitle = $me->page; $me->raw->moderator = $me->moderatorName(); $me->raw->moderatorInstitution = $me->moderatorBusinessName(); $me->raw->moderatorProfession = $me->moderatorProfession(); $me->raw->hash = hash_hmac( "md5", JisonParser_Phraser_Handler::superSanitize( $me->raw->author . $me->raw->authorInstitution . $me->raw->authorProfession ), JisonParser_Phraser_Handler::superSanitize($data) ); $me->raw->author = $me->authorName(); $me->raw->authorInstitution = $me->authorBusinessName(); $me->raw->authorProfession = $me->authorProfession(); $me->raw->href = $me->href; $me->raw->answers = $me->answers(); $me->raw->dateLastUpdated = $me->lastModif; $me->raw->dateOriginated = $me->findDatePageOriginated(); $me->raw->language = $me->language(); $me->raw->count = $me->countAll(); $me->raw->keywords = $me->keywords(); $me->raw->categories = $me->categories(); $me->raw->scientificField = $me->scientificField(); $me->raw->minimumMathNeeded = $me->minimumMathNeeded(); $me->raw->minimumStatisticsNeeded = $me->minimumStatisticsNeeded(); $me->raw->text = $data; return $me; } static function pageFutureLink($page) { $me = new FutureLink_MetadataAssembler($page); $me->raw = new FutureLink_Metadata(); $me->raw->websiteTitle = $me->websiteTitle; $me->raw->websiteSubtitle = $me->page; $me->raw->moderator = $me->moderatorName(); $me->raw->moderatorInstitution = $me->moderatorBusinessName(); $me->raw->moderatorProfession = $me->moderatorProfession(); $me->raw->hash = ''; //hash isn't yet known $me->raw->author = $me->authorName(); $me->raw->authorInstitution = $me->authorBusinessName(); $me->raw->authorProfession = $me->authorProfession(); $me->raw->href = $me->href; $me->raw->answers = $me->answers(); $me->raw->dateLastUpdated = $me->lastModif; $me->raw->dateOriginated = $me->findDatePageOriginated(); $me->raw->language = $me->language(); $me->raw->count = $me->countAll(); $me->raw->keywords = $me->keywords(); $me->raw->categories = $me->categories(); $me->raw->scientificField = $me->scientificField(); $me->raw->minimumMathNeeded = $me->minimumMathNeeded(); $me->raw->minimumStatisticsNeeded = $me->minimumStatisticsNeeded(); $me->raw->text = ''; //text isn't yet known return $me; } public function answers() { $answers = []; foreach ($this->questions() as $question) { $answers[] = [ 'question' => strip_tags($question['Value']), 'answer' => '', ]; } return $answers; } public function questions() { if (empty($this->questions)) { $this->questions = (new Tracker_Query('Wiki Attributes')) ->byName() ->filterFieldByValue('Type', 'Question') ->filterFieldByValue('Page', $this->page) ->render(false) ->query(); } return $this->questions; } private function endValue($item, $implodeOn = '') { if (isset($item) && is_array($item)) { $item = end($item); $item = $item['Value']; } if (! empty($implodeOn)) { $item = implode(JisonParser_Phraser_Handler::sanitizeToWords($item), ','); } return $item; } public function keywords($out = true) { if (empty($this->keywords)) { $this->keywords = (new Tracker_Query('Wiki Attributes')) ->byName() ->filterFieldByValue('Type', 'Keywords') ->filterFieldByValue('Page', $this->page) ->render(false) ->query(); } if ($out == true) { return $this->endValue($this->keywords, true); } return $this->keywords; } public function author($version = -1) { global $tikilib; //TODO: abstract if (empty($this->authorData)) { if ($version < 0) { $user = TikiLib::lib('trk')->getOne("SELECT user FROM tiki_pages WHERE pageName = ?", [$this->page]); } else { $user = TikiLib::lib('trk')->getOne("SELECT user FROM tiki_history WHERE pageName = ? AND version = ?", [$this->page, $version]); } if (empty($user)) { return []; } $authorData = (new Tracker_Query("Users")) ->byName() ->filterFieldByValue('login', $user) ->render(false) ->getOne(); $authorData = end($authorData); if (empty($authorData['Name'])) { $authorData['Name'] = $tikilib->get_user_preference($user, "realName"); } $this->authorData = $authorData; } return $this->authorData; } public function authorName() { $author = $this->author(); return (! empty($author['Name']) ? $author['Name'] : ''); } public function authorBusinessName() { $author = $this->author(); return (! empty($author['Business Name']) ? $author['Business Name'] : ''); } public function authorProfession() { $author = $this->author(); return (! empty($author['Profession']) ? $author['Profession'] : ''); } public function moderator() { global $tikilib; if (empty($this->moderatorData)) { //TODO: abstract $moderatorData = (new Tracker_Query("Users")) ->byName() ->filterFieldByValue('login', 'admin') //admin is un-deletable ->render(false) ->getOne(); $moderatorData = end($moderatorData); if (empty($authorData['Name'])) { $moderatorData['Name'] = $tikilib->get_user_preference('admin', "realName"); } $this->moderatorData = $moderatorData; } return $this->moderatorData; } public function moderatorName() { $moderator = $this->moderator(); return (! empty($moderator['Name']) ? $moderator['Name'] : ''); } public function moderatorBusinessName() { $moderator = $this->moderator(); return (! empty($moderator['Business Name']) ? $moderator['Business Name'] : ''); } public function moderatorProfession() { $moderator = $this->moderator(); return (! empty($moderator['Profession']) ? $moderator['Profession'] : ''); } public function findDatePageOriginated() { if (empty($this->findDatePageOriginated)) { $this->findDatePageOriginated = TikiLib::lib('trk')->getOne('SELECT lastModif FROM tiki_history WHERE pageName = ? ORDER BY lastModif DESC', [$this->page]); if (empty($date)) { //page doesn't yet have history $this->findDatePageOriginated = TikiLib::lib('trk')->getOne('SELECT lastModif FROM tiki_pages WHERE pageName = ?', [$this->page]); } } return $this->findDatePageOriginated; } public function countAll() { if (empty($this->countAll)) { $this->countAll = count( (new Tracker_Query('Wiki Attributes')) ->byName() ->filterFieldByValue('Type', 'FutureLink Accepted') ->render(false) ->query() ); } return $this->countAll; } public function categories() { if (empty($this->categories)) { foreach (TikiLib::lib('categ')->get_object_categories('wiki page', $this->page) as $categoryId) { $this->categories[] = TikiLib::lib('categ')->get_category_name($categoryId); } } return $this->categories; } public function scientificField($out = true) { if (empty($this->scientificField)) { //TODO: abstract $this->scientificField = (new Tracker_Query('Wiki Attributes')) ->byName() ->filterFieldByValue('Type', 'Scientific Field') ->filterFieldByValue('Page', $this->page) ->render(false) ->query(); } if ($out == true) { return $this->endValue($this->scientificField, true); } return $this->scientificField; } public function minimumMathNeeded($out = true) { if (empty($this->minimumMathNeeded)) { //TODO: abstract $this->minimumMathNeeded = (new Tracker_Query('Wiki Attributes')) ->byName() ->filterFieldByValue('Type', 'Minimum Math Needed') ->filterFieldByValue('Page', $this->page) ->render(false) ->query(); } if ($out == true) { return $this->endValue($this->minimumMathNeeded, true); } return $this->minimumMathNeeded; } public function minimumStatisticsNeeded($out = true) { if (empty($this->minimumStatisticsNeeded)) { //TODO: abstract $this->minimumStatisticsNeeded = (new Tracker_Query('Wiki Attributes')) ->byName() ->filterFieldByValue('Type', 'Minimum Statistics Needed') ->filterFieldByValue('Page', $this->page) ->render(false) ->query(); } if ($out == true) { return $this->endValue($this->minimumStatisticsNeeded, true); } return $this->minimumStatisticsNeeded; } public function language() { if (empty($this->language)) { //TODO: abstract $langLib = TikiLib::lib('language'); $languages = $langLib->list_languages(); foreach ($languages as $listLanguage) { if ($listLanguage['value'] == $this->lang) { $this->language = urlencode($listLanguage['name']); break; } } } return $this->language; } }
tikiorg/tiki
lib/core/FutureLink/MetadataAssembler.php
PHP
lgpl-2.1
11,741
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): global _p with open(os.devnull, 'w') as devnull: _p = ssubprocess.Popen( ['logger', '-p', 'daemon.notice', '-t', 'sshuttle'], stdin=ssubprocess.PIPE, stdout=devnull, stderr=devnull ) def close_stdin(): sys.stdin.close() def stdout_to_syslog(): sys.stdout.flush() os.dup2(_p.stdin.fileno(), sys.stdout.fileno()) def stderr_to_syslog(): sys.stderr.flush() os.dup2(_p.stdin.fileno(), sys.stderr.fileno())
sshuttle/sshuttle
sshuttle/ssyslog.py
Python
lgpl-2.1
588
require 'yaml' module ReVIEW class I18n ALPHA_U = %w[0 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z].freeze ALPHA_L = %w[0 a b c d e f g h i j k l m n o p q r s t u v w x y z].freeze ROMAN_U = %w[0 I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI XXVII].freeze ROMAN_L = %w[0 i ii iii iv v vi vii viii ix x xi xii xiii xiv xv xvi xvii xviii xix xx xxi xxii xxiii xxiv xxv xxvi xxvii].freeze ALPHA_UW = %w[0 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z].freeze ALPHA_LW = %w[0 a b c d e f g h i j k l m n o p q r s t u v w x y z].freeze ROMAN_UW = %w[0 Ⅰ Ⅱ Ⅲ Ⅳ V Ⅵ Ⅶ Ⅷ Ⅸ X Ⅺ Ⅻ].freeze ARABIC_UW = %w[〇 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27].freeze ARABIC_LW = %w[〇 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27].freeze JAPAN = %w[〇 一 二 三 四 五 六 七 八 九 十 十一 十二 十三 十四 十五 十六 十七 十八 十九 二十 二十一 二十二 二十三 二十四 二十五 二十六 二十七].freeze def self.setup(locale = 'ja', ymlfile = 'locale.yml') @i18n = ReVIEW::I18n.new(locale) lfile = nil if ymlfile lfile = File.expand_path(ymlfile, Dir.pwd) # backward compatibility raise ReVIEW::ConfigError, 'locale.yaml is obsoleted. Please use locale.yml.' if !File.exist?(lfile) && (ymlfile == 'locale.yml') && File.exist?(File.expand_path('locale.yaml', Dir.pwd)) end @i18n.update_localefile(lfile) if lfile && File.file?(lfile) end def self.i18n(*_args) raise NotImplementedError, 'I18n.i18n is obsoleted. Please use I18n.setup(locale, [ymlfile])' end def self.t(str, args = nil) @i18n.t(str, args) end def self.locale=(locale) if @i18n @i18n.locale = locale else I18n.setup(locale) end end class << self alias_method :v, :t ## for EPUBMaker backward compatibility end def self.update(user_i18n, locale = nil) @i18n.update(user_i18n, locale) end def self.get(word, locale = nil) @i18n.get(word, locale) end attr_accessor :locale def initialize(locale = nil) @locale = locale load_default end def load_default load_file(File.expand_path('i18n.yml', File.dirname(__FILE__))) end def load_file(path) @store = YAML.load_file(path) end def update_localefile(path) user_i18n = YAML.load_file(path) locale = user_i18n['locale'] if locale user_i18n.delete('locale') if @store[locale] @store[locale].merge!(user_i18n) else @store[locale] = user_i18n end else user_i18n.each do |key, values| raise KeyError, "Invalid locale file: #{path}" unless values.is_a? Hash @store[key].merge!(values) end end end def update(user_i18n, locale = nil) locale ||= @locale if @store[locale] @store[locale].merge!(user_i18n) else @store[locale] = user_i18n end end def get(word, locale = nil) locale ||= @locale @store[locale][word] end def t(str, args = nil) frmt = @store[@locale][str].dup frmt.gsub!('%%', '##') unless args.is_a?(Array) args = args.nil? && frmt !~ /\%/ ? [] : [args] end percents = frmt.scan(/%[A-Za-z]{1,3}/) remove_args = [] percents.each_with_index do |i, idx| case i when '%pA' frmt.sub!(i, ALPHA_U[args[idx]]) remove_args << idx when '%pa' frmt.sub!(i, ALPHA_L[args[idx]]) remove_args << idx when '%pAW' frmt.sub!(i, ALPHA_UW[args[idx]]) remove_args << idx when '%paW' frmt.sub!(i, ALPHA_LW[args[idx]]) remove_args << idx when '%pR' frmt.sub!(i, ROMAN_U[args[idx]]) remove_args << idx when '%pr' frmt.sub!(i, ROMAN_L[args[idx]]) remove_args << idx when '%pRW' frmt.sub!(i, ROMAN_UW[args[idx]]) remove_args << idx when '%pJ' frmt.sub!(i, JAPAN[args[idx]]) remove_args << idx when '%pdW' frmt.sub!(i, ARABIC_LW[args[idx]]) remove_args << idx when '%pDW' frmt.sub!(i, ARABIC_UW[args[idx]]) remove_args << idx end end remove_args.reverse_each do |idx| args.delete_at idx end args_matched = (frmt.count('%') <= args.size) frmt.gsub!('##', '%%') args_matched ? (frmt % args) : frmt rescue str end end end
krororo/review
lib/review/i18n.rb
Ruby
lgpl-2.1
4,986
/* * Copyright (c) Codice Foundation * * This 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 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 * Lesser General Public License for more details. A copy of the GNU Lesser General Public License * is distributed along with this program and can be found at * <http://www.gnu.org/licenses/lgpl.html>. * */ package org.codice.imaging.nitf.core.tre.impl; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import static javax.xml.bind.DatatypeConverter.parseHexBinary; import org.codice.imaging.nitf.core.common.NitfFormatException; import org.codice.imaging.nitf.core.tre.Tre; import org.codice.imaging.nitf.core.tre.TreGroup; import org.junit.Test; /** * Tests for parsing MTIMSA. * * This is defined in NGA.STND.0044 1.1, as part of MIE4NITF. See Section 5.9.4.7 and Table 17. */ public class MTIMSA_Test extends SharedTreTest { public MTIMSA_Test() { } @Test public void SimpleParse() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write("MTIMSA0015300199fa238862-73ed-41fc-8d52-bfc7a954428c00295cb5511-7350-479b-9c8a-f028aba01e840000030045.0000000E+0100000000620160716215756.012345678".getBytes(StandardCharsets.ISO_8859_1)); baos.write(parseHexBinary("0000000001312D00")); baos.write(parseHexBinary("01")); baos.write(parseHexBinary("01020304")); baos.write(parseHexBinary("00000001")); baos.write(parseHexBinary("4e")); Tre mtimsa = doParseAndCheckResults(baos); assertEquals(1, mtimsa.getIntValue("DT_SIZE")); assertEquals(16909060, mtimsa.getIntValue("NUMBER_FRAMES")); assertEquals(1, mtimsa.getIntValue("NUMBER_DT")); TreGroup deltaTimes = mtimsa.getEntry("DELTA_TIME").getGroups().get(0); assertEquals(1, deltaTimes.getEntries().size()); assertEquals(78, deltaTimes.getIntValue("DT")); } @Test public void Uint64Parse() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write("MTIMSA0016000199fa238862-73ed-41fc-8d52-bfc7a954428c00295cb5511-7350-479b-9c8a-f028aba01e840000030045.0000000E+0100000000620160716215756.012345678".getBytes(StandardCharsets.ISO_8859_1)); baos.write(parseHexBinary("0000000001312D00")); baos.write(parseHexBinary("08")); baos.write(parseHexBinary("01020304")); baos.write(parseHexBinary("00000001")); baos.write(parseHexBinary("7ffffffffffffffe")); Tre mtimsa = doParseAndCheckResults(baos); assertEquals(8, mtimsa.getLongValue("DT_SIZE")); assertEquals(16909060, mtimsa.getLongValue("NUMBER_FRAMES")); assertEquals(1, mtimsa.getLongValue("NUMBER_DT")); TreGroup deltaTimes = mtimsa.getEntry("DELTA_TIME").getGroups().get(0); assertEquals(1, deltaTimes.getEntries().size()); assertEquals(0x7FFFFFFFFFFFFFFEL, deltaTimes.getLongValue("DT")); } private Tre doParseAndCheckResults(ByteArrayOutputStream baos) throws NitfFormatException, IOException { Tre mtimsa = parseTRE(baos.toByteArray(), baos.toByteArray().length, "MTIMSA"); assertEquals(15, mtimsa.getEntries().size()); assertEquals("001", mtimsa.getFieldValue("IMAGE_SEG_INDEX")); assertEquals("99", mtimsa.getFieldValue("GEOCOORDS_STATIC")); assertEquals("fa238862-73ed-41fc-8d52-bfc7a954428c", mtimsa.getFieldValue("LAYER_ID")); assertEquals("002", mtimsa.getFieldValue("CAMERA_SET_INDEX")); assertEquals("95cb5511-7350-479b-9c8a-f028aba01e84", mtimsa.getFieldValue("CAMERA_ID")); assertEquals("000003", mtimsa.getFieldValue("TIME_INTERVAL_INDEX")); assertEquals("004", mtimsa.getFieldValue("TEMP_BLOCK_INDEX")); assertEquals("5.0000000E+01", mtimsa.getFieldValue("NOMINAL_FRAME_RATE")); assertEquals(50.0, mtimsa.getDoubleValue("NOMINAL_FRAME_RATE"), 0.000000001); assertEquals("000000006", mtimsa.getFieldValue("REFERENCE_FRAME_NUM")); assertEquals("20160716215756.012345678", mtimsa.getFieldValue("BASE_TIMESTAMP")); assertEquals(20000000, mtimsa.getIntValue("DT_MULTIPLIER")); return mtimsa; } }
codice/imaging-nitf
core/src/test/java/org/codice/imaging/nitf/core/tre/impl/MTIMSA_Test.java
Java
lgpl-2.1
4,636
/* * (C) 2001 Clemson University and The University of Chicago * * See COPYING in top-level directory. */ #ifndef __DBPF_OPEN_CACHE_H__ #define __DBPF_OPEN_CACHE_H__ #include <db.h> #include "trove.h" #include "trove-internal.h" enum open_cache_open_type { DBPF_FD_BUFFERED_READ = 1, DBPF_FD_BUFFERED_WRITE, DBPF_FD_DIRECT_READ, DBPF_FD_DIRECT_WRITE }; struct open_cache_ref { int fd; enum open_cache_open_type type; void* internal; /* pointer to underlying data structure */ }; void dbpf_open_cache_initialize(void); void dbpf_open_cache_finalize(void); int dbpf_open_cache_get( TROVE_coll_id coll_id, TROVE_handle handle, enum open_cache_open_type type, struct open_cache_ref* out_ref); void dbpf_open_cache_put( struct open_cache_ref* in_ref); int dbpf_open_cache_remove( TROVE_coll_id coll_id, TROVE_handle handle); #endif /* __DBPF_OPEN_CACHE_H__ */ /* * Local variables: * c-indent-level: 4 * c-basic-offset: 4 * End: * * vim: ts=8 sts=4 sw=4 expandtab */
sumitn/pvfs
src/io/trove/trove-dbpf/dbpf-open-cache.h
C
lgpl-2.1
1,043
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: guitartab.svg Example File (demos/mobile/guitartuner/images/guitartab.svg)</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">guitartab.svg Example File</h1> <span class="small-subtitle">demos/mobile/guitartuner/images/guitartab.svg</span> <!-- $$$demos/mobile/guitartuner/images/guitartab.svg-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt; &lt;!-- Created with Inkscape (http://www.inkscape.org/) --&gt; &lt;svg xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:cc=&quot;http://creativecommons.org/ns#&quot; xmlns:rdf=&quot;http://www.w3.org/1999/02/22-rdf-syntax-ns#&quot; xmlns:svg=&quot;http://www.w3.org/2000/svg&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:sodipodi=&quot;http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd&quot; xmlns:inkscape=&quot;http://www.inkscape.org/namespaces/inkscape&quot; width=&quot;70.661781&quot; height=&quot;55.997791&quot; id=&quot;svg2&quot; version=&quot;1.1&quot; inkscape:version=&quot;0.47 r22583&quot; sodipodi:docname=&quot;guitartab.svg&quot;&gt; &lt;defs id=&quot;defs4&quot;&gt; &lt;inkscape:perspective sodipodi:type=&quot;inkscape:persp3d&quot; inkscape:vp_x=&quot;0 : 526.18109 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_z=&quot;744.09448 : 526.18109 : 1&quot; inkscape:persp3d-origin=&quot;372.04724 : 350.78739 : 1&quot; id=&quot;perspective10&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3604&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3632&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3632-4&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3632-9&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3632-8&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3632-2&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3690&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;inkscape:perspective id=&quot;perspective3712&quot; inkscape:persp3d-origin=&quot;0.5 : 0.33333333 : 1&quot; inkscape:vp_z=&quot;1 : 0.5 : 1&quot; inkscape:vp_y=&quot;0 : 1000 : 0&quot; inkscape:vp_x=&quot;0 : 0.5 : 1&quot; sodipodi:type=&quot;inkscape:persp3d&quot; /&gt; &lt;/defs&gt; &lt;sodipodi:namedview id=&quot;base&quot; pagecolor=&quot;#ffffff&quot; bordercolor=&quot;#666666&quot; borderopacity=&quot;1.0&quot; inkscape:pageopacity=&quot;0.0&quot; inkscape:pageshadow=&quot;2&quot; inkscape:zoom=&quot;0.98994949&quot; inkscape:cx=&quot;343.43632&quot; inkscape:cy=&quot;198.00574&quot; inkscape:document-units=&quot;px&quot; inkscape:current-layer=&quot;layer1&quot; showgrid=&quot;false&quot; inkscape:window-width=&quot;1280&quot; inkscape:window-height=&quot;888&quot; inkscape:window-x=&quot;-4&quot; inkscape:window-y=&quot;-4&quot; inkscape:window-maximized=&quot;1&quot; showguides=&quot;true&quot; inkscape:guide-bbox=&quot;true&quot; borderlayer=&quot;true&quot; /&gt; &lt;metadata id=&quot;metadata7&quot;&gt; &lt;rdf:RDF&gt; &lt;cc:Work rdf:about=&quot;&quot;&gt; &lt;dc:format&gt;image/svg+xml&lt;/dc:format&gt; &lt;dc:type rdf:resource=&quot;http://purl.org/dc/dcmitype/StillImage&quot; /&gt; &lt;dc:title /&gt; &lt;/cc:Work&gt; &lt;/rdf:RDF&gt; &lt;/metadata&gt; &lt;g inkscape:label=&quot;Layer 1&quot; inkscape:groupmode=&quot;layer&quot; id=&quot;layer1&quot; transform=&quot;translate(-45.793001,-702.07386)&quot;&gt; &lt;rect style=&quot;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:1.96666431;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0&quot; id=&quot;rect3728&quot; width=&quot;68.695114&quot; height=&quot;54.031128&quot; x=&quot;46.776333&quot; y=&quot;703.05719&quot; /&gt; &lt;g id=&quot;g3732&quot; transform=&quot;matrix(0.11166616,0,0,0.11166616,41.003771,673.42071)&quot;&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816&quot; d=&quot;m 133.63811,570.46864 0,-225.36571&quot; style=&quot;fill:none;stroke:#000000;stroke-width:17.61199951;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816-7&quot; d=&quot;m 223.89631,570.46864 0,-225.36571&quot; style=&quot;fill:none;stroke:#000000;stroke-width:17.61199951;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816-0&quot; d=&quot;m 314.15451,570.46864 0,-225.36571&quot; style=&quot;fill:none;stroke:#000000;stroke-width:17.61199951;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816-4&quot; d=&quot;m 404.4127,570.46864 0,-225.36571&quot; style=&quot;fill:none;stroke:#000000;stroke-width:17.61199951;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816-8&quot; d=&quot;m 494.6709,570.46864 0,-225.36571&quot; style=&quot;fill:none;stroke:#000000;stroke-width:17.61199951;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816-45&quot; d=&quot;m 584.92911,570.46864 0,-225.36571&quot; style=&quot;fill:none;stroke:#000000;stroke-width:17.61199951;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816-5&quot; d=&quot;m 124.89988,344.21478 468.77277,0&quot; style=&quot;fill:none;stroke:#000000;stroke-width:19.51578331;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;path sodipodi:nodetypes=&quot;cc&quot; id=&quot;path2816-5-1&quot; d=&quot;m 125.76355,400.6818 467.80305,0&quot; style=&quot;fill:none;stroke:#000000;stroke-width:19.4955883;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none&quot; /&gt; &lt;/g&gt; &lt;/g&gt; &lt;/svg&gt;</pre> </div> <!-- @@@demos/mobile/guitartuner/images/guitartab.svg --> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
kobolabs/qt-everywhere-4.8.0
doc/html/demos-mobile-guitartuner-images-guitartab-svg.html
HTML
lgpl-2.1
10,793
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <head> <meta http-equiv=Content-Type content="text/html; charset=iso-8859-1"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 10"> <meta name=Originator content="Microsoft Word 10"> <link rel=File-List href="header_files/filelist.xml"> <link rel=Edit-Time-Data href="header_files/editdata.mso"> <!--[if !mso]> <style> v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--> <title>Main Page</title> <!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Author>Randy Ribler</o:Author> <o:Template>Normal</o:Template> <o:LastAuthor>Randy Ribler</o:LastAuthor> <o:Revision>6</o:Revision> <o:TotalTime>16</o:TotalTime> <o:Created>2004-07-23T05:34:00Z</o:Created> <o:LastSaved>2004-07-23T06:03:00Z</o:LastSaved> <o:Pages>1</o:Pages> <o:Words>5</o:Words> <o:Characters>32</o:Characters> <o:Company>LC</o:Company> <o:Lines>1</o:Lines> <o:Paragraphs>1</o:Paragraphs> <o:CharactersWithSpaces>36</o:CharactersWithSpaces> <o:Version>10.2625</o:Version> </o:DocumentProperties> </xml><![endif]--><!--[if gte mso 9]><xml> <w:WordDocument> <w:SpellingState>Clean</w:SpellingState> <w:GrammarState>Clean</w:GrammarState> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--> <link rel=Stylesheet type="text/css" media=all href=RM_stylesheet.css> <style> <!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; mso-believe-normal-left:yes;} h1 {mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; text-align:center; mso-pagination:widow-orphan; mso-outline-level:1; font-size:24.0pt; font-family:"Times New Roman"; font-weight:bold;} h2 {mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; mso-outline-level:2; font-size:18.0pt; font-family:"Times New Roman"; font-weight:bold;} a:link, span.MsoHyperlink {color:#252E78; text-decoration:underline; text-underline:single;} a:visited, span.MsoHyperlinkFollowed {color:#3D2185; text-decoration:underline; text-underline:single;} p {mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} address {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; font-style:italic;} pre {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt; font-size:10.0pt; font-family:"Courier New"; mso-fareast-font-family:"Times New Roman";} p.formuladsp, li.formuladsp, div.formuladsp {mso-style-name:formuladsp; mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; text-align:center; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} p.mdtable, li.mdtable, div.mdtable {mso-style-name:mdtable; mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; background:#F4F4FB; border:none; mso-border-alt:solid #868686 .75pt; padding:0in; mso-padding-alt:0in 0in 0in 0in; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} p.mdrow, li.mdrow, div.mdrow {mso-style-name:mdrow; mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} p.mdescleft, li.mdescleft, div.mdescleft {mso-style-name:mdescleft; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; background:#FAFAFA; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; font-style:italic;} p.mdescright, li.mdescright, div.mdescright {mso-style-name:mdescright; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; background:#FAFAFA; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; font-style:italic;} p.memitemleft, li.memitemleft, div.memitemleft {mso-style-name:memitemleft; margin:3.0pt; mso-pagination:widow-orphan; background:#FAFAFA; border:none; mso-border-top-alt:solid #E0E0E0 .75pt; padding:0in; mso-padding-alt:1.0pt 0in 0in 0in; font-size:9.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} p.memitemright, li.memitemright, div.memitemright {mso-style-name:memitemright; margin:3.0pt; mso-pagination:widow-orphan; background:#FAFAFA; border:none; mso-border-top-alt:solid #E0E0E0 .75pt; padding:0in; mso-padding-alt:1.0pt 0in 0in 0in; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} p.search, li.search, div.search {mso-style-name:search; mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; font-weight:bold;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} --> </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman";} table.MsoTableGrid {mso-style-name:"Table Grid"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; border:solid windowtext 1.0pt; mso-border-alt:solid windowtext .5pt; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-border-insideh:.5pt solid windowtext; mso-border-insidev:.5pt solid windowtext; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman";} </style> <![endif]--><![if mso 9]> <style> p.MsoNormal {margin-left:15.0pt;} </style> <![endif]><!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="4098"> <o:colormru v:ext="edit" colors="#060"/> <o:colormenu v:ext="edit" strokecolor="#060"/> </o:shapedefaults></xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1"/> </o:shapelayout></xml><![endif]--> </head> <body bgcolor=white lang=EN-US link="#252E78" vlink="#3D2185" style='tab-interval: .5in;margin-left:15.0pt;margin-right:15.0pt'> <div class=Section1> <p class=MsoNormal style='margin-top:0in;margin-right:15.0pt;margin-bottom: 0in;margin-left:15.0pt;margin-bottom:.0001pt'><!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="_x0000_s1026" type="#_x0000_t75" style='position:absolute; left:0;text-align:left;margin-left:30pt;margin-top:9pt;width:72.75pt;height:57.75pt; z-index:1'> <v:imagedata src="header_files/image001.jpg" o:title="NCSAlogo"/> </v:shape><![endif]--><![if !vml]><span style='mso-ignore:vglayout;position: absolute;z-index:1;left:0px;margin-left:40px;margin-top:12px;width:97px; height:77px'><img width=97 height=77 src="header_files/image002.jpg" v:shapes="_x0000_s1026"></span><![endif]><span style='mso-spacerun:yes'> </span><b style='mso-bidi-font-weight:normal'><span style='font-size:22.0pt'><o:p></o:p></span></b></p> <div align=center> <table class=MsoTableGrid border=1 cellspacing=0 cellpadding=0 style='margin-left:103.45pt;border-collapse:collapse;border:none;mso-border-bottom-alt: solid #006600 2.25pt;mso-yfti-tbllook:480;mso-padding-alt:0in 5.4pt 0in 5.4pt'> <tr style='mso-yfti-irow:0;mso-yfti-lastrow:yes;height:29.25pt'> <td width=443 valign=top style='width:332.6pt;border:none;border-bottom:solid #006600 2.25pt; padding:0in 5.4pt 0in 5.4pt;height:29.25pt'> <p class=MsoNormal><b style='mso-bidi-font-weight:normal'><span style='font-size:22.0pt'>HDF5 C++ API Reference Manual</span></b></p> </td> </tr> </table> </div> <p class=MsoNormal><o:p>&nbsp;</o:p></p> <p class=MsoNormal><o:p>&nbsp;</o:p></p> <p class=MsoNormal><o:p>&nbsp;</o:p></p> </div> </body> </html> <!-- Generated by Doxygen 1.3.9.1 --> <div class="qindex"><a class="qindex" href="index.html">Main&nbsp;Page</a> | <a class="qindex" href="namespaces.html">Namespace List</a> | <a class="qindex" href="hierarchy.html">Class&nbsp;Hierarchy</a> | <a class="qindex" href="annotated.html">Class&nbsp;List</a> | <a class="qindex" href="files.html">File&nbsp;List</a> | <a class="qindex" href="functions.html">Class&nbsp;Members</a> | <a class="qindex" href="globals.html">File&nbsp;Members</a> | <a class="qindex" href="examples.html">Examples</a></div> <h1>H5Attribute.cpp File Reference</h1><code>#include &lt;iostream&gt;</code><br> <code>#include &lt;string&gt;</code><br> <code>#include "<a class="el" href="H5Include_8h-source.html">H5Include.h</a>"</code><br> <code>#include "<a class="el" href="H5Exception_8h-source.html">H5Exception.h</a>"</code><br> <code>#include "<a class="el" href="H5IdComponent_8h-source.html">H5IdComponent.h</a>"</code><br> <code>#include "<a class="el" href="H5PropList_8h-source.html">H5PropList.h</a>"</code><br> <code>#include "<a class="el" href="H5Object_8h-source.html">H5Object.h</a>"</code><br> <code>#include "<a class="el" href="H5AbstractDs_8h-source.html">H5AbstractDs.h</a>"</code><br> <code>#include "<a class="el" href="H5Attribute_8h-source.html">H5Attribute.h</a>"</code><br> <code>#include "<a class="el" href="H5DcreatProp_8h-source.html">H5DcreatProp.h</a>"</code><br> <code>#include "<a class="el" href="H5CommonFG_8h-source.html">H5CommonFG.h</a>"</code><br> <code>#include "<a class="el" href="H5DataType_8h-source.html">H5DataType.h</a>"</code><br> <code>#include "<a class="el" href="H5DataSpace_8h-source.html">H5DataSpace.h</a>"</code><br> <code>#include "H5private.h"</code><br> <table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Namespaces</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">namespace &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceH5.html">H5</a></td></tr> </table> <hr size="1"><address style="align: right;"><small>Generated on Tue Aug 14 13:56:59 2007 by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.3.9.1 </small></address> </body> </html>
einon/affymetrix-power-tools
external/hdf5/doc/html/cpplus_RM/H5Attribute_8cpp.html
HTML
lgpl-2.1
13,166
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.web.cache.session; import java.time.Duration; import java.time.Instant; import java.util.concurrent.atomic.AtomicBoolean; /** * @author Paul Ferraro */ public class SimpleSessionCreationMetaData implements SessionCreationMetaData { private final Instant creationTime; private volatile Duration maxInactiveInterval = Duration.ZERO; private final AtomicBoolean valid = new AtomicBoolean(true); public SimpleSessionCreationMetaData() { this(Instant.now()); } public SimpleSessionCreationMetaData(Instant creationTime) { this.creationTime = creationTime; } @Override public Instant getCreationTime() { return this.creationTime; } @Override public Duration getMaxInactiveInterval() { return this.maxInactiveInterval; } @Override public void setMaxInactiveInterval(Duration duration) { this.maxInactiveInterval = duration; } @Override public boolean isValid() { return this.valid.get(); } @Override public boolean invalidate() { return this.valid.compareAndSet(true, false); } }
wildfly-clustering/wildfly-clustering-web-hotrod
src/main/java/org/wildfly/clustering/web/cache/session/SimpleSessionCreationMetaData.java
Java
lgpl-2.1
2,184
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- template designed by Marco Von Ballmoos --> <title>Docs for page State.php</title> <link rel="stylesheet" href="../media/stylesheet.css" /> <script src="../media/lib/classTree.js"></script> <script language="javascript" type="text/javascript"> var imgPlus = new Image(); var imgMinus = new Image(); imgPlus.src = "../media/images/plus.png"; imgMinus.src = "../media/images/minus.png"; function showNode(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; var oImg = document.layers["img" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; var oImg = document.all["img" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); var oImg = document.getElementById("img" + Node); break; } oImg.src = imgMinus.src; oTable.style.display = "block"; } function hideNode(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; var oImg = document.layers["img" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; var oImg = document.all["img" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); var oImg = document.getElementById("img" + Node); break; } oImg.src = imgPlus.src; oTable.style.display = "none"; } function nodeIsVisible(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); break; } return (oTable && oTable.style.display == "block"); } function toggleNodeVisibility(Node){ if (nodeIsVisible(Node)){ hideNode(Node); }else{ showNode(Node); } } </script> </head> <body> <div class="page-body"> <h2 class="file-name"><img src="../media/images/Page_logo.png" alt="File" style="vertical-align: middle">/Gdata/YouTube/Extension/State.php</h2> <a name="sec-description"></a> <div class="info-box"> <div class="info-box-title">Description</div> <div class="nav-bar"> <span class="disabled">Description</span> | <a href="#sec-classes">Classes</a> | <a href="#sec-includes">Includes</a> </div> <div class="info-box-body"> <!-- ========== Info from phpDoc block ========= --> <p class="short-description">Zend Framework</p> <p class="description"><p>LICENSE</p><p>This source file is subject to the new BSD license that is bundled with this package in the file LICENSE.txt. It is also available through the world-wide-web at this URL: http://framework.zend.com/license/new-bsd If you did not receive a copy of the license and are unable to obtain it through the world-wide-web, please send an email to license@zend.com so we can send you a copy immediately.</p></p> <ul class="tags"> <li><span class="field">copyright:</span> Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)</li> <li><span class="field">license:</span> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a></li> </ul> </div> </div> <a name="sec-classes"></a> <div class="info-box"> <div class="info-box-title">Classes</div> <div class="nav-bar"> <a href="#sec-description">Description</a> | <span class="disabled">Classes</span> | <a href="#sec-includes">Includes</a> </div> <div class="info-box-body"> <table cellpadding="2" cellspacing="0" class="class-table"> <tr> <th class="class-table-header">Class</th> <th class="class-table-header">Description</th> </tr> <tr> <td style="padding-right: 2em; vertical-align: top; white-space: nowrap"> <img src="../media/images/Class.png" alt=" class" title=" class"/> <a href="../Zend_Gdata/Zend_Gdata_YouTube_Extension_State.html">Zend_Gdata_YouTube_Extension_State</a> </td> <td> Represents the yt:state element used by the YouTube data API </td> </tr> </table> </div> </div> <a name="sec-includes"></a> <div class="info-box"> <div class="info-box-title">Includes</div> <div class="nav-bar"> <a href="#sec-description">Description</a> | <a href="#sec-classes">Classes</a> | <span class="disabled">Includes</span> </div> <div class="info-box-body"> <a name="_Zend/Gdata/Extension_php"><!-- --></a> <div class="evenrow"> <div> <img src="../media/images/Page.png" alt=" " /> <span class="include-title"> <span class="include-type">require_once</span> (<span class="include-name">'Zend/Gdata/Extension.php'</span>) (line <span class="line-number">25</span>) </span> </div> <!-- ========== Info from phpDoc block ========= --> <ul class="tags"> <li><span class="field">see:</span> <a href="../Zend_Gdata/Zend_Gdata_Extension.html">Zend_Gdata_Extension</a></li> </ul> </div> </div> </div> <p class="notes" id="credit"> Documentation generated on Thu, 15 May 2008 05:38:01 -0700 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.2</a> </p> </div></body> </html>
JojoCMS-Plugins/jojo_gcal
external/ZendGdata-1.5.2/documentation/api/core/Zend_Gdata/_Gdata---YouTube---Extension---State.php.html
HTML
lgpl-2.1
6,264
/* * ///////////////////////////////////////////////////////////////////////////// * // This file is part of the "Hyrax Data Server" project. * // * // * // Copyright (c) 2013 OPeNDAP, Inc. * // Author: Nathan David Potter <ndp@opendap.org> * // * // This library 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. * // * // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * // * // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. * ///////////////////////////////////////////////////////////////////////////// */ package opendap.xml; import net.sf.saxon.s9api.*; import opendap.io.HyraxStringEncoding; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.jdom.transform.XSLTransformer; import org.slf4j.Logger; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.util.Date; import java.util.HashMap; /** * User: ndp * Date: Apr 23, 2008 * Time: 9:22:11 AM */ public class Transformer { private static Logger log; static { log = org.slf4j.LoggerFactory.getLogger(Transformer.class); } private Processor proc; private Serializer serializer; private XsltTransformer transform; private Date cacheTime; private String xsltDoc; private DocumentBuilder builder; private Transformer(){ proc = null; serializer = null; transform = null; cacheTime = null; xsltDoc = null; builder = null; } public Transformer(String xsltDocument) throws SaxonApiException { this(); proc = new Processor(false); xsltDoc = xsltDocument; init(proc, new StreamSource(xsltDoc)); } public Transformer(Processor proc, String xsltDocument) throws SaxonApiException { this(); xsltDoc = xsltDocument; init(proc, new StreamSource(xsltDoc)); } public Transformer(StreamSource xsltDocStream) throws SaxonApiException { this(); proc = new Processor(false); init(proc, xsltDocStream); } private void init(Processor processor,StreamSource xsltDocument) throws SaxonApiException { proc = processor; // Get an XSLT processor and serializer serializer = new Serializer(); serializer.setOutputProperty(Serializer.Property.METHOD, "xml"); serializer.setOutputProperty(Serializer.Property.INDENT, "yes"); builder = getDocumentBuilder(); loadTransform(xsltDocument); } public XdmNode build(java.io.File file ) throws SaxonApiException { return builder.build(file); } public XdmNode build(javax.xml.transform.Source source) throws SaxonApiException { return builder.build(source); } public DocumentBuilder getDocumentBuilder() { DocumentBuilder builder = proc.newDocumentBuilder(); builder.setLineNumbering(true); return builder; } public void reloadTransformIfRequired() throws SaxonApiException { if(xsltDoc!=null){ File f = new File(xsltDoc); if(f.lastModified()>cacheTime.getTime()){ loadTransform(new StreamSource(xsltDoc)); } } } private void loadTransform(StreamSource xsltDocStream) throws SaxonApiException{ // Get an XSLT compiler with our transform in it. XsltCompiler comp = proc.newXsltCompiler(); XsltExecutable exp = comp.compile(xsltDocStream); transform = exp.load(); // loads the transform file. cacheTime = new Date(); } public Processor getProcessor(){ return proc; } public void setProcessor(Processor processor){ proc = processor; } public Serializer getSerializer() { return serializer; } public void setSource(Source s) throws SaxonApiException { transform.setSource(s); } public void setOutputStream(OutputStream os){ serializer.setOutputStream(os); transform.setDestination(serializer); } public Destination getDestination(){ return transform.getDestination(); } public void setDestination(Destination destination){ transform.setDestination(destination); } public void setDestination(Transformer destination){ transform.setDestination(destination.getCurrentTransform()); } /* Unused method, dumping. ndp - 09/14/2015 public void transform(Source inputDocumentSource, StreamSource transformDocumentSource, OutputStream os) throws SaxonApiException { // Transformer t = new Transformer(transformDocumentSource); serializer.setOutputStream(os); transform.setSource(inputDocumentSource); transform.setDestination(serializer); transform.transform(); } */ public static ByteArrayInputStream transform(Source inputDocumentSource, StreamSource transformDocumentSource) throws SaxonApiException { Transformer t = new Transformer(transformDocumentSource); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(inputDocumentSource,baos); return new ByteArrayInputStream(baos.toByteArray()); } public static Document getTransformedDocument(Source inputDocumentSource, StreamSource transformDocumentSource) throws SaxonApiException, IOException, JDOMException { Transformer t = new Transformer(transformDocumentSource); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(inputDocumentSource,baos); SAXBuilder sb = new SAXBuilder(); Document result = sb.build(new ByteArrayInputStream(baos.toByteArray())); log.debug("Transform complete."); return result; } public XPathCompiler newXPathCompiler(){ return proc.newXPathCompiler(); } public void transform(XdmNode doc, OutputStream os) throws SaxonApiException { serializer.setOutputStream(os); transform.setInitialContextNode(doc); transform.setDestination(serializer); transform.transform(); } public void transform(Source s, OutputStream os) throws SaxonApiException { serializer.setOutputStream(os); transform.setSource(s); transform.setDestination(serializer); transform.transform(); } public void transform() throws SaxonApiException { transform.transform(); } public void transform(Source s) throws SaxonApiException { transform.setSource(s); transform.transform(); } public InputStream transform(String inputDocumentUrl) throws SaxonApiException { StreamSource s = new StreamSource(inputDocumentUrl); ByteArrayOutputStream os = new ByteArrayOutputStream(); serializer.setOutputStream(os); transform.setSource(s); transform.setDestination(serializer); transform.transform(); ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray()); log.debug("Transformed document is "+os.size()+" bytes."); return bis; } public Document getTransformedDocument(Source inputDocumentSource) throws SaxonApiException, IOException, JDOMException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); log.debug("getTransformedDocument() - Transforming..."); transform(inputDocumentSource, baos); log.debug("getTransformedDocument() - Transform completed."); SAXBuilder sb = new SAXBuilder(); Document result = sb.build(new ByteArrayInputStream(baos.toByteArray())); log.debug("getTransformedDocument() - Docuemtn built."); return result; } private HashMap<QName,XdmValue> currentParameters = new HashMap<QName,XdmValue>(); public void setParameter(QName name, XdmValue value){ currentParameters.put(name,value); transform.setParameter(name,value); } public void clearParameter(String name) throws SaxonApiException { QName qname = new QName(name); setParameter(qname, null); currentParameters.remove(qname); } public void clearAllParameters() { QName qname; for (QName qName : currentParameters.keySet()) { qname = qName; setParameter(qname, null); } currentParameters.clear(); } public void setParameter(Element param) throws SaxonApiException { Document doc = new Document(); doc.setRootElement(param); XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); ByteArrayInputStream reader = new ByteArrayInputStream(xmlo.outputString(doc).getBytes(HyraxStringEncoding.getCharset())); log.debug("Serialized Parameter: \n{}\n",reader.toString()); XdmNode valueNode = build(new StreamSource(reader)); setParameter(new QName(param.getName()), valueNode); } public void setParameter(String name, String value) throws SaxonApiException { // Build the remoteHost parameter to pass into the XSLT String nodeString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; nodeString += "<"+name+">" + value + "</"+name+">"; ByteArrayInputStream reader = new ByteArrayInputStream(nodeString.getBytes(HyraxStringEncoding.getCharset())); XdmNode valueNode = build(new StreamSource(reader)); // Pass the remoteHost parameter setParameter(new QName(name), valueNode); } public void setParameter(String name, XdmNode value) throws SaxonApiException { setParameter(new QName(name), value); } public void setImportXMLParameter(String name, String importFile) throws SaxonApiException { // Build the remoteHost parameter to pass into the XSLT String nodeString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; nodeString += "<"+name+" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" >" + "<xsl:import href=\""+ importFile +"\" />" + "SMOOTCHYSMOOTCHYWOO"+ "</"+name+">"; ByteArrayInputStream reader = new ByteArrayInputStream(nodeString.getBytes(HyraxStringEncoding.getCharset())); XdmNode valueNode = build(new StreamSource(reader)); // Pass the remoteHost parameter setParameter(new QName(name), valueNode); } public static void printUsage(PrintStream ps) { ps.println("\n"); ps.println("Usage:"); ps.println(" "+Transformer.class.getName()+" SourceXmlURI XSLTransformURI"); ps.println("\n"); } public static void main(String args[]) { try { if (args.length != 2) { Transformer.printUsage(System.err); System.exit(-1); } jdomXsltTransform(args[0], args[1], System.out); saxonXsltTransform(args[0], args[1], System.out); } catch (Exception e) { e.printStackTrace(System.err); } } public static void jdomXsltTransform(String srcDocUri, String xslDocUri, OutputStream os) throws Exception { XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); // Element e = new Element("test"); // char c = 0x18; // e.setText("Here is that bad thing: "+c); // System.out.println(xmlo.outputString(e)); Document sourceDoc, xsltDoc; log.debug("jdomXsltTransform() - Loading source document "+srcDocUri); sourceDoc = getXMLDoc(srcDocUri); if(sourceDoc==null){ String msg = "FAILED to get source document! srcDocUri: "+srcDocUri; log.error("jdomXsltTransform() - {}",msg); throw new IOException(msg); } log.debug("jdomXsltTransform() - Got and parsed XML document: "+srcDocUri); log.debug(xmlo.outputString(sourceDoc)); log.debug("jdomXsltTransform() - Loading transform document "+srcDocUri); xsltDoc = getXMLDoc(xslDocUri); log.debug("jdomXsltTransform() - Got and parsed XSL document: "+xslDocUri); log.debug(xmlo.outputString(xsltDoc)); log.debug("jdomXsltTransform() - Applying transform..."); XSLTransformer transformer = new XSLTransformer(xsltDoc); log.debug("jdomXsltTransform() - Transformer is an instance of "+transformer.getClass().getName()); Document result = transformer.transform(sourceDoc); if(result==null){ String msg = "FAILED to get result document from transform! srcDocUri: "+srcDocUri+" xsltDocUri: "+xslDocUri; log.error("jdomXsltTransform() - {}",msg); throw new IOException(msg); } xmlo.output(result, os); log.debug(xmlo.outputString(result)); } public XsltTransformer getCurrentTransform(){ return transform; } public static Document getXMLDoc(String s) throws Exception{ // get a validating jdom parser to parse and validate the XML document. SAXBuilder parser = new SAXBuilder("org.apache.xerces.parsers.SAXParser", false); parser.setFeature("http://apache.org/xml/features/validation/schema", false); Document doc; if(s.startsWith("http://")){ log.debug("Appears to be a URL: "+s); GetMethod request = new GetMethod(s); InputStream is=null; try { HttpClient httpClient = new HttpClient(); // Execute the method. int statusCode = httpClient.executeMethod(request); if (statusCode == HttpStatus.SC_OK || statusCode==HttpStatus.SC_ACCEPTED) { is = request.getResponseBodyAsStream(); doc = parser.build(is); } else { log.error("HttpClient failed to executeMethod(). Status: " + request.getStatusLine()); doc = null; } return doc; } finally { if(is!=null) is.close(); log.debug("Releasing Http connection."); request.releaseConnection(); } } else { File file = new File(s); if(!file.exists()){ throw new IOException("Cannot find file: "+ s); } if(!file.canRead()){ throw new IOException("Cannot read file: "+ s); } FileInputStream fis = null; try { fis = new FileInputStream(file); doc = parser.build(fis); } finally { if(fis!=null){ fis.close(); } } return doc; } } /* private static String getXSLTImpl(){ String str = "SystemProperty javax.xml.transform.TransformerFactory: \n"; try { String impl = System.getProperty("javax.xml.transform.TransformerFactory"); if(impl!=null){ Class classDefinition = Class.forName(impl); javax.xml.transform.TransformerFactory s = (javax.xml.transform.TransformerFactory) classDefinition.newInstance(); str += " TransformerFactory class = "+s.getClass().getName() +"\n"; str += " Transformer class = "+s.newTransformer().getClass().getName()+"\n"; } else { str += " Java System Property Not Set.\n"; } } catch(Exception e){ e.printStackTrace(System.serializer); System.exit(1); } return str; } */ private static void saxonXsltTransform(String srcDocUri, String xslTransformUri, OutputStream os) throws IOException, SaxonApiException { log.debug("Performing transform using Saxon"); Processor proc = new Processor(false); XsltTransformer trans = Transformer.getXsltTransformer(proc, xslTransformUri); if(trans==null){ String msg = "FAILED to get XsltTransformer instance! srcDocUri: "+srcDocUri+" xslTransformUri: "+xslTransformUri; log.error("saxonXsltTransform() - {}",msg); throw new IOException(msg); } XdmNode source = Transformer.getXdmNode(proc,srcDocUri); Serializer out = new Serializer(); out.setOutputProperty(Serializer.Property.METHOD, "xml"); out.setOutputProperty(Serializer.Property.INDENT, "yes"); out.setOutputStream(os); trans.setInitialContextNode(source); trans.setDestination(out); trans.transform(); os.write(0x0a); log.debug("Output written to: "+os); } public static XdmNode getElementAsXdmNode(Processor proc, Element src) throws IOException, SaxonApiException { XdmNode result; ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLOutputter xmlo = new XMLOutputter(Format.getCompactFormat()); xmlo.output(src,baos); return proc.newDocumentBuilder().build(new StreamSource(new ByteArrayInputStream(baos.toByteArray()))); } public static XdmNode getXdmNode(Processor proc, String srcDocUri) throws IOException, SaxonApiException { XdmNode source; if(srcDocUri.startsWith("http://")){ log.debug("Appears to be a URL: "+srcDocUri); GetMethod request = new GetMethod(srcDocUri); InputStream is = null; try { HttpClient httpClient = new HttpClient(); // Execute the method. int statusCode = httpClient.executeMethod(request); if (statusCode != HttpStatus.SC_OK) { log.error("HttpClient failed to executeMethod(). Status: " + request.getStatusLine()); source = null; } else { is = request.getResponseBodyAsStream(); source = proc.newDocumentBuilder().build(new StreamSource(is)); } return source; } finally { if(is!=null) is.close(); log.debug("Releasing Http connection."); request.releaseConnection(); } } else { File file = new File(srcDocUri); if(!file.exists()){ throw new IOException("Cannot find file: "+ srcDocUri); } if(!file.canRead()){ throw new IOException("Cannot read file: "+ srcDocUri); } source = proc.newDocumentBuilder().build(new StreamSource(file)); return source; } } private static XsltTransformer getXsltTransformer(Processor proc, String xslTransformUri) throws IOException, SaxonApiException { XsltCompiler comp = proc.newXsltCompiler(); XsltExecutable exp; XsltTransformer trans; if(xslTransformUri.startsWith("http://")){ log.debug("Appears to be a URL: "+xslTransformUri); GetMethod request = new GetMethod(xslTransformUri); InputStream is = null; try { HttpClient httpClient = new HttpClient(); // Execute the method. int statusCode = httpClient.executeMethod(request); if (statusCode != HttpStatus.SC_OK) { log.error("HttpClient failed to executeMethod(). Status: " + request.getStatusLine()); trans = null; } else { is = request.getResponseBodyAsStream(); exp = comp.compile(new StreamSource(is)); trans = exp.load(); } return trans; } finally { if(is!=null) is.close(); log.debug("Releasing Http connection."); request.releaseConnection(); } } else { File file = new File(xslTransformUri); if(!file.exists()){ throw new IOException("Cannot find file: "+ xslTransformUri); } if(!file.canRead()){ throw new IOException("Cannot read file: "+ xslTransformUri); } exp = comp.compile(new StreamSource(file)); trans = exp.load(); return trans; } } }
OPENDAP/olfs
src/opendap/xml/Transformer.java
Java
lgpl-2.1
21,609
<!DOCTYPE html> <html class="theme-next pisces use-motion" lang="zh-Hans"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/> <meta http-equiv="Cache-Control" content="no-transform" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta name="google-site-verification" content="gycD6xI_8qOHMtIBar00dPigFZBFUR072ImOIf55Qcc" /> <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" /> <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" /> <link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" /> <meta name="keywords" content="Hexo, NexT" /> <link rel="alternate" href="/atom.xml" title="张召的个人博客" type="application/atom+xml" /> <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" /> <meta name="description" content="认识自己,改变自己"> <meta property="og:type" content="website"> <meta property="og:title" content="张召的个人博客"> <meta property="og:url" content="http://zsilence.github.io/tags/段子/index.html"> <meta property="og:site_name" content="张召的个人博客"> <meta property="og:description" content="认识自己,改变自己"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="张召的个人博客"> <meta name="twitter:description" content="认识自己,改变自己"> <script type="text/javascript" id="hexo.configurations"> var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Pisces', sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false,"onmobile":false}, fancybox: true, motion: true, duoshuo: { userId: '0', author: '博主' }, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"} } }; </script> <link rel="canonical" href="http://zsilence.github.io/tags/段子/"/> <title>标签: 段子 | 张召的个人博客</title> </head> <body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"> <div class="container sidebar-position-right "> <div class="headband"></div> <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"> <div class="header-inner"><div class="site-brand-wrapper"> <div class="site-meta "> <div class="custom-logo-site-title"> <a href="/" class="brand" rel="start"> <span class="logo-line-before"><i></i></span> <span class="site-title">张召的个人博客</span> <span class="logo-line-after"><i></i></span> </a> </div> <p class="site-subtitle">记录成长</p> </div> <div class="site-nav-toggle"> <button> <span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span> </button> </div> </div> <nav class="site-nav"> <ul id="menu" class="menu"> <li class="menu-item menu-item-home"> <a href="/" rel="section"> <i class="menu-item-icon fa fa-fw fa-home"></i> <br /> 首页 </a> </li> <li class="menu-item menu-item-categories"> <a href="/categories/" rel="section"> <i class="menu-item-icon fa fa-fw fa-th"></i> <br /> 分类 </a> </li> <li class="menu-item menu-item-about"> <a href="/about/" rel="section"> <i class="menu-item-icon fa fa-fw fa-user"></i> <br /> 关于 </a> </li> <li class="menu-item menu-item-archives"> <a href="/archives/" rel="section"> <i class="menu-item-icon fa fa-fw fa-archive"></i> <br /> 归档 </a> </li> <li class="menu-item menu-item-tags"> <a href="/tags/" rel="section"> <i class="menu-item-icon fa fa-fw fa-tags"></i> <br /> 标签 </a> </li> </ul> </nav> </div> </header> <main id="main" class="main"> <div class="main-inner"> <div class="content-wrap"> <div id="content" class="content"> <div id="posts" class="posts-collapse"> <div class="collection-title"> <h1>段子<small>标签</small> </h1> </div> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/08/28/16/" itemprop="url"> <span itemprop="name">16 什么是户口</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-08-28T16:53:45+08:00" content="2016-08-28" > 08-28 </time> </div> </header> </article> </div> </div> </div> <div class="sidebar-toggle"> <div class="sidebar-toggle-line-wrap"> <span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span> </div> </div> <aside id="sidebar" class="sidebar"> <div class="sidebar-inner"> <section class="site-overview sidebar-panel sidebar-panel-active"> <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="张召" /> <p class="site-author-name" itemprop="name">张召</p> <p class="site-description motion-element" itemprop="description">认识自己,改变自己</p> </div> <nav class="site-state motion-element"> <div class="site-state-item site-state-posts"> <a href="/archives/"> <span class="site-state-item-count">34</span> <span class="site-state-item-name">日志</span> </a> </div> <div class="site-state-item site-state-categories"> <a href="/categories/index.html"> <span class="site-state-item-count">4</span> <span class="site-state-item-name">分类</span> </a> </div> <div class="site-state-item site-state-tags"> <a href="/tags/index.html"> <span class="site-state-item-count">17</span> <span class="site-state-item-name">标签</span> </a> </div> </nav> <div class="feed-link motion-element"> <a href="/atom.xml" rel="alternate"> <i class="fa fa-rss"></i> RSS </a> </div> <div class="links-of-author motion-element"> </div> <div class="links-of-blogroll motion-element links-of-blogroll-inline"> <div class="links-of-blogroll-title"> <i class="fa fa-fw fa-globe"></i> </div> <ul class="links-of-blogroll-list"> <li class="links-of-blogroll-item"> <a href="http://zhiqiang.org/blog/" title="张志强" target="_blank">张志强</a> </li> <li class="links-of-blogroll-item"> <a href="http://blog.farmostwood.net/" title="木遥" target="_blank">木遥</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.changhai.org/" title="卢昌海" target="_blank">卢昌海</a> </li> <li class="links-of-blogroll-item"> <a href="http://blog.hanyan.me/" title="TooCold" target="_blank">TooCold</a> </li> <li class="links-of-blogroll-item"> <a href="http://freemind.pluskid.org/" title="pluskid(张驰原)" target="_blank">pluskid(张驰原)</a> </li> <li class="links-of-blogroll-item"> <a href="http://whzecomjm.com/" title="远溯博索" target="_blank">远溯博索</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.geekonomics10000.com/" title="同人于野(万维钢)" target="_blank">同人于野(万维钢)</a> </li> <li class="links-of-blogroll-item"> <a href="https://zqyin.wordpress.com/" title="尹璋琦" target="_blank">尹璋琦</a> </li> <li class="links-of-blogroll-item"> <a href="https://yihui.name/" title="谢益辉" target="_blank">谢益辉</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.physixfan.com/" title="宇宙的心弦(范翔)" target="_blank">宇宙的心弦(范翔)</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.matrix67.com/blog/" title="Matrix67(顾森)" target="_blank">Matrix67(顾森)</a> </li> <li class="links-of-blogroll-item"> <a href="http://localhost-8080.com/" title="考据癖" target="_blank">考据癖</a> </li> <li class="links-of-blogroll-item"> <a href="http://mindhacks.cn/" title="刘未鹏" target="_blank">刘未鹏</a> </li> <li class="links-of-blogroll-item"> <a href="http://macshuo.com/" title="池建强" target="_blank">池建强</a> </li> <li class="links-of-blogroll-item"> <a href="http://dbanotes.net/" title="Fenng(冯大辉)" target="_blank">Fenng(冯大辉)</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.ruanyifeng.com/blog/" title="阮一峰" target="_blank">阮一峰</a> </li> <li class="links-of-blogroll-item"> <a href="http://shibeichen.com/" title="师北宸" target="_blank">师北宸</a> </li> <li class="links-of-blogroll-item"> <a href="http://blog.youxu.info/" title="徐宥" target="_blank">徐宥</a> </li> <li class="links-of-blogroll-item"> <a href="http://blog.csdn.net/haoel/" title="陈皓" target="_blank">陈皓</a> </li> <li class="links-of-blogroll-item"> <a href="http://coolshell.cn/" title="酷壳" target="_blank">酷壳</a> </li> <li class="links-of-blogroll-item"> <a href="https://www.byvoid.com/zhs/" title="郭家宝" target="_blank">郭家宝</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.chenshuo.com/" title="陈硕" target="_blank">陈硕</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.luanxiang.org/blog/" title="余晟" target="_blank">余晟</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.wangjianshuo.com/" title="王建硕" target="_blank">王建硕</a> </li> <li class="links-of-blogroll-item"> <a href="http://www.yinwang.org/" title="王垠" target="_blank">王垠</a> </li> <li class="links-of-blogroll-item"> <a href="https://tumutanzi.com/" title="谭智军" target="_blank">谭智军</a> </li> </ul> </div> </section> </div> </aside> </div> </main> <footer id="footer" class="footer"> <div class="footer-inner"> <div class="copyright" > &copy; 2016 - <span itemprop="copyrightYear">2017</span> <span class="with-love"> <i class="fa fa-heart"></i> </span> <span class="author" itemprop="copyrightHolder">张召</span> </div> <div class="powered-by"> 由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动 </div> <div class="theme-info"> 主题 - <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next"> NexT.Pisces </a> </div> </div> </footer> <div class="back-to-top"> <i class="fa fa-arrow-up"></i> </div> </div> <script type="text/javascript"> if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } </script> <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script> <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script> <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script> <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script> <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script> <script id="dsq-count-scr" src="https://zsilence.disqus.com/count.js" async></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'], ["\\(","\\)"] ], processEscapes: true, skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] } }); </script> <script type="text/x-mathjax-config"> MathJax.Hub.Queue(function() { var all = MathJax.Hub.getAllJax(), i; for (i=0; i < all.length; i += 1) { all[i].SourceElement().parentNode.className += ' has-jax'; } }); </script> <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> </body> </html>
zsilence/zsilence.github.io
tags/段子/index.html
HTML
lgpl-2.1
16,584
// EstatusParser.cs - Parses the html of // http://www.itlalaguna.edu.mx/servicios/escolares/estatus_alumno/estatuscbb.asp. // Author: Alain Peralta <malain.pera@gmail.com> // Copyright(C) 2015 Alain Peralta // This library 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. // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 // USA using MAlainp.ITLBase.Items; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MAlainp.ITLBase.Parsers { public class EstatusParser : Parser { const string studentIdRegex = "[0-9]{8}"; const string studentName = "face=\"Arial\">[@A-Z�\\? ]+&nbsp;"; const string studentStatus = "<font size=\"2\" face=\"Arial\">[A-Za-z ]+</font>"; const string studentCarrer = "<font size=\"2\" face=\"Arial\">&nbsp;[A-Z ]+"; const string studentSemester = "<font size=\"2\" face=\"Arial\">&nbsp;[0-9]+"; string html; /// <summary> /// Gets an object with the student's information /// </summary> public Student Student { get; private set; } /// <summary> /// Initializes a new instance of <see cref="MAlainp.ITLBase.Parsers.EstatusParser"/> class. /// </summary> /// <param name="url">The URL for doing the post request.</param> /// <param name="studentId">The Student identifier aka 'Numero de control'.</param> /// <param name="password">The Student Password.</param> public EstatusParser(string url, string studentId, string password) : base(url, studentId, password) { } /// <summary> /// Parses the HTML and extracts the Student Id, Name, Status, Semester and carrer. /// </summary> /// <returns><c>true</c>, if HTML was parsed, <c>false</c> otherwise.</returns> public override async Task<bool> ParseHTMLAsync() { html = await Post(); var rexSId = new Regex(studentIdRegex); var sId = int.Parse(rexSId.Match(html).ToString().Trim()); var rexSName = new Regex(studentName); var sName = rexSName.Match(html).ToString(); sName = sName.Remove(sName.IndexOf('&')).Substring(sName.IndexOf('>') + 1).Replace('�', 'Ñ'); var rexStatus = new Regex(studentStatus); var sStatus = rexStatus.Match(html).ToString(); sStatus = sStatus.Substring(sStatus.IndexOf('>') + 1); sStatus = sStatus.Remove(sStatus.IndexOf('<')); var rexCarrer = new Regex(studentCarrer); var sCarrer = rexCarrer.Match(html).ToString(); sCarrer = sCarrer.Substring(sCarrer.IndexOf(';') + 1).Trim(); var rexSemester = new Regex(studentSemester); var sSemester = rexSemester.Match(html).ToString().Trim(); var iSemester = int.Parse(sSemester.Substring(sSemester.IndexOf(';') + 1)); Student = new Student(sId, sName, sStatus, sCarrer, iSemester); return true; } } }
malainp/ITLBase
MAlainp.ITLBase/Parsers/EstatusParser.cs
C#
lgpl-2.1
3,673
/* * * Copyright (C) 2011 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * 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 * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file dPython.h - This file was copied from VTK and was originally named vtkPython.h // \author David Gobbi // \author Last changed by $Author: jcfr $ // \date 2012 */ //---------------------------------------------------------------------------------- #ifndef __PythonQtPythonInclude_h #define __PythonQtPythonInclude_h // Undefine macros that Python.h defines to avoid redefinition warning. #undef _POSIX_C_SOURCE #undef _POSIX_THREADS #undef _XOPEN_SOURCE // // Use the real python debugging library if it is provided. // Otherwise use the "documented" trick involving checking for _DEBUG // and undefined that symbol while we include Python headers. // Update: this method does not fool Microsoft Visual C++ 8 anymore; two // of its header files (crtdefs.h and use_ansi.h) check if _DEBUG was set // or not, and set flags accordingly (_CRT_MANIFEST_RETAIL, // _CRT_MANIFEST_DEBUG, _CRT_MANIFEST_INCONSISTENT). The next time the // check is performed in the same compilation unit, and the flags are found, // and error is triggered. Let's prevent that by setting _CRT_NOFORCE_MANIFEST. // // If PYTHONQT_USE_RELEASE_PYTHON_FALLBACK is enabled, try to link // release Python DLL if it is available by undefining _DEBUG while // including Python.h #if defined(PYTHONQT_USE_RELEASE_PYTHON_FALLBACK) && defined(_DEBUG) # undef _DEBUG // Include these low level headers before undefing _DEBUG. Otherwise when doing // a debug build against a release build of python the compiler will end up // including these low level headers without DEBUG enabled, causing it to try // and link release versions of this low level C api. # include <basetsd.h> # include <assert.h> # include <ctype.h> # include <errno.h> # include <io.h> # include <math.h> # include <sal.h> # include <stdarg.h> # include <stddef.h> # include <stdio.h> # include <stdlib.h> # include <string.h> # include <sys/stat.h> # include <time.h> # include <wchar.h> # if defined(_MSC_VER) && _MSC_VER >= 1400 # define _CRT_NOFORCE_MANIFEST 1 # endif # include <Python.h> # define _DEBUG #else # include <Python.h> #endif #endif
jcfr/PythonQt
src/PythonQtPythonInclude.h
C
lgpl-2.1
3,584
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="pl"> <context> <name>LXQtSysStatColours</name> <message> <location filename="../lxqtsysstatcolours.ui" line="14"/> <source>System Statistics Colors</source> <translation>Kolory statystyk systemowych</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="24"/> <source>Graph</source> <translation>Graf</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="30"/> <source>&amp;Grid</source> <translation>&amp;Siatka</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="40"/> <location filename="../lxqtsysstatcolours.ui" line="57"/> <location filename="../lxqtsysstatcolours.ui" line="73"/> <location filename="../lxqtsysstatcolours.ui" line="90"/> <location filename="../lxqtsysstatcolours.ui" line="117"/> <location filename="../lxqtsysstatcolours.ui" line="144"/> <location filename="../lxqtsysstatcolours.ui" line="151"/> <location filename="../lxqtsysstatcolours.ui" line="178"/> <location filename="../lxqtsysstatcolours.ui" line="205"/> <location filename="../lxqtsysstatcolours.ui" line="232"/> <location filename="../lxqtsysstatcolours.ui" line="239"/> <location filename="../lxqtsysstatcolours.ui" line="265"/> <location filename="../lxqtsysstatcolours.ui" line="282"/> <source>Change ...</source> <translation>Zmień…</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="47"/> <source>T&amp;itle</source> <translation>Tyt&amp;uł</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="67"/> <source>CPU</source> <translation>Procesor</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="80"/> <source>&amp;Nice</source> <translation>&amp;Nice</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="97"/> <source>Ot&amp;her</source> <translation>&amp;Inne</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="107"/> <source>&amp;Frequency</source> <translation>C&amp;zęstotliwość</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="124"/> <source>S&amp;ystem</source> <translation>S&amp;ystem</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="134"/> <source>&amp;User</source> <translation>&amp;Użytkownik</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="172"/> <source>Memory</source> <translation>Pamięć</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="185"/> <source>Cache&amp;d</source> <translation>W pamięci po&amp;dręcznej</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="195"/> <source>S&amp;wap</source> <translation>Pamięć &amp;wymiany</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="212"/> <source>&amp;Applications</source> <translation>Progr&amp;amy</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="222"/> <source>&amp;Buffers</source> <translation>&amp;Bufor</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="249"/> <source>Network</source> <translation>Sieć</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="255"/> <source>&amp;Received</source> <translation>Odeb&amp;rano</translation> </message> <message> <location filename="../lxqtsysstatcolours.ui" line="272"/> <source>&amp;Transmitted</source> <translation>&amp;Wysłano</translation> </message> </context> <context> <name>LXQtSysStatConfiguration</name> <message> <location filename="../lxqtsysstatconfiguration.ui" line="14"/> <source>System Statistics Settings</source> <translation>Ustawienia statystyk systemu</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="22"/> <source>Graph</source> <translation>Graf</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="34"/> <source>&amp;Minimal size</source> <translation>&amp;Minimalny rozmiar</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="44"/> <source>Update &amp;interval</source> <translation>Aktual&amp;izuj częstotliwość</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="54"/> <source>&amp;Title</source> <translation>&amp;Tytuł</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="64"/> <source>&amp;Grid lines</source> <translation>Linie &amp;siatki</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="80"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Minimal width if the panel is horizontal.&lt;/p&gt;&lt;p&gt;Minimal height is the panel is vertical.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Minimalna szerokość dla poziomego panelu.&lt;/p&gt;&lt;p&gt;Minimalna wysokość dla pionowego panelu.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="83"/> <source> px</source> <translation> px</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="99"/> <source> s</source> <translation> s</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="124"/> <source>Data</source> <translation>Dane</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="149"/> <source>Use &amp;frequency</source> <translation>Używaj c&amp;zęstotliwości</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="207"/> <source>Ma&amp;ximum</source> <translation>Mak&amp;symalne</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="222"/> <source>XXX KBs</source> <translation>XXX KBs</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="241"/> <source>Lo&amp;garithmic scale</source> <translation>Skala lo&amp;garytmiczna</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="248"/> <source> steps</source> <translation> kroki</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="286"/> <source>&amp;Source</source> <translation>Źró&amp;dło</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="296"/> <source>T&amp;ype</source> <translation>&amp;Rodzaj</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="312"/> <source>Colours</source> <translation>Kolory</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="327"/> <source>Use t&amp;heme colours</source> <translation>Używaj kolorów &amp;motywu</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="337"/> <source>Use c&amp;ustom colours</source> <translation>Używaj &amp;niestandardowych kolorów</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.ui" line="344"/> <source>Custom colour ...</source> <translation>Niestandardowy kolot…</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="41"/> <source>CPU</source> <translation>Procesor</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="42"/> <source>Memory</source> <translation>Pamięć</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="43"/> <source>Network</source> <translation>Sieć</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="54"/> <source>cpu</source> <translation>cpu</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="55"/> <source>cpu0</source> <translation>cpu0</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="56"/> <source>cpu1</source> <translation>cpu1</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="57"/> <source>cpu2</source> <translation>cpu2</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="58"/> <source>cpu3</source> <translation>cpu3</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="59"/> <source>cpu4</source> <translation>cpu4</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="60"/> <source>cpu5</source> <translation>cpu5</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="61"/> <source>cpu6</source> <translation>cpu6</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="62"/> <source>cpu7</source> <translation>cpu7</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="63"/> <source>cpu8</source> <translation>cpu8</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="64"/> <source>cpu9</source> <translation>cpu9</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="65"/> <source>cpu10</source> <translation>cpu10</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="66"/> <source>cpu11</source> <translation>cpu11</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="67"/> <source>cpu12</source> <translation>cpu12</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="68"/> <source>cpu13</source> <translation>cpu13</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="69"/> <source>cpu14</source> <translation>cpu14</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="70"/> <source>cpu15</source> <translation>cpu15</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="71"/> <source>cpu16</source> <translation>cpu16</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="72"/> <source>cpu17</source> <translation>cpu17</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="73"/> <source>cpu18</source> <translation>cpu18</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="74"/> <source>cpu19</source> <translation>cpu19</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="75"/> <source>cpu20</source> <translation>cpu20</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="76"/> <source>cpu21</source> <translation>cpu21</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="77"/> <source>cpu22</source> <translation>cpu22</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="78"/> <source>cpu23</source> <translation>cpu23</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="79"/> <source>memory</source> <translation>pamięć</translation> </message> <message> <location filename="../lxqtsysstatconfiguration.cpp" line="80"/> <source>swap</source> <translation>pamięć wymiany</translation> </message> </context> <context> <name>LXQtSysStatContent</name> <message> <location filename="../lxqtsysstat.cpp" line="397"/> <source>system: %1%&lt;br&gt;user: %2%&lt;br&gt;nice: %3%&lt;br&gt;other: %4%&lt;br&gt;freq: %5%</source> <comment>CPU tooltip information</comment> <translation>system: %1%&lt;br&gt;użytkownik: %2%&lt;br&gt;nice: %3%&lt;br&gt;inne: %4%&lt;br&gt;częst.: %5%</translation> </message> <message> <location filename="../lxqtsysstat.cpp" line="446"/> <source>system: %1%&lt;br&gt;user: %2%&lt;br&gt;nice: %3%&lt;br&gt;other: %4%&lt;br&gt;freq: n/a</source> <comment>CPU tooltip information</comment> <translation>system: %1%&lt;br&gt;użytkownik: %2%&lt;br&gt;nice: %3%&lt;br&gt;inne: %4%&lt;br&gt;częst.: n/a</translation> </message> <message> <location filename="../lxqtsysstat.cpp" line="488"/> <source>apps: %1%&lt;br&gt;buffers: %2%&lt;br&gt;cached: %3%</source> <comment>Memory tooltip information</comment> <translation>aplikacje: %1%&lt;br&gt;bufory: %2%&lt;br&gt;w pamięci podr.: %3%</translation> </message> <message> <location filename="../lxqtsysstat.cpp" line="522"/> <source>used: %1%</source> <comment>Swap tooltip information</comment> <translation>użyto: %1%</translation> </message> <message> <location filename="../lxqtsysstat.cpp" line="552"/> <source>min: %1%&lt;br&gt;max: %2%</source> <comment>Network tooltip information</comment> <translation>min: %1%&lt;br&gt;maks: %2%</translation> </message> </context> </TS>
lxde/lxqt-panel
plugin-sysstat/translations/sysstat_pl.ts
TypeScript
lgpl-2.1
15,700
CC=gcc CFLAGS=-Wall -c LDFLAGS=-lwiringPi -lpthread BINARIES=*.o all: rc_switch.o rc_switch.o: $(CC) $(CFLAGS) rc_switch.c -o rc_switch.o $(LDFLAGS) test_sender.o: test/test_sender.c rc_switch.o $(CC) test/test_sender.c -o test/test_sender.o rc_switch.o $(LDFLAGS) test_receiver.o: test/test_receiver.c rc_switch.o $(CC) test/test_receiver.c -o test/test_receiver.o rc_switch.o $(LDFLAGS) test_switch: test_switch_a.o test_switch_b.o test_switch_c.o test_switch_d.o test_switch_a.o: test/test_switch_a.c rc_switch.o $(CC) test/test_switch_a.c -o test/test_switch_a.o rc_switch.o $(LDFLAGS) test_switch_b.o: test/test_switch_b.c rc_switch.o $(CC) test/test_switch_b.c -o test/test_switch_b.o rc_switch.o $(LDFLAGS) test_switch_c.o: test/test_switch_c.c rc_switch.o $(CC) test/test_switch_c.c -o test/test_switch_c.o rc_switch.o $(LDFLAGS) test_switch_d.o: test/test_switch_d.c rc_switch.o $(CC) test/test_switch_c.c -o test/test_switch_d.o rc_switch.o $(LDFLAGS) test: test_switch test_sender.o .PHONY: clean clean: rm -f test/*.o *.o
lexruee/rc-switch-c
Makefile
Makefile
lgpl-2.1
1,059
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library 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. 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.io.quadtree; /** * exception indicating an error will reading or manipulating an spatial index implemented in * deegree * * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class IndexException extends Exception { /** * just a random number for serialization with the api. */ private static final long serialVersionUID = -5603584819816036353L; /** * */ public IndexException() { super(); } /** * @param message */ public IndexException( String message ) { super( message ); } /** * @param message * @param e */ public IndexException( String message, Throwable e ) { super( message, e ); } /** * @param e */ public IndexException( Throwable e ) { super( e ); } }
lat-lon/deegree2-base
deegree2-core/src/main/java/org/deegree/io/quadtree/IndexException.java
Java
lgpl-2.1
2,303
// Platform.h #ifndef SEVENZIPCORE_PLATFORM_H #define SEVENZIPCORE_PLATFORM_H #if defined(_WIN32) || defined(__WIN32__) #ifndef __WINDOWS__ #define __WINDOWS__ #endif #include <Windows.h> #endif #define FOLDER_SEPARATOR_WINDOWS TEXT('\\') #define FOLDER_SEPARATOR_POSIX TEXT('/') #ifdef __WINDOWS__ #define FOLDER_SEPARATOR TEXT('\\') #define FOLDER_SEPARATOR_STRING TEXT("\\") #define FOLDER_POSSIBLE_SEPARATOR TEXT("\\/") #else #define FOLDER_SEPARATOR TEXT('/') #define FOLDER_SEPARATOR_STRING TEXT("/") #define FOLDER_POSSIBLE_SEPARATOR TEXT("/") #endif #define FILE_EXTENSION_SEPARATOR TEXT('.') #define FILE_EXTENSION_SEPARATOR_STRING TEXT(".") #endif // SEVENZIPCORE_PLATFORM_H
raychow/EightZip
EightZip/SevenZipCore/Platform.h
C
lgpl-2.1
691
package fr.toss.FF7.armor; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import fr.toss.FF7.ItemRegistry1; import fr.toss.common.Main; public class Iceshield extends ItemArmor { public String textureName; public Iceshield(ArmorMaterial material, int render_idx, int type) { super(material, 0, type); this.textureName = "Iceshield"; setUnlocalizedName("Iceshield"); setCreativeTab(ItemRegistry1.FF7Armor); this.setTextureName(Main.MODID + ":" + getUnlocalizedName()); } @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { return Main.MODID + ":textures/armor/" + this.textureName + "_" + (this.armorType == 2 ? "2" : "1") + ".png"; } @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { this.itemIcon = iconRegister.registerIcon("FF7" + ":" + getUnlocalizedName().substring(5)); } }
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/FF7/armor/Iceshield.java
Java
lgpl-2.1
1,121
/* * Copyright (C) 2009-2012 the libgit2 contributors * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_fileops_h__ #define INCLUDE_fileops_h__ #include "common.h" #include "map.h" #include "posix.h" #include "path.h" /** * Filebuffer methods * * Read whole files into an in-memory buffer for processing */ extern int git_futils_readbuffer(git_buf *obj, const char *path); extern int git_futils_readbuffer_updated( git_buf *obj, const char *path, time_t *mtime, size_t *size, int *updated); extern int git_futils_readbuffer_fd(git_buf *obj, git_file fd, size_t len); /** * File utils * * These are custom filesystem-related helper methods. They are * rather high level, and wrap the underlying POSIX methods * * All these methods return 0 on success, * or an error code on failure and an error message is set. */ /** * Create and open a file, while also * creating all the folders in its path */ extern int git_futils_creat_withpath(const char *path, const mode_t dirmode, const mode_t mode); /** * Create an open a process-locked file */ extern int git_futils_creat_locked(const char *path, const mode_t mode); /** * Create an open a process-locked file, while * also creating all the folders in its path */ extern int git_futils_creat_locked_withpath(const char *path, const mode_t dirmode, const mode_t mode); /** * Create a path recursively * * If a base parameter is being passed, it's expected to be valued with a * path pointing to an already existing directory. */ extern int git_futils_mkdir_r(const char *path, const char *base, const mode_t mode); /** * Flags to pass to `git_futils_mkdir`. * * * GIT_MKDIR_EXCL is "exclusive" - i.e. generate an error if dir exists. * * GIT_MKDIR_PATH says to make all components in the path. * * GIT_MKDIR_CHMOD says to chmod the final directory entry after creation * * GIT_MKDIR_CHMOD_PATH says to chmod each directory component in the path * * GIT_MKDIR_SKIP_LAST says to leave off the last element of the path * * GIT_MKDIR_VERIFY_DIR says confirm final item is a dir, not just EEXIST * * Note that the chmod options will be executed even if the directory already * exists, unless GIT_MKDIR_EXCL is given. */ typedef enum { GIT_MKDIR_EXCL = 1, GIT_MKDIR_PATH = 2, GIT_MKDIR_CHMOD = 4, GIT_MKDIR_CHMOD_PATH = 8, GIT_MKDIR_SKIP_LAST = 16, GIT_MKDIR_VERIFY_DIR = 32, } git_futils_mkdir_flags; /** * Create a directory or entire path. * * This makes a directory (and the entire path leading up to it if requested), * and optionally chmods the directory immediately after (or each part of the * path if requested). * * @param path The path to create. * @param base Root for relative path. These directories will never be made. * @param mode The mode to use for created directories. * @param flags Combination of the mkdir flags above. * @return 0 on success, else error code */ extern int git_futils_mkdir(const char *path, const char *base, mode_t mode, uint32_t flags); /** * Create all the folders required to contain * the full path of a file */ extern int git_futils_mkpath2file(const char *path, const mode_t mode); /** * Flags to pass to `git_futils_rmdir_r`. * * * GIT_RMDIR_EMPTY_HIERARCHY - the default; remove hierarchy of empty * dirs and generate error if any files are found. * * GIT_RMDIR_REMOVE_FILES - attempt to remove files in the hierarchy. * * GIT_RMDIR_SKIP_NONEMPTY - skip non-empty directories with no error. * * GIT_RMDIR_EMPTY_PARENTS - remove containing directories up to base * if removing this item leaves them empty * * GIT_RMDIR_REMOVE_BLOCKERS - remove blocking file that causes ENOTDIR * * The old values translate into the new as follows: * * * GIT_DIRREMOVAL_EMPTY_HIERARCHY == GIT_RMDIR_EMPTY_HIERARCHY * * GIT_DIRREMOVAL_FILES_AND_DIRS ~= GIT_RMDIR_REMOVE_FILES * * GIT_DIRREMOVAL_ONLY_EMPTY_DIRS == GIT_RMDIR_SKIP_NONEMPTY */ typedef enum { GIT_RMDIR_EMPTY_HIERARCHY = 0, GIT_RMDIR_REMOVE_FILES = (1 << 0), GIT_RMDIR_SKIP_NONEMPTY = (1 << 1), GIT_RMDIR_EMPTY_PARENTS = (1 << 2), GIT_RMDIR_REMOVE_BLOCKERS = (1 << 3), } git_futils_rmdir_flags; /** * Remove path and any files and directories beneath it. * * @param path Path to to top level directory to process. * @param base Root for relative path. * @param flags Combination of git_futils_rmdir_flags values * @return 0 on success; -1 on error. */ extern int git_futils_rmdir_r(const char *path, const char *base, uint32_t flags); /** * Create and open a temporary file with a `_git2_` suffix. * Writes the filename into path_out. * @return On success, an open file descriptor, else an error code < 0. */ extern int git_futils_mktmp(git_buf *path_out, const char *filename); /** * Move a file on the filesystem, create the * destination path if it doesn't exist */ extern int git_futils_mv_withpath(const char *from, const char *to, const mode_t dirmode); /** * Copy a file * * The filemode will be used for the newly created file. */ extern int git_futils_cp( const char *from, const char *to, mode_t filemode); /** * Flags that can be passed to `git_futils_cp_r`. */ typedef enum { GIT_CPDIR_CREATE_EMPTY_DIRS = 1, GIT_CPDIR_COPY_SYMLINKS = 2, GIT_CPDIR_COPY_DOTFILES = 4, GIT_CPDIR_OVERWRITE = 8, GIT_CPDIR_CHMOD = 16 } git_futils_cpdir_flags; /** * Copy a directory tree. * * This copies directories and files from one root to another. You can * pass a combinationof GIT_CPDIR flags as defined above. * * If you pass the CHMOD flag, then the dirmode will be applied to all * directories that are created during the copy, overiding the natural * permissions. If you do not pass the CHMOD flag, then the dirmode * will actually be copied from the source files and the `dirmode` arg * will be ignored. */ extern int git_futils_cp_r( const char *from, const char *to, uint32_t flags, mode_t dirmode); /** * Open a file readonly and set error if needed. */ extern int git_futils_open_ro(const char *path); /** * Get the filesize in bytes of a file */ extern git_off_t git_futils_filesize(git_file fd); #define GIT_MODE_PERMS_MASK 0777 #define GIT_CANONICAL_PERMS(MODE) (((MODE) & 0100) ? 0755 : 0644) #define GIT_MODE_TYPE(MODE) ((MODE) & ~GIT_MODE_PERMS_MASK) /** * Convert a mode_t from the OS to a legal git mode_t value. */ extern mode_t git_futils_canonical_mode(mode_t raw_mode); /** * Read-only map all or part of a file into memory. * When possible this function should favor a virtual memory * style mapping over some form of malloc()+read(), as the * data access will be random and is not likely to touch the * majority of the region requested. * * @param out buffer to populate with the mapping information. * @param fd open descriptor to configure the mapping from. * @param begin first byte to map, this should be page aligned. * @param end number of bytes to map. * @return * - 0 on success; * - -1 on error. */ extern int git_futils_mmap_ro( git_map *out, git_file fd, git_off_t begin, size_t len); /** * Read-only map an entire file. * * @param out buffer to populate with the mapping information. * @param path path to file to be opened. * @return * - 0 on success; * - GIT_ENOTFOUND if not found; * - -1 on an unspecified OS related error. */ extern int git_futils_mmap_ro_file( git_map *out, const char *path); /** * Release the memory associated with a previous memory mapping. * @param map the mapping description previously configured. */ extern void git_futils_mmap_free(git_map *map); /** * Find a "global" file (i.e. one in a user's home directory). * * @param pathbuf buffer to write the full path into * @param filename name of file to find in the home directory * @return * - 0 if found; * - GIT_ENOTFOUND if not found; * - -1 on an unspecified OS related error. */ extern int git_futils_find_global_file(git_buf *path, const char *filename); /** * Find a "system" file (i.e. one shared for all users of the system). * * @param pathbuf buffer to write the full path into * @param filename name of file to find in the home directory * @return * - 0 if found; * - GIT_ENOTFOUND if not found; * - -1 on an unspecified OS related error. */ extern int git_futils_find_system_file(git_buf *path, const char *filename); /** * Create a "fake" symlink (text file containing the target path). * * @param new symlink file to be created * @param old original symlink target * @return 0 on success, -1 on error */ extern int git_futils_fake_symlink(const char *new, const char *old); /** * A file stamp represents a snapshot of information about a file that can * be used to test if the file changes. This portable implementation is * based on stat data about that file, but it is possible that OS specific * versions could be implemented in the future. */ typedef struct { git_time_t mtime; git_off_t size; unsigned int ino; } git_futils_filestamp; /** * Compare stat information for file with reference info. * * This function updates the file stamp to current data for the given path * and returns 0 if the file is up-to-date relative to the prior setting or * 1 if the file has been changed. (This also may return GIT_ENOTFOUND if * the file doesn't exist.) * * @param stamp File stamp to be checked * @param path Path to stat and check if changed * @return 0 if up-to-date, 1 if out-of-date, <0 on error */ extern int git_futils_filestamp_check( git_futils_filestamp *stamp, const char *path); /** * Set or reset file stamp data * * This writes the target file stamp. If the source is NULL, this will set * the target stamp to values that will definitely be out of date. If the * source is not NULL, this copies the source values to the target. * * @param tgt File stamp to write to * @param src File stamp to copy from or NULL to clear the target */ extern void git_futils_filestamp_set( git_futils_filestamp *tgt, const git_futils_filestamp *src); #endif /* INCLUDE_fileops_h__ */
nacho/libgit2
src/fileops.h
C
lgpl-2.1
10,139
<?php /** * CMS Aïdoo * * Copyright (C) 2013 Flamant Bleu Studio * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ abstract class CMS_Object_MonoLangEntity extends CMS_Object_Abstract { public function __construct($data = null) { parent::__construct($data, "all"); } /** * Retourne des instances d'objets selon des critères de recherche * @param array $where filtre les résultats * @param mixed $order ordonne les résultats * @param mixed $limit limite les résultats */ public static function get($where = array(), $order = null, $limit = null) { return parent::get($where, $order, $limit, "all"); } }
flamant-bleu-studio/aidoo_core
current_version/library/CMS/Object/MonoLangEntity.php
PHP
lgpl-2.1
1,331
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain Version 0.6.0 // The SmartSoft Toolchain has been developed by: // // ZAFH Servicerobotic Ulm // Christian Schlegel (schlegel@hs-ulm.de) // University of Applied Sciences // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // smart-robotics.sourceforge.net // // This file is generated once. Modify this file to your needs. // If you want the workflow to re-generate this file, please // delete it before running the workflow. //------------------------------------------------------------------------ // // Copyright (C) 2010 Manuel Wopfner // // wopfner@hs-ulm.de // // Christian Schlegel (schlegel@hs-ulm.de) // University of Applied Sciences // Prittwitzstr. 10 // 89075 Ulm (Germany) // // This file is part of the "SmartLaserHokuyoURGServer component". // // This library 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. // // 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 "PushTimedHandler.hh" #include "gen/SmartLaserHokuyoURGServer.hh" #include <iostream> void PushTimedHandler::handlePushTimer(CHS::PushTimedServer<CommBasicObjects::CommMobileLaserScan> & server) throw() { if (COMP->ini.scanner.verbose) std::cout << "send scan via push timed\n"; COMP->ScanLock.acquire(); server.put(COMP->global_scan); COMP->ScanLock.release(); }
carlos22/SmartSoftCorba
src/components/SmartLaserHokuyoURGServer/src/PushTimedHandler.cc
C++
lgpl-2.1
2,195
/* * virlog.h: internal logging and debugging * * Copyright (C) 2006-2008, 2011-2012 Red Hat, Inc. * * This library 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. * * 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, see * <http://www.gnu.org/licenses/>. * */ #pragma once #include "internal.h" #ifdef PACKAGER_VERSION # ifdef PACKAGER # define VIR_LOG_VERSION_STRING \ "libvirt version: " VERSION ", package: " PACKAGER_VERSION " (" PACKAGER ")" # else # define VIR_LOG_VERSION_STRING \ "libvirt version: " VERSION ", package: " PACKAGER_VERSION # endif #else # define VIR_LOG_VERSION_STRING \ "libvirt version: " VERSION #endif /* * To be made public */ typedef enum { VIR_LOG_DEBUG = 1, VIR_LOG_INFO, VIR_LOG_WARN, VIR_LOG_ERROR, } virLogPriority; #define VIR_LOG_DEFAULT VIR_LOG_WARN typedef enum { VIR_LOG_TO_STDERR = 0, VIR_LOG_TO_SYSLOG, VIR_LOG_TO_FILE, VIR_LOG_TO_JOURNALD, VIR_LOG_TO_OUTPUT_LAST, } virLogDestination; typedef struct _virLogSource virLogSource; struct _virLogSource { const char *name; unsigned int priority; unsigned int serial; }; /* * G_GNUC_UNUSED is to make gcc keep quiet if all the * log statements in a file are conditionally disabled * at compile time due to configure options. */ #define VIR_LOG_INIT(n) \ static G_GNUC_UNUSED virLogSource virLogSelf = { \ .name = "" n "", \ .priority = VIR_LOG_ERROR, \ .serial = 0, \ } #define VIR_DEBUG_INT(src, filename, linenr, funcname, ...) \ virLogMessage(src, VIR_LOG_DEBUG, filename, linenr, funcname, NULL, __VA_ARGS__) #define VIR_INFO_INT(src, filename, linenr, funcname, ...) \ virLogMessage(src, VIR_LOG_INFO, filename, linenr, funcname, NULL, __VA_ARGS__) #define VIR_WARN_INT(src, filename, linenr, funcname, ...) \ virLogMessage(src, VIR_LOG_WARN, filename, linenr, funcname, NULL, __VA_ARGS__) #define VIR_ERROR_INT(src, filename, linenr, funcname, ...) \ virLogMessage(src, VIR_LOG_ERROR, filename, linenr, funcname, NULL, __VA_ARGS__) #define VIR_DEBUG(...) \ VIR_DEBUG_INT(&virLogSelf, __FILE__, __LINE__, __func__, __VA_ARGS__) #define VIR_INFO(...) \ VIR_INFO_INT(&virLogSelf, __FILE__, __LINE__, __func__, __VA_ARGS__) #define VIR_WARN(...) \ VIR_WARN_INT(&virLogSelf, __FILE__, __LINE__, __func__, __VA_ARGS__) #define VIR_ERROR(...) \ VIR_ERROR_INT(&virLogSelf, __FILE__, __LINE__, __func__, __VA_ARGS__) struct _virLogMetadata { const char *key; const char *s; /* String value, or NULL to use "i" */ int iv; }; typedef struct _virLogMetadata virLogMetadata; typedef struct _virLogOutput virLogOutput; typedef struct _virLogFilter virLogFilter; /** * virLogOutputFunc: * @src: the source of the log message * @priority: the priority for the message * @filename: file where the message was emitted * @linenr: line where the message was emitted * @funcname: the function emitting the message * @timestamp: zero terminated string with timestamp of the message * @metadata: NULL or metadata array, terminated by an item with NULL key * @rawstr: the unformatted message to log, zero terminated * @str: the message to log, preformatted and zero terminated * @data: extra output logging data * * Callback function used to output messages */ typedef void (*virLogOutputFunc) (virLogSource *src, virLogPriority priority, const char *filename, int linenr, const char *funcname, const char *timestamp, struct _virLogMetadata *metadata, const char *rawstr, const char *str, void *data); /** * virLogCloseFunc: * @data: extra output logging data * * Callback function used to close a log output */ typedef void (*virLogCloseFunc) (void *data); int virLogGetNbFilters(void); int virLogGetNbOutputs(void); char *virLogGetFilters(void); char *virLogGetOutputs(void); virLogPriority virLogGetDefaultPriority(void); int virLogSetDefaultPriority(virLogPriority priority); void virLogSetFromEnv(void); void virLogOutputFree(virLogOutput *output); void virLogOutputListFree(virLogOutput **list, int count); void virLogFilterFree(virLogFilter *filter); void virLogFilterListFree(virLogFilter **list, int count); int virLogSetOutputs(const char *outputs); int virLogSetFilters(const char *filters); char *virLogGetDefaultOutput(void); void virLogSetDefaultOutput(const char *fname, bool godaemon, bool privileged); /* * Internal logging API */ void virLogLock(void); void virLogUnlock(void); int virLogReset(void); int virLogParseDefaultPriority(const char *priority); int virLogPriorityFromSyslog(int priority); void virLogMessage(virLogSource *source, virLogPriority priority, const char *filename, int linenr, const char *funcname, struct _virLogMetadata *metadata, const char *fmt, ...) G_GNUC_PRINTF(7, 8); bool virLogProbablyLogMessage(const char *str); virLogOutput *virLogOutputNew(virLogOutputFunc f, virLogCloseFunc c, void *data, virLogPriority priority, virLogDestination dest, const char *name) ATTRIBUTE_NONNULL(1); virLogFilter *virLogFilterNew(const char *match, virLogPriority priority) ATTRIBUTE_NONNULL(1); int virLogFindOutput(virLogOutput **outputs, size_t noutputs, virLogDestination dest, const void *opaque); int virLogDefineOutputs(virLogOutput **outputs, size_t noutputs) ATTRIBUTE_NONNULL(1); int virLogDefineFilters(virLogFilter **filters, size_t nfilters); virLogOutput *virLogParseOutput(const char *src) ATTRIBUTE_NONNULL(1); virLogFilter *virLogParseFilter(const char *src) ATTRIBUTE_NONNULL(1); int virLogParseOutputs(const char *src, virLogOutput ***outputs) ATTRIBUTE_NONNULL(1); int virLogParseFilters(const char *src, virLogFilter ***filters) ATTRIBUTE_NONNULL(1);
nertpinx/libvirt
src/util/virlog.h
C
lgpl-2.1
6,902
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: remotecontrol.ui Example File (help/remotecontrol/remotecontrol.ui)</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">remotecontrol.ui Example File</h1> <span class="small-subtitle">help/remotecontrol/remotecontrol.ui</span> <!-- $$$help/remotecontrol/remotecontrol.ui-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> &lt;ui version=&quot;4.0&quot; &gt; &lt;class&gt;RemoteControlClass&lt;/class&gt; &lt;widget class=&quot;QMainWindow&quot; name=&quot;RemoteControlClass&quot; &gt; &lt;property name=&quot;geometry&quot; &gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;344&lt;/width&gt; &lt;height&gt;364&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;windowTitle&quot; &gt; &lt;string&gt;RemoteControl&lt;/string&gt; &lt;/property&gt; &lt;widget class=&quot;QWidget&quot; name=&quot;centralWidget&quot; &gt; &lt;layout class=&quot;QGridLayout&quot; &gt; &lt;item row=&quot;0&quot; column=&quot;0&quot; &gt; &lt;widget class=&quot;QLabel&quot; name=&quot;label&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Start URL:&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;0&quot; column=&quot;1&quot; colspan=&quot;2&quot; &gt; &lt;widget class=&quot;QLineEdit&quot; name=&quot;startUrlLineEdit&quot; /&gt; &lt;/item&gt; &lt;item row=&quot;1&quot; column=&quot;1&quot; &gt; &lt;widget class=&quot;QPushButton&quot; name=&quot;launchButton&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Launch Qt HelpViewer&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;1&quot; column=&quot;2&quot; &gt; &lt;spacer&gt; &lt;property name=&quot;orientation&quot; &gt; &lt;enum&gt;Qt::Horizontal&lt;/enum&gt; &lt;/property&gt; &lt;property name=&quot;sizeHint&quot; &gt; &lt;size&gt; &lt;width&gt;101&lt;/width&gt; &lt;height&gt;20&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;/spacer&gt; &lt;/item&gt; &lt;item row=&quot;2&quot; column=&quot;1&quot; &gt; &lt;spacer&gt; &lt;property name=&quot;orientation&quot; &gt; &lt;enum&gt;Qt::Vertical&lt;/enum&gt; &lt;/property&gt; &lt;property name=&quot;sizeType&quot; &gt; &lt;enum&gt;QSizePolicy::Fixed&lt;/enum&gt; &lt;/property&gt; &lt;property name=&quot;sizeHint&quot; &gt; &lt;size&gt; &lt;width&gt;113&lt;/width&gt; &lt;height&gt;16&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;/spacer&gt; &lt;/item&gt; &lt;item row=&quot;3&quot; column=&quot;0&quot; colspan=&quot;3&quot; &gt; &lt;widget class=&quot;QGroupBox&quot; name=&quot;actionGroupBox&quot; &gt; &lt;property name=&quot;enabled&quot; &gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;title&quot; &gt; &lt;string&gt;Actions&lt;/string&gt; &lt;/property&gt; &lt;layout class=&quot;QGridLayout&quot; &gt; &lt;item row=&quot;0&quot; column=&quot;0&quot; &gt; &lt;widget class=&quot;QLabel&quot; name=&quot;label_2&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Search in Index:&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;0&quot; column=&quot;1&quot; colspan=&quot;2&quot; &gt; &lt;layout class=&quot;QHBoxLayout&quot; &gt; &lt;property name=&quot;spacing&quot; &gt; &lt;number&gt;0&lt;/number&gt; &lt;/property&gt; &lt;item&gt; &lt;widget class=&quot;QLineEdit&quot; name=&quot;indexLineEdit&quot; /&gt; &lt;/item&gt; &lt;item&gt; &lt;widget class=&quot;QToolButton&quot; name=&quot;indexButton&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string/&gt; &lt;/property&gt; &lt;property name=&quot;icon&quot; &gt; &lt;iconset resource=&quot;remotecontrol.qrc&quot; &gt;:/remotecontrol/enter.png&lt;/iconset&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/item&gt; &lt;item row=&quot;1&quot; column=&quot;0&quot; &gt; &lt;widget class=&quot;QLabel&quot; name=&quot;label_4&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Identifier:&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;1&quot; column=&quot;1&quot; colspan=&quot;2&quot; &gt; &lt;layout class=&quot;QHBoxLayout&quot; &gt; &lt;property name=&quot;spacing&quot; &gt; &lt;number&gt;0&lt;/number&gt; &lt;/property&gt; &lt;item&gt; &lt;widget class=&quot;QLineEdit&quot; name=&quot;identifierLineEdit&quot; /&gt; &lt;/item&gt; &lt;item&gt; &lt;widget class=&quot;QToolButton&quot; name=&quot;identifierButton&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string/&gt; &lt;/property&gt; &lt;property name=&quot;icon&quot; &gt; &lt;iconset resource=&quot;remotecontrol.qrc&quot; &gt;:/remotecontrol/enter.png&lt;/iconset&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/item&gt; &lt;item row=&quot;2&quot; column=&quot;0&quot; &gt; &lt;widget class=&quot;QLabel&quot; name=&quot;label_3&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Show URL:&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;2&quot; column=&quot;1&quot; colspan=&quot;2&quot; &gt; &lt;layout class=&quot;QHBoxLayout&quot; &gt; &lt;property name=&quot;spacing&quot; &gt; &lt;number&gt;0&lt;/number&gt; &lt;/property&gt; &lt;item&gt; &lt;widget class=&quot;QLineEdit&quot; name=&quot;urlLineEdit&quot; /&gt; &lt;/item&gt; &lt;item&gt; &lt;widget class=&quot;QToolButton&quot; name=&quot;urlButton&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string/&gt; &lt;/property&gt; &lt;property name=&quot;icon&quot; &gt; &lt;iconset resource=&quot;remotecontrol.qrc&quot; &gt;:/remotecontrol/enter.png&lt;/iconset&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/item&gt; &lt;item row=&quot;3&quot; column=&quot;1&quot; &gt; &lt;widget class=&quot;QPushButton&quot; name=&quot;syncContentsButton&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Sync Contents&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;3&quot; column=&quot;2&quot; &gt; &lt;spacer&gt; &lt;property name=&quot;orientation&quot; &gt; &lt;enum&gt;Qt::Horizontal&lt;/enum&gt; &lt;/property&gt; &lt;property name=&quot;sizeHint&quot; &gt; &lt;size&gt; &lt;width&gt;81&lt;/width&gt; &lt;height&gt;20&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;/spacer&gt; &lt;/item&gt; &lt;item row=&quot;4&quot; column=&quot;0&quot; colspan=&quot;3&quot; &gt; &lt;widget class=&quot;QCheckBox&quot; name=&quot;contentsCheckBox&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Show Contents&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;5&quot; column=&quot;0&quot; &gt; &lt;widget class=&quot;QCheckBox&quot; name=&quot;indexCheckBox&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Show Index&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item row=&quot;6&quot; column=&quot;0&quot; colspan=&quot;3&quot; &gt; &lt;widget class=&quot;QCheckBox&quot; name=&quot;bookmarksCheckBox&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Show Bookmarks&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/widget&gt; &lt;widget class=&quot;QMenuBar&quot; name=&quot;menuBar&quot; &gt; &lt;property name=&quot;geometry&quot; &gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;344&lt;/width&gt; &lt;height&gt;21&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;widget class=&quot;QMenu&quot; name=&quot;menuFile&quot; &gt; &lt;property name=&quot;title&quot; &gt; &lt;string&gt;File&lt;/string&gt; &lt;/property&gt; &lt;addaction name=&quot;actionQuit&quot; /&gt; &lt;/widget&gt; &lt;addaction name=&quot;menuFile&quot; /&gt; &lt;/widget&gt; &lt;widget class=&quot;QStatusBar&quot; name=&quot;statusBar&quot; /&gt; &lt;action name=&quot;actionQuit&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;Quit&lt;/string&gt; &lt;/property&gt; &lt;/action&gt; &lt;/widget&gt; &lt;layoutdefault spacing=&quot;6&quot; margin=&quot;11&quot; /&gt; &lt;resources&gt; &lt;include location=&quot;remotecontrol.qrc&quot; /&gt; &lt;/resources&gt; &lt;connections/&gt; &lt;/ui&gt;</pre> </div> <!-- @@@help/remotecontrol/remotecontrol.ui --> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
kobolabs/qt-everywhere-4.8.0
doc/html/help-remotecontrol-remotecontrol-ui.html
HTML
lgpl-2.1
11,761
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_03) on Wed Jan 09 13:25:10 CET 2008 --> <TITLE> TransactionCallback (Spring Framework API 2.5) </TITLE> <META NAME="date" CONTENT="2008-01-09"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="TransactionCallback (Spring Framework API 2.5)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/TransactionCallback.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/springframework/transaction/support/SmartTransactionObject.html" title="interface in org.springframework.transaction.support"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/springframework/transaction/support/TransactionCallbackWithoutResult.html" title="class in org.springframework.transaction.support"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/springframework/transaction/support/TransactionCallback.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TransactionCallback.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.springframework.transaction.support</FONT> <BR> Interface TransactionCallback</H2> <DL> <DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../org/springframework/transaction/support/TransactionCallbackWithoutResult.html" title="class in org.springframework.transaction.support">TransactionCallbackWithoutResult</A></DD> </DL> <HR> <DL> <DT><PRE>public interface <B>TransactionCallback</B></DL> </PRE> <P> Callback interface for transactional code. Used with <A HREF="../../../../org/springframework/transaction/support/TransactionTemplate.html" title="class in org.springframework.transaction.support"><CODE>TransactionTemplate</CODE></A>'s <code>execute</code> method, often as anonymous class within a method implementation. <p>Typically used to assemble various calls to transaction-unaware data access services into a higher-level service method with transaction demarcation. As an alternative, consider the use of declarative transaction demarcation (e.g. through Spring's <A HREF="../../../../org/springframework/transaction/annotation/Transactional.html" title="annotation in org.springframework.transaction.annotation"><CODE>Transactional</CODE></A> annotation). <P> <P> <DL> <DT><B>Since:</B></DT> <DD>17.03.2003</DD> <DT><B>Author:</B></DT> <DD>Juergen Hoeller</DD> <DT><B>See Also:</B><DD><A HREF="../../../../org/springframework/transaction/support/TransactionTemplate.html" title="class in org.springframework.transaction.support"><CODE>TransactionTemplate</CODE></A>, <A HREF="../../../../org/springframework/transaction/support/CallbackPreferringPlatformTransactionManager.html" title="interface in org.springframework.transaction.support"><CODE>CallbackPreferringPlatformTransactionManager</CODE></A></DL> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/springframework/transaction/support/TransactionCallback.html#doInTransaction(org.springframework.transaction.TransactionStatus)">doInTransaction</A></B>(<A HREF="../../../../org/springframework/transaction/TransactionStatus.html" title="interface in org.springframework.transaction">TransactionStatus</A>&nbsp;status)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets called by <A HREF="../../../../org/springframework/transaction/support/TransactionTemplate.html#execute(org.springframework.transaction.support.TransactionCallback)"><CODE>TransactionTemplate.execute(org.springframework.transaction.support.TransactionCallback)</CODE></A> within a transactional context.</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="doInTransaction(org.springframework.transaction.TransactionStatus)"><!-- --></A><H3> doInTransaction</H3> <PRE> <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> <B>doInTransaction</B>(<A HREF="../../../../org/springframework/transaction/TransactionStatus.html" title="interface in org.springframework.transaction">TransactionStatus</A>&nbsp;status)</PRE> <DL> <DD>Gets called by <A HREF="../../../../org/springframework/transaction/support/TransactionTemplate.html#execute(org.springframework.transaction.support.TransactionCallback)"><CODE>TransactionTemplate.execute(org.springframework.transaction.support.TransactionCallback)</CODE></A> within a transactional context. Does not need to care about transactions itself, although it can retrieve and influence the status of the current transaction via the given status object, e.g. setting rollback-only. <p>Allows for returning a result object created within the transaction, i.e. a domain object or a collection of domain objects. A RuntimeException thrown by the callback is treated as application exception that enforces a rollback. An exception gets propagated to the caller of the template. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>status</CODE> - associated transaction status <DT><B>Returns:</B><DD>a result object, or <code>null</code><DT><B>See Also:</B><DD><A HREF="../../../../org/springframework/transaction/support/TransactionTemplate.html#execute(org.springframework.transaction.support.TransactionCallback)"><CODE>TransactionTemplate.execute(org.springframework.transaction.support.TransactionCallback)</CODE></A>, <A HREF="../../../../org/springframework/transaction/support/CallbackPreferringPlatformTransactionManager.html#execute(org.springframework.transaction.TransactionDefinition, org.springframework.transaction.support.TransactionCallback)"><CODE>CallbackPreferringPlatformTransactionManager.execute(org.springframework.transaction.TransactionDefinition, org.springframework.transaction.support.TransactionCallback)</CODE></A></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/TransactionCallback.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/springframework/transaction/support/SmartTransactionObject.html" title="interface in org.springframework.transaction.support"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/springframework/transaction/support/TransactionCallbackWithoutResult.html" title="class in org.springframework.transaction.support"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/springframework/transaction/support/TransactionCallback.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TransactionCallback.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &copy; 2002-2007 <a href=http://www.springframework.org/ target=_top>The Spring Framework</a>.</i> </BODY> </HTML>
cacheonix/cacheonix-core
3rdparty/spring-framework-2.5.1/docs/api/org/springframework/transaction/support/TransactionCallback.html
HTML
lgpl-2.1
12,874
import urllib2 import re JIRA_URL='https://bugreports.qt-project.org/browse' class JIRA: __instance__ = None # Helper class class Bug: CREATOR = 'QTCREATORBUG' SIMULATOR = 'QTSIM' SDK = 'QTSDK' QT = 'QTBUG' QT_QUICKCOMPONENTS = 'QTCOMPONENTS' # constructor of JIRA def __init__(self, number, bugType=Bug.CREATOR): if JIRA.__instance__ == None: JIRA.__instance__ = JIRA.__impl(number, bugType) JIRA.__dict__['_JIRA__instance__'] = JIRA.__instance__ else: JIRA.__instance__._bugType = bugType JIRA.__instance__._number = number JIRA.__instance__.__fetchStatusAndResolutionFromJira__() # overriden to make it possible to use JIRA just like the # underlying implementation (__impl) def __getattr__(self, attr): return getattr(self.__instance__, attr) # overriden to make it possible to use JIRA just like the # underlying implementation (__impl) def __setattr__(self, attr, value): return setattr(self.__instance__, attr, value) # function to get an instance of the singleton @staticmethod def getInstance(): if '_JIRA__instance__' in JIRA.__dict__: return JIRA.__instance__ else: return JIRA.__impl(0, Bug.CREATOR) # function to check if the given bug is open or not @staticmethod def isBugStillOpen(number, bugType=Bug.CREATOR): tmpJIRA = JIRA(number, bugType) return tmpJIRA.isOpen() # function similar to performWorkaroundForBug - but it will execute the # workaround (function) only if the bug is still open # returns True if the workaround function has been executed, False otherwise @staticmethod def performWorkaroundIfStillOpen(number, bugType=Bug.CREATOR, *args): if JIRA.isBugStillOpen(number, bugType): return JIRA.performWorkaroundForBug(number, bugType, *args) else: test.warning("Bug is closed... skipping workaround!", "You should remove potential code inside performWorkaroundForBug()") return False # function that performs the workaround (function) for the given bug # if the function needs additional arguments pass them as 3rd parameter @staticmethod def performWorkaroundForBug(number, bugType=Bug.CREATOR, *args): functionToCall = JIRA.getInstance().__bugs__.get("%s-%d" % (bugType, number), None) if functionToCall: test.warning("Using workaround for %s-%d" % (bugType, number)) functionToCall(*args) return True else: JIRA.getInstance()._exitFatal_(bugType, number) return False # implementation of JIRA singleton class __impl: # constructor of __impl def __init__(self, number, bugType): self._number = number self._bugType = bugType self._localOnly = os.getenv("SYSTEST_JIRA_NO_LOOKUP")=="1" self.__initBugDict__() self.__fetchStatusAndResolutionFromJira__() # function to retrieve the status of the current bug def getStatus(self): return self._status # function to retrieve the resolution of the current bug def getResolution(self): return self._resolution # this function checks the resolution of the given bug # and returns True if the bug can still be assumed as 'Open' and False otherwise def isOpen(self): # handle special cases if self._resolution == None: return True if self._resolution in ('Duplicate', 'Moved', 'Incomplete', 'Cannot Reproduce', 'Invalid'): test.warning("Resolution of bug is '%s' - assuming 'Open' for now." % self._resolution, "Please check the bugreport manually and update this test.") return True return self._resolution != 'Done' # this function tries to fetch the status and resolution from JIRA for the given bug # if this isn't possible or the lookup is disabled it does only check the internal # dict whether a function for the given bug is deposited or not def __fetchStatusAndResolutionFromJira__(self): global JIRA_URL data = None if not self._localOnly: try: bugReport = urllib2.urlopen('%s/%s-%d' % (JIRA_URL, self._bugType, self._number)) data = bugReport.read() except: data = self.__tryExternalTools__() if data == None: test.warning("Sorry, ssl module missing - cannot fetch data via HTTPS", "Try to install the ssl module by yourself, or set the python " "path inside SQUISHDIR/etc/paths.ini to use a python version with " "ssl support OR install wget or curl to get rid of this warning!") self._localOnly = True if data == None: if '%s-%d' % (self._bugType, self._number) in self.__bugs__: test.warning("Using internal dict - bug status could have changed already", "Please check manually!") self._status = None self._resolution = None return else: test.fatal("No workaround function deposited for %s-%d" % (self._bugType, self._number)) self._resolution = 'Done' return else: data = data.replace("\r", "").replace("\n", "") resPattern = re.compile('<span\s+id="resolution-val".*?>(?P<resolution>.*?)</span>') statPattern = re.compile('<span\s+id="status-val".*?>(.*?<img.*?>)?(?P<status>.*?)</span>') status = statPattern.search(data) resolution = resPattern.search(data) if status: self._status = status.group("status").strip() else: test.fatal("FATAL: Cannot get status of bugreport %s-%d" % (self._bugType, self._number), "Looks like JIRA has changed.... Please verify!") self._status = None if resolution: self._resolution = resolution.group("resolution").strip() else: test.fatal("FATAL: Cannot get resolution of bugreport %s-%d" % (self._bugType, self._number), "Looks like JIRA has changed.... Please verify!") self._resolution = None # simple helper function - used as fallback if python has no ssl support # tries to find curl or wget in PATH and fetches data with it instead of # using urllib2 def __tryExternalTools__(self): global JIRA_URL cmdAndArgs = { 'curl':'-k', 'wget':'-qO-' } for call in cmdAndArgs: prog = which(call) if prog: return getOutputFromCmdline('"%s" %s %s/%s-%d' % (prog, cmdAndArgs[call], JIRA_URL, self._bugType, self._number)) return None # this function initializes the bug dict for localOnly usage and # for later lookup which function to call for which bug # ALWAYS update this dict when adding a new function for a workaround! def __initBugDict__(self): self.__bugs__= { 'QTCREATORBUG-6853':self._workaroundCreator6853_, 'QTCREATORBUG-6918':self._workaroundCreator_MacEditorFocus_, 'QTCREATORBUG-6953':self._workaroundCreator_MacEditorFocus_, 'QTCREATORBUG-6994':self._workaroundCreator6994_, 'QTCREATORBUG-7002':self._workaroundCreator7002_ } # helper function - will be called if no workaround for the requested bug is deposited def _exitFatal_(self, bugType, number): test.fatal("No workaround found for bug %s-%d" % (bugType, number)) ############### functions that hold workarounds ################################# def _workaroundCreator6994_(self, *args): if args[0] in ('Mobile Qt Application', 'Qt Gui Application', 'Qt Custom Designer Widget'): args[1].remove('Harmattan') test.xverify(False, "Removed Harmattan from expected targets.") def _workaroundCreator6853_(self, *args): if "Release" in args[0] and platform.system() == "Linux": snooze(1) def _workaroundCreator_MacEditorFocus_(self, *args): editor = args[0] nativeMouseClick(editor.mapToGlobal(QPoint(50, 50)).x, editor.mapToGlobal(QPoint(50, 50)).y, Qt.LeftButton) def _workaroundCreator7002_(self, *args): if platform.system() in ("Linux", "Darwin"): result = args[0] result.append(QtQuickConstants.Targets.EMBEDDED_LINUX)
hdweiss/qt-creator-visualizer
tests/system/shared/workarounds.py
Python
lgpl-2.1
9,260
//////////////////////////////////////////////////////////////// // // Copyright (C) 2005 Affymetrix, Inc. // // 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 "calvin_files/array/test/PATAssignmentTest.h" // #include "calvin_files/array/src/PATAssignment.h" // using namespace affymetrix_calvin_array; using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION( PATAssignmentMethodTest ); void PATAssignmentMethodTest::setUp() { } void PATAssignmentMethodTest::tearDown() { } void PATAssignmentMethodTest::test_MediaToString() { CPPUNIT_ASSERT(PATAssignmentMethodToString(NoAssignment) == L"None"); CPPUNIT_ASSERT(PATAssignmentMethodToString(AffyBarcodeAssignment) == L"AffyBarcode"); CPPUNIT_ASSERT(PATAssignmentMethodToString(UserSelectedAssignment) == L"UserSelected"); CPPUNIT_ASSERT(PATAssignmentMethodToString(OtherAssignment) == L"Other"); } void PATAssignmentMethodTest::test_MediaFromString() { CPPUNIT_ASSERT(PATAssignmentMethodFromString(L"None") == NoAssignment); CPPUNIT_ASSERT(PATAssignmentMethodFromString(L"AffyBarcode") == AffyBarcodeAssignment); CPPUNIT_ASSERT(PATAssignmentMethodFromString(L"UserSelected") == UserSelectedAssignment); CPPUNIT_ASSERT(PATAssignmentMethodFromString(L"Other") == OtherAssignment); }
einon/affymetrix-power-tools
sdk/calvin_files/array/test/PATAssignmentTest.cpp
C++
lgpl-2.1
1,945
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: MultiExplodeTest.php 59579 2016-09-01 13:59:16Z kroky6 $ class TikiLib_MultiExplodeTest extends PHPUnit_Framework_TestCase { private $saved; function setUp() { global $prefs; $this->saved = $prefs['namespace_separator']; } function tearDown() { global $prefs; $prefs['namespace_separator'] = $this->saved; } function testSimple() { $lib = TikiLib::lib('tiki'); $this->assertEquals(array('A', 'B'), $lib->multi_explode(':', 'A:B')); $this->assertEquals(array('A', '', 'B'), $lib->multi_explode(':', 'A::B')); $this->assertEquals(array('A', '', '', 'B'), $lib->multi_explode(':', 'A:::B')); } function testEmpty() { $lib = TikiLib::lib('tiki'); $this->assertEquals(array(''), $lib->multi_explode(':', '')); $this->assertEquals(array('', ''), $lib->multi_explode(':', ':')); $this->assertEquals(array('', 'B'), $lib->multi_explode(':', ':B')); $this->assertEquals(array('A', ''), $lib->multi_explode(':', 'A:')); } function testIgnoreCharactersUsedInNamespace() { global $prefs; $lib = TikiLib::lib('tiki'); $prefs['namespace_separator'] = ':+:'; $this->assertEquals(array('A:+:B:+:C', 'A:+:B'), $lib->multi_explode(':', 'A:+:B:+:C:A:+:B')); $this->assertEquals(array('A', '-', 'B:+:C', 'A:+:B'), $lib->multi_explode(':', 'A:-:B:+:C:A:+:B')); $prefs['namespace_separator'] = ':-:'; $this->assertEquals(array('A', '+', 'B', '+', 'C', 'A', '+', 'B'), $lib->multi_explode(':', 'A:+:B:+:C:A:+:B')); $this->assertEquals(array('A:-:B', '+', 'C', 'A', '+', 'B'), $lib->multi_explode(':', 'A:-:B:+:C:A:+:B')); } function testSimpleImplode() { $lib = TikiLib::lib('tiki'); $this->assertEquals('A:B', $lib->multi_implode(':', array('A', 'B'))); $this->assertEquals('A+C:B+D', $lib->multi_implode(array(':', '+'), array(array('A', 'C'), array('B', 'D')))); } }
XavierSolerFR/diem25tiki
lib/test/TikiLib/MultiExplodeTest.php
PHP
lgpl-2.1
2,090
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library 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. * * 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * 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 * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ // -*- C++ -*- /* * Copyright (C) 1990,91,92 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1.1.1 $ | | Description: | This file defines the jack dragger class, so named because | with the default geometry, it looks like the children's toy. | This dragger allows you to perform rotations,uniform scales | and translations, all in one spiffy gadget. | | Translation is done with a dragPointDragger, rotation with a | rotateSphericalDragger, and scaling with a scaleUniformDragger. | | NOTE TO DEVELOPERS: | For info about the structure of SoJackDragger: | [1] compile: /usr/share/src/Inventor/samples/ivNodeKitStructure | [2] type: ivNodeKitStructure SoJackDragger. | [3] The program prints a diagram of the scene graph and a table with | information about each part. | | The following parts in this dragger are created at construction time. | 'ResourceName' corresponds to the name of the default geometry for the | part. The dragger's constructor gets the scene graph for 'ResourceName' | by querying the global dictionary ( SoDB::getByName("ResourceName"); ). | | Resource Name: Part Name: | | jackScalerScaler - scaler.scaler | jackScalerScalerActive - scaler.scalerActive | jackScalerFeedback - scaler.feedback | jackScalerFeedbackActive - scaler.feedbackActive | | jackRotatorRotator - rotator.rotator | jackRotatorRotatorActive - rotator.rotatorActive | jackRotatorFeedback - rotator.feedback | jackRotatorFeedbackActive - rotator.feedbackActive | | jackTranslatorLineTranslator - | - translator.xTranslator.translator | - translator.yTranslator.translator | - translator.zTranslator.translator | | jackTranslatorLineTranslatorActive - | - translator.xTranslator.translatorActive | - translator.yTranslator.translatorActive | - translator.zTranslator.translatorActive | | jackTranslatorPlaneTranslator - | - translator.yzTranslator.translator | - translator.xzTranslator.translator | - translator.xyTranslator.translator | | jackTranslatorPlaneTranslatorActive - | - translator.yzTranslator.translatorActive | - translator.xzTranslator.translatorActive | - translator.xyTranslator.translatorActive | | jackTranslatorXFeedback - translator.xFeedback | jackTranslatorYFeedback - translator.yFeedback | jackTranslatorZFeedback - translator.zFeedback | | jackTranslatorXYFeedback - translator.xyFeedback | jackTranslatorXZFeedback - translator.xzFeedback | jackTranslatorYZFeedback - translator.yzFeedback | | Author(s): Paul Isaacs | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #ifndef _SO_JACK_DRAGGER_ #define _SO_JACK_DRAGGER_ #include <Inventor/SbLinear.h> #include <Inventor/draggers/SoDragger.h> #include <Inventor/fields/SoSFVec3f.h> #include <Inventor/fields/SoSFRotation.h> #include <Inventor/sensors/SoSensor.h> class SbDict; class SoFieldSensor; // C-api: prefix=SoJackDrag // C-api: public=rotation,translation,scaleFactor class SoJackDragger : public SoDragger { SO_KIT_HEADER(SoJackDragger); // For making the dragger surround what lies above it. SO_KIT_CATALOG_ENTRY_HEADER(surroundScale); // For keeping the dragger even size in all 3 dimensions SO_KIT_CATALOG_ENTRY_HEADER(antiSquish); SO_KIT_CATALOG_ENTRY_HEADER(scaler); SO_KIT_CATALOG_ENTRY_HEADER(rotator); SO_KIT_CATALOG_ENTRY_HEADER(translator); public: // Constructors SoJackDragger(); SoSFRotation rotation; SoSFVec3f translation; SoSFVec3f scaleFactor; SoINTERNAL public: static void initClass(); // initialize the class protected: SoFieldSensor *rotFieldSensor; SoFieldSensor *translFieldSensor; SoFieldSensor *scaleFieldSensor; static void fieldSensorCB( void *, SoSensor * ); static void valueChangedCB( void *, SoDragger * ); static void invalidateSurroundScaleCB( void *, SoDragger * ); // detach/attach any sensors, callbacks, and/or field connections. // Also set geometry of childDraggers to be our default instead of their // regular default, using our resources. // Called by: start/end of SoBaseKit::readInstance // and on new copy by: start/end of SoBaseKit::copy. // Classes that redefine must call setUpConnections(TRUE,TRUE) // at end of constructor. // Returns the state of the node when this was called. virtual SbBool setUpConnections( SbBool onOff, SbBool doItAlways = FALSE ); virtual void setDefaultOnNonWritingFields(); virtual ~SoJackDragger(); private: static const char geomBuffer[]; }; #endif /* _SO_JACK_DRAGGER_ */
aumuell/open-inventor
lib/interaction/include/Inventor/draggers/SoJackDragger.h
C
lgpl-2.1
7,015
#ifndef __PLAYSCENE_HPP__ #define __PLAYSCENE_HPP__ #include <fichin/fScene.hpp> #include <fichin/fSprite.hpp> #include "Character.hpp" class PlayScene: public fScene{ public: void init(); void update(float dt); private: Character *c; fTilemap *t; fGroup *enemies; }; #endif // __PLAYSCENE_HPP__
pabab/fichin_examples
platformer/PlayScene.hpp
C++
lgpl-2.1
308
/* GStreamer * * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net> * 2006 Edgard Lima <edgard.lima@indt.org.br> * 2009 Texas Instruments, Inc - http://www.ti.com/ * * gstv4l2bufferpool.c V4L2 buffer pool class * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifndef _GNU_SOURCE # define _GNU_SOURCE /* O_CLOEXEC */ #endif #include <fcntl.h> #include <sys/mman.h> #include <string.h> #include <unistd.h> #include "gst/video/video.h" #include "gst/video/gstvideometa.h" #include "gst/video/gstvideopool.h" #include "gst/allocators/gstdmabuf.h" #include <gstv4l2bufferpool.h> #include "v4l2_calls.h" #include "gst/gst-i18n-plugin.h" #include <gst/glib-compat-private.h> GST_DEBUG_CATEGORY_EXTERN (v4l2_debug); GST_DEBUG_CATEGORY_EXTERN (GST_CAT_PERFORMANCE); #define GST_CAT_DEFAULT v4l2_debug #define GST_V4L2_IMPORT_QUARK gst_v4l2_buffer_pool_import_quark () /* * GstV4l2BufferPool: */ #define gst_v4l2_buffer_pool_parent_class parent_class G_DEFINE_TYPE (GstV4l2BufferPool, gst_v4l2_buffer_pool, GST_TYPE_BUFFER_POOL); enum _GstV4l2BufferPoolAcquireFlags { GST_V4L2_POOL_ACQUIRE_FLAG_RESURECT = GST_BUFFER_POOL_ACQUIRE_FLAG_LAST, GST_V4L2_BUFFER_POOL_ACQUIRE_FAG_LAST }; static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer); static gboolean gst_v4l2_is_buffer_valid (GstBuffer * buffer, GstV4l2MemoryGroup ** group) { GstMemory *mem = gst_buffer_peek_memory (buffer, 0); gboolean valid = FALSE; if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY)) goto done; if (gst_is_dmabuf_memory (mem)) mem = gst_mini_object_get_qdata (GST_MINI_OBJECT (mem), GST_V4L2_MEMORY_QUARK); if (mem && gst_is_v4l2_memory (mem)) { GstV4l2Memory *vmem = (GstV4l2Memory *) mem; valid = TRUE; if (group) *group = vmem->group; } done: return valid; } static GstFlowReturn gst_v4l2_buffer_pool_copy_buffer (GstV4l2BufferPool * pool, GstBuffer * dest, GstBuffer * src) { const GstVideoFormatInfo *finfo = pool->caps_info.finfo; GST_LOG_OBJECT (pool, "copying buffer"); if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN && finfo->format != GST_VIDEO_FORMAT_ENCODED)) { GstVideoFrame src_frame, dest_frame; GST_DEBUG_OBJECT (pool, "copy video frame"); /* we have raw video, use videoframe copy to get strides right */ if (!gst_video_frame_map (&src_frame, &pool->caps_info, src, GST_MAP_READ)) goto invalid_buffer; if (!gst_video_frame_map (&dest_frame, &pool->caps_info, dest, GST_MAP_WRITE)) { gst_video_frame_unmap (&src_frame); goto invalid_buffer; } gst_video_frame_copy (&dest_frame, &src_frame); gst_video_frame_unmap (&src_frame); gst_video_frame_unmap (&dest_frame); } else { GstMapInfo map; GST_DEBUG_OBJECT (pool, "copy raw bytes"); if (!gst_buffer_map (src, &map, GST_MAP_READ)) goto invalid_buffer; gst_buffer_fill (dest, 0, map.data, gst_buffer_get_size (src)); gst_buffer_unmap (src, &map); gst_buffer_resize (dest, 0, gst_buffer_get_size (src)); } GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, pool, "slow copy into buffer %p", dest); return GST_FLOW_OK; invalid_buffer: { GST_ERROR_OBJECT (pool, "could not map buffer"); return GST_FLOW_ERROR; } } struct UserPtrData { GstBuffer *buffer; gboolean is_frame; GstVideoFrame frame; GstMapInfo map; }; static GQuark gst_v4l2_buffer_pool_import_quark (void) { static GQuark quark = 0; if (quark == 0) quark = g_quark_from_string ("GstV4l2BufferPoolUsePtrData"); return quark; } static void _unmap_userptr_frame (struct UserPtrData *data) { if (data->is_frame) gst_video_frame_unmap (&data->frame); else gst_buffer_unmap (data->buffer, &data->map); if (data->buffer) gst_buffer_unref (data->buffer); g_slice_free (struct UserPtrData, data); } static GstFlowReturn gst_v4l2_buffer_pool_import_userptr (GstV4l2BufferPool * pool, GstBuffer * dest, GstBuffer * src) { GstFlowReturn ret = GST_FLOW_OK; GstV4l2MemoryGroup *group = NULL; GstMapFlags flags; const GstVideoFormatInfo *finfo = pool->caps_info.finfo; struct UserPtrData *data = NULL; GST_LOG_OBJECT (pool, "importing userptr"); /* get the group */ if (!gst_v4l2_is_buffer_valid (dest, &group)) goto not_our_buffer; if (V4L2_TYPE_IS_OUTPUT (pool->obj->type)) flags = GST_MAP_READ; else flags = GST_MAP_WRITE; data = g_slice_new0 (struct UserPtrData); if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN && finfo->format != GST_VIDEO_FORMAT_ENCODED)) { data->is_frame = TRUE; if (!gst_video_frame_map (&data->frame, &pool->caps_info, src, flags)) goto invalid_buffer; if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group, data->frame.info.size, finfo->n_planes, data->frame.data, data->frame.info.offset)) goto import_failed; } else { gsize offset[1] = { 0 }; gpointer ptr[1]; data->is_frame = FALSE; if (!gst_buffer_map (src, &data->map, flags)) goto invalid_buffer; ptr[0] = data->map.data; if (!gst_v4l2_allocator_import_userptr (pool->vallocator, group, data->map.size, 1, ptr, offset)) goto import_failed; } data->buffer = gst_buffer_ref (src); gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK, data, (GDestroyNotify) _unmap_userptr_frame); return ret; not_our_buffer: { GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool"); return GST_FLOW_ERROR; } invalid_buffer: { GST_ERROR_OBJECT (pool, "could not map buffer"); g_slice_free (struct UserPtrData, data); return GST_FLOW_ERROR; } import_failed: { GST_ERROR_OBJECT (pool, "failed to import data"); _unmap_userptr_frame (data); return GST_FLOW_ERROR; } } static GstFlowReturn gst_v4l2_buffer_pool_import_dmabuf (GstV4l2BufferPool * pool, GstBuffer * dest, GstBuffer * src) { GstV4l2MemoryGroup *group = NULL; GstMemory *dma_mem[GST_VIDEO_MAX_PLANES] = { 0 }; guint n_mem = gst_buffer_n_memory (src); gint i; GST_LOG_OBJECT (pool, "importing dmabuf"); if (!gst_v4l2_is_buffer_valid (dest, &group)) goto not_our_buffer; if (n_mem > GST_VIDEO_MAX_PLANES) goto too_many_mems; for (i = 0; i < n_mem; i++) dma_mem[i] = gst_buffer_peek_memory (src, i); if (!gst_v4l2_allocator_import_dmabuf (pool->vallocator, group, n_mem, dma_mem)) goto import_failed; gst_mini_object_set_qdata (GST_MINI_OBJECT (dest), GST_V4L2_IMPORT_QUARK, gst_buffer_ref (src), (GDestroyNotify) gst_buffer_unref); return GST_FLOW_OK; not_our_buffer: { GST_ERROR_OBJECT (pool, "destination buffer invalid or not from our pool"); return GST_FLOW_ERROR; } too_many_mems: { GST_ERROR_OBJECT (pool, "could not map buffer"); return GST_FLOW_ERROR; } import_failed: { GST_ERROR_OBJECT (pool, "failed to import dmabuf"); return GST_FLOW_ERROR; } } static GstFlowReturn gst_v4l2_buffer_pool_prepare_buffer (GstV4l2BufferPool * pool, GstBuffer * dest, GstBuffer * src) { GstFlowReturn ret = GST_FLOW_OK; gboolean own_src = FALSE; if (src == NULL) { if (pool->other_pool == NULL) { GST_ERROR_OBJECT (pool, "can't prepare buffer, source buffer missing"); return GST_FLOW_ERROR; } ret = gst_buffer_pool_acquire_buffer (pool->other_pool, &src, NULL); if (ret != GST_FLOW_OK) { GST_ERROR_OBJECT (pool, "failed to acquire buffer from downstream pool"); goto done; } own_src = TRUE; } switch (pool->obj->mode) { case GST_V4L2_IO_MMAP: case GST_V4L2_IO_DMABUF: ret = gst_v4l2_buffer_pool_copy_buffer (pool, dest, src); break; case GST_V4L2_IO_USERPTR: ret = gst_v4l2_buffer_pool_import_userptr (pool, dest, src); break; case GST_V4L2_IO_DMABUF_IMPORT: ret = gst_v4l2_buffer_pool_import_dmabuf (pool, dest, src); break; default: break; } if (own_src) gst_buffer_unref (src); done: return ret; } static GstFlowReturn gst_v4l2_buffer_pool_alloc_buffer (GstBufferPool * bpool, GstBuffer ** buffer, GstBufferPoolAcquireParams * params) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GstV4l2MemoryGroup *group = NULL; GstBuffer *newbuf = NULL; GstV4l2Object *obj; GstVideoInfo *info; obj = pool->obj; info = &obj->info; switch (obj->mode) { case GST_V4L2_IO_RW: newbuf = gst_buffer_new_allocate (pool->allocator, pool->size, &pool->params); break; case GST_V4L2_IO_MMAP: group = gst_v4l2_allocator_alloc_mmap (pool->vallocator); break; case GST_V4L2_IO_DMABUF: group = gst_v4l2_allocator_alloc_dmabuf (pool->vallocator, pool->allocator); break; case GST_V4L2_IO_USERPTR: group = gst_v4l2_allocator_alloc_userptr (pool->vallocator); break; case GST_V4L2_IO_DMABUF_IMPORT: group = gst_v4l2_allocator_alloc_dmabufin (pool->vallocator); break; default: newbuf = NULL; g_assert_not_reached (); break; } if (group != NULL) { gint i; newbuf = gst_buffer_new (); for (i = 0; i < group->n_mem; i++) gst_buffer_append_memory (newbuf, group->mem[i]); } else if (newbuf == NULL) { goto allocation_failed; } /* add metadata to raw video buffers */ if (pool->add_videometa) gst_buffer_add_video_meta_full (newbuf, GST_VIDEO_FRAME_FLAG_NONE, GST_VIDEO_INFO_FORMAT (info), GST_VIDEO_INFO_WIDTH (info), GST_VIDEO_INFO_HEIGHT (info), GST_VIDEO_INFO_N_PLANES (info), info->offset, info->stride); *buffer = newbuf; return GST_FLOW_OK; /* ERRORS */ allocation_failed: { GST_ERROR_OBJECT (pool, "failed to allocate buffer"); return GST_FLOW_ERROR; } } static gboolean gst_v4l2_buffer_pool_set_config (GstBufferPool * bpool, GstStructure * config) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GstV4l2Object *obj = pool->obj; GstCaps *caps; guint size, min_buffers, max_buffers; GstAllocator *allocator; GstAllocationParams params; gboolean can_allocate = FALSE; gboolean updated = FALSE; gboolean ret; pool->add_videometa = gst_buffer_pool_config_has_option (config, GST_BUFFER_POOL_OPTION_VIDEO_META); /* parse the config and keep around */ if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers, &max_buffers)) goto wrong_config; if (!gst_buffer_pool_config_get_allocator (config, &allocator, &params)) goto wrong_config; GST_DEBUG_OBJECT (pool, "config %" GST_PTR_FORMAT, config); if (pool->allocator) gst_object_unref (pool->allocator); pool->allocator = NULL; switch (obj->mode) { case GST_V4L2_IO_DMABUF: pool->allocator = gst_dmabuf_allocator_new (); can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP); break; case GST_V4L2_IO_MMAP: can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP); break; case GST_V4L2_IO_USERPTR: can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR); break; case GST_V4L2_IO_DMABUF_IMPORT: can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF); break; case GST_V4L2_IO_RW: pool->allocator = g_object_ref (allocator); pool->params = params; /* No need to change the configuration */ goto done; break; default: g_assert_not_reached (); break; } if (min_buffers < GST_V4L2_MIN_BUFFERS) { updated = TRUE; min_buffers = GST_V4L2_MIN_BUFFERS; GST_INFO_OBJECT (pool, "increasing minimum buffers to %u", min_buffers); } if (max_buffers > VIDEO_MAX_FRAME || max_buffers == 0) { updated = TRUE; max_buffers = VIDEO_MAX_FRAME; GST_INFO_OBJECT (pool, "reducing maximum buffers to %u", max_buffers); } if (min_buffers > max_buffers) { updated = TRUE; min_buffers = max_buffers; GST_INFO_OBJECT (pool, "reducing minimum buffers to %u", min_buffers); } else if (min_buffers != max_buffers) { if (!can_allocate) { updated = TRUE; max_buffers = min_buffers; GST_INFO_OBJECT (pool, "can't allocate, setting maximum to minimum"); } } if (!pool->add_videometa && obj->need_video_meta) { GST_INFO_OBJECT (pool, "adding needed video meta"); updated = TRUE; gst_buffer_pool_config_add_option (config, GST_BUFFER_POOL_OPTION_VIDEO_META); } if (updated) gst_buffer_pool_config_set_params (config, caps, size, min_buffers, max_buffers); /* keep a GstVideoInfo with defaults for the when we need to copy */ gst_video_info_from_caps (&pool->caps_info, caps); done: ret = GST_BUFFER_POOL_CLASS (parent_class)->set_config (bpool, config); /* If anything was changed documentation recommand to return FALSE */ return !updated && ret; /* ERRORS */ wrong_config: { GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config); return FALSE; } } static gboolean gst_v4l2_buffer_pool_streamon (GstV4l2BufferPool * pool) { GstV4l2Object *obj = pool->obj; switch (obj->mode) { case GST_V4L2_IO_MMAP: case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_DMABUF_IMPORT: if (!pool->streaming) { if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMON, &obj->type) < 0) goto streamon_failed; pool->streaming = TRUE; GST_DEBUG_OBJECT (pool, "Started streaming"); } break; default: break; } return TRUE; streamon_failed: { GST_ERROR_OBJECT (pool, "error with STREAMON %d (%s)", errno, g_strerror (errno)); return FALSE; } } static gboolean gst_v4l2_buffer_pool_streamoff (GstV4l2BufferPool * pool) { GstV4l2Object *obj = pool->obj; switch (obj->mode) { case GST_V4L2_IO_MMAP: case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_DMABUF_IMPORT: if (pool->streaming) { if (v4l2_ioctl (pool->video_fd, VIDIOC_STREAMOFF, &obj->type) < 0) goto streamoff_failed; pool->streaming = FALSE; GST_DEBUG_OBJECT (pool, "Stopped streaming"); } break; default: break; } return TRUE; streamoff_failed: { GST_ERROR_OBJECT (pool, "error with STREAMOFF %d (%s)", errno, g_strerror (errno)); return FALSE; } } static void gst_v4l2_buffer_pool_group_released (GstV4l2BufferPool * pool) { GstBufferPoolAcquireParams params = { 0 }; GstBuffer *buffer = NULL; GstFlowReturn ret; GST_DEBUG_OBJECT (pool, "A buffer was lost, reallocating it"); params.flags = (GstBufferPoolAcquireFlags) GST_V4L2_POOL_ACQUIRE_FLAG_RESURECT; ret = gst_buffer_pool_acquire_buffer (GST_BUFFER_POOL (pool), &buffer, &params); if (ret == GST_FLOW_OK) gst_buffer_unref (buffer); } static gboolean gst_v4l2_buffer_pool_start (GstBufferPool * bpool) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class); GstV4l2Object *obj = pool->obj; GstStructure *config; GstCaps *caps; guint size, min_buffers, max_buffers; guint max_latency, min_latency, copy_threshold = 0; gboolean can_allocate = FALSE; GST_DEBUG_OBJECT (pool, "activating pool"); config = gst_buffer_pool_get_config (bpool); if (!gst_buffer_pool_config_get_params (config, &caps, &size, &min_buffers, &max_buffers)) goto wrong_config; /* TODO Also consider min_buffers_for_output when implemented */ min_latency = MAX (GST_V4L2_MIN_BUFFERS, obj->min_buffers_for_capture); switch (obj->mode) { case GST_V4L2_IO_RW: can_allocate = TRUE; break; case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_MMAP: { guint count; can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP); /* first, lets request buffers, and see how many we can get: */ GST_DEBUG_OBJECT (pool, "requesting %d MMAP buffers", min_buffers); count = gst_v4l2_allocator_start (pool->vallocator, min_buffers, V4L2_MEMORY_MMAP); if (count < GST_V4L2_MIN_BUFFERS) { min_buffers = count; goto no_buffers; } /* V4L2 buffer pool are often very limited in the amount of buffers it * can offer. The copy_threshold will workaround this limitation by * falling back to copy if the pipeline needed more buffers. This also * prevent having to do REQBUFS(N)/REQBUFS(0) everytime configure is * called. */ if (count != min_buffers) { GST_WARNING_OBJECT (pool, "using %u buffers instead of %u", count, min_buffers); min_buffers = count; copy_threshold = min_latency; /* The initial minimum could be provide either by GstBufferPool or * driver needs. */ min_buffers = count; } break; } case GST_V4L2_IO_USERPTR: { guint count; can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, USERPTR); GST_DEBUG_OBJECT (pool, "requesting %d USERPTR buffers", min_buffers); count = gst_v4l2_allocator_start (pool->vallocator, min_buffers, V4L2_MEMORY_USERPTR); /* There is no rational to not get what we asked */ if (count < min_buffers) { min_buffers = count; goto no_buffers; } min_buffers = count; break; } case GST_V4L2_IO_DMABUF_IMPORT: { guint count; can_allocate = GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, DMABUF); GST_DEBUG_OBJECT (pool, "requesting %d DMABUF buffers", min_buffers); count = gst_v4l2_allocator_start (pool->vallocator, min_buffers, V4L2_MEMORY_DMABUF); /* There is no rational to not get what we asked */ if (count < min_buffers) { min_buffers = count; goto no_buffers; } min_buffers = count; break; } default: min_buffers = 0; copy_threshold = 0; g_assert_not_reached (); break; } if (can_allocate) max_latency = max_buffers; else max_latency = min_buffers; pool->size = size; pool->copy_threshold = copy_threshold; pool->max_latency = max_latency; pool->min_latency = min_latency; pool->num_queued = 0; if (max_buffers < min_buffers) max_buffers = min_buffers; gst_buffer_pool_config_set_params (config, caps, size, min_buffers, max_buffers); pclass->set_config (bpool, config); gst_structure_free (config); if (pool->other_pool) if (!gst_buffer_pool_set_active (pool->other_pool, TRUE)) goto other_pool_failed; /* now, allocate the buffers: */ if (!pclass->start (bpool)) goto start_failed; if (!V4L2_TYPE_IS_OUTPUT (obj->type)) pool->group_released_handler = g_signal_connect_swapped (pool->vallocator, "group-released", G_CALLBACK (gst_v4l2_buffer_pool_group_released), pool); return TRUE; /* ERRORS */ wrong_config: { GST_ERROR_OBJECT (pool, "invalid config %" GST_PTR_FORMAT, config); gst_structure_free (config); return FALSE; } no_buffers: { GST_ERROR_OBJECT (pool, "we received %d buffer from device '%s', we want at least %d", min_buffers, obj->videodev, GST_V4L2_MIN_BUFFERS); gst_structure_free (config); return FALSE; } start_failed: { GST_ERROR_OBJECT (pool, "failed to start streaming"); return FALSE; } other_pool_failed: { GST_ERROR_OBJECT (pool, "failed to active the other pool %" GST_PTR_FORMAT, pool->other_pool); return FALSE; } } static gboolean gst_v4l2_buffer_pool_stop (GstBufferPool * bpool) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class); gboolean ret; gint i; GST_DEBUG_OBJECT (pool, "stopping pool"); if (pool->group_released_handler > 0) { g_signal_handler_disconnect (pool->vallocator, pool->group_released_handler); pool->group_released_handler = 0; } if (pool->other_pool) { gst_object_unref (pool->other_pool); pool->other_pool = NULL; } if (!gst_v4l2_buffer_pool_streamoff (pool)) goto streamoff_failed; gst_v4l2_allocator_flush (pool->vallocator); for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (pool->buffers[i]) { GstBuffer *buffer = pool->buffers[i]; pool->buffers[i] = NULL; if (V4L2_TYPE_IS_OUTPUT (pool->obj->type)) gst_buffer_unref (buffer); else pclass->release_buffer (bpool, buffer); g_atomic_int_add (&pool->num_queued, -1); } } ret = GST_BUFFER_POOL_CLASS (parent_class)->stop (bpool); if (ret) { GstV4l2Return vret; vret = gst_v4l2_allocator_stop (pool->vallocator); if (vret == GST_V4L2_BUSY) GST_WARNING_OBJECT (pool, "some buffers are still outstanding"); ret = (vret == GST_V4L2_OK); } return ret; /* ERRORS */ streamoff_failed: GST_ERROR_OBJECT (pool, "device refused to stop streaming"); return FALSE; } static void gst_v4l2_buffer_pool_flush_start (GstBufferPool * bpool) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GST_DEBUG_OBJECT (pool, "start flushing"); gst_poll_set_flushing (pool->poll, TRUE); GST_OBJECT_LOCK (pool); pool->empty = FALSE; g_cond_broadcast (&pool->empty_cond); GST_OBJECT_UNLOCK (pool); if (pool->other_pool) gst_buffer_pool_set_flushing (pool->other_pool, TRUE); } static void gst_v4l2_buffer_pool_flush_stop (GstBufferPool * bpool) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GstV4l2Object *obj = pool->obj; gint i; GST_DEBUG_OBJECT (pool, "stop flushing"); /* If we haven't started streaming yet, simply call streamon */ if (!pool->streaming) goto streamon; if (pool->other_pool) gst_buffer_pool_set_flushing (pool->other_pool, FALSE); if (!gst_v4l2_buffer_pool_streamoff (pool)) goto stop_failed; gst_v4l2_allocator_flush (pool->vallocator); /* Reset our state */ switch (obj->mode) { case GST_V4L2_IO_RW: break; case GST_V4L2_IO_MMAP: case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_DMABUF_IMPORT: { gsize num_allocated; num_allocated = gst_v4l2_allocator_num_allocated (pool->vallocator); for (i = 0; i < num_allocated; i++) { /* Re-enqueue buffers */ if (pool->buffers[i]) { GstBufferPool *bpool = (GstBufferPool *) pool; GstBuffer *buffer = pool->buffers[i]; pool->buffers[i] = NULL; /* Remove qdata, this will unmap any map data in * userptr/dmabuf-import */ gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer), GST_V4L2_IMPORT_QUARK, NULL, NULL); if (V4L2_TYPE_IS_OUTPUT (obj->type)) gst_buffer_unref (buffer); else gst_v4l2_buffer_pool_release_buffer (bpool, buffer); g_atomic_int_add (&pool->num_queued, -1); } } break; } default: g_assert_not_reached (); break; } streamon: /* Start streaming on capture device only */ if (!V4L2_TYPE_IS_OUTPUT (obj->type)) gst_v4l2_buffer_pool_streamon (pool); gst_poll_set_flushing (pool->poll, FALSE); return; /* ERRORS */ stop_failed: { GST_ERROR_OBJECT (pool, "device refused to flush"); } } static GstFlowReturn gst_v4l2_buffer_pool_poll (GstV4l2BufferPool * pool) { gint ret; GST_OBJECT_LOCK (pool); while (pool->empty) g_cond_wait (&pool->empty_cond, GST_OBJECT_GET_LOCK (pool)); GST_OBJECT_UNLOCK (pool); if (!pool->can_poll_device) goto done; GST_LOG_OBJECT (pool, "polling device"); again: ret = gst_poll_wait (pool->poll, GST_CLOCK_TIME_NONE); if (G_UNLIKELY (ret < 0)) { switch (errno) { case EBUSY: goto stopped; case EAGAIN: case EINTR: goto again; case ENXIO: GST_WARNING_OBJECT (pool, "v4l2 device doesn't support polling. Disabling" " using libv4l2 in this case may cause deadlocks"); pool->can_poll_device = FALSE; goto done; default: goto select_error; } } if (gst_poll_fd_has_error (pool->poll, &pool->pollfd)) goto select_error; done: return GST_FLOW_OK; /* ERRORS */ stopped: { GST_DEBUG_OBJECT (pool, "stop called"); return GST_FLOW_FLUSHING; } select_error: { GST_ELEMENT_ERROR (pool->obj->element, RESOURCE, READ, (NULL), ("poll error %d: %s (%d)", ret, g_strerror (errno), errno)); return GST_FLOW_ERROR; } } static GstFlowReturn gst_v4l2_buffer_pool_qbuf (GstV4l2BufferPool * pool, GstBuffer * buf) { GstV4l2MemoryGroup *group = NULL; gint index; if (!gst_v4l2_is_buffer_valid (buf, &group)) { GST_LOG_OBJECT (pool, "unref copied/invalid buffer %p", buf); gst_buffer_unref (buf); return GST_FLOW_OK; } index = group->buffer.index; if (pool->buffers[index] != NULL) goto already_queued; GST_LOG_OBJECT (pool, "queuing buffer %i", index); g_atomic_int_inc (&pool->num_queued); pool->buffers[index] = buf; if (!gst_v4l2_allocator_qbuf (pool->vallocator, group)) goto queue_failed; GST_OBJECT_LOCK (pool); pool->empty = FALSE; g_cond_signal (&pool->empty_cond); GST_OBJECT_UNLOCK (pool); return GST_FLOW_OK; already_queued: { GST_ERROR_OBJECT (pool, "the buffer %i was already queued", index); return GST_FLOW_ERROR; } queue_failed: { GST_ERROR_OBJECT (pool, "could not queue a buffer %i", index); /* Mark broken buffer to the allocator */ GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_TAG_MEMORY); g_atomic_int_add (&pool->num_queued, -1); pool->buffers[index] = NULL; return GST_FLOW_ERROR; } } static GstFlowReturn gst_v4l2_buffer_pool_dqbuf (GstV4l2BufferPool * pool, GstBuffer ** buffer) { GstFlowReturn res; GstBuffer *outbuf; GstV4l2Object *obj = pool->obj; GstClockTime timestamp; GstV4l2MemoryGroup *group; gint i; if ((res = gst_v4l2_buffer_pool_poll (pool)) != GST_FLOW_OK) goto poll_failed; GST_LOG_OBJECT (pool, "dequeueing a buffer"); group = gst_v4l2_allocator_dqbuf (pool->vallocator); if (group == NULL) goto dqbuf_failed; /* get our GstBuffer with that index from the pool, if the buffer was * outstanding we have a serious problem. */ outbuf = pool->buffers[group->buffer.index]; if (outbuf == NULL) goto no_buffer; /* mark the buffer outstanding */ pool->buffers[group->buffer.index] = NULL; if (g_atomic_int_dec_and_test (&pool->num_queued)) { GST_OBJECT_LOCK (pool); pool->empty = TRUE; GST_OBJECT_UNLOCK (pool); } timestamp = GST_TIMEVAL_TO_TIME (group->buffer.timestamp); #ifndef GST_DISABLE_GST_DEBUG for (i = 0; i < group->n_mem; i++) { GST_LOG_OBJECT (pool, "dequeued buffer %p seq:%d (ix=%d), mem %p used %d, plane=%d, flags %08x, ts %" GST_TIME_FORMAT ", pool-queued=%d, buffer=%p", outbuf, group->buffer.sequence, group->buffer.index, group->mem[i], group->planes[i].bytesused, i, group->buffer.flags, GST_TIME_ARGS (timestamp), pool->num_queued, outbuf); } #endif /* set top/bottom field first if v4l2_buffer has the information */ if (group->buffer.field == V4L2_FIELD_INTERLACED_TB) { GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED); GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF); } else if (group->buffer.field == V4L2_FIELD_INTERLACED_BT) { GST_BUFFER_FLAG_SET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED); GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF); } else { GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_INTERLACED); GST_BUFFER_FLAG_UNSET (outbuf, GST_VIDEO_BUFFER_FLAG_TFF); } if (GST_VIDEO_INFO_FORMAT (&obj->info) == GST_VIDEO_FORMAT_ENCODED) { if (group->buffer.flags & V4L2_BUF_FLAG_KEYFRAME) GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT); else GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT); } GST_BUFFER_TIMESTAMP (outbuf) = timestamp; *buffer = outbuf; return GST_FLOW_OK; /* ERRORS */ poll_failed: { GST_DEBUG_OBJECT (pool, "poll error %s", gst_flow_get_name (res)); return res; } dqbuf_failed: { return GST_FLOW_ERROR; } no_buffer: { GST_ERROR_OBJECT (pool, "No free buffer found in the pool at index %d.", group->buffer.index); return GST_FLOW_ERROR; } } static GstFlowReturn gst_v4l2_buffer_pool_acquire_buffer (GstBufferPool * bpool, GstBuffer ** buffer, GstBufferPoolAcquireParams * params) { GstFlowReturn ret; GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class); GstV4l2Object *obj = pool->obj; GST_DEBUG_OBJECT (pool, "acquire"); /* If this is being called to resurect a lost buffer */ if (params && params->flags & GST_V4L2_POOL_ACQUIRE_FLAG_RESURECT) { ret = pclass->acquire_buffer (bpool, buffer, params); goto done; } switch (obj->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: /* capture, This function should return a buffer with new captured data */ switch (obj->mode) { case GST_V4L2_IO_RW: { /* take empty buffer from the pool */ ret = pclass->acquire_buffer (bpool, buffer, params); break; } case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_MMAP: { /* just dequeue a buffer, we basically use the queue of v4l2 as the * storage for our buffers. This function does poll first so we can * interrupt it fine. */ ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer); if (G_UNLIKELY (ret != GST_FLOW_OK)) goto done; break; } case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF_IMPORT: { /* dequeue filled buffer */ ret = gst_v4l2_buffer_pool_dqbuf (pool, buffer); break; } default: ret = GST_FLOW_ERROR; g_assert_not_reached (); break; } break; case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: /* playback, This function should return an empty buffer */ switch (obj->mode) { case GST_V4L2_IO_RW: /* get an empty buffer */ ret = pclass->acquire_buffer (bpool, buffer, params); break; case GST_V4L2_IO_MMAP: case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF_IMPORT: /* get a free unqueued buffer */ ret = pclass->acquire_buffer (bpool, buffer, params); break; default: ret = GST_FLOW_ERROR; g_assert_not_reached (); break; } break; default: ret = GST_FLOW_ERROR; g_assert_not_reached (); break; } done: return ret; } static void gst_v4l2_buffer_pool_release_buffer (GstBufferPool * bpool, GstBuffer * buffer) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (bpool); GstBufferPoolClass *pclass = GST_BUFFER_POOL_CLASS (parent_class); GstV4l2Object *obj = pool->obj; GST_DEBUG_OBJECT (pool, "release buffer %p", buffer); switch (obj->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: /* capture, put the buffer back in the queue so that we can refill it * later. */ switch (obj->mode) { case GST_V4L2_IO_RW: /* release back in the pool */ pclass->release_buffer (bpool, buffer); break; case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_MMAP: case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF_IMPORT: { if (gst_v4l2_is_buffer_valid (buffer, NULL)) { /* queue back in the device */ if (pool->other_pool) gst_v4l2_buffer_pool_prepare_buffer (pool, buffer, NULL); if (gst_v4l2_buffer_pool_qbuf (pool, buffer) != GST_FLOW_OK) pclass->release_buffer (bpool, buffer); } else { /* Simply release invalide/modified buffer, the allocator will * give it back later */ GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY); pclass->release_buffer (bpool, buffer); } break; } default: g_assert_not_reached (); break; } break; case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: switch (obj->mode) { case GST_V4L2_IO_RW: /* release back in the pool */ pclass->release_buffer (bpool, buffer); break; case GST_V4L2_IO_MMAP: case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF_IMPORT: { GstV4l2MemoryGroup *group; guint index; if (!gst_v4l2_is_buffer_valid (buffer, &group)) { /* Simply release invalide/modified buffer, the allocator will * give it back later */ GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY); pclass->release_buffer (bpool, buffer); break; } index = group->buffer.index; if (pool->buffers[index] == NULL) { GST_LOG_OBJECT (pool, "buffer %u not queued, putting on free list", index); /* Remove qdata, this will unmap any map data in userptr */ gst_mini_object_set_qdata (GST_MINI_OBJECT (buffer), GST_V4L2_IMPORT_QUARK, NULL, NULL); /* reset to default size */ gst_v4l2_allocator_reset_group (pool->vallocator, group); /* playback, put the buffer back in the queue to refill later. */ pclass->release_buffer (bpool, buffer); } else { /* We keep a ref on queued buffer, so this should never happen */ g_assert_not_reached (); } break; } default: g_assert_not_reached (); break; } break; default: g_assert_not_reached (); break; } } static void gst_v4l2_buffer_pool_finalize (GObject * object) { GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (object); gint i; for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (pool->buffers[i]) gst_buffer_replace (&(pool->buffers[i]), NULL); } if (pool->video_fd >= 0) v4l2_close (pool->video_fd); gst_poll_free (pool->poll); if (pool->vallocator) gst_object_unref (pool->vallocator); if (pool->allocator) gst_object_unref (pool->allocator); if (pool->other_pool) gst_object_unref (pool->other_pool); /* FIXME Is this required to keep around ? */ gst_object_unref (pool->obj->element); g_cond_clear (&pool->empty_cond); /* FIXME have we done enough here ? */ G_OBJECT_CLASS (parent_class)->finalize (object); } static void gst_v4l2_buffer_pool_init (GstV4l2BufferPool * pool) { pool->poll = gst_poll_new (TRUE); pool->can_poll_device = TRUE; g_cond_init (&pool->empty_cond); pool->empty = TRUE; } static void gst_v4l2_buffer_pool_class_init (GstV4l2BufferPoolClass * klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); GstBufferPoolClass *bufferpool_class = GST_BUFFER_POOL_CLASS (klass); object_class->finalize = gst_v4l2_buffer_pool_finalize; bufferpool_class->start = gst_v4l2_buffer_pool_start; bufferpool_class->stop = gst_v4l2_buffer_pool_stop; bufferpool_class->set_config = gst_v4l2_buffer_pool_set_config; bufferpool_class->alloc_buffer = gst_v4l2_buffer_pool_alloc_buffer; bufferpool_class->acquire_buffer = gst_v4l2_buffer_pool_acquire_buffer; bufferpool_class->release_buffer = gst_v4l2_buffer_pool_release_buffer; bufferpool_class->flush_start = gst_v4l2_buffer_pool_flush_start; bufferpool_class->flush_stop = gst_v4l2_buffer_pool_flush_stop; } /** * gst_v4l2_buffer_pool_new: * @obj: the v4l2 object owning the pool * * Construct a new buffer pool. * * Returns: the new pool, use gst_object_unref() to free resources */ GstBufferPool * gst_v4l2_buffer_pool_new (GstV4l2Object * obj, GstCaps * caps) { GstV4l2BufferPool *pool; GstStructure *config; gchar *name, *parent_name; gint fd; fd = v4l2_dup (obj->video_fd); if (fd < 0) goto dup_failed; /* setting a significant unique name */ parent_name = gst_object_get_name (GST_OBJECT (obj->element)); name = g_strconcat (parent_name, ":", "pool:", V4L2_TYPE_IS_OUTPUT (obj->type) ? "sink" : "src", NULL); g_free (parent_name); pool = (GstV4l2BufferPool *) g_object_new (GST_TYPE_V4L2_BUFFER_POOL, "name", name, NULL); g_free (name); gst_poll_fd_init (&pool->pollfd); pool->pollfd.fd = fd; gst_poll_add_fd (pool->poll, &pool->pollfd); if (V4L2_TYPE_IS_OUTPUT (obj->type)) gst_poll_fd_ctl_write (pool->poll, &pool->pollfd, TRUE); else gst_poll_fd_ctl_read (pool->poll, &pool->pollfd, TRUE); pool->video_fd = fd; pool->obj = obj; pool->can_poll_device = TRUE; pool->vallocator = gst_v4l2_allocator_new (GST_OBJECT (pool), obj->video_fd, &obj->format); if (pool->vallocator == NULL) goto allocator_failed; gst_object_ref (obj->element); config = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (pool)); gst_buffer_pool_config_set_params (config, caps, obj->info.size, 0, 0); /* This will simply set a default config, but will not configure the pool * because min and max are not valid */ gst_buffer_pool_set_config (GST_BUFFER_POOL_CAST (pool), config); return GST_BUFFER_POOL (pool); /* ERRORS */ dup_failed: { GST_ERROR ("failed to dup fd %d (%s)", errno, g_strerror (errno)); return NULL; } allocator_failed: { GST_ERROR_OBJECT (pool, "Failed to create V4L2 allocator"); return NULL; } } static GstFlowReturn gst_v4l2_do_read (GstV4l2BufferPool * pool, GstBuffer * buf) { GstFlowReturn res; GstV4l2Object *obj = pool->obj; gint amount; GstMapInfo map; gint toread; toread = obj->info.size; GST_LOG_OBJECT (pool, "reading %d bytes into buffer %p", toread, buf); gst_buffer_map (buf, &map, GST_MAP_WRITE); do { if ((res = gst_v4l2_buffer_pool_poll (pool)) != GST_FLOW_OK) goto poll_error; amount = v4l2_read (obj->video_fd, map.data, toread); if (amount == toread) { break; } else if (amount == -1) { if (errno == EAGAIN || errno == EINTR) { continue; } else goto read_error; } else { /* short reads can happen if a signal interrupts the read */ continue; } } while (TRUE); GST_LOG_OBJECT (pool, "read %d bytes", amount); gst_buffer_unmap (buf, &map); gst_buffer_resize (buf, 0, amount); return GST_FLOW_OK; /* ERRORS */ poll_error: { GST_DEBUG ("poll error %s", gst_flow_get_name (res)); goto cleanup; } read_error: { GST_ELEMENT_ERROR (obj->element, RESOURCE, READ, (_("Error reading %d bytes from device '%s'."), toread, obj->videodev), GST_ERROR_SYSTEM); res = GST_FLOW_ERROR; goto cleanup; } cleanup: { gst_buffer_unmap (buf, &map); gst_buffer_resize (buf, 0, 0); return res; } } /** * gst_v4l2_buffer_pool_process: * @bpool: a #GstBufferPool * @buf: a #GstBuffer, maybe be replaced * * Process @buf in @bpool. For capture devices, this functions fills @buf with * data from the device. For output devices, this functions send the contents of * @buf to the device for playback. * * Returns: %GST_FLOW_OK on success. */ GstFlowReturn gst_v4l2_buffer_pool_process (GstV4l2BufferPool * pool, GstBuffer ** buf) { GstFlowReturn ret = GST_FLOW_OK; GstBufferPool *bpool = GST_BUFFER_POOL_CAST (pool); GstV4l2Object *obj = pool->obj; GST_DEBUG_OBJECT (pool, "process buffer %p", buf); g_return_val_if_fail (gst_buffer_pool_is_active (bpool), GST_FLOW_ERROR); if (GST_BUFFER_POOL_IS_FLUSHING (pool)) return GST_FLOW_FLUSHING; switch (obj->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: /* capture */ switch (obj->mode) { case GST_V4L2_IO_RW: /* capture into the buffer */ ret = gst_v4l2_do_read (pool, *buf); break; case GST_V4L2_IO_MMAP: case GST_V4L2_IO_DMABUF: { GstBuffer *tmp; if ((*buf)->pool == bpool) { if (gst_buffer_get_size (*buf) == 0) goto eos; /* start copying buffers when we are running low on buffers */ if (g_atomic_int_get (&pool->num_queued) < pool->copy_threshold) { GstBuffer *copy; if (GST_V4L2_ALLOCATOR_CAN_ALLOCATE (pool->vallocator, MMAP)) { if (gst_buffer_pool_acquire_buffer (bpool, &copy, NULL) == GST_FLOW_OK) { gst_v4l2_buffer_pool_release_buffer (bpool, copy); goto done; } } /* copy the buffer */ copy = gst_buffer_copy_region (*buf, GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP, 0, -1); GST_LOG_OBJECT (pool, "copy buffer %p->%p", *buf, copy); /* and requeue so that we can continue capturing */ gst_buffer_unref (*buf); *buf = copy; } /* nothing, data was inside the buffer when we did _acquire() */ goto done; } /* buffer not from our pool, grab a frame and copy it into the target */ if ((ret = gst_v4l2_buffer_pool_dqbuf (pool, &tmp)) != GST_FLOW_OK) goto done; /* An empty buffer on capture indicates the end of stream */ if (gst_buffer_get_size (tmp) == 0) { gst_v4l2_buffer_pool_release_buffer (bpool, tmp); goto eos; } ret = gst_v4l2_buffer_pool_copy_buffer (pool, *buf, tmp); /* an queue the buffer again after the copy */ gst_v4l2_buffer_pool_release_buffer (bpool, tmp); if (ret != GST_FLOW_OK) goto copy_failed; break; } case GST_V4L2_IO_USERPTR: { struct UserPtrData *data; /* Replace our buffer with downstream allocated buffer */ data = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf), GST_V4L2_IMPORT_QUARK); gst_buffer_replace (buf, data->buffer); _unmap_userptr_frame (data); break; } case GST_V4L2_IO_DMABUF_IMPORT: { GstBuffer *tmp; /* Replace our buffer with downstream allocated buffer */ tmp = gst_mini_object_steal_qdata (GST_MINI_OBJECT (*buf), GST_V4L2_IMPORT_QUARK); gst_buffer_replace (buf, tmp); gst_buffer_unref (tmp); break; } default: g_assert_not_reached (); break; } break; case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: /* playback */ switch (obj->mode) { case GST_V4L2_IO_RW: /* FIXME, do write() */ GST_WARNING_OBJECT (pool, "implement write()"); break; case GST_V4L2_IO_USERPTR: case GST_V4L2_IO_DMABUF_IMPORT: case GST_V4L2_IO_DMABUF: case GST_V4L2_IO_MMAP: { GstBuffer *to_queue = NULL; GstV4l2MemoryGroup *group; gint index; if ((*buf)->pool != bpool) goto copying; if (!gst_v4l2_is_buffer_valid (*buf, &group)) goto copying; index = group->buffer.index; GST_LOG_OBJECT (pool, "processing buffer %i from our pool", index); index = group->buffer.index; if (pool->buffers[index] != NULL) { GST_LOG_OBJECT (pool, "buffer %i already queued, copying", index); goto copying; } /* we can queue directly */ to_queue = gst_buffer_ref (*buf); copying: if (to_queue == NULL) { GstBufferPoolAcquireParams params = { 0 }; GST_LOG_OBJECT (pool, "alloc buffer from our pool"); /* this can return EOS if all buffers are outstanding which would * be strange because we would expect the upstream element to have * allocated them and returned to us.. */ params.flags = GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT; ret = gst_buffer_pool_acquire_buffer (bpool, &to_queue, &params); if (ret != GST_FLOW_OK) goto acquire_failed; ret = gst_v4l2_buffer_pool_prepare_buffer (pool, to_queue, *buf); if (ret != GST_FLOW_OK) { gst_buffer_unref (to_queue); goto prepare_failed; } } if ((ret = gst_v4l2_buffer_pool_qbuf (pool, to_queue)) != GST_FLOW_OK) goto queue_failed; /* if we are not streaming yet (this is the first buffer, start * streaming now */ if (!gst_v4l2_buffer_pool_streamon (pool)) { gst_buffer_unref (to_queue); goto start_failed; } if (g_atomic_int_get (&pool->num_queued) >= pool->min_latency) { GstBuffer *out; /* all buffers are queued, try to dequeue one and release it back * into the pool so that _acquire can get to it again. */ ret = gst_v4l2_buffer_pool_dqbuf (pool, &out); if (ret == GST_FLOW_OK) /* release the rendered buffer back into the pool. This wakes up any * thread waiting for a buffer in _acquire(). */ gst_buffer_unref (out); } break; } default: g_assert_not_reached (); break; } break; default: g_assert_not_reached (); break; } done: return ret; /* ERRORS */ copy_failed: { GST_ERROR_OBJECT (pool, "failed to copy buffer"); return ret; } eos: { GST_DEBUG_OBJECT (pool, "end of stream reached"); return GST_FLOW_EOS; } acquire_failed: { if (ret == GST_FLOW_FLUSHING) GST_DEBUG_OBJECT (pool, "flushing"); else GST_WARNING_OBJECT (pool, "failed to acquire a buffer: %s", gst_flow_get_name (ret)); return ret; } prepare_failed: { GST_ERROR_OBJECT (pool, "failed to prepare data"); return ret; } queue_failed: { GST_ERROR_OBJECT (pool, "failed to queue buffer"); return ret; } start_failed: { GST_ERROR_OBJECT (pool, "failed to start streaming"); return GST_FLOW_ERROR; } } void gst_v4l2_buffer_pool_set_other_pool (GstV4l2BufferPool * pool, GstBufferPool * other_pool) { g_return_if_fail (!gst_buffer_pool_is_active (GST_BUFFER_POOL (pool))); if (pool->other_pool) gst_object_unref (pool->other_pool); pool->other_pool = gst_object_ref (other_pool); }
greg80303/gst-plugins-good
sys/v4l2/gstv4l2bufferpool.c
C
lgpl-2.1
48,159
// // ProcessRunConfiguration.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com) // // 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. using System; using System.Linq; using MonoDevelop.Core; using MonoDevelop.Core.Serialization; namespace MonoDevelop.Projects { public class ProcessRunConfiguration: ProjectRunConfiguration { public ProcessRunConfiguration (string name): base (name) { } [ItemProperty (DefaultValue = "")] public string StartArguments { get; set; } = ""; [ItemProperty (DefaultValue = "")] public FilePath StartWorkingDirectory { get; set; } = ""; [ItemProperty ("ConsolePause", DefaultValue = true)] public bool PauseConsoleOutput { get; set; } = true; [ItemProperty (DefaultValue = false)] public bool ExternalConsole { get; set; } = false; [ItemProperty (SkipEmpty = true, WrapObject = false)] public EnvironmentVariableCollection EnvironmentVariables { get; private set; } = new EnvironmentVariableCollection (); public override string Summary { get { string envVars = null; if (EnvironmentVariables.Count > 0) { var v = EnvironmentVariables.First (); envVars = v.Key + "=" + v.Value; if (EnvironmentVariables.Count > 1) envVars += "..."; } if (!string.IsNullOrEmpty (StartArguments) && envVars != null) return GettextCatalog.GetString ("Run with arguments '{0}' and environment variables '{1}'", StartArguments, envVars); else if (!string.IsNullOrEmpty (StartArguments)) return GettextCatalog.GetString ("Run with arguments '{0}'", StartArguments); else if (envVars != null) return GettextCatalog.GetString ("Run with environment variables '{0}''", envVars); else return GettextCatalog.GetString ("Run with no additional arguments"); } } protected override void OnCopyFrom (ProjectRunConfiguration config, bool isRename) { base.OnCopyFrom (config, isRename); var other = (ProcessRunConfiguration)config; StartArguments = other.StartArguments; StartWorkingDirectory = other.StartWorkingDirectory; EnvironmentVariables = new EnvironmentVariableCollection (other.EnvironmentVariables); ExternalConsole = other.ExternalConsole; PauseConsoleOutput = other.PauseConsoleOutput; } } }
mono/linux-packaging-monodevelop
src/core/MonoDevelop.Core/MonoDevelop.Projects/ProcessRunConfiguration.cs
C#
lgpl-2.1
3,347
/* * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) * Copyright (C) 2003, 2007, 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2009 Torch Mobile, Inc. * * This library 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 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "config.h" #include "RegExpConstructor.h" #include "ArrayPrototype.h" #include "Error.h" #include "ExceptionHelpers.h" #include "JSArray.h" #include "JSFunction.h" #include "JSString.h" #include "Lookup.h" #include "ObjectPrototype.h" #include "RegExpMatchesArray.h" #include "RegExpObject.h" #include "RegExpPrototype.h" #include "RegExp.h" #include "RegExpCache.h" #include "UStringConcatenate.h" #include <wtf/PassOwnPtr.h> namespace JSC { static JSValue regExpConstructorInput(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorMultiline(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorLastMatch(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorLastParen(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorLeftContext(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorRightContext(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar1(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar2(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar3(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar4(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar5(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar6(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar7(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar8(ExecState*, JSValue, const Identifier&); static JSValue regExpConstructorDollar9(ExecState*, JSValue, const Identifier&); static void setRegExpConstructorInput(ExecState*, JSObject*, JSValue); static void setRegExpConstructorMultiline(ExecState*, JSObject*, JSValue); } // namespace JSC #include "RegExpConstructor.lut.h" namespace JSC { ASSERT_CLASS_FITS_IN_CELL(RegExpConstructor); const ClassInfo RegExpConstructor::s_info = { "Function", &InternalFunction::s_info, 0, ExecState::regExpConstructorTable, CREATE_METHOD_TABLE(RegExpConstructor) }; const ClassInfo RegExpMatchesArray::s_info = {"Array", &JSArray::s_info, 0, 0, CREATE_METHOD_TABLE(RegExpMatchesArray)}; /* Source for RegExpConstructor.lut.h @begin regExpConstructorTable input regExpConstructorInput None $_ regExpConstructorInput DontEnum multiline regExpConstructorMultiline None $* regExpConstructorMultiline DontEnum lastMatch regExpConstructorLastMatch DontDelete|ReadOnly $& regExpConstructorLastMatch DontDelete|ReadOnly|DontEnum lastParen regExpConstructorLastParen DontDelete|ReadOnly $+ regExpConstructorLastParen DontDelete|ReadOnly|DontEnum leftContext regExpConstructorLeftContext DontDelete|ReadOnly $` regExpConstructorLeftContext DontDelete|ReadOnly|DontEnum rightContext regExpConstructorRightContext DontDelete|ReadOnly $' regExpConstructorRightContext DontDelete|ReadOnly|DontEnum $1 regExpConstructorDollar1 DontDelete|ReadOnly $2 regExpConstructorDollar2 DontDelete|ReadOnly $3 regExpConstructorDollar3 DontDelete|ReadOnly $4 regExpConstructorDollar4 DontDelete|ReadOnly $5 regExpConstructorDollar5 DontDelete|ReadOnly $6 regExpConstructorDollar6 DontDelete|ReadOnly $7 regExpConstructorDollar7 DontDelete|ReadOnly $8 regExpConstructorDollar8 DontDelete|ReadOnly $9 regExpConstructorDollar9 DontDelete|ReadOnly @end */ RegExpResult& RegExpResult::operator=(const RegExpConstructorPrivate& rhs) { this->input = rhs.input; this->ovector = rhs.lastOvector(); this->lastNumSubPatterns = rhs.lastNumSubPatterns; return *this; } RegExpConstructor::RegExpConstructor(JSGlobalObject* globalObject, Structure* structure) : InternalFunction(globalObject, structure) { } void RegExpConstructor::finishCreation(ExecState* exec, RegExpPrototype* regExpPrototype) { Base::finishCreation(exec->globalData(), Identifier(exec, "RegExp")); ASSERT(inherits(&s_info)); // ECMA 15.10.5.1 RegExp.prototype putDirectWithoutTransition(exec->globalData(), exec->propertyNames().prototype, regExpPrototype, DontEnum | DontDelete | ReadOnly); // no. of arguments for constructor putDirectWithoutTransition(exec->globalData(), exec->propertyNames().length, jsNumber(2), ReadOnly | DontDelete | DontEnum); } void RegExpConstructor::destroy(JSCell* cell) { jsCast<RegExpConstructor*>(cell)->RegExpConstructor::~RegExpConstructor(); } RegExpMatchesArray::RegExpMatchesArray(ExecState* exec) : JSArray(exec->globalData(), exec->lexicalGlobalObject()->regExpMatchesArrayStructure()) , m_didFillArrayInstance(false) { } void RegExpMatchesArray::finishCreation(JSGlobalData& globalData, const RegExpConstructorPrivate& data) { Base::finishCreation(globalData, data.lastNumSubPatterns + 1); m_regExpResult = data; } void RegExpMatchesArray::destroy(JSCell* cell) { jsCast<RegExpMatchesArray*>(cell)->RegExpMatchesArray::~RegExpMatchesArray(); } void RegExpMatchesArray::fillArrayInstance(ExecState* exec) { unsigned lastNumSubpatterns = m_regExpResult.lastNumSubPatterns; for (unsigned i = 0; i <= lastNumSubpatterns; ++i) { int start = m_regExpResult.ovector[2 * i]; if (start >= 0) JSArray::putByIndex(this, exec, i, jsSubstring(exec, m_regExpResult.input, start, m_regExpResult.ovector[2 * i + 1] - start)); else JSArray::putByIndex(this, exec, i, jsUndefined()); } PutPropertySlot slot; JSArray::put(this, exec, exec->propertyNames().index, jsNumber(m_regExpResult.ovector[0]), slot); JSArray::put(this, exec, exec->propertyNames().input, jsString(exec, m_regExpResult.input), slot); m_didFillArrayInstance = true; } JSObject* RegExpConstructor::arrayOfMatches(ExecState* exec) const { return RegExpMatchesArray::create(exec, d); } JSValue RegExpConstructor::getBackref(ExecState* exec, unsigned i) const { if (!d.lastOvector().isEmpty() && i <= d.lastNumSubPatterns) { int start = d.lastOvector()[2 * i]; if (start >= 0) return jsSubstring(exec, d.lastInput, start, d.lastOvector()[2 * i + 1] - start); } return jsEmptyString(exec); } JSValue RegExpConstructor::getLastParen(ExecState* exec) const { unsigned i = d.lastNumSubPatterns; if (i > 0) { ASSERT(!d.lastOvector().isEmpty()); int start = d.lastOvector()[2 * i]; if (start >= 0) return jsSubstring(exec, d.lastInput, start, d.lastOvector()[2 * i + 1] - start); } return jsEmptyString(exec); } JSValue RegExpConstructor::getLeftContext(ExecState* exec) const { if (!d.lastOvector().isEmpty()) return jsSubstring(exec, d.lastInput, 0, d.lastOvector()[0]); return jsEmptyString(exec); } JSValue RegExpConstructor::getRightContext(ExecState* exec) const { if (!d.lastOvector().isEmpty()) return jsSubstring(exec, d.lastInput, d.lastOvector()[1], d.lastInput.length() - d.lastOvector()[1]); return jsEmptyString(exec); } bool RegExpConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<RegExpConstructor, InternalFunction>(exec, ExecState::regExpConstructorTable(exec), jsCast<RegExpConstructor*>(cell), propertyName, slot); } bool RegExpConstructor::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor<RegExpConstructor, InternalFunction>(exec, ExecState::regExpConstructorTable(exec), jsCast<RegExpConstructor*>(object), propertyName, descriptor); } JSValue regExpConstructorDollar1(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 1); } JSValue regExpConstructorDollar2(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 2); } JSValue regExpConstructorDollar3(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 3); } JSValue regExpConstructorDollar4(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 4); } JSValue regExpConstructorDollar5(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 5); } JSValue regExpConstructorDollar6(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 6); } JSValue regExpConstructorDollar7(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 7); } JSValue regExpConstructorDollar8(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 8); } JSValue regExpConstructorDollar9(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 9); } JSValue regExpConstructorInput(ExecState* exec, JSValue slotBase, const Identifier&) { return jsString(exec, asRegExpConstructor(slotBase)->input()); } JSValue regExpConstructorMultiline(ExecState*, JSValue slotBase, const Identifier&) { return jsBoolean(asRegExpConstructor(slotBase)->multiline()); } JSValue regExpConstructorLastMatch(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getBackref(exec, 0); } JSValue regExpConstructorLastParen(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getLastParen(exec); } JSValue regExpConstructorLeftContext(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getLeftContext(exec); } JSValue regExpConstructorRightContext(ExecState* exec, JSValue slotBase, const Identifier&) { return asRegExpConstructor(slotBase)->getRightContext(exec); } void RegExpConstructor::put(JSCell* cell, ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot) { lookupPut<RegExpConstructor, InternalFunction>(exec, propertyName, value, ExecState::regExpConstructorTable(exec), jsCast<RegExpConstructor*>(cell), slot); } void setRegExpConstructorInput(ExecState* exec, JSObject* baseObject, JSValue value) { asRegExpConstructor(baseObject)->setInput(value.toString(exec)->value(exec)); } void setRegExpConstructorMultiline(ExecState* exec, JSObject* baseObject, JSValue value) { asRegExpConstructor(baseObject)->setMultiline(value.toBoolean(exec)); } // ECMA 15.10.4 JSObject* constructRegExp(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, bool callAsConstructor) { JSValue arg0 = args.at(0); JSValue arg1 = args.at(1); if (arg0.inherits(&RegExpObject::s_info)) { if (!arg1.isUndefined()) return throwError(exec, createTypeError(exec, "Cannot supply flags when constructing one RegExp from another.")); // If called as a function, this just returns the first argument (see 15.10.3.1). if (callAsConstructor) { RegExp* regExp = static_cast<RegExpObject*>(asObject(arg0))->regExp(); return RegExpObject::create(exec, globalObject, globalObject->regExpStructure(), regExp); } return asObject(arg0); } UString pattern = arg0.isUndefined() ? UString("") : arg0.toString(exec)->value(exec); if (exec->hadException()) return 0; RegExpFlags flags = NoFlags; if (!arg1.isUndefined()) { flags = regExpFlags(arg1.toString(exec)->value(exec)); if (exec->hadException()) return 0; if (flags == InvalidFlags) return throwError(exec, createSyntaxError(exec, "Invalid flags supplied to RegExp constructor.")); } RegExp* regExp = RegExp::create(exec->globalData(), pattern, flags); if (!regExp->isValid()) return throwError(exec, createSyntaxError(exec, regExp->errorMessage())); return RegExpObject::create(exec, exec->lexicalGlobalObject(), globalObject->regExpStructure(), regExp); } static EncodedJSValue JSC_HOST_CALL constructWithRegExpConstructor(ExecState* exec) { ArgList args(exec); return JSValue::encode(constructRegExp(exec, asInternalFunction(exec->callee())->globalObject(), args, true)); } ConstructType RegExpConstructor::getConstructData(JSCell*, ConstructData& constructData) { constructData.native.function = constructWithRegExpConstructor; return ConstructTypeHost; } // ECMA 15.10.3 static EncodedJSValue JSC_HOST_CALL callRegExpConstructor(ExecState* exec) { ArgList args(exec); return JSValue::encode(constructRegExp(exec, asInternalFunction(exec->callee())->globalObject(), args)); } CallType RegExpConstructor::getCallData(JSCell*, CallData& callData) { callData.native.function = callRegExpConstructor; return CallTypeHost; } void RegExpConstructor::setInput(const UString& input) { d.input = input; } const UString& RegExpConstructor::input() const { // Can detect a distinct initial state that is invisible to JavaScript, by checking for null // state (since jsString turns null strings to empty strings). return d.input; } void RegExpConstructor::setMultiline(bool multiline) { d.multiline = multiline; } bool RegExpConstructor::multiline() const { return d.multiline; } } // namespace JSC
Irrelon/JavaScriptCore
runtime/RegExpConstructor.cpp
C++
lgpl-2.1
14,820
/* modified by Thibaut Weise Szymon Rusinkiewicz Princeton University gl_camera.cc Manages OpenGL camera and trackball/arcball interaction */ #include "rgbd/forest/common.hpp" #include "rgbd/forest/gl_camera.hpp" #include "rgbd/forest/trackball.hpp" using namespace std; #define DOF 10.0f #define MAXDOF 10000.0f #define TRACKBALL_R 0.8f #define WHEEL_MOVE 0.2f // Mouse rotation helper - compute trackball position from mouse pos math_vector_3f gl_camera::mouse2tb(float x, float y) { // normalize points to -0.5 to 0.5 x = (x-(float)viewx)/(float)vieww - 0.5f; y = (y-(float)viewy)/(float)viewh - 0.5f; float r2 = x*x + y*y; float t = 0.5 * (TRACKBALL_R*TRACKBALL_R); float z; if (r2 < t) z = sqrt(2*t - r2); else z = t / sqrt(r2); math_vector_3f pos(x, y, z); return pos; } // Mouse helper - rotate void gl_camera::rotate(int mousex, int mousey) { float x1 = 2 * (float)lastmousex / (float) vieww - 1; float y1 = 2 * (float)lastmousey / (float) viewh - 1; float x2 = 2 * (float)mousex / (float) vieww - 1; float y2 = 2 * (float)mousey / (float) viewh - 1; x1 = MAX( -1, MIN( x1, 1 ) ); y1 = MAX( -1, MIN( y1, 1 ) ); x2 = MAX( -1, MIN( x2, 1 ) ); y2 = MAX( -1, MIN( y2, 1 ) ); math_matrix_3x3f rot = trackball( x1,y1,x2,y2); // apply rotation m_camera_rm = rigid_motion<float>(spincenter) * rigid_motion<float>(rot) * rigid_motion<float>(-spincenter) * m_camera_rm; } // Mouse helper - translate void gl_camera::movexy(int mousex, int mousey) { float dx = (mousex - lastmousex) * (m_scene_size / 500.0f); float dy = (mousey - lastmousey) * (m_scene_size / 500.0f); m_camera_rm = rigid_motion<float>(math_vector_3f(dx, dy, 0.0f)) * m_camera_rm; } // Mouse helper - translate in z void gl_camera::movez(int mousey) { float dy = (float)(mousey - lastmousey); m_camera_rm = rigid_motion<float>(math_vector_3f(0.0f,0.0f, dy)) * m_camera_rm; } // Mouse helper - wheel motion void gl_camera::wheel(Mouse::button updown) { float dz = 50.0f * WHEEL_MOVE; if (updown == Mouse::WHEELUP) dz = -dz; m_camera_rm = rigid_motion<float>(math_vector_3f(0.0f, 0.0f, dz)) * m_camera_rm; } void gl_camera::rotate_180() { math_vector_3f spinaxis = math_vector_3f(1.f,0.f,0.f); float spinamount = (float)PI; math_vector_3f center = m_camera_rm * m_scene_center; // apply rotation m_camera_rm = rigid_motion<float>(center) * rigid_motion<float>(axis_to_rotation_matrix(spinamount, spinaxis)) * rigid_motion<float>(-center) * m_camera_rm; } // mouse wheel event simulated based on motion in y direction void gl_camera::mouse_wheel_y(int y) { mouse_wheel(y-lastmousey); lastmousey = y; } // Handle a mouse event void gl_camera::mouse_wheel(int delta) { m_camera_rm = rigid_motion<float>(math_vector_3f(0.0f, 0.0f, delta * m_scene_size / 500.0f)) * m_camera_rm; } // Handle a mouse event void gl_camera::mouse( bool left, bool right, int mousex, int mousey ) { Mouse::button b = Mouse::NONE; if(left && !right) b = Mouse::ROTATE; else if(right && !left) b = Mouse::MOVEXY; mouse(mousex,mousey,b); } // Handle a mouse event void gl_camera::mouse( int mousex, int mousey, Mouse::button b, const math_vector_3f &scene_center ) { spincenter = m_camera_rm * scene_center; lastmousex = mousex; lastmousey = mousey; lastb = b; } // Handle a mouse event void gl_camera::mouse_move( int mousex, int mousey, const math_vector_3f & /*scene_center*/ ) { Mouse::button b = lastb; if (b == Mouse::NONE && lastb == Mouse::NONE) { return; } // Handle rotation if ((b == Mouse::ROTATE) && (lastb == Mouse::ROTATE)) { rotate(mousex, mousey); } if ((b == Mouse::MOVEZ) && (lastb == Mouse::MOVEZ)) movez(mousey); // Handle translation if ((b == Mouse::MOVEXY) && (lastb == Mouse::MOVEXY)) movexy(mousex, mousey); if (b == Mouse::WHEELUP || b == Mouse::WHEELDOWN) wheel(b); lastmousex = mousex; lastmousey = mousey; lastb = b; } void gl_camera::use_light( bool _use_light) { if(_use_light) { if(true) { // set light parameters GLfloat mat_specular[4] = { 0.18f, 0.18f, 0.18f, 1.f }; GLfloat mat_shininess[] = { 64.f }; GLfloat global_ambient[] = { 0.05f, 0.05f, 0.05f, 1.f }; GLfloat light0_ambient[] = { 0.0f, 0.0f, 0.0f, 1.f }; GLfloat light0_diffuse[] = { 0.9f, 0.9f, 0.9f, 1.f }; GLfloat light0_specular[] = { 0.85f, 0.85f, 0.85f, 1.f }; glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light0_specular); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE); glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0.0); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);// todo include this into spotlight node glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); } else { float defaultPosition[4] = {0.0,0.0,0.0,1.0}; float defaultSpotDirection[3] = {0.0,0.0,1.0}; float defaultAmbientColor[4] = {0.005f,0.005f,0.005f,1.f}; float defaultDiffuseColor[4] = {0.9f,0.9f,0.9f,1.f}; float defaultSpecularColor[4] = {0.5f,0.5f,0.5f,1.f}; glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,defaultAmbientColor); glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,defaultDiffuseColor); glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,defaultSpecularColor); glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,200.f); glLightfv(GL_LIGHT0, GL_POSITION, defaultPosition); glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, defaultSpotDirection); glLightfv(GL_LIGHT0, GL_AMBIENT, defaultAmbientColor); glLightfv(GL_LIGHT0, GL_DIFFUSE, defaultDiffuseColor); glLightfv(GL_LIGHT0, GL_SPECULAR, defaultSpecularColor); glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0.f); glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 120.f); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);// todo include this into spotlight node glEnable(GL_COLOR_MATERIAL); } } else { glDisable(GL_LIGHTING); } } // Set up the OpenGL camera for rendering void gl_camera::setup(const math_vector_3f &scene_center, float scene_size) const { glViewport(viewx, viewy, vieww, viewh); // set viewport for rendering math_vector_3f center = m_camera_rm * scene_center; float fardist = -(center[2] - 8*scene_size);//max( -(center[2] - scene_size), scene_size / DOF); float neardist = max( -(center[2] + scene_size), scene_size / MAXDOF); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(field_of_view, (float)vieww/(float)viewh, neardist, fardist ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // setup light GLfloat light0_position[] = { lightdir[0], lightdir[1], lightdir[2], 0 }; GLfloat light1_position[] = { -lightdir[0], -lightdir[1], -lightdir[2], 0 }; glLightfv(GL_LIGHT0, GL_POSITION, light0_position); glLightfv(GL_LIGHT1, GL_POSITION, light1_position); // global camera position float gl_rm[16]; to_opengl( m_camera_rm, gl_rm ); glMultMatrixf( gl_rm ); } void gl_camera::setup( const math_matrix_3x3f & K, int w, int h, float zNear, float zFar) { glViewport(viewx, viewy, vieww, viewh); // set viewport for rendering glMatrixMode(GL_PROJECTION); glLoadIdentity(); math_matrix_4x4f mat; mat.set_identity(); // X mat[0][0] = 2.f/(float)w*K[0][0]; // use camera instrinsics and convert to GL [0,h] => [-1,1] mat[0][2] = (2.f/(float)w*(K[0][2]+0.5f))-1.f; // 0.5 offset as GL pixel middle point is at 0.5,0.5 // Y mat[1][1] = 2.f/(float)h*K[1][1]; // use camera instrinsics and convert to GL [0,h] => [-1,1] mat[1][2] = (2.f/(float)h*(K[1][2]+0.5f))-1.f; // Z mat[2][2] = (zFar+zNear)/(zFar-zNear); mat[2][3] = -2.f*zFar*zNear/(zFar-zNear); // W mat[3][2] = 1; // not as in GL where it would be -1 mat[3][3] = 0; mat = mat.transpose(); glMultMatrixf( (float*) (&mat) ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // setup light GLfloat light0_position[] = { lightdir[0], lightdir[1], lightdir[2], 0 }; GLfloat light1_position[] = { -lightdir[0], -lightdir[1], -lightdir[2], 0 }; glLightfv(GL_LIGHT0, GL_POSITION, light0_position); glLightfv(GL_LIGHT1, GL_POSITION, light1_position); // global camera position float gl_rm[16]; to_opengl( m_camera_rm, gl_rm ); glMultMatrixf( gl_rm ); } // look at scene center void gl_camera::resetview(const math_vector_3f &scene_center, float scene_size) { m_scene_center = scene_center; m_scene_size = scene_size; m_camera_rm = rigid_motion<float>(math_vector_3f(0, 0, -2.0f * scene_size)) * rigid_motion<float>(-scene_center); spincenter = m_camera_rm * m_scene_center; } // look at scene center void gl_camera::resetview(const math_vector_3f &scene_center) { m_scene_center = scene_center; m_camera_rm = rigid_motion<float>(math_vector_3f(0, 0, -2.0f * m_scene_size)) * rigid_motion<float>(-scene_center); spincenter = m_camera_rm * m_scene_center; } void gl_camera::rotate( const math_matrix_3x3f & _rot ) { math_vector_3f center = m_camera_rm * m_scene_center; // apply rotation m_camera_rm = rigid_motion<float>(center) * rigid_motion<float>(_rot) * rigid_motion<float>(-center) * m_camera_rm; } void gl_camera::pre_rotate( const math_matrix_3x3f & _rot ) { math_vector_3f center = m_scene_center; // apply rotation m_camera_rm = m_camera_rm * rigid_motion<float>(center) * rigid_motion<float>(_rot) * rigid_motion<float>(-center); } void gl_camera::translate( const math_vector_3f & _t ) { m_camera_rm = rigid_motion<float>(_t) * m_camera_rm; } void gl_camera::clear(float r, float g, float b, float a) { //glDisable( GL_TEXTURE_RECTANGLE_NV ); glDisable( GL_TEXTURE_1D ); glDisable( GL_TEXTURE_2D ); //glDisable( GL_TEXTURE_3D ); glDisable( GL_FOG ); glDisable( GL_ALPHA_TEST ); glDisable( GL_DEPTH_TEST ); glDisable( GL_BLEND ); glDisable(GL_DITHER); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_NORMALIZE); glDisable(GL_LIGHTING); glDisable(GL_NORMALIZE); glDisable(GL_COLOR_MATERIAL); glDisable(GL_TEXTURE_2D); glEnable(GL_SCISSOR_TEST); glScissor(viewx, viewy, vieww, viewh); // set viewport for rendering glClearColor(r,g,b,a); glClearDepth(1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); }
GuillaumeGibert/swooz
swooz-tracking/trunk/src/rgbd/forest/gl_camera.cpp
C++
lgpl-2.1
11,105
#!/bin/env python # This is the building script for Python maxent extension module. # Simply type "python setup.py build" at command line to build the extension. # After that you can type "python setup.py install" to install the extension # module. # # The script assume you use gcc on unix and msvc on win32 platform. from sys import platform, exec_prefix from distutils.core import setup, Extension # change the lines below according to your boost location if platform == "win32": libmaxent_name = 'libmaxent' extra_compile_args = [ "-DWIN32", "-DPYTHON_MODULE", "-DHAVE_FORTRAN=1", "-DBOOST_DISABLE_THREADS", "-DBOOST_DISABLE_ASSERTS", "/GR", ] data_files = [('Lib/site-packages/maxent' , ['stlport_vc7146.dll', 'libifcoremd.dll', 'libmmd.dll']), ] opt_lib = [] else: # unix libmaxent_name = 'maxent' extra_compile_args = [ "-DNDEBUG", "-DPYTHON_MODULE", "-DBOOST_DISABLE_THREADS", ] data_files = [] # various options detected from running ../configure opt_lib = [] opt_lib_path = [] ac_cv_lib_z_main = "@ac_cv_lib_z_main@" if ac_cv_lib_z_main == 'yes': opt_lib.append('z') fclibs = "/usr/lib/x86_64-linux-gnu/libboost_chrono.a" opt_lib_path.append("/usr/lib/x86_64-linux-gnu/") opt_lib.append('boost_chrono') opt_lib.append('boost_timer') # if fclibs != '': # for s in fclibs.split(): # if s[:2] == '-L': # opt_lib_path.append(s[2:]) # elif s[:2] == '-l': # opt_lib.append(s[2:]) # else: # raise 'unknow FCLIBS item: %s' % s setup(name = "maxent", version = "version-devel", author = "Le Zhang", author_email = "ejoy@users.sourceforge.net", url = "http://homepages.inf.ed.ac.uk/lzhang10/maxent_toolkit.html", description = "A Maximum Entropy Modeling toolkit in python", long_description = """Maxent is a powerful, flexible, and easy-to-use Maximum Entropy Modeling library for Python. The core engine is written in C++ with speed and portability in mind. The win32 version of this module was compiled with MSVC7.1, Intel Fortran 8.0, STLPort 4.6. """, license = "LGPL", packages = ['maxent'], ext_modules=[ Extension("maxent._cmaxent", ["maxent_wrap.cxx"], include_dirs=[ "../src", ], library_dirs=[ "../build/src", ] + opt_lib_path, libraries = [libmaxent_name] + opt_lib, extra_compile_args = extra_compile_args, ) ], data_files = data_files, )
lzhang10/maxent
python/setup.py
Python
lgpl-2.1
2,832
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> <title>EpcgReaderServerTableRowStatusListener xref</title> <link type="text/css" rel="stylesheet" href="../../../../../../../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../../../../../../../apidocs/org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/EpcgReaderServerTableRowStatusListener.html">View Javadoc</a></div><pre> <a name="1" href="#1">1</a> <em class="jxr_comment">/*</em> <a name="2" href="#2">2</a> <em class="jxr_comment"> * Copyright (C) 2007 ETH Zurich</em> <a name="3" href="#3">3</a> <em class="jxr_comment"> *</em> <a name="4" href="#4">4</a> <em class="jxr_comment"> * This file is part of Fosstrak (www.fosstrak.org).</em> <a name="5" href="#5">5</a> <em class="jxr_comment"> *</em> <a name="6" href="#6">6</a> <em class="jxr_comment"> * Fosstrak is free software; you can redistribute it and/or</em> <a name="7" href="#7">7</a> <em class="jxr_comment"> * modify it under the terms of the GNU Lesser General Public</em> <a name="8" href="#8">8</a> <em class="jxr_comment"> * License version 2.1, as published by the Free Software Foundation.</em> <a name="9" href="#9">9</a> <em class="jxr_comment"> *</em> <a name="10" href="#10">10</a> <em class="jxr_comment"> * Fosstrak is distributed in the hope that it will be useful,</em> <a name="11" href="#11">11</a> <em class="jxr_comment"> * but WITHOUT ANY WARRANTY; without even the implied warranty of</em> <a name="12" href="#12">12</a> <em class="jxr_comment"> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU</em> <a name="13" href="#13">13</a> <em class="jxr_comment"> * Lesser General Public License for more details.</em> <a name="14" href="#14">14</a> <em class="jxr_comment"> *</em> <a name="15" href="#15">15</a> <em class="jxr_comment"> * You should have received a copy of the GNU Lesser General Public</em> <a name="16" href="#16">16</a> <em class="jxr_comment"> * License along with Fosstrak; if not, write to the Free</em> <a name="17" href="#17">17</a> <em class="jxr_comment"> * Software Foundation, Inc., 51 Franklin Street, Fifth Floor,</em> <a name="18" href="#18">18</a> <em class="jxr_comment"> * Boston, MA 02110-1301 USA</em> <a name="19" href="#19">19</a> <em class="jxr_comment"> */</em> <a name="20" href="#20">20</a> <a name="21" href="#21">21</a> <strong class="jxr_keyword">package</strong> org.fosstrak.reader.rprm.core.mgmt.agent.snmp.table; <a name="22" href="#22">22</a> <a name="23" href="#23">23</a> <strong class="jxr_keyword">import</strong> org.fosstrak.reader.rprm.core.ReaderDevice; <a name="24" href="#24">24</a> <strong class="jxr_keyword">import</strong> org.apache.log4j.Logger; <a name="25" href="#25">25</a> <strong class="jxr_keyword">import</strong> org.snmp4j.agent.mo.MOTableRow; <a name="26" href="#26">26</a> <strong class="jxr_keyword">import</strong> org.snmp4j.agent.mo.snmp.RowStatus; <a name="27" href="#27">27</a> <strong class="jxr_keyword">import</strong> org.snmp4j.agent.mo.snmp.RowStatusEvent; <a name="28" href="#28">28</a> <strong class="jxr_keyword">import</strong> org.snmp4j.agent.mo.snmp.RowStatusListener; <a name="29" href="#29">29</a> <strong class="jxr_keyword">import</strong> org.snmp4j.smi.OID; <a name="30" href="#30">30</a> <a name="31" href="#31">31</a> <em class="jxr_javadoccomment">/**</em> <a name="32" href="#32">32</a> <em class="jxr_javadoccomment"> * Row status listener to be used with the</em> <a name="33" href="#33">33</a> <em class="jxr_javadoccomment"> * &lt;code&gt;epcgReaderServerRowStatus&lt;/code&gt; column.</em> <a name="34" href="#34">34</a> <em class="jxr_javadoccomment"> */</em> <a name="35" href="#35">35</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../../../../../org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/EpcgReaderServerTableRowStatusListener.html">EpcgReaderServerTableRowStatusListener</a> implements RowStatusListener { <a name="36" href="#36">36</a> <a name="37" href="#37">37</a> <em class="jxr_javadoccomment">/**</em> <a name="38" href="#38">38</a> <em class="jxr_javadoccomment"> * The logger.</em> <a name="39" href="#39">39</a> <em class="jxr_javadoccomment"> */</em> <a name="40" href="#40">40</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> Logger log = Logger.getLogger(EpcgReaderServerTableRowStatusListener.<strong class="jxr_keyword">class</strong>); <a name="41" href="#41">41</a> <a name="42" href="#42">42</a> <em class="jxr_javadoccomment">/**</em> <a name="43" href="#43">43</a> <em class="jxr_javadoccomment"> * The reader device.</em> <a name="44" href="#44">44</a> <em class="jxr_javadoccomment"> */</em> <a name="45" href="#45">45</a> <strong class="jxr_keyword">private</strong> <a href="../../../../../../../../../org/fosstrak/reader/rprm/core/ReaderDevice.html">ReaderDevice</a> readerDevice; <a name="46" href="#46">46</a> <a name="47" href="#47">47</a> <em class="jxr_javadoccomment">/**</em> <a name="48" href="#48">48</a> <em class="jxr_javadoccomment"> * The constructor.</em> <a name="49" href="#49">49</a> <em class="jxr_javadoccomment"> * </em> <a name="50" href="#50">50</a> <em class="jxr_javadoccomment"> * @param readerDevice</em> <a name="51" href="#51">51</a> <em class="jxr_javadoccomment"> * The reader device</em> <a name="52" href="#52">52</a> <em class="jxr_javadoccomment"> */</em> <a name="53" href="#53">53</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../../../../../org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/EpcgReaderServerTableRowStatusListener.html">EpcgReaderServerTableRowStatusListener</a>(<a href="../../../../../../../../../org/fosstrak/reader/rprm/core/ReaderDevice.html">ReaderDevice</a> readerDevice) { <a name="54" href="#54">54</a> <strong class="jxr_keyword">this</strong>.readerDevice = readerDevice; <a name="55" href="#55">55</a> } <a name="56" href="#56">56</a> <a name="57" href="#57">57</a> <em class="jxr_javadoccomment">/**</em> <a name="58" href="#58">58</a> <em class="jxr_javadoccomment"> * Called whenever the row status changed.</em> <a name="59" href="#59">59</a> <em class="jxr_javadoccomment"> * </em> <a name="60" href="#60">60</a> <em class="jxr_javadoccomment"> * @param event</em> <a name="61" href="#61">61</a> <em class="jxr_javadoccomment"> * Row status event</em> <a name="62" href="#62">62</a> <em class="jxr_javadoccomment"> */</em> <a name="63" href="#63">63</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> rowStatusChanged(RowStatusEvent event) { <a name="64" href="#64">64</a> <strong class="jxr_keyword">if</strong> (event.getNewStatus() == RowStatus.destroy) { <a name="65" href="#65">65</a> MOTableRow row = event.getRow(); <a name="66" href="#66">66</a> OID rowIndex = row.getIndex(); <a name="67" href="#67">67</a> <em class="jxr_comment">// TODO: remove the server</em> <a name="68" href="#68">68</a> } <a name="69" href="#69">69</a> } <a name="70" href="#70">70</a> <a name="71" href="#71">71</a> } </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
Fosstrak/fosstrak.github.io
reader/xref/org/fosstrak/reader/rprm/core/mgmt/agent/snmp/table/EpcgReaderServerTableRowStatusListener.html
HTML
lgpl-2.1
7,663
// // MenuImpl.cs // // Author: // Andreas Willich <sabotageandi@gmail.com> // // Copyright (c) 2012 Andreas Willich // // This library 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. // // 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 using System; using System.Runtime.InteropServices; using Efl.Evas; namespace Efl.Elementary.Impl { public class MenuImpl : Evas.EvasObject { [DllImport(Library.Name)] protected static extern IntPtr elm_menu_add (IntPtr parent); [DllImport(Library.Name)] protected static extern void elm_menu_parent_set (IntPtr obj, IntPtr parent); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_parent_get (IntPtr obj); [DllImport(Library.Name)] protected static extern void elm_menu_move (IntPtr obj, int x, int y); [DllImport(Library.Name)] protected static extern void elm_menu_close (IntPtr obj); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_items_get (IntPtr obj); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_item_object_get (IntPtr it); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_item_add (IntPtr obj, IntPtr parent, string icon, string label, EvasSmartCallback func, IntPtr data); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_item_add_object (IntPtr obj, IntPtr parent, IntPtr subobj, EvasSmartCallback func, IntPtr data); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_item_separator_add (IntPtr obj, IntPtr parent); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_selected_item_get (IntPtr obj); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_last_item_get (IntPtr obj); [DllImport(Library.Name)] protected static extern IntPtr elm_menu_first_item_get (IntPtr obj); } }
SabotageAndi/efl-sharp
elementary-sharp/src/Impl/MenuImpl.cs
C#
lgpl-2.1
2,509
//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Roman Zulak // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Utils/Platform.h" #if defined(LLVM_ON_WIN32) #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <sstream> #include <stdlib.h> #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOGDI #define NOGDI #endif #ifndef NOMINMAX #define NOMINMAX #endif #include <Windows.h> #include <Psapi.h> // EnumProcessModulesEx #include <direct.h> // _getcwd #include <shlobj.h> // SHGetFolderPath #pragma comment(lib, "Advapi32.lib") #define MAX_PATHC (MAX_PATH + 1) namespace cling { namespace utils { namespace platform { inline namespace windows { static void GetErrorAsString(DWORD Err, std::string& ErrStr, const char* Prefix) { llvm::raw_string_ostream Strm(ErrStr); if (Prefix) Strm << Prefix << ": returned " << Err << " "; LPTSTR Message = nullptr; const DWORD Size = ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&Message, 0, nullptr); if (Size && Message) { Strm << Message; ::LocalFree(Message); ErrStr = llvm::StringRef(Strm.str()).rtrim().str(); } } static void ReportError(DWORD Err, const char* Prefix) { std::string Message; GetErrorAsString(Err, Message, Prefix); llvm::errs() << Err << '\n'; } bool GetLastErrorAsString(std::string& ErrStr, const char* Prefix) { if (const DWORD Err = ::GetLastError()) { GetErrorAsString(Err, ErrStr, Prefix); return true; } return false; } bool ReportLastError(const char* Prefix) { if (const DWORD Err = ::GetLastError()) { ReportError(Err, Prefix); return true; } return false; } namespace { // Taken from clang/lib/Driver/MSVCToolChain.cpp static bool readFullStringValue(HKEY hkey, const char *valueName, std::string &value) { std::wstring WideValueName; if (valueName && !llvm::ConvertUTF8toWide(valueName, WideValueName)) return false; // First just query for the required size. DWORD valueSize = 0, type = 0; DWORD result = ::RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL, &valueSize); if (result == ERROR_SUCCESS) { if (type != REG_SZ || !valueSize) return false; llvm::SmallVector<wchar_t, MAX_PATHC> buffer; buffer.resize(valueSize/sizeof(wchar_t)); result = ::RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, reinterpret_cast<BYTE*>(&buffer[0]), &valueSize); if (result == ERROR_SUCCESS) { // String might be null terminated, which we don't want while (!buffer.empty() && buffer.back() == 0) buffer.pop_back(); std::wstring WideValue(buffer.data(), buffer.size()); // The destination buffer must be empty as an invariant of the conversion // function; but this function is sometimes called in a loop that passes // in the same buffer, however. Simply clear it out so we can overwrite it value.clear(); return llvm::convertWideToUTF8(WideValue, value); } } ReportError(result, "RegQueryValueEx"); return false; } static void logSearch(const char* Name, const std::string& Value, const char* Found = nullptr) { if (Found) llvm::errs() << "Found " << Name << " '" << Value << "' that matches " << Found << " version\n"; else llvm::errs() << Name << " '" << Value << "' not found.\n"; } static void trimString(const char* Value, const char* Sub, std::string& Out) { const char* End = ::strstr(Value, Sub); Out = End ? std::string(Value, End) : Value; } static bool getVSRegistryString(const char* Product, int VSVersion, std::string& Path, const char* Verbose) { std::ostringstream Key; Key << "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\" << Product << "\\" << VSVersion << ".0"; std::string IDEInstallDir; if (!GetSystemRegistryString(Key.str().c_str(), "InstallDir", IDEInstallDir) || IDEInstallDir.empty()) { if (Verbose) logSearch("Registry", Key.str()); return false; } trimString(IDEInstallDir.c_str(), "\\Common7\\IDE", Path); if (Verbose) logSearch("Registry", Key.str(), Verbose); return true; } static bool getVSEnvironmentString(int VSVersion, std::string& Path, const char* Verbose) { std::ostringstream Key; Key << "VS" << VSVersion * 10 << "COMNTOOLS"; const char* Tools = ::getenv(Key.str().c_str()); if (!Tools) { if (Verbose) logSearch("Environment", Key.str()); return false; } trimString(Tools, "\\Common7\\Tools", Path); if (Verbose) logSearch("Environment", Key.str(), Verbose); return true; } static bool getVisualStudioVer(int VSVersion, std::string& Path, const char* Verbose) { if (getVSRegistryString("VisualStudio", VSVersion, Path, Verbose)) return true; if (getVSRegistryString("VCExpress", VSVersion, Path, Verbose)) return true; if (getVSEnvironmentString(VSVersion, Path, Verbose)) return true; return false; } // Find the most recent version of Universal CRT or Windows 10 SDK. // vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include // directory by name and uses the last one of the list. // So we compare entry names lexicographically to find the greatest one. static bool getWindows10SDKVersion(std::string& SDKPath, std::string& SDKVersion) { // Save input SDKVersion to match, and clear SDKVersion for > comparsion std::string UcrtCompiledVers; UcrtCompiledVers.swap(SDKVersion); std::error_code EC; llvm::SmallString<MAX_PATHC> IncludePath(SDKPath); llvm::sys::path::append(IncludePath, "Include"); for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd; DirIt != DirEnd && !EC; DirIt.increment(EC)) { if (!llvm::sys::fs::is_directory(DirIt->path())) continue; llvm::StringRef Candidate = llvm::sys::path::filename(DirIt->path()); // There could be subfolders like "wdf" in the "Include" directory, so only // test names that start with "10." or match input. const bool Match = Candidate == UcrtCompiledVers; if (Match || (Candidate.startswith("10.") && Candidate > SDKVersion)) { SDKPath = DirIt->path(); Candidate.str().swap(SDKVersion); if (Match) return true; } } return !SDKVersion.empty(); } static bool getUniversalCRTSdkDir(std::string& Path, std::string& UCRTVersion) { // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry // for the specific key "KitsRoot10". So do we. if (!GetSystemRegistryString("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\" "Windows Kits\\Installed Roots", "KitsRoot10", Path)) return false; return getWindows10SDKVersion(Path, UCRTVersion); } bool getWindowsSDKDir(std::string& WindowsSDK) { return GetSystemRegistryString("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\" "Microsoft SDKs\\Windows\\$VERSION", "InstallationFolder", WindowsSDK); } } // anonymous namespace bool GetSystemRegistryString(const char *keyPath, const char *valueName, std::string& outValue) { HKEY hRootKey = NULL; const char* subKey = NULL; if (::strncmp(keyPath, "HKEY_CLASSES_ROOT", 17) == 0) { hRootKey = HKEY_CLASSES_ROOT; subKey = keyPath + 17; } else if (::strncmp(keyPath, "HKEY_USERS", 10) == 0) { hRootKey = HKEY_USERS; subKey = keyPath + 10; } else if (::strncmp(keyPath, "HKEY_LOCAL_MACHINE", 18) == 0) { hRootKey = HKEY_LOCAL_MACHINE; subKey = keyPath + 18; } else if (::strncmp(keyPath, "HKEY_CURRENT_USER", 17) == 0) { hRootKey = HKEY_CURRENT_USER; subKey = keyPath + 17; } else { return false; } // Accept HKEY_CLASSES_ROOT or HKEY_CLASSES_ROOT\\ as the key to lookup in switch (subKey[0]) { case '\\': ++subKey; case 0: break; default: return false; // HKEY_CLASSES_ROOT_MORE_STUFF ? } long lResult; bool returnValue = false; HKEY hKey = NULL; // If we have a $VERSION placeholder, do the highest-version search. if (const char *placeHolder = ::strstr(subKey, "$VERSION")) { char bestName[256]; bestName[0] = '\0'; const char *keyEnd = placeHolder - 1; const char *nextKey = placeHolder; // Find end of previous key. while ((keyEnd > subKey) && (*keyEnd != '\\')) keyEnd--; // Find end of key containing $VERSION. while (*nextKey && (*nextKey != '\\')) nextKey++; size_t partialKeyLength = keyEnd - subKey; char partialKey[256]; if (partialKeyLength > sizeof(partialKey)) partialKeyLength = sizeof(partialKey); ::strncpy(partialKey, subKey, partialKeyLength); partialKey[partialKeyLength] = '\0'; HKEY hTopKey = NULL; lResult = ::RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY, &hTopKey); if (lResult == ERROR_SUCCESS) { char keyName[256]; // int bestIndex = -1; double bestValue = 0.0; DWORD size = sizeof(keyName) - 1; for (DWORD index = 0; ::RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS; index++) { const char *sp = keyName; while (*sp && !isdigit(*sp)) sp++; if (!*sp) continue; const char *ep = sp + 1; while (*ep && (isdigit(*ep) || (*ep == '.'))) ep++; char numBuf[32]; ::strncpy(numBuf, sp, sizeof(numBuf) - 1); numBuf[sizeof(numBuf) - 1] = '\0'; double dvalue = ::strtod(numBuf, NULL); if (dvalue > bestValue) { // Test that InstallDir is indeed there before keeping this index. // Open the chosen key path remainder. ::strcpy(bestName, keyName); // Append rest of key. ::strncat(bestName, nextKey, sizeof(bestName) - 1); bestName[sizeof(bestName) - 1] = '\0'; lResult = ::RegOpenKeyExA(hTopKey, bestName, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (lResult == ERROR_SUCCESS) { if (readFullStringValue(hKey, valueName, outValue)) { // bestIndex = (int)index; bestValue = dvalue; returnValue = true; } ::RegCloseKey(hKey); } } size = sizeof(keyName) - 1; } ::RegCloseKey(hTopKey); } else ReportError(lResult, "RegOpenKeyEx"); } else { // If subKey is empty, then valueName is subkey, and we retreive that if (subKey[0]==0) { subKey = valueName; valueName = nullptr; } lResult = ::RegOpenKeyExA(hRootKey, subKey, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); if (lResult == ERROR_SUCCESS) { returnValue = readFullStringValue(hKey, valueName, outValue); ::RegCloseKey(hKey); } else ReportError(lResult, "RegOpenKeyEx"); } return returnValue; } static int GetVisualStudioVersionCompiledWith() { #if (_MSC_VER < 1900) return (_MSC_VER / 100) - 6; #elif (_MSC_VER < 1910) return 14; #else #error "Unsupported/Untested _MSC_VER" // As of now this is what is should be...have fun! return 15; #endif } static void fixupPath(std::string& Path, const char* Append = nullptr) { const char kSep = '\\'; if (Append) { if (Path.empty()) return; if (Path.back() != kSep) Path.append(1, kSep); Path.append(Append); } else { while (!Path.empty() && Path.back() == kSep) Path.pop_back(); } } bool GetVisualStudioDirs(std::string& Path, std::string* WinSDK, std::string* UniversalSDK, bool Verbose) { if (WinSDK) { if (!getWindowsSDKDir(*WinSDK)) { WinSDK->clear(); if (Verbose) llvm::errs() << "Could not get Windows SDK path\n"; } else fixupPath(*WinSDK); } if (UniversalSDK) { // On input UniversalSDK is the best version to match std::string UCRTVersion; UniversalSDK->swap(UCRTVersion); if (!getUniversalCRTSdkDir(*UniversalSDK, UCRTVersion)) { UniversalSDK->clear(); if (Verbose) llvm::errs() << "Could not get Universal SDK path\n"; } else fixupPath(*UniversalSDK, "ucrt"); } const char* Msg = Verbose ? "compiled" : nullptr; // Try for the version compiled with first const int VSVersion = GetVisualStudioVersionCompiledWith(); if (getVisualStudioVer(VSVersion, Path, Msg)) { fixupPath(Path); return true; } // Check the environment variables that vsvars32.bat sets. // We don't do this first so we can run from other VSStudio shells properly if (const char* VCInstall = ::getenv("VCINSTALLDIR")) { trimString(VCInstall, "\\VC", Path); if (Verbose) llvm::errs() << "Using VCINSTALLDIR '" << VCInstall << "'\n"; return true; } // Try for any other version we can get Msg = Verbose ? "highest" : nullptr; const int Versions[] = { 14, 12, 11, 10, 9, 8, 0 }; for (unsigned i = 0; Versions[i]; ++i) { if (Versions[i] != VSVersion && getVisualStudioVer(Versions[i], Path, Msg)) { fixupPath(Path); return true; } } return false; } bool IsDLL(const std::string& Path) { bool isDLL = false; HANDLE hFile = ::CreateFileA(Path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hFile == INVALID_HANDLE_VALUE) { ReportLastError("CreateFile"); return false; } HANDLE hFileMapping = ::CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (hFileMapping == INVALID_HANDLE_VALUE) { ReportLastError("CreateFileMapping"); ::CloseHandle(hFile); return false; } LPVOID lpFileBase = ::MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0); if (!lpFileBase) { ReportLastError("CreateFileMapping"); ::CloseHandle(hFileMapping); ::CloseHandle(hFile); return false; } PIMAGE_DOS_HEADER pDOSHeader = static_cast<PIMAGE_DOS_HEADER>(lpFileBase); if (pDOSHeader->e_magic == IMAGE_DOS_SIGNATURE) { PIMAGE_NT_HEADERS pNTHeader = reinterpret_cast<PIMAGE_NT_HEADERS>( (PBYTE)lpFileBase + pDOSHeader->e_lfanew); if ((pNTHeader->Signature == IMAGE_NT_SIGNATURE) && ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL))) isDLL = true; } ::UnmapViewOfFile(lpFileBase); ::CloseHandle(hFileMapping); ::CloseHandle(hFile); return isDLL; } } // namespace windows std::string GetCwd() { char Buffer[MAX_PATHC]; if (::_getcwd(Buffer, sizeof(Buffer))) return Buffer; ::perror("Could not get current working directory"); return std::string(); } std::string NormalizePath(const std::string& Path) { char Buf[MAX_PATHC]; if (const char* Result = ::_fullpath(Buf, Path.c_str(), sizeof(Buf))) return std::string(Result); ReportLastError("_fullpath"); return std::string(); } bool IsMemoryValid(const void *P) { MEMORY_BASIC_INFORMATION MBI; if (::VirtualQuery(P, &MBI, sizeof(MBI)) == 0) { ReportLastError("VirtualQuery"); return false; } if (MBI.State != MEM_COMMIT) return false; return true; } const void* DLOpen(const std::string& Path, std::string* Err) { HMODULE dyLibHandle = ::LoadLibraryA(Path.c_str()); if (!dyLibHandle && Err) GetLastErrorAsString(*Err, "LoadLibrary"); return reinterpret_cast<void*>(dyLibHandle); } const void* DLSym(const std::string& Name, std::string* Err) { #ifdef _WIN64 const DWORD Flags = LIST_MODULES_64BIT; #else const DWORD Flags = LIST_MODULES_32BIT; #endif DWORD Bytes; std::string ErrStr; llvm::SmallVector<HMODULE, 128> Modules; Modules.resize(Modules.capacity()); if (::EnumProcessModulesEx(::GetCurrentProcess(), &Modules[0], Modules.capacity_in_bytes(), &Bytes, Flags) != 0) { // Search the modules we got const DWORD NumNeeded = Bytes/sizeof(HMODULE); const DWORD NumFirst = Modules.size(); if (NumNeeded < NumFirst) Modules.resize(NumNeeded); // In reverse so user loaded modules are searched first for (auto It = Modules.rbegin(), End = Modules.rend(); It < End; ++It) { if (const void* Addr = ::GetProcAddress(*It, Name.c_str())) return Addr; } if (NumNeeded > NumFirst) { // The number of modules was too small to get them all, so call again Modules.resize(NumNeeded); if (::EnumProcessModulesEx(::GetCurrentProcess(), &Modules[0], Modules.capacity_in_bytes(), &Bytes, Flags) != 0) { for (DWORD i = NumNeeded-1; i > NumFirst; --i) { if (const void* Addr = ::GetProcAddress(Modules[i], Name.c_str())) return Addr; } } else if (Err) GetLastErrorAsString(*Err, "EnumProcessModulesEx"); } } else if (Err) GetLastErrorAsString(*Err, "EnumProcessModulesEx"); return nullptr; } void DLClose(const void* Lib, std::string* Err) { if (::FreeLibrary(reinterpret_cast<HMODULE>(const_cast<void*>(Lib))) == 0) { if (Err) GetLastErrorAsString(*Err, "FreeLibrary"); } } bool GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char Buf[MAX_PATHC]; // Generic form of C:\Windows\System32 HRESULT result = ::SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, Buf); if (result != S_OK) { ReportError(result, "SHGetFolderPathA"); return false; } Paths.push_back(Buf); Buf[0] = 0; // Reset Buf. // Generic form of C:\Windows result = ::SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, Buf); if (result != S_OK) { ReportError(result, "SHGetFolderPathA"); return false; } Paths.push_back(Buf); return true; } static void CloseHandle(HANDLE H) { if (::CloseHandle(H) == 0) ReportLastError("CloseHandle"); } bool Popen(const std::string& Cmd, llvm::SmallVectorImpl<char>& Buf, bool RdE) { Buf.resize(0); SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; HANDLE Process = ::GetCurrentProcess(); HANDLE hOutputReadTmp, hOutputRead, hOutputWrite, hErrorWrite; if (::CreatePipe(&hOutputReadTmp, &hOutputWrite, &saAttr, 0) == 0) return false; if (RdE) { if (::DuplicateHandle(Process, hOutputWrite, Process, &hErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) { ReportLastError("DuplicateHandle"); ::CloseHandle(hOutputReadTmp); ::CloseHandle(hOutputWrite); return false; } } // Create new output read handle. Set the Properties to FALSE, otherwise the // child inherits the properties and, as a result, non-closeable handles to // the pipes are created. if (::DuplicateHandle(Process, hOutputReadTmp, Process, &hOutputRead, 0, FALSE, DUPLICATE_SAME_ACCESS) == 0) { ReportLastError("DuplicateHandle"); ::CloseHandle(hOutputReadTmp); ::CloseHandle(hOutputWrite); if (RdE) ::CloseHandle(hErrorWrite); return false; } // Close inheritable copies of the handles you do not want to be inherited. CloseHandle(hOutputReadTmp); STARTUPINFOA si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdOutput = hOutputWrite; if (RdE) si.hStdError = hErrorWrite; PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx // CreateProcessW can write back to second arguement, CreateProcessA not BOOL Result = ::CreateProcessA(NULL, (LPSTR)Cmd.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi); DWORD Err = ::GetLastError(); // Close pipe handles (do not continue to modify the parent) to make sure // that no handles to the write end of the output pipe are maintained in this // process or else the pipe will not close when the child process exits and // the ReadFile will hang. CloseHandle(hOutputWrite); if (RdE) CloseHandle(hErrorWrite); if (Result != 0) { DWORD dwRead; const size_t Chunk = Buf.capacity_in_bytes(); while (true) { const size_t Len = Buf.size(); Buf.resize(Len + Chunk); Result = ::ReadFile(hOutputRead, &Buf[Len], Chunk, &dwRead, NULL); if (!Result || !dwRead) { Err = ::GetLastError(); if (Err != ERROR_BROKEN_PIPE) ReportError(Err, "ReadFile"); Buf.resize(Len); break; } if (dwRead < Chunk) Buf.resize(Len + dwRead); } // Close process and thread handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else ReportError(Err, "CreateProcess"); CloseHandle(hOutputRead); return !Buf.empty(); } } // namespace platform } // namespace utils } // namespace cling #endif // LLVM_ON_WIN32
georgtroska/root
interpreter/cling/lib/Utils/PlatformWin.cpp
C++
lgpl-2.1
22,012
# JSON class The *JSON* class is used to parse JSON string, encode JSON data into string. This class also supports read/write JSON file. This class is implemented as JavaScript class. You have to allocate the object to use it. ```` let file = new JSONFile() ; file.write(stdout, object) ; ```` ## `read` class method Read text from file and parse it into JSON object. ```` var object: Object = JSON.read(file: File): value | null ```` ### Parameter(s) |Parameter |Type |Description | |:--- |:--- |:--- | |file |[File](https://github.com/steelwheels/KiwiScript/blob/master/KiwiLibrary/Document/Class/File.md) |The file object to read JSON data| ### Return value The JSON object is returned when the read and parse operation was succeeded, otherwise this value will be *null*. ## `write` class method Encode JSON data into string and write it to text file. ```` var result: Bool = JSON.write(file: File, obj: Object) ```` ### Parameter(s) |Parameter |Type |Description | |:--- |:--- |:--- | |file |[File](https://github.com/steelwheels/KiwiScript/blob/master/KiwiLibrary/Document/Class/File.md) |The file object to write.| |object |Object |The source object to be encoded | ### Return value The the file writing is finished without any errors, this value will be 'true'. # References * [Kiwi Library](https://github.com/steelwheels/KiwiScript/blob/master/KiwiLibrary/Document/Library.md): Document for this library
steelwheels/KiwiScript
KiwiLibrary/Document/Class/JSON.md
Markdown
lgpl-2.1
1,560
/* Test of case-insensitive memory area comparison function. Copyright (C) 2007-2012 Free Software Foundation, Inc. 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 3 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, see <http://www.gnu.org/licenses/>. */ /* Written by Bruno Haible <bruno@clisp.org>, 2009. */ #include <config.h> #include "mbmemcasecmp.h" #include <locale.h> #include <stdbool.h> #include <string.h> #include "macros.h" #include "test-mbmemcasecmp.h" int main (int argc, char *argv[]) { /* configure should already have checked that the locale is supported. */ if (setlocale (LC_ALL, "") == NULL) return 1; test_ascii (mbmemcasecmp); if (argc > 1) switch (argv[1][0]) { case '1': /* Locale encoding is ISO-8859-1 or ISO-8859-15. */ test_iso_8859_1 (mbmemcasecmp, true); return 0; case '2': /* Locale encoding is UTF-8, locale is not Turkish. */ test_utf_8 (mbmemcasecmp, false); return 0; case '3': /* Locale encoding is UTF-8, locale is Turkish. */ test_utf_8 (mbmemcasecmp, true); return 0; } return 1; }
novel/fbsd-libvirt
.gnulib/tests/test-mbmemcasecmp.c
C
lgpl-2.1
1,672
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! library 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #pragma once #include <math.h> #include <cmath> #include <limits> namespace cb { namespace Math { #if defined(_WIN32) && !defined(__MINGW32__) #include <float.h> // Windows doesn't have round() inline static double round(double x) {return floor(x + 0.5);} inline static float round(float x) {return floorf(x + 0.5);} // Or isnan inline static bool isnan(double x) {return _isnan(x);} inline static bool isnan(float x) {return _isnan(x);} // Or isinf inline static bool isinf(double x) {return !_finite(x) && !_isnan(x);} inline static bool isinf(float x) {return !_finite(x) && !_isnan(x);} #else inline static double round(double x) {return ::round(x);} inline static float round(float x) {return roundf(x);} inline static bool isnan(double x) {return std::isnan(x);} inline static bool isnan(float x) {return std::isnan(x);} inline static bool isinf(double x) {return std::isinf(x);} inline static bool isinf(float x) {return std::isinf(x);} #endif inline static bool isfinite(double x) {return !(isnan(x) || isinf(x));} inline static bool isfinite(float x) {return !(isnan(x) || isinf(x));} inline static double nextUp(double x) { return nextafter(x, std::numeric_limits<double>::infinity()); } inline static double nextDown(double x) { return nextafter(x, -std::numeric_limits<double>::infinity()); } } } #ifndef M_PI #define M_PI 3.14159265358979323846 #endif
CauldronDevelopmentLLC/cbang
src/cbang/Math.h
C
lgpl-2.1
3,066
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_03) on Wed Jan 09 13:25:23 CET 2008 --> <TITLE> org.springframework.beans.factory.xml (Spring Framework API 2.5) </TITLE> <META NAME="date" CONTENT="2008-01-09"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../org/springframework/beans/factory/xml/package-summary.html" target="classFrame">org.springframework.beans.factory.xml</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Interfaces</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="BeanDefinitionDecorator.html" title="interface in org.springframework.beans.factory.xml" target="classFrame"><I>BeanDefinitionDecorator</I></A> <BR> <A HREF="BeanDefinitionDocumentReader.html" title="interface in org.springframework.beans.factory.xml" target="classFrame"><I>BeanDefinitionDocumentReader</I></A> <BR> <A HREF="BeanDefinitionParser.html" title="interface in org.springframework.beans.factory.xml" target="classFrame"><I>BeanDefinitionParser</I></A> <BR> <A HREF="DocumentLoader.html" title="interface in org.springframework.beans.factory.xml" target="classFrame"><I>DocumentLoader</I></A> <BR> <A HREF="NamespaceHandler.html" title="interface in org.springframework.beans.factory.xml" target="classFrame"><I>NamespaceHandler</I></A> <BR> <A HREF="NamespaceHandlerResolver.html" title="interface in org.springframework.beans.factory.xml" target="classFrame"><I>NamespaceHandlerResolver</I></A> <BR> <A HREF="XmlBeanDefinitionParser.html" title="interface in org.springframework.beans.factory.xml" target="classFrame"><I>XmlBeanDefinitionParser</I></A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="AbstractBeanDefinitionParser.html" title="class in org.springframework.beans.factory.xml" target="classFrame">AbstractBeanDefinitionParser</A> <BR> <A HREF="AbstractSimpleBeanDefinitionParser.html" title="class in org.springframework.beans.factory.xml" target="classFrame">AbstractSimpleBeanDefinitionParser</A> <BR> <A HREF="AbstractSingleBeanDefinitionParser.html" title="class in org.springframework.beans.factory.xml" target="classFrame">AbstractSingleBeanDefinitionParser</A> <BR> <A HREF="BeanDefinitionParserDelegate.html" title="class in org.springframework.beans.factory.xml" target="classFrame">BeanDefinitionParserDelegate</A> <BR> <A HREF="BeansDtdResolver.html" title="class in org.springframework.beans.factory.xml" target="classFrame">BeansDtdResolver</A> <BR> <A HREF="DefaultBeanDefinitionDocumentReader.html" title="class in org.springframework.beans.factory.xml" target="classFrame">DefaultBeanDefinitionDocumentReader</A> <BR> <A HREF="DefaultDocumentLoader.html" title="class in org.springframework.beans.factory.xml" target="classFrame">DefaultDocumentLoader</A> <BR> <A HREF="DefaultNamespaceHandlerResolver.html" title="class in org.springframework.beans.factory.xml" target="classFrame">DefaultNamespaceHandlerResolver</A> <BR> <A HREF="DelegatingEntityResolver.html" title="class in org.springframework.beans.factory.xml" target="classFrame">DelegatingEntityResolver</A> <BR> <A HREF="DocumentDefaultsDefinition.html" title="class in org.springframework.beans.factory.xml" target="classFrame">DocumentDefaultsDefinition</A> <BR> <A HREF="NamespaceHandlerSupport.html" title="class in org.springframework.beans.factory.xml" target="classFrame">NamespaceHandlerSupport</A> <BR> <A HREF="ParserContext.html" title="class in org.springframework.beans.factory.xml" target="classFrame">ParserContext</A> <BR> <A HREF="PluggableSchemaResolver.html" title="class in org.springframework.beans.factory.xml" target="classFrame">PluggableSchemaResolver</A> <BR> <A HREF="ResourceEntityResolver.html" title="class in org.springframework.beans.factory.xml" target="classFrame">ResourceEntityResolver</A> <BR> <A HREF="SimplePropertyNamespaceHandler.html" title="class in org.springframework.beans.factory.xml" target="classFrame">SimplePropertyNamespaceHandler</A> <BR> <A HREF="UtilNamespaceHandler.html" title="class in org.springframework.beans.factory.xml" target="classFrame">UtilNamespaceHandler</A> <BR> <A HREF="XmlBeanDefinitionReader.html" title="class in org.springframework.beans.factory.xml" target="classFrame">XmlBeanDefinitionReader</A> <BR> <A HREF="XmlBeanFactory.html" title="class in org.springframework.beans.factory.xml" target="classFrame">XmlBeanFactory</A> <BR> <A HREF="XmlReaderContext.html" title="class in org.springframework.beans.factory.xml" target="classFrame">XmlReaderContext</A></FONT></TD> </TR> </TABLE> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Exceptions</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="XmlBeanDefinitionStoreException.html" title="class in org.springframework.beans.factory.xml" target="classFrame">XmlBeanDefinitionStoreException</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
cacheonix/cacheonix-core
3rdparty/spring-framework-2.5.1/docs/api/org/springframework/beans/factory/xml/package-frame.html
HTML
lgpl-2.1
5,300
/* * This program 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. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.function; /** * Computes the minimum of all data-row columns defined in the field-list. This computes the horizontal minimum, to * compute the minimum value in a group, use the ItemMinFunction instead. * * @author Thomas Morgner * @deprecated Use a formula */ public class ColumnMinimumExpression extends ColumnAggregationExpression { /** * Default Constructor. */ public ColumnMinimumExpression() { } /** * Returns the minimum value. Non-comparable values are ignored. * * @return the minimum value computed by the function. */ public Object getValue() { final Object[] values = getFieldValues(); Comparable computedResult = null; for ( int i = 0; i < values.length; i++ ) { final Object value = values[i]; if ( value instanceof Comparable == false ) { continue; } final Comparable n = (Comparable) value; if ( computedResult == null ) { computedResult = n; } else if ( computedResult.compareTo( n ) < 0 ) { computedResult = n; } } return computedResult; } }
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/function/ColumnMinimumExpression.java
Java
lgpl-2.1
2,011
/* * PKCS #11 PAM Login Module * Copyright (C) 2003 Mario Strasser <mast@gmx.net>, * * This library 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. * * 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. * * $Id$ */ #define __PKCS11_LIB_C__ /* * common includes */ #include <dlfcn.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <ctype.h> #include "debug.h" #include "error.h" #include "cert_info.h" #include "pkcs11_lib.h" /* * this functions is completely common between both implementation. */ int pkcs11_pass_login(pkcs11_handle_t *h, int nullok) { int rv; char *pin; /* get password */ pin =getpass("PIN for token: "); #ifdef DEBUG_SHOW_PASSWORD DBG1("PIN = [%s]", pin); #endif if (NULL == pin) { set_error("Error encountered while reading PIN"); return -1; } /* for safety reasons, clean PIN string from memory asap */ /* check password length */ if (!nullok && strlen(pin) == 0) { set_error("Empty passwords not allowed"); return -1; } /* perform pkcs #11 login */ rv = pkcs11_login(h, pin); cleanse(pin, strlen(pin)); if (rv != 0) { set_error("pkcs11_login() failed: %s", get_error()); return -1; } return 0; } /* * memcmp_pad_max() is a specialized version of memcmp() which compares two * pieces of data up to a maximum length. If the two data match up the * maximum length, they are considered matching. Trailing blanks do not cause * the match to fail if one of the data is shorted. * * Examples of matches: * "one" | * "one " | * ^maximum length * * "Number One | X" (X is beyond maximum length) * "Number One " | * ^maximum length * * Examples of mismatches: * " one" * "one" * * "Number One X|" * "Number One |" * ^maximum length */ static int memcmp_pad_max(void *d1, size_t d1_len, void *d2, size_t d2_len, size_t max_sz) { size_t len, extra_len; char *marker; /* No point in comparing anything beyond max_sz */ if (d1_len > max_sz) d1_len = max_sz; if (d2_len > max_sz) d2_len = max_sz; /* Find shorter of the two data. */ if (d1_len <= d2_len) { len = d1_len; extra_len = d2_len; marker = d2; } else { /* d1_len > d2_len */ len = d2_len; extra_len = d1_len; marker = d1; } /* Have a match in the shortest length of data? */ if (memcmp(d1, d2, len) != 0) /* CONSTCOND */ return (1); /* If the rest of longer data is nulls or blanks, call it a match. */ while (len < extra_len && marker[len]) if (!isspace(marker[len++])) /* CONSTCOND */ return (1); return (0); } int get_random_value(unsigned char *data, int length) { static const char *random_device = "/dev/urandom"; int rv, fh, l; DBG2("reading %d random bytes from %s", length, random_device); fh = open(random_device, O_RDONLY); if (fh == -1) { set_error("open() failed: %s", strerror(errno)); return -1; } l = 0; while (l < length) { rv = read(fh, data + l, length - l); if (rv <= 0) { close(fh); set_error("read() failed: %s", strerror(errno)); return -1; } l += rv; } close(fh); DBG5("random-value[%d] = [%02x:%02x:%02x:...:%02x]", length, data[0], data[1], data[2], data[length - 1]); return 0; } void cleanse(void *ptr, size_t len) { #ifdef HAVE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } #ifdef HAVE_NSS /* * Using NSS to find the manage the PKCS #11 modules */ #include "nss.h" #include "nspr.h" #include "cert.h" #include "secmod.h" #include "secutil.h" #include "pk11pub.h" #include "cert_st.h" #include "secutil.h" #include "cryptohi.h" #include "ocsp.h" #include <unistd.h> #include <errno.h> #include "syslog.h" #include "cert_vfy.h" #ifndef PAM_PKCS11_POLL_TIME #define PAM_PKCS11_POLL_TIME 500 /* ms */ #endif struct pkcs11_handle_str { SECMODModule *module; PRBool is_user_module; PK11SlotInfo *slot; cert_object_t **certs; int cert_count; }; static int app_has_NSS = 0; static char * password_passthrough(PK11SlotInfo *slot, PRBool retry, void *arg) { /* give up if 1) no password was supplied, or 2) the password has already * been rejected once by this token. */ if (retry || (arg == NULL)) { return NULL; } return PL_strdup((char *)arg); } int crypto_init(cert_policy *policy) { SECStatus rv; DBG("Initializing NSS ..."); if (NSS_IsInitialized()) { app_has_NSS = 1; /* we should save the app's password function */ PK11_SetPasswordFunc(password_passthrough); DBG("... NSS is initialized"); return 0; } if (policy->nss_dir) { /* initialize with read only databases */ DBG1("Initializing NSS ... database=%s", policy->nss_dir); rv = NSS_Init(policy->nss_dir); } else { /* not database secified */ DBG("Initializing NSS ... with no db"); rv = NSS_NoDB_Init(NULL); } if (rv != SECSuccess) { DBG1("NSS_Initialize failed: %s", SECU_Strerror(PR_GetError())); return -1; } /* register a callback */ PK11_SetPasswordFunc(password_passthrough); if (policy->ocsp_policy == OCSP_ON) { CERT_EnableOCSPChecking(CERT_GetDefaultCertDB()); } DBG("... NSS Complete"); return 0; } static SECMODModule *find_module_by_library(const char *pkcs11_module) { SECMODModule *module = NULL; SECMODModuleList *modList = SECMOD_GetDefaultModuleList(); /* threaded applications should also acquire the * DefaultModuleListLock */ DBG("Looking up module in list"); for ( ; modList; modList = modList->next) { char *dllName = modList->module->dllName; DBG2("modList = %p next = %p\n", modList, modList->next); DBG1("dllName= %s \n", dllName ? dllName : "<null>"); if (dllName && strcmp(dllName,pkcs11_module) == 0) { module = SECMOD_ReferenceModule(modList->module); break; } } return module; } /* * NSS allows you to load a specific module. If the user specified a module * to load, load it, otherwise select on of the standard modules from the * secmod.db list. */ int load_pkcs11_module(const char *pkcs11_module, pkcs11_handle_t **hp) { pkcs11_handle_t *h = (pkcs11_handle_t *)calloc(sizeof(pkcs11_handle_t),1); SECMODModule *module = NULL; #define SPEC_TEMPLATE "library=\"%s\" name=\"SmartCard\"" char *moduleSpec = NULL; if (!pkcs11_module || (strcasecmp(pkcs11_module,"any module") == 0)) { h->is_user_module = PR_FALSE; h->module = NULL; *hp = h; return 0; } /* found it, use the existing module */ module = find_module_by_library(pkcs11_module); if (module) { h->is_user_module = PR_FALSE; h->module = module; *hp = h; return 0; } /* specified module is not already loaded, load it now */ moduleSpec = malloc(sizeof(SPEC_TEMPLATE) + strlen(pkcs11_module)); if (!moduleSpec) { DBG1("Malloc failed when allocating module spec: %s", strerror(errno)); free (h); return -1; } sprintf(moduleSpec,SPEC_TEMPLATE, pkcs11_module); DBG2("loading Module explicitly, moduleSpec=<%s> module=%s", moduleSpec, pkcs11_module); module = SECMOD_LoadUserModule(moduleSpec, NULL, 0); free(moduleSpec); if ((!module) || !module->loaded) { DBG1("Failed to load SmartCard software %s", SECU_Strerror(PR_GetError())); free (h); if (module) { SECMOD_DestroyModule(module); } return -1; } h->is_user_module = PR_TRUE; h->module = module; *hp = h; DBG("load module complete"); return 0; } int init_pkcs11_module(pkcs11_handle_t *h, int flag) { return 0; /* NSS initialized the module on load */ } int find_slot_by_number(pkcs11_handle_t *h, unsigned int slot_num, unsigned int *slotID) { SECMODModule *module = h->module; int i; /* if module is null, * any of the PKCS #11 modules specified in the system config * is available, find one */ if (module == NULL) { PK11SlotList *list; PK11SlotListElement *le; PK11SlotInfo *slot = NULL; /* find a slot, we haven't specifically selected a module, * so find an appropriate one. */ /* get them all */ list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_TRUE, NULL); if (list == NULL) { return -1; } for (le = list->head; le; le = le->next) { CK_SLOT_INFO slInfo; SECStatus rv; slInfo.flags = 0; rv = PK11_GetSlotInfo(le->slot, &slInfo); if (rv == SECSuccess && (slInfo.flags & CKF_REMOVABLE_DEVICE)) { slot = PK11_ReferenceSlot(le->slot); module = SECMOD_ReferenceModule(PK11_GetModule(le->slot)); break; } } PK11_FreeSlotList(list); if (slot == NULL) { return -1; } h->slot = slot; h->module = module; *slotID = PK11_GetSlotID(slot); return 0; } /* * we're configured with a specific module, look for a present slot * on that module. */ if (slot_num == 0) { /* threaded applications should also acquire the * DefaultModuleListLock */ for (i=0; i < module->slotCount; i++) { if (module->slots[i] && PK11_IsPresent(module->slots[i])) { h->slot = PK11_ReferenceSlot(module->slots[i]); *slotID = PK11_GetSlotID(h->slot); return 0; } } } /* we're configured for a specific module and token, see if it's present */ slot_num--; if (slot_num < module->slotCount && module->slots && module->slots[slot_num] && PK11_IsPresent(module->slots[slot_num])) { h->slot = PK11_ReferenceSlot(module->slots[slot_num]); *slotID = PK11_GetSlotID(h->slot); return 0; } return -1; } /* * find a slot by it's slot number or label. If slot number is '0' any * slot is ok. */ int find_slot_by_number_and_label(pkcs11_handle_t *h, int wanted_slot_id, const char *wanted_token_label, unsigned int *slot_num) { int rv; const char *token_label = NULL; PK11SlotInfo *slot = NULL; /* we want a specific slot id, or we don't kare about the label */ if ((wanted_token_label == NULL) || (wanted_slot_id != 0)) { rv = find_slot_by_number(h, wanted_slot_id, slot_num); /* if we don't care about the label, or we failed, we're done */ if ((wanted_token_label == NULL) || (rv != 0)) { return rv; } /* verify it's the label we want */ token_label = PK11_GetTokenName(h->slot); if ((token_label != NULL) && (strcmp (wanted_token_label, token_label) == 0)) { return 0; } return -1; } /* we want a specific slot by label only */ slot = PK11_FindSlotByName(wanted_token_label); if (!slot) { return -1; } /* make sure it's in the right module */ if (h->module) { if (h->module != PK11_GetModule(slot)) { PK11_FreeSlot(slot); return -1; } } else { /* no module was specified, use the one slot came in */ h->module = SECMOD_ReferenceModule(PK11_GetModule(slot)); } h->slot = slot; /* Adopt the reference */ *slot_num = PK11_GetSlotID(h->slot); return 0; } int wait_for_token(pkcs11_handle_t *h, int wanted_slot_id, const char *wanted_token_label, unsigned int *slot_num) { int rv; rv = -1; do { /* see if the card we're looking for is inserted */ rv = find_slot_by_number_and_label (h, wanted_slot_id, wanted_token_label, slot_num); if (rv != 0) { PK11SlotInfo *slot; PRIntervalTime slot_poll_interval; /* only for legacy hardware */ /* if the card is not inserted, then block until something happens */ slot_poll_interval = PR_MillisecondsToInterval(PAM_PKCS11_POLL_TIME); slot = SECMOD_WaitForAnyTokenEvent(h->module, 0 /* flags */, slot_poll_interval); /* unexpected error */ if (slot == NULL) { break; } /* something happened, continue loop and check if the card * we're looking for is inserted */ PK11_FreeSlot(slot); continue; } } while (rv != 0); return rv; } /* * This function will search the slot list to find a slot based on the slot * label. If the wanted_slot_label is "none", then we will return the first * slot with the token presented. * * This function return 0 if it found a matching slot; otherwise, it returns * -1. */ int find_slot_by_slotlabel(pkcs11_handle_t *h, const char *wanted_slot_label, unsigned int *slotID) { SECMODModule *module = h->module; PK11SlotInfo *slot; int rv; int i; if (slotID == NULL || wanted_slot_label == NULL || strlen(wanted_slot_label) == 0 || module == NULL) return (-1); if (strcmp(wanted_slot_label, "none") == 0) { rv = find_slot_by_number(h, 0, slotID); return (rv); } else { /* wanted_slot_label is not "none" */ for (i = 0; i < module->slotCount; i++) { if (module->slots[i] && PK11_IsPresent(module->slots[i])) { const char *slot_label; slot = PK11_ReferenceSlot(module->slots[i]); slot_label = PK11_GetSlotName(slot); if (memcmp_pad_max((void *)slot_label, strlen(slot_label), (void *)wanted_slot_label, strlen(wanted_slot_label), strlen(wanted_slot_label)) == 0) { h->slot = slot; *slotID = PK11_GetSlotID(slot); return 0; } } } } return (-1); } int find_slot_by_slotlabel_and_tokenlabel(pkcs11_handle_t *h, const char *wanted_slot_label, const char *wanted_token_label, unsigned int *slot_num) { SECMODModule *module = h->module; PK11SlotInfo *slot; unsigned long i; int rv; if (slot_num == NULL || module == NULL) return (-1); if (wanted_token_label == NULL){ rv = find_slot_by_slotlabel(h, wanted_slot_label, slot_num); return (rv); } /* wanted_token_label != NULL */ if (strcmp(wanted_slot_label, "none") == 0) { for (i = 0; i < module->slotCount; i++) { if (module->slots[i] && PK11_IsPresent(module->slots[i])) { const char *token_label; slot = PK11_ReferenceSlot(module->slots[i]); token_label = PK11_GetTokenName(slot); if (memcmp_pad_max((void *) token_label, strlen(token_label), (void *)wanted_token_label, strlen(wanted_token_label), 33) == 0) { h->slot = slot; *slot_num = PK11_GetSlotID(slot); return (0); } } } return (-1); } else { for (i = 0; i < module->slotCount; i++) { if (module->slots[i] && PK11_IsPresent(module->slots[i])) { const char *slot_label; const char *token_label; slot = PK11_ReferenceSlot(module->slots[i]); slot_label = PK11_GetSlotName(slot); token_label = PK11_GetTokenName(slot); if ((memcmp_pad_max((void *)slot_label, strlen(slot_label), (void *)wanted_slot_label, strlen(wanted_slot_label), 64) == 0) && (memcmp_pad_max((void *)token_label, strlen(token_label), (void *)wanted_token_label, strlen(wanted_token_label), 33) == 0)) { h->slot = slot; *slot_num = PK11_GetSlotID(slot); return (0); } } } return (-1); } } int wait_for_token_by_slotlabel(pkcs11_handle_t *h, const char *wanted_slot_label, const char *wanted_token_label, unsigned int *slot_num) { int rv; rv = -1; do { /* see if the card we're looking for is inserted */ rv = find_slot_by_slotlabel_and_tokenlabel (h, wanted_slot_label, wanted_token_label, slot_num); if (rv != 0) { PK11SlotInfo *slot; PRIntervalTime slot_poll_interval; /* only for legacy hardware */ /* if the card is not inserted, then block until something happens */ slot_poll_interval = PR_MillisecondsToInterval(PAM_PKCS11_POLL_TIME); slot = SECMOD_WaitForAnyTokenEvent(h->module, 0 /* flags */, slot_poll_interval); /* unexpected error */ if (slot == NULL) { break; } /* something happened, continue loop and check if the card * we're looking for is inserted */ PK11_FreeSlot(slot); continue; } } while (rv != 0); return rv; } void release_pkcs11_module(pkcs11_handle_t *h) { SECStatus rv; close_pkcs11_session(h); if (h->is_user_module) { rv = SECMOD_UnloadUserModule(h->module); if (rv != SECSuccess) { DBG1("Unloading UserModule failed: %s", SECU_Strerror(PR_GetError())); } } if (h->module) { SECMOD_DestroyModule(h->module); } cleanse(h, sizeof(pkcs11_handle_t)); free(h); /* if we initialized NSS, then we need to shut it down */ if (!app_has_NSS) { rv = NSS_Shutdown(); if (rv != SECSuccess) { DBG1("NSS Shutdown Failed: %s", SECU_Strerror(PR_GetError())); } } } int open_pkcs11_session(pkcs11_handle_t *h, unsigned int slot_num) { /* NSS manages the sessions under the covers, use this function to * select a slot */ if (h->slot != NULL) { /* we've already selected the slot */ if (PK11_GetSlotID(h->slot) == slot_num) { return 0; } /* the slot we've selected isn't the one we want to open */ PK11_FreeSlot(h->slot); h->slot = NULL; } /* look the slot up */ h->slot = SECMOD_LookupSlot(h->module->moduleID, slot_num); if (h->slot == NULL) { return -1; } /* make sure it is present */ if (!PK11_IsPresent(h->slot)) { PK11_FreeSlot(h->slot); h->slot = NULL; return -1; } return 0; } int pkcs11_login(pkcs11_handle_t *h, char *password) { SECStatus rv; if (h->slot == NULL) { DBG("Login failed: No Slot selected"); return -1; } rv = PK11_Authenticate(h->slot, PR_FALSE, password); if (rv != SECSuccess) { DBG1("Login failed: %s", SECU_Strerror(PR_GetError())); } return (rv == SECSuccess) ? 0 : -1; } int get_slot_login_required(pkcs11_handle_t *h) { if (h->slot == NULL) { DBG("Login failed: No Slot selected"); return -1; } return PK11_NeedLogin(h->slot); } int get_slot_protected_authentication_path(pkcs11_handle_t *h) { if (h->slot == NULL) { DBG("Login failed: No Slot selected"); return -1; } return PK11_ProtectedAuthenticationPath(h->slot); } int close_pkcs11_session(pkcs11_handle_t *h) { if (h->slot) { PK11_Logout(h->slot); PK11_FreeSlot(h->slot); h->slot = NULL; } if (h->certs) { CERT_DestroyCertArray((CERTCertificate **)h->certs, h->cert_count); h->certs = NULL; h->cert_count = 0; } return 0; } const char *get_slot_tokenlabel(pkcs11_handle_t *h) { if (!h->slot) { return NULL; } return PK11_GetTokenName(h->slot); } cert_object_t **get_certificate_list(pkcs11_handle_t *h, int *count) { CERTCertList * certList; CERTCertListNode *node; cert_object_t **certs; int certCount = 0; int certIndex = 0; SECStatus rv; if (!h->slot) { return NULL; } if (h->certs) { *count = h->cert_count; return h->certs; } certList = PK11_ListCertsInSlot(h->slot); if (!certList) { DBG1("Couldn't get Certs from token: %s", SECU_Strerror(PR_GetError())); return NULL; } /* only want signing certs */ rv = CERT_FilterCertListByUsage(certList, certUsageSSLClient, PR_FALSE); if (rv != SECSuccess) { CERT_DestroyCertList(certList); DBG1("Couldn't filter out email certs: %s", SECU_Strerror(PR_GetError())); return NULL; } /* only user certs have keys */ rv = CERT_FilterCertListForUserCerts(certList); if (rv != SECSuccess) { CERT_DestroyCertList(certList); DBG1("Couldn't filter out user certs: %s", SECU_Strerror(PR_GetError())); return NULL; } /* convert the link list from NSS to the array used by pam_pkcs11 */ for (node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node,certList); node = CERT_LIST_NEXT(node)) { if (node->cert) { DBG3("cert %d: found (%s), \"%s\"", certCount, node->cert->nickname, node->cert->subjectName); certCount++; } } if (certCount == 0) { CERT_DestroyCertList(certList); DBG("no certs found found"); return NULL; } certs = malloc(sizeof(cert_object_t *)*certCount); if (certs == NULL) { return NULL; } for (node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node,certList); node = CERT_LIST_NEXT(node)) { if (node->cert) { certs[certIndex++] = (cert_object_t *)CERT_DupCertificate(node->cert); if (certIndex == certCount) { break; } } } CERT_DestroyCertList(certList); h->certs = certs; h->cert_count = certIndex; *count = certIndex; return certs; } int get_private_key(pkcs11_handle_t *h, cert_object_t *cert) { /* all certs returned from NSS are user certs, and the private key * has already been identified */ return 0; } X509 *get_X509_certificate(cert_object_t *cert) { return (CERTCertificate *)cert; } int sign_value(pkcs11_handle_t *h, cert_object_t *cert, CK_BYTE *data, CK_ULONG length, CK_BYTE **signature, CK_ULONG *signature_length) { SECOidTag algtag; SECKEYPrivateKey *key; SECItem result; SECStatus rv; if (h->slot == NULL) { return -1; } /* get the key */ key = PK11_FindPrivateKeyFromCert(h->slot, (CERTCertificate *)cert, NULL); if (key == NULL) { DBG1("Couldn't Find key for Cert: %s", SECU_Strerror(PR_GetError())); return -1; } /* get the oid */ algtag = SEC_GetSignatureAlgorithmOidTag(key->keyType, SEC_OID_SHA1); /* sign the data */ rv = SEC_SignData(&result, data, length, key, algtag); SECKEY_DestroyPrivateKey(key); if (rv != SECSuccess) { DBG1("Signature failed: %s", SECU_Strerror(PR_GetError())); return -1; } *signature = (CK_BYTE *)result.data; *signature_length = result.len; return 0; } struct tuple_str { PRErrorCode errNum; const char * errString; }; typedef struct tuple_str tuple_str; #define ER2(a,b) {a, b}, #define ER3(a,b,c) {a, c}, #include "secerr.h" #include "sslerr.h" const tuple_str errStrings[] = { /* keep this list in ascending order of error numbers */ #include "SSLerrs.h" #include "SECerrs.h" #include "NSPRerrs.h" }; const PRInt32 numStrings = sizeof(errStrings) / sizeof(tuple_str); /* Returns a UTF-8 encoded constant error string for "errNum". * Returns NULL of errNum is unknown. */ const char * SECU_Strerror(PRErrorCode errNum) { PRInt32 low = 0; PRInt32 high = numStrings - 1; PRInt32 i; PRErrorCode num; static int initDone; /* make sure table is in ascending order. * binary search depends on it. */ if (!initDone) { PRErrorCode lastNum = ((PRInt32)0x80000000); for (i = low; i <= high; ++i) { num = errStrings[i].errNum; if (num <= lastNum) { fprintf(stderr, "sequence error in error strings at item %d\n" "error %d (%s)\n" "should come after \n" "error %d (%s)\n", i, lastNum, errStrings[i-1].errString, num, errStrings[i].errString); } lastNum = num; } initDone = 1; } /* Do binary search of table. */ while (low + 1 < high) { i = (low + high) / 2; num = errStrings[i].errNum; if (errNum == num) return errStrings[i].errString; if (errNum < num) high = i; else low = i; } if (errNum == errStrings[low].errNum) return errStrings[low].errString; if (errNum == errStrings[high].errNum) return errStrings[high].errString; return NULL; } #else #include "cert_st.h" #include <openssl/x509.h> #include <openssl/err.h> #include "rsaref/pkcs11.h" struct cert_object_str { CK_KEY_TYPE key_type; CK_CERTIFICATE_TYPE type; CK_BYTE *id; CK_ULONG id_length; CK_OBJECT_HANDLE private_key; X509 *x509; }; typedef struct { CK_SLOT_ID id; CK_BBOOL token_present; CK_UTF8CHAR label[33]; /* token label */ CK_UTF8CHAR slotDescription[64]; } slot_t; struct pkcs11_handle_str { void *module_handle; CK_FUNCTION_LIST_PTR fl; int should_finalize; slot_t *slots; CK_ULONG slot_count; CK_SESSION_HANDLE session; cert_object_t **certs; int cert_count; int current_slot; }; int crypto_init(cert_policy *policy) { /* arg is ignored for OPENSSL */ (void)policy; OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); return 0; } int load_pkcs11_module(const char *module, pkcs11_handle_t **hp) { int rv; struct stat module_stat; CK_C_GetFunctionList C_GetFunctionList_ptr; pkcs11_handle_t *h; DBG1("PKCS #11 module = [%s]", module); /* reset pkcs #11 handle */ h = (pkcs11_handle_t *)calloc(sizeof(pkcs11_handle_t), 1); if (h == NULL) { set_error("pkcs11_handle_t malloc failed: %s", strerror(errno)); return -1; } /* check module permissions */ rv = stat(module, &module_stat); if (rv < 0) { set_error("stat() failed: %s", strerror(errno)); free(h); return -1; } DBG3("module permissions: uid = %d, gid = %d, mode = %o", module_stat.st_uid, module_stat.st_gid, module_stat.st_mode & 0777); if (module_stat.st_mode & S_IWGRP || module_stat.st_mode & S_IWOTH || module_stat.st_uid != 0) { set_error("the pkcs #11 module MUST be owned by root and MUST NOT " "be writable by the group or others"); free(h); return -1; } /* load module */ DBG1("loading module %s", module); h->module_handle = dlopen(module, RTLD_NOW); if (h->module_handle == NULL) { set_error("dlopen() failed: %s", dlerror()); free(h); return -1; } /* try to get the function list */ DBG("getting function list"); C_GetFunctionList_ptr = (CK_C_GetFunctionList)dlsym(h->module_handle, "C_GetFunctionList"); if (C_GetFunctionList_ptr == NULL) { set_error("dlsym() failed: %s", dlerror()); free(h); return -1; } rv = C_GetFunctionList_ptr(&h->fl); if (rv != CKR_OK) { set_error("C_GetFunctionList() failed: %i", rv); free(h); return -1; } *hp = h; return 0; } static int refresh_slots(pkcs11_handle_t *h) { CK_ULONG i, slot_count; CK_SLOT_ID_PTR slots; CK_RV rv; int j; slot_count = -1; slots = NULL; rv = h->fl->C_GetSlotList(FALSE, NULL, &slot_count); if (rv != CKR_OK) { set_error("C_GetSlotList() failed: 0x%08lX", rv); return -1; } /* number of slots has changed */ if (slot_count != h->slot_count) { free(h->slots); h->slots = NULL; /* get a list of all slots */ rv = h->fl->C_GetSlotList(FALSE, NULL, &h->slot_count); if (rv != CKR_OK) { set_error("C_GetSlotList() failed: 0x%08lX", rv); return -1; } DBG1("number of slots (a): %ld", h->slot_count); if (h->slot_count == 0) { set_error("there are no slots available"); return 0; // That's not, strictly, an error. } slots = malloc(h->slot_count * sizeof(CK_SLOT_ID)); if (slots == NULL) { set_error("not enough free memory available"); return -1; } h->slots = malloc(h->slot_count * sizeof(slot_t)); if (h->slots == NULL) { free(slots); set_error("not enough free memory available"); return -1; } memset(h->slots, 0, h->slot_count * sizeof(slot_t)); rv = h->fl->C_GetSlotList(FALSE, slots, &h->slot_count); if (rv != CKR_OK) { free(slots); set_error("C_GetSlotList() failed: 0x%08lX", rv); return -1; } DBG1("number of slots (b): %ld", h->slot_count); /* show some information about the slots/tokens and setup slot info */ for (i = 0; i < h->slot_count; i++) { h->slots[i].id = slots[i]; } free(slots); } for (i = 0; i < h->slot_count; i++) { CK_SLOT_INFO sinfo; CK_TOKEN_INFO tinfo; DBG1("slot %ld:", i + 1); rv = h->fl->C_GetSlotInfo(h->slots[i].id, &sinfo); if (rv != CKR_OK) { set_error("C_GetSlotInfo() failed: 0x%08lX", rv); return -1; } (void) memcpy(h->slots[i].slotDescription, sinfo.slotDescription, sizeof(h->slots[i].slotDescription)); DBG1("- description: %.64s", sinfo.slotDescription); DBG1("- manufacturer: %.32s", sinfo.manufacturerID); DBG1("- flags: %04lx", sinfo.flags); if (sinfo.flags & CKF_TOKEN_PRESENT) { DBG("- token:"); rv = h->fl->C_GetTokenInfo(h->slots[i].id, &tinfo); if (rv != CKR_OK) { set_error("C_GetTokenInfo() failed: 0x%08lX", rv); return -1; } DBG1(" - label: %.32s", tinfo.label); DBG1(" - manufacturer: %.32s", tinfo.manufacturerID); DBG1(" - model: %.16s", tinfo.model); DBG1(" - serial: %.16s", tinfo.serialNumber); DBG1(" - flags: %04lx", tinfo.flags); h->slots[i].token_present = TRUE; memcpy(h->slots[i].label, tinfo.label, 32); for (j = 31; h->slots[i].label[j] == ' '; j--) h->slots[i].label[j] = 0; } } return 0; } int init_pkcs11_module(pkcs11_handle_t *h,int flag) { int rv; /* CK_SLOT_ID_PTR slots; */ CK_INFO info; /* Set up arguments to allow native threads According with pkcs#11v2.20, must set all pointers to null and flags CKF_OS_LOCKING_OK */ CK_C_INITIALIZE_ARGS initArgs = { .CreateMutex = NULL, .DestroyMutex = NULL, .LockMutex = NULL, .UnlockMutex = NULL, .flags = CKF_OS_LOCKING_OK, .pReserved = NULL }; /* initialise the module */ if (flag) rv = h->fl->C_Initialize((CK_VOID_PTR) &initArgs); else rv = h->fl->C_Initialize(NULL); if (rv == CKR_OK) h->should_finalize = 1; else if (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED) { set_error("C_Initialize() failed: %i", rv); return -1; } rv = h->fl->C_GetInfo(&info); if (rv != CKR_OK) { set_error("C_GetInfo() failed: %i", rv); return -1; } /* show some information about the module */ DBG("module information:"); DBG2("- version: %hhd.%hhd", info.cryptokiVersion.major, info.cryptokiVersion.minor); DBG1("- manufacturer: %.32s", info.manufacturerID); DBG1("- flags: %04lx", info.flags); DBG1("- library description: %.32s", info.libraryDescription); DBG2("- library version: %hhd.%hhd", info.libraryVersion.major, info.libraryVersion.minor); /* * As per PKCS#11 v2.2 we can call C_GetSlotList multiple times to check for * added/removed slots */ h->slot_count = -1; h->slots = NULL; return refresh_slots(h); } void release_pkcs11_module(pkcs11_handle_t *h) { /* finalise pkcs #11 module */ if (h->fl != NULL) if (h->should_finalize) h->fl->C_Finalize(NULL); /* unload the module */ if (h->module_handle != NULL) dlclose(h->module_handle); /* release all allocated memory */ if (h->slots != NULL) free(h->slots); cleanse(h, sizeof(pkcs11_handle_t)); free(h); } int find_slot_by_number(pkcs11_handle_t *h, unsigned int slot_num, unsigned int *slot) { /* zero means find the best slot */ if (slot_num == 0) { for (slot_num = 0; slot_num < h->slot_count && !h->slots[slot_num].token_present; slot_num++); } else { /* otherwise it's an index into the slot table (it is *NOT* the slot * id!).... */ slot_num--; } if ((slot_num >= h->slot_count) || (!h->slots[slot_num].token_present)) { return -1; } *slot = slot_num; return 0; } int find_slot_by_number_and_label(pkcs11_handle_t *h, int wanted_slot_id, const char *wanted_token_label, unsigned int *slot_num) { unsigned int slot_index; int rv; const char *token_label = NULL; /* we want a specific slot id, or we don't care about the label */ if ((wanted_token_label == NULL) || (wanted_slot_id != 0)) { rv = find_slot_by_number(h, wanted_slot_id, slot_num); /* if we don't care about the label, or we failed, we're done */ if ((wanted_token_label == NULL) || (rv != 0)) { return rv; } /* verify it's the label we want */ token_label = h->slots[*slot_num].label; if ((token_label != NULL) && (strcmp (wanted_token_label, token_label) == 0)) { return 0; } return -1; } /* look up the slot by it's label from the list */ for (slot_index = 0; slot_index < h->slot_count; slot_index++) { if (h->slots[slot_index].token_present) { token_label = h->slots[slot_index].label; if ((token_label != NULL) && (strcmp (wanted_token_label, token_label) == 0)) { *slot_num = slot_index; return 0; } } } return -1; } /* * This function will search the slot list to find a slot based on the slot * label. If the wanted_slot_label is "none", then we will return the first * slot with the token presented. * * This function return 0 if it found a matching slot; otherwise, it returns * -1. */ int find_slot_by_slotlabel(pkcs11_handle_t *h, const char *wanted_slot_label, unsigned int *slot_num) { unsigned long idx; size_t len; if (slot_num == NULL || wanted_slot_label == NULL || strlen(wanted_slot_label) == 0) return (-1); if (strcmp(wanted_slot_label, "none") == 0) { for (idx = 0; idx < h->slot_count; idx++) { if (h->slots[idx].token_present) { *slot_num = idx; return (0); } } } else { /* Look up the slot by it's slotDescription */ len = strlen(wanted_slot_label); for (idx = 0; idx < h->slot_count; idx++) { if (h->slots[idx].token_present && memcmp_pad_max(h->slots[idx].slotDescription, 64, (void *)wanted_slot_label, len, len) == 0) { *slot_num = idx; return (0); } } } return (-1); } int find_slot_by_slotlabel_and_tokenlabel(pkcs11_handle_t *h, const char *wanted_slot_label, const char *wanted_token_label, unsigned int *slot_num) { unsigned long i; int rv; if (slot_num == NULL) return (-1); if (wanted_token_label == NULL) { rv = find_slot_by_slotlabel(h, wanted_slot_label, slot_num); return (rv); } /* wanted_token_label != NULL */ if (strcmp(wanted_slot_label, "none") == 0) { for (i= 0; i < h->slot_count; i++) { if (h->slots[i].token_present && strcmp(wanted_token_label, (char *)h->slots[i].label) == 0) { *slot_num = i; return (0); } } return (-1); } else { for (i = 0; i < h->slot_count; i++) { if (h->slots[i].token_present) { const char *slot_label = h->slots[i].slotDescription; const char *token_label = h->slots[i].label; if ((memcmp_pad_max((void *)slot_label, strlen(slot_label), (void *)wanted_slot_label, strlen(wanted_slot_label), strlen(wanted_slot_label)) == 0) && (memcmp_pad_max((void *)token_label, strlen(token_label), (void *)wanted_token_label, strlen(wanted_token_label), 33) == 0)) { *slot_num = i; return (0); } } } return (-1); } } int wait_for_token_by_slotlabel(pkcs11_handle_t *h, const char *wanted_slot_label, const char *wanted_token_label, unsigned int *slot_num) { int rv; do { /* see if the card we're looking for is inserted */ rv = find_slot_by_slotlabel_and_tokenlabel (h, wanted_slot_label, wanted_token_label, slot_num); if (rv != 0) { /* could call C_WaitForSlotEvent, for now just poll */ sleep(10); refresh_slots(h); continue; } } while (rv != 0); return rv; } int wait_for_token(pkcs11_handle_t *h, int wanted_slot_id, const char *wanted_token_label, unsigned int *slot_num) { int rv; do { /* see if the card we're looking for is inserted */ rv = find_slot_by_number_and_label (h, wanted_slot_id, wanted_token_label, slot_num); if (rv != 0) { /* could call C_WaitForSlotEvent, for now just poll */ sleep(10); refresh_slots(h); continue; } } while (rv != 0); return rv; } int open_pkcs11_session(pkcs11_handle_t *h, unsigned int slot) { int rv; DBG1("opening a new PKCS #11 session for slot %d", slot + 1); if (slot >= h->slot_count) { set_error("invalid slot number %d", slot); return -1; } /* open a readonly user-session */ rv = h->fl->C_OpenSession(h->slots[slot].id, CKF_SERIAL_SESSION, NULL, NULL, &h->session); if (rv != CKR_OK) { set_error("C_OpenSession() failed: %i", rv); return -1; } h->current_slot = slot; return 0; } int pkcs11_login(pkcs11_handle_t *h, char *password) { int rv; DBG("login as user CKU_USER"); if (password) rv = h->fl->C_Login(h->session, CKU_USER, (unsigned char*)password, strlen(password)); else rv = h->fl->C_Login(h->session, CKU_USER, NULL, 0); if ((rv != CKR_OK) && (rv != CKR_USER_ALREADY_LOGGED_IN)) { set_error("C_Login() failed: %i", rv); return -1; } return 0; } int get_slot_login_required(pkcs11_handle_t *h) { int rv; CK_TOKEN_INFO tinfo; rv = h->fl->C_GetTokenInfo(h->slots[h->current_slot].id, &tinfo); if (rv != CKR_OK) { set_error("C_GetTokenInfo() failed: %i", rv); return -1; } return tinfo.flags & CKF_LOGIN_REQUIRED; } int get_slot_protected_authentication_path(pkcs11_handle_t *h) { int rv; CK_TOKEN_INFO tinfo; rv = h->fl->C_GetTokenInfo(h->slots[h->current_slot].id, &tinfo); if (rv != CKR_OK) { set_error("C_GetTokenInfo() failed: %i", rv); return -1; } return tinfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH; } static void free_certs(cert_object_t **certs, int cert_count) { int i; for (i = 0; i < cert_count; i++) { if (!certs[i]) { continue; } if (certs[i]->x509 != NULL) X509_free(certs[i]->x509); if (certs[i]->id != NULL) free(certs[i]->id); free(certs[i]); } free(certs); } int close_pkcs11_session(pkcs11_handle_t *h) { int rv; /* close user-session */ DBG("logout user"); rv = h->fl->C_Logout(h->session); if (rv != CKR_OK && rv != CKR_USER_NOT_LOGGED_IN && rv != CKR_FUNCTION_NOT_SUPPORTED) { set_error("C_Logout() failed: %i", rv); return -1; } DBG("closing the PKCS #11 session"); rv = h->fl->C_CloseSession(h->session); if (rv != CKR_OK && rv != CKR_FUNCTION_NOT_SUPPORTED) { set_error("C_CloseSession() failed: %i", rv); return -1; } DBG("releasing keys and certificates"); if (h->certs != NULL) { free_certs(h->certs, h->cert_count); h->certs = NULL; h->cert_count = 0; } return 0; } /* get a list of certificates */ cert_object_t **get_certificate_list(pkcs11_handle_t *h, int *ncerts) { CK_BYTE *id_value; CK_BYTE *cert_value; CK_OBJECT_HANDLE object; CK_ULONG object_count; X509 *x509; cert_object_t **certs = NULL; int rv; CK_OBJECT_CLASS cert_class = CKO_CERTIFICATE; CK_CERTIFICATE_TYPE cert_type = CKC_X_509; CK_ATTRIBUTE cert_template[] = { {CKA_CLASS, &cert_class, sizeof(CK_OBJECT_CLASS)} , {CKA_CERTIFICATE_TYPE, &cert_type, sizeof(CK_CERTIFICATE_TYPE)} , {CKA_ID, NULL, 0} , {CKA_VALUE, NULL, 0} }; if (h->certs) { *ncerts = h->cert_count; return h->certs; } rv = h->fl->C_FindObjectsInit(h->session, cert_template, 2); if (rv != CKR_OK) { set_error("C_FindObjectsInit() failed: %i", rv); return NULL; } while(1) { /* look for certificates */ rv = h->fl->C_FindObjects(h->session, &object, 1, &object_count); if (rv != CKR_OK) { set_error("C_FindObjects() failed: %i", rv); goto getlist_error; } if (object_count == 0) break; /* no more certs */ /* Cert found, read */ /* pass 1: get cert id */ /* retrieve cert object id length */ cert_template[2].pValue = NULL; cert_template[2].ulValueLen = 0; rv = h->fl->C_GetAttributeValue(h->session, object, cert_template, 3); if (rv != CKR_OK) { set_error("CertID length: C_GetAttributeValue() failed: %i", rv); goto getlist_error; } /* allocate enough space */ id_value = malloc(cert_template[2].ulValueLen); if (id_value == NULL) { set_error("CertID malloc(%ul): not enough free memory available", cert_template[2].ulValueLen); goto getlist_error; } /* read cert id into allocated space */ cert_template[2].pValue = id_value; rv = h->fl->C_GetAttributeValue(h->session, object, cert_template, 3); if (rv != CKR_OK) { free(id_value); set_error("CertID value: C_GetAttributeValue() failed: %i", rv); goto getlist_error; } /* pass 2: get certificate */ /* retrieve cert length */ cert_template[3].pValue = NULL; rv = h->fl->C_GetAttributeValue(h->session, object, cert_template, 4); if (rv != CKR_OK) { set_error("Cert Length: C_GetAttributeValue() failed: %i", rv); goto getlist_error; } /* allocate enough space */ cert_value = malloc(cert_template[3].ulValueLen); if (cert_value == NULL) { set_error("Cert Length malloc(%ul): not enough free memory available", cert_template[3].ulValueLen); goto getlist_error; } /* read certificate into allocated space */ cert_template[3].pValue = cert_value; rv = h->fl->C_GetAttributeValue(h->session, object, cert_template, 4); if (rv != CKR_OK) { free(cert_value); set_error("Cert Value: C_GetAttributeValue() failed: %i", rv); goto getlist_error; } /* Pass 3: store certificate */ /* convert to X509 data structure */ x509 = d2i_X509(NULL, (const unsigned char **)&cert_template[3].pValue, cert_template[3].ulValueLen); if (x509 == NULL) { free(id_value); free(cert_value); set_error("d2i_x509() failed: %s", ERR_error_string(ERR_get_error(), NULL)); goto getlist_error; } /* finally add certificate to chain */ certs= realloc(h->certs,(h->cert_count+1) * sizeof(cert_object_t *)); if (!certs) { free(id_value); X509_free(x509); set_error("realloc() not space to re-size cert table"); goto getlist_error; } h->certs=certs; DBG1("Saving Certificate #%d:", h->cert_count + 1); certs[h->cert_count] = NULL; DBG1("- type: %02lx", cert_type); DBG1("- id: %02x", id_value[0]); h->certs[h->cert_count] = (cert_object_t *)calloc(sizeof(cert_object_t),1); if (h->certs[h->cert_count] == NULL) { free(id_value); X509_free(x509); set_error("malloc() not space to allocate cert object"); goto getlist_error; } h->certs[h->cert_count]->type = cert_type; h->certs[h->cert_count]->id = id_value; h->certs[h->cert_count]->id_length = cert_template[2].ulValueLen; h->certs[h->cert_count]->x509 = x509; h->certs[h->cert_count]->private_key = CK_INVALID_HANDLE; h->certs[h->cert_count]->key_type = 0; ++h->cert_count; } /* end of while(1) */ /* release FindObject Sesion */ rv = h->fl->C_FindObjectsFinal(h->session); if (rv != CKR_OK) { set_error("C_FindObjectsFinal() failed: %i", rv); free_certs(certs, h->cert_count); certs = NULL; h->certs = NULL; h->cert_count = 0; return NULL; } *ncerts = h->cert_count; /* arriving here means that's all right */ DBG1("Found %d certificates in token",h->cert_count); return h->certs; /* some error arrived: clean as possible, and return fail */ getlist_error: rv = h->fl->C_FindObjectsFinal(h->session); if (rv != CKR_OK) { set_error("C_FindObjectsFinal() failed: %i", rv); } free_certs(h->certs, h->cert_count); h->certs = NULL; h->cert_count = 0; return NULL; } /* retrieve the private key associated with a given certificate */ int get_private_key(pkcs11_handle_t *h, cert_object_t *cert) { CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY; CK_BBOOL key_sign = CK_TRUE; CK_ATTRIBUTE key_template[] = { {CKA_CLASS, &key_class, sizeof(key_class)} , {CKA_SIGN, &key_sign, sizeof(key_sign)} , {CKA_ID, NULL, 0} }; CK_KEY_TYPE key_type; CK_ATTRIBUTE attr_template[] = { {CKA_KEY_TYPE, &key_type, sizeof(key_type)} }; CK_OBJECT_HANDLE object; CK_ULONG object_count; int rv; if (cert->private_key != CK_INVALID_HANDLE) { /* we've already found the private key for this certificate */ return 0; } /* search for a specific ID is any */ if (cert->id && cert->id_length) { key_template[2].pValue = cert->id; key_template[2].ulValueLen = cert->id_length; rv = h->fl->C_FindObjectsInit(h->session, key_template, 3); } else { rv = h->fl->C_FindObjectsInit(h->session, key_template, 2); } if (rv != CKR_OK) { set_error("C_FindObjectsInit() failed: %i", rv); return -1; } rv = h->fl->C_FindObjects(h->session, &object, 1, &object_count); if (rv != CKR_OK) { set_error("C_FindObjects() failed: %i", rv); goto get_privkey_failed; } if (object_count <= 0) { /* cert without prk: perhaps CA or CA-chain cert */ set_error("No private key found for cert: %i", rv); goto get_privkey_failed; } /* and finally release Find session */ rv = h->fl->C_FindObjectsFinal(h->session); if (rv != CKR_OK) { set_error("C_FindObjectsFinal() failed: %i", rv); return -1; } /* get private key type */ rv = h->fl->C_GetAttributeValue(h->session, object, attr_template, sizeof(attr_template) / sizeof(CK_ATTRIBUTE)); if (rv != CKR_OK) { set_error("C_GetAttributeValue() failed! %i", rv); return -1; } DBG1("private key type: 0x%08lX", key_type); cert->private_key = object; cert->key_type = key_type; return 0; get_privkey_failed: rv = h->fl->C_FindObjectsFinal(h->session); if (rv != CKR_OK) { set_error("C_FindObjectsFinal() failed: %i", rv); } return -1; } const char *get_slot_tokenlabel(pkcs11_handle_t *h) { return h->slots[h->current_slot].label; } X509 *get_X509_certificate(cert_object_t *cert) { return cert->x509; } #define MAX_SIGNATURE_LENGTH 65536 int sign_value(pkcs11_handle_t *h, cert_object_t *cert, CK_BYTE *data, CK_ULONG length, CK_BYTE **signature, CK_ULONG *signature_length) { int rv; int h_offset = 0; #ifdef USE_HASH_SHA1 CK_BYTE hash[15 + SHA_DIGEST_LENGTH] = "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14"; #else CK_BYTE hash[19 + SHA256_DIGEST_LENGTH] = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20"; #endif CK_MECHANISM mechanism = { 0, NULL, 0 }; if (get_private_key(h, cert) == -1) { set_error("Couldn't find private key for certificate"); return -1; } /* set mechanism */ switch (cert->key_type) { case CKK_RSA: mechanism.mechanism = CKM_RSA_PKCS; break; case CKK_ECDSA: mechanism.mechanism = CKM_ECDSA; #ifdef USE_HASH_SHA1 h_offset = 15; #else h_offset = 19; #endif break; default: set_error("unsupported private key type 0x%08lX", cert->key_type); return -1; } /* compute hash-value */ #ifdef USE_HASH_SHA1 DBG("hashing with SHA1"); SHA1(data, length, &hash[15]); DBG5("hash[%ld] = [...:%02x:%02x:%02x:...:%02x]", sizeof(hash), hash[15], hash[16], hash[17], hash[sizeof(hash) - 1]); #else SHA256(data, length, &hash[19]); DBG5("hash[%ld] = [...:%02x:%02x:%02x:...:%02x]", sizeof(hash), hash[19], hash[20], hash[21], hash[sizeof(hash) - 1]); #endif /* sign the token */ rv = h->fl->C_SignInit(h->session, &mechanism, cert->private_key); if (rv != CKR_OK) { set_error("C_SignInit() failed: %i", rv); return -1; } *signature = NULL; *signature_length = 1024; while (*signature == NULL) { CK_ULONG current_signature_length = *signature_length; *signature = malloc(*signature_length); if (*signature == NULL) { set_error("not enough free memory available"); return -1; } rv = h->fl->C_Sign(h->session, hash + h_offset, sizeof(hash) - h_offset, *signature, signature_length); if (rv == CKR_BUFFER_TOO_SMALL) { /* increase signature length as long as it it to short */ free(*signature); *signature = NULL; if (current_signature_length >= *signature_length) { /* workaround for buggy PKCS#11 implementation: it didn't change or even lowered buffer size - forcing using larger (double size) buffer */ *signature_length = current_signature_length * 2; } DBG1("increased signature buffer-length to %ld", *signature_length); if (*signature_length > MAX_SIGNATURE_LENGTH) { set_error("signature too long"); return -1; } } else if (rv != CKR_OK) { free(*signature); *signature = NULL; set_error("C_Sign() failed: %i", rv); return -1; } } DBG5("signature[%ld] = [%02x:%02x:%02x:...:%02x]", *signature_length, (*signature)[0], (*signature)[1], (*signature)[2], (*signature)[*signature_length - 1]); return 0; } #endif /* HAVE_NSS */
OpenSC/pam_pkcs11
src/common/pkcs11_lib.c
C
lgpl-2.1
49,059
/* * DomUI Java User Interface library * Copyright (c) 2010 by Frits Jalvingh, Itris B.V. * * This library 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. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * See the "sponsors" file for a list of supporters. * * The latest version of DomUI and related code, support and documentation * can be found at http://www.domui.org/ * The contact for the project is Frits Jalvingh <jal@etc.to>. */ package to.etc.domui.util.images; import org.eclipse.jdt.annotation.NonNull; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; /** * This is a reference to some individual original image as returned by * IImageRetriever. It is a must-close resource. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on Nov 30, 2009 */ public interface IImageReference extends Closeable { @Override void close() throws IOException; /** * If this retriever accesses resources that can change after use this must return some usable * indication of the version, usually a "last date changed" timestamp. This value should remain * unchanged over invocations if the object accessed has not changed. It should return -1 if * the source object has been deleted; it should return 0 if the timestamp does not matter. * This gets called multiple times; it should be fast. * * @return */ long getVersionLong() throws Exception; /** * This must return the image's actual mime type. * @return * @throws Exception */ @NonNull String getMimeType() throws Exception; /** * Returns the datastream containing this image. This may be called only ONCE for an image and must * be closed after use. * @return * @throws Exception */ InputStream getInputStream() throws Exception; }
fjalvingh/domui
to.etc.domui/src/main/java/to/etc/domui/util/images/IImageReference.java
Java
lgpl-2.1
2,425
// // ICommandUserInterface.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2010 Novell, Inc (http://www.novell.com) // // 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. using System; namespace MonoDevelop.Components.Commands { public interface ICommandBar { void Update (object activeTarget); void SetEnabled (bool enabled); } }
mono/linux-packaging-monodevelop
src/core/MonoDevelop.Ide/MonoDevelop.Components.Commands/ICommandBar.cs
C#
lgpl-2.1
1,405
/** * A library to interact with Virtual Worlds such as OpenSim * Copyright (C) 2012 Jitendra Chauhan, Email: jitendra.chauhan@gmail.com * * This library 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. * * 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 */ package com.ngt.jopenmetaverse.shared.sim.events.friends; import java.math.BigInteger; import com.ngt.jopenmetaverse.shared.sim.events.EventArgs; import com.ngt.jopenmetaverse.shared.types.UUID; import com.ngt.jopenmetaverse.shared.types.Vector3; /// <summary> /// Data sent in response to a <see cref="FindFriend"/> request which contains the information to allow us to map the friends location /// </summary> public class FriendFoundReplyEventArgs extends EventArgs { private UUID m_AgentID; //ulong private BigInteger m_RegionHandle; private Vector3 m_Location; /// <summary>Get the ID of the agent we have received location information for</summary> public UUID getAgentID() {return m_AgentID;} /// <summary>Get the region handle where our mapped friend is located</summary> public BigInteger getRegionHandle() {return m_RegionHandle;} /// <summary>Get the simulator local position where our friend is located</summary> public Vector3 getLocation() {return m_Location;} /// <summary> /// Construct a new instance of the FriendFoundReplyEventArgs class /// </summary> /// <param name="agentID">The ID of the agent we have requested location information for</param> /// <param name="regionHandle">The region handle where our friend is located</param> /// <param name="location">The simulator local position our friend is located</param> public FriendFoundReplyEventArgs(UUID agentID, BigInteger regionHandle, Vector3 location) { this.m_AgentID = agentID; this.m_RegionHandle = regionHandle; this.m_Location = location; } }
nybbs2003/jopenmetaverse
src/main/java/com/ngt/jopenmetaverse/shared/sim/events/friends/FriendFoundReplyEventArgs.java
Java
lgpl-2.1
2,621
#pragma once #include "fetchers.hh" namespace nix::fetchers { struct Cache { virtual ~Cache() { } virtual void add( ref<Store> store, const Attrs & inAttrs, const Attrs & infoAttrs, const StorePath & storePath, bool locked) = 0; virtual std::optional<std::pair<Attrs, StorePath>> lookup( ref<Store> store, const Attrs & inAttrs) = 0; struct Result { bool expired = false; Attrs infoAttrs; StorePath storePath; }; virtual std::optional<Result> lookupExpired( ref<Store> store, const Attrs & inAttrs) = 0; }; ref<Cache> getCache(); }
NixOS/nix
src/libfetchers/cache.hh
C++
lgpl-2.1
665
JSlider ======= LGPL tl;dr Use for free, in comercial, and open source project alike. Modifications of JSlider itself must be licesed under LGPL of GPL(Open Source). Creation of new effects for JSlider(Documentation below) does *not* count as a modification to JSlider itself, and can therfor be licensed as you wish. A slider library that allows for simple creation of slider, and endless customization. To get started, go to "releases" and download the latest non-prerelease version, and include it. ### Usage Usage is fairly simple. To create the most simple slider, you must have a div, with a UL in it, which has LI elements in it. These LI elements are your slides. ```html <div id="your-slider-id"> <ul id="slides"> <li class="slide">slide1</div> <li class="slide">slide2</div> <li class="slide">slide3</div> </ul> </div> ``` The "class" and "id" attribtues are *not* required, although you do need a way to select the DIV later. After you have those elements, you need to write some javascript. Go inside a JavaScrpt file, or create a *script* tag and write. ```js var slider = new JSlider("div#your-slider-id"); //You can use any selector here slider.start(); //This starts the automated slider ``` If you have done everything correctly you should be able to sit back and whatch them slides go. You may also set some options for JSlider. This is done by passing an Object containing key=>value pairs to the JSlider constructor. For example, to set how long the slider should stay at each slide, do: ```js var slider = new JSlider("div#your-slider-id", { "delay" : 5000 //Set the delay to 5000ms }); //You can use any selector here slider.start(); //This starts the automated slider ``` The code above will make JSlider wait for 5 seconds before it slides to the next slide. ###Effects You can choose the effect you would like to use to slide between the slides. You can allso implement you own, which you can read about below. The build in effect can be accesed by typeing jSlider.Effect.<em>effect name</em> The built in effect are, as of the current version, as follows. <ul> <li><b>CAROUSEL</b>The classic slider effect. Slides between the slides, and when it comes to the last slide, it slide naturally to the first one</li> <li><b>SLIDE</b> Simple slide animation, but will not carousel. Rather, it will stop on the last one. Mainly for use with a Slide thats just meant for touch scroll.</li> <li><b>REWIND_SLIDE</b> Same as slide, only with the rewind effect when it the slides "come to an end" </li> <li><b>FADE</b> Fades between the slides. Will rewind. </li> </ul> To implement you own effect, create an object ```js { /** * This function will * be ran when the slide loads, * and is to initialize stuff you need. * The fade effect for instance makes all slides * position absolute, so to be able to fade between the slides. */ init: function(){} goto: function(){} } ``` ###Options Currently avaible options are(passed in as an object as the second parameter to the JSlider constructor): <ul> <li><b>(number)delay</b> : (ms) Set how long JSlider should wait before it slide.</li> <li><b>(number)duration</b> : (ms) Sets the animation duration</li> <li><b>(jSlider.Effect)effect</b> : What effect should be use on transitioning. Default is jSlider.Effect.SLIDE</li> <li> <b>button</b> <ul> <li><b>(jQuery|HTMLELement|selector)next</b> : Register a button to use as next button</li> <li><b>(jQuery|HTMLELement|selector)prev</b> : Register a button to use as prev button</li> <li><b>(jQuery|HTMLELement|selector)start</b> : Register a button to use as start button</li> <li><b>(jQuery|HTMLELement|selector)stop</b> : Register a button to use as stop button</li> </ul> </li> <li> <b>on</b> <ul> <li><em>eventName<em> => <em>A function that will be called on said event, with a jQuery object of the current slide as the first(and only) parameter</li> </ul> </li> </ul> ###Events <ul> <li><b>ready</b> Will be triggered when the slider is ready. This is after the JSlider has done it's style changes and the effect has been initilized. Do not rely on heigh/width of the slides(&lt;li>) before this event has been triggered.</li> </ul> ###Bining event **You may bind event one of three ways.** ```js var slider = new JSlider("div#your-slider-id", { "on" : { "eventName" : function(currentSlide) {} //FIRST WAY } }); slider.on('eventName', function(currentSlider) {}); //SECOND WAY $("div#your-slider-id").on('jslider-eventName', function(currentSlider) {}); //THIRD WAY ``` As you may notice, if you want to use jQuery when binding the event, you must prefix the event name with "jslider-". So instead of "start" it will be "jslider-start". ###Functions There is also some avaible function in the JSlider object. <ul> <li><b>(void)start()</b> : Start the slider </li> <li><b>(void)stop()</b> : Stop the slider </li> <li><b>(void)next()</b> : Go to the next slide </li> <li><b>(void)prev()</b> : Go to the previous slide </li> <li><b>(void)on("eventName", function(currentSlide){})</b> : Bind an event </li> </ul> ###Contributing Make a fork and send pull requests. <b>Dependecies</b> <ul> <li>jQuery</li> </ul> ###Versioning JSlider uses [semantic versioning](http://www.semver.org). Copyright &copy; 2014 Sigurd Berg Svela
sigurdsvela/JSlider
README.md
Markdown
lgpl-2.1
5,345
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qkbddriverplugin_qws.cpp --> <title>Qt 4.7: List of All Members for QKbdDriverPlugin</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> </head> <body class="offline narrow creator"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.nokia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://developer.qt.nokia.com/">DEV</a></li> <li class="nav-topright-labs"><a href="http://labs.qt.nokia.com/blogs/">LABS</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://doc.qt.nokia.com/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.nokia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.7</a></span></li> <li class="shortCut-topleft-active"><a href="http://doc.qt.nokia.com">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu sf-js-enabled sf-shadow" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul id="topmenuLook"> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="licensing.html">Licenses and Credits</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul id="topmenuTopic"> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UI's &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li> <li><a href="platform-specific.html">Platform-specific info</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul id="topmenuexample"> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UI's &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li> <li class="defaultLink"><a href="platform-specific.html">Platform-specific info</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Bread crumbs goes here --> <li><a href="modules.html">Modules</a></li> <li><a href="qtgui.html">QtGui</a></li> <li>QKbdDriverPlugin</li> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content"> <h1 class="title">List of All Members for QKbdDriverPlugin</h1> <p>This is the complete list of members for <a href="qkbddriverplugin.html">QKbdDriverPlugin</a>, including inherited members.</p> <table class="propsummary"> <tr><td class="topAlign"><ul> <li class="fn"><b><a href="qkbddriverplugin.html#QKbdDriverPlugin">QKbdDriverPlugin</a></b> ( QObject * )</li> <li class="fn"><b><a href="qkbddriverplugin.html#dtor.QKbdDriverPlugin">~QKbdDriverPlugin</a></b> ()</li> <li class="fn"><b><a href="qobject.html#blockSignals">blockSignals</a></b> ( bool ) : bool</li> <li class="fn"><b><a href="qobject.html#childEvent">childEvent</a></b> ( QChildEvent * )</li> <li class="fn"><b><a href="qobject.html#children">children</a></b> () const : const QObjectList &amp;</li> <li class="fn"><b><a href="qobject.html#connect">connect</a></b> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType ) : bool</li> <li class="fn"><b><a href="qobject.html#connect-2">connect</a></b> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const : bool</li> <li class="fn"><b><a href="qobject.html#connectNotify">connectNotify</a></b> ( const char * )</li> <li class="fn"><b><a href="qkbddriverplugin.html#create">create</a></b> ( const QString &amp;, const QString &amp; ) : QWSKeyboardHandler *</li> <li class="fn"><b><a href="qobject.html#customEvent">customEvent</a></b> ( QEvent * )</li> <li class="fn"><b><a href="qobject.html#d_ptr-var">d_ptr</a></b> : QScopedPointer&lt;QObjectData&gt;</li> <li class="fn"><b><a href="qobject.html#deleteLater">deleteLater</a></b> ()</li> <li class="fn"><b><a href="qobject.html#destroyed">destroyed</a></b> ( QObject * )</li> <li class="fn"><b><a href="qobject.html#disconnect">disconnect</a></b> ( const QObject *, const char *, const QObject *, const char * ) : bool</li> <li class="fn"><b><a href="qobject.html#disconnect-2">disconnect</a></b> ( const char *, const QObject *, const char * ) : bool</li> <li class="fn"><b><a href="qobject.html#disconnect-3">disconnect</a></b> ( const QObject *, const char * ) : bool</li> <li class="fn"><b><a href="qobject.html#disconnectNotify">disconnectNotify</a></b> ( const char * )</li> <li class="fn"><b><a href="qobject.html#dumpObjectInfo">dumpObjectInfo</a></b> ()</li> <li class="fn"><b><a href="qobject.html#dumpObjectTree">dumpObjectTree</a></b> ()</li> <li class="fn"><b><a href="qobject.html#dynamicPropertyNames">dynamicPropertyNames</a></b> () const : QList&lt;QByteArray&gt;</li> <li class="fn"><b><a href="qobject.html#event">event</a></b> ( QEvent * ) : bool</li> <li class="fn"><b><a href="qobject.html#eventFilter">eventFilter</a></b> ( QObject *, QEvent * ) : bool</li> <li class="fn"><b><a href="qobject.html#findChild">findChild</a></b> ( const QString &amp; ) const : T</li> <li class="fn"><b><a href="qobject.html#findChildren">findChildren</a></b> ( const QString &amp; ) const : QList&lt;T&gt;</li> <li class="fn"><b><a href="qobject.html#findChildren-2">findChildren</a></b> ( const QRegExp &amp; ) const : QList&lt;T&gt;</li> </ul></td><td class="topAlign"><ul> <li class="fn"><b><a href="qobject.html#inherits">inherits</a></b> ( const char * ) const : bool</li> <li class="fn"><b><a href="qobject.html#installEventFilter">installEventFilter</a></b> ( QObject * )</li> <li class="fn"><b><a href="qobject.html#isWidgetType">isWidgetType</a></b> () const : bool</li> <li class="fn"><b><a href="qkbddriverplugin.html#keys">keys</a></b> () const : QStringList</li> <li class="fn"><b><a href="qobject.html#killTimer">killTimer</a></b> ( int )</li> <li class="fn"><b><a href="qobject.html#metaObject">metaObject</a></b> () const : const QMetaObject *</li> <li class="fn"><b><a href="qobject.html#moveToThread">moveToThread</a></b> ( QThread * )</li> <li class="fn"><b><a href="qobject.html#objectName-prop">objectName</a></b> () const : QString</li> <li class="fn"><b><a href="qobject.html#parent">parent</a></b> () const : QObject *</li> <li class="fn"><b><a href="qobject.html#property">property</a></b> ( const char * ) const : QVariant</li> <li class="fn"><b><a href="qobject.html#receivers">receivers</a></b> ( const char * ) const : int</li> <li class="fn"><b><a href="qobject.html#removeEventFilter">removeEventFilter</a></b> ( QObject * )</li> <li class="fn"><b><a href="qobject.html#sender">sender</a></b> () const : QObject *</li> <li class="fn"><b><a href="qobject.html#objectName-prop">setObjectName</a></b> ( const QString &amp; )</li> <li class="fn"><b><a href="qobject.html#setParent">setParent</a></b> ( QObject * )</li> <li class="fn"><b><a href="qobject.html#setProperty">setProperty</a></b> ( const char *, const QVariant &amp; ) : bool</li> <li class="fn"><b><a href="qobject.html#signalsBlocked">signalsBlocked</a></b> () const : bool</li> <li class="fn"><b><a href="qobject.html#startTimer">startTimer</a></b> ( int ) : int</li> <li class="fn"><b><a href="qobject.html#staticMetaObject-var">staticMetaObject</a></b> : const QMetaObject</li> <li class="fn"><b><a href="qobject.html#staticQtMetaObject-var">staticQtMetaObject</a></b> : const QMetaObject</li> <li class="fn"><b><a href="qobject.html#thread">thread</a></b> () const : QThread *</li> <li class="fn"><b><a href="qobject.html#timerEvent">timerEvent</a></b> ( QTimerEvent * )</li> <li class="fn"><b><a href="qobject.html#tr">tr</a></b> ( const char *, const char *, int ) : QString</li> <li class="fn"><b><a href="qobject.html#trUtf8">trUtf8</a></b> ( const char *, const char *, int ) : QString</li> </ul> </td></tr> </table> <div class="feedback t_button"> [+] Documentation Feedback</div> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2010 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> <div id="feedbackBox"> <div id="feedcloseX" class="feedclose t_button">X</div> <form id="feedform" action="http://doc.qt.nokia.com/docFeedbck/feedback.php" method="get"> <p id="noteHead">Thank you for giving your feedback.</p> <p class="note">Make sure it is related to this specific page. For more general bugs and requests, please use the <a href="http://bugreports.qt.nokia.com/secure/Dashboard.jspa">Qt Bug Tracker</a>.</p> <p><textarea id="feedbox" name="feedText" rows="5" cols="40"></textarea></p> <p><input id="feedsubmit" class="feedclose" type="submit" name="feedback" /></p> </form> </div> <div id="blurpage"> </div> </body> </html>
sunblithe/qt-everywhere-opensource-src-4.7.1
doc/html/qkbddriverplugin-members.html
HTML
lgpl-2.1
14,082
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef GMOBILE1D_H #define GMOBILE1D_H #include "Kernel.h" #include "GGroup.h" //Forward Declarations class GMobile1D; template<> InputParameters validParams<GMobile1D>(); class GMobile1D : public Kernel { public: GMobile1D(const InputParameters & parameters); protected: virtual Real computeQpResidual(); virtual Real computeQpJacobian(); virtual Real computeQpOffDiagJacobian(unsigned int jvar); int getGroupNumber(std::string); double getConcBySize(int); double getAbsorbCoef(int); private: int _number_v; int _number_i; int _max_mobile_v; int _max_mobile_i; const GGroup & _gc; std::vector<unsigned int> _no_v_vars; std::vector<const VariableValue *> _val_v_vars; std::vector<unsigned int> _no_i_vars; std::vector<const VariableValue *> _val_i_vars; std::vector<const VariableValue *> _val_i_auxvars; int _cur_size; int max_v,max_i; }; #endif
shortlab/geminio
include/kernels/GMobile1D.h
C
lgpl-2.1
1,802
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.projects.speakerid; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.util.Arrays; import java.util.Observable; import java.util.Observer; import javax.swing.JFrame; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.util.chart.Axis; import net.sf.jaer.util.chart.Category; import net.sf.jaer.util.chart.Series; import net.sf.jaer.util.chart.XYChart; import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent; import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent.Ear; import ch.unizh.ini.jaer.chip.cochlea.CochleaAMSEvent; import java.util.logging.Logger; import net.sf.jaer.DevelopmentStatus; /** * extended ISI Filter. now splits ISIs into 2 different streams, one for each ear. resulting in 2*nBins bins. * * original from Holger (some parts are from tobi's ISIhistogrammer) see: ISIFilter * * @author Philipp * */ @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class ISIFilterTwoEars extends EventFilter2D implements Observer { protected static final Logger log = Logger.getLogger("ISIFilterTwoEars"); private int nBins = getPrefs().getInt("nBins", 50); private int maxIsiUs = getPrefs().getInt("maxIsiUs", 10000); private int minIsiUs = getPrefs().getInt("minIsiUs", 0); private int neighborhoodRangeLower = getPrefs().getInt("neighborhoodRangeLower", 0); private int neighborhoodRangeUpper = getPrefs().getInt("neighborhoodRangeUpper", 0); private boolean useLeftEar = getPrefs().getBoolean("useLeftEar", true); private boolean useRightEar = getPrefs().getBoolean("useRightEar", true); private boolean sameChannelAndNeuron = getPrefs().getBoolean("sameChannelAndNeuron", true); private String useChannels = getPrefs().get("useChannels", "1-64"); private boolean[] useChannelsBool = new boolean[64]; private float[] leftBins = new float[nBins]; private int maxLeftBinIndex = 0; private float[] rightBins = new float[nBins]; private int maxRightBinIndex = 0; int nChans = 1; int ear; int[][][] lastTs = new int[64][4][2]; JFrame isiFrame = null; int nextDecayTimestamp = 0, lastDecayTimestamp = 0; private int tauDecayMs = getPrefs().getInt("tauDecayMs", 1000); public ISIFilterTwoEars(AEChip chip) { super(chip); chip.addObserver(this); setPropertyTooltip("Plot properties", "maxIsiUs", "maximim ISI in us, larger ISI's are discarded"); setPropertyTooltip("Plot properties", "minIsiUs", "minimum ISI in us, smaller ISI's are discarded"); setPropertyTooltip("Plot properties", "NBins", "number of histogram bins"); setPropertyTooltip("Plot properties", "tauDecayMs", "histogram bins are decayed to zero with this time constant in ms"); setPropertyTooltip("Plot properties", "logPlotEnabled", "enable to plot log histogram counts, disable for linear scale"); setPropertyTooltip("Include spikes from ...", "useChannels", "channels to use for the histogram seperated by ; (i.e. '1-5;10-15;20-25')"); setPropertyTooltip("Include spikes from ...", "useLeftEar", "Use the left ear"); setPropertyTooltip("Include spikes from ...", "useRightEar", "Use the right ear"); setPropertyTooltip("ISI to spikes in ...", "neighborhoodRangeLower", "The number of lower neighboring channels to use for ISIs"); setPropertyTooltip("ISI to spikes in ...", "neighborhoodRangeUpper", "The number of upper neighboring channels to use for ISIs"); setPropertyTooltip("ISI to spikes in ...", "sameChannelAndNeuron", "If ISIs should be computed to the last spike in the same neuron of the same channel"); parseUseChannel(); resetBins(); } @Override synchronized public EventPacket<? extends BasicEvent> filterPacket(EventPacket<? extends BasicEvent> in) { for (BasicEvent e : in) { try { BinauralCochleaEvent i = (BinauralCochleaEvent) e; if (i.getEar() == Ear.LEFT) { ear = 0; if (useLeftEar == false) { break; } } else { ear = 1; if (useRightEar == false) { break; } } CochleaAMSEvent camsevent = ((CochleaAMSEvent) e); int neuron = camsevent.getThreshold(); int ts = e.timestamp; int ch = e.x; if (!useChannelsBool[ch]) { continue; } int start = ch - this.neighborhoodRangeLower; if (start < 0) { start = 0; } for (int compareChan = start; compareChan <= ch + this.neighborhoodRangeUpper && compareChan < 64; compareChan++) { if (ch == compareChan) { if (this.sameChannelAndNeuron) { addIsi(ts - lastTs[ch][neuron][ear]); } } else { for (int compareNeuron = 1; compareNeuron < 4; compareNeuron++) { addIsi(ts - lastTs[ch][compareNeuron][ear]); } } } lastTs[ch][neuron][ear] = ts; decayHistogram(ts); } catch (Exception e1) { log.warning("In for-loop in filterPacket caught exception " + e1); e1.printStackTrace(); } } isiFrame.repaint(); return in; } synchronized public void resetBins() { if (leftBins.length != nBins) { leftBins = new float[nBins]; } Arrays.fill(leftBins, 0); maxLeftBinIndex = 0; if (rightBins.length != nBins) { rightBins = new float[nBins]; } Arrays.fill(rightBins, 0); maxRightBinIndex = 0; lastTs = new int[64][4][2]; if (activitySeriesLeft != null) { activitySeriesLeft.setCapacity(nBins); } if (activitySeriesRight != null) { activitySeriesRight.setCapacity(nBins); } if (isiFrame != null) { isiFrame.repaint(0); } } private void addIsi(int isi) { if (isi < minIsiUs) { return; } if (isi >= maxIsiUs) { return; } int bin = (((isi - minIsiUs) * nBins) / (maxIsiUs - minIsiUs)); if (ear == 0) { leftBins[bin]++; if (leftBins[bin] > leftBins[maxLeftBinIndex]) { maxLeftBinIndex = bin; } } else { rightBins[bin]++; if (rightBins[bin] > rightBins[maxRightBinIndex]) { maxRightBinIndex = bin; } } } public void doPrintBins() { for (float i : leftBins) { System.out.print(String.format("%.0f ", i)); } for (float i : rightBins) { System.out.print(String.format("%.0f ", i)); } System.out.println(""); } @Override public void resetFilter() { resetBins(); } @Override public void initFilter() { resetBins(); } public void update(Observable o, Object arg) { // THIS FUNCTION CAUSES A NULL POINTER EXCEPTION WHEN CHANGING THE HARDWARE, SO I COMMENTED IT OUT // -Peter // if (arg.equals(Chip2D.EVENT_SIZEX) || arg.equals(Chip2D.EVENT_SIZEY)) { // resetBins(); // } } /** * @return the nBins */ public int getNBins() { return nBins; } /** * @param nBins the nBins to set */ public void setNBins(int nBins) { int old = this.nBins; if (nBins < 1) { nBins = 1; } this.nBins = nBins; getPrefs().putInt("nBins", nBins); resetBins(); getSupport().firePropertyChange("nBins", old, this.nBins); } /** * @return the neighborhoodRangeLower */ public int getNeighborhoodRangeLower() { return neighborhoodRangeLower; } /** * @param neighborhoodRangeLower the neighborhoodRangeLower to set */ public void setNeighborhoodRangeLower(int neighborhoodRangeLower) { int oldneighborhoodRangeLower = this.neighborhoodRangeLower; this.neighborhoodRangeLower = neighborhoodRangeLower; getPrefs().putFloat("neighborhoodRangeLower", neighborhoodRangeLower); getSupport().firePropertyChange("neighborhoodRangeLower", oldneighborhoodRangeLower, this.neighborhoodRangeLower); } /** * @return the neighborhoodRangeUpper */ public int getNeighborhoodRangeUpper() { return neighborhoodRangeUpper; } /** * @param neighborhoodRangeUpper the neighborhoodRangeUpper to set */ public void setNeighborhoodRangeUpper(int neighborhoodRangeUpper) { int oldneighborhoodRangeUpper = this.neighborhoodRangeUpper; this.neighborhoodRangeUpper = neighborhoodRangeUpper; getPrefs().putFloat("neighborhoodRangeUpper", neighborhoodRangeUpper); getSupport().firePropertyChange("neighborhoodRangeUpper", oldneighborhoodRangeUpper, this.neighborhoodRangeUpper); } /** * @return the maxIsiUs */ public int getMaxIsiUs() { return maxIsiUs; } /** * @param maxIsiUs the maxIsiUs to set */ synchronized public void setMaxIsiUs(int maxIsiUs) { int old = this.maxIsiUs; if (maxIsiUs < minIsiUs) { maxIsiUs = minIsiUs; } this.maxIsiUs = maxIsiUs; getPrefs().putInt("maxIsiUs", maxIsiUs); resetBins(); if (binAxis != null) { binAxis.setUnit(String.format("%d,%d us", minIsiUs, maxIsiUs)); } if (isiFrame != null) { isiFrame.repaint(); } getSupport().firePropertyChange("maxIsiUs", old, maxIsiUs); } /** * @return the minIsiUs */ public int getMinIsiUs() { return minIsiUs; } /** * @param minIsiUs the minIsiUs to set */ public void setMinIsiUs(int minIsiUs) { int old = this.minIsiUs; if (minIsiUs > maxIsiUs) { minIsiUs = maxIsiUs; } this.minIsiUs = minIsiUs; getPrefs().putInt("minIsiUs", minIsiUs); resetBins(); if (binAxis != null) { binAxis.setUnit(String.format("%d,%d us", minIsiUs, maxIsiUs)); } if (isiFrame != null) { isiFrame.repaint(); } getSupport().firePropertyChange("minIsiUs", old, minIsiUs); } /** * @return the tauDecayMs */ public int getTauDecayMs() { return tauDecayMs; } /** * @param tauDecayMs the tauDecayMs to set */ public void setTauDecayMs(int tauDecayMs) { int oldtau = this.tauDecayMs; this.tauDecayMs = tauDecayMs; getPrefs().putFloat("tauDecayMs", tauDecayMs); getSupport().firePropertyChange("tauDecayMs", oldtau, this.tauDecayMs); } @Override public synchronized void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); setIsiDisplay(yes); } @Override public synchronized void cleanup() { super.cleanup(); setIsiDisplay(false); } public void decayHistogram(int timestamp) { if (timestamp > lastDecayTimestamp) { float decayconstant = (float) java.lang.Math.exp(-(float) (timestamp - lastDecayTimestamp) / (float) (tauDecayMs * 1000)); for (int i = 0; i < leftBins.length; i++) { leftBins[i] = leftBins[i] * decayconstant; } for (int i = 0; i < rightBins.length; i++) { rightBins[i] = rightBins[i] * decayconstant; } } lastDecayTimestamp = timestamp; } private Axis binAxis; private XYChart chart; public Series activitySeriesLeft; private Axis activityAxisLeft; private Category activityCategoryLeft; public Series activitySeriesRight; private Axis activityAxisRight; private Category activityCategoryRight; private boolean logPlotEnabled = getPrefs().getBoolean("logPlotEnabled", false); private void setIsiDisplay(boolean yes) { if (!yes) { if (isiFrame != null) { isiFrame.dispose(); isiFrame = null; } } else { isiFrame = new JFrame("ISIs") { @Override synchronized public void paint(Graphics g) { super.paint(g); try { if (leftBins != null && rightBins != null) { activitySeriesLeft.clear(); activitySeriesRight.clear(); //log.info("numbins="+myBins.numOfBins); for (int i = 0; i < nBins; i++) { if (isLogPlotEnabled()) { activitySeriesLeft.add(i, (float) Math.log(leftBins[i])); activitySeriesRight.add(i, (float) Math.log(rightBins[i])); } else { activitySeriesLeft.add(i, leftBins[i]); activitySeriesRight.add(i, rightBins[i]); } } binAxis.setMaximum(nBins); binAxis.setMinimum(0); if (isLogPlotEnabled()) { activityAxisLeft.setMaximum((float) Math.log(leftBins[maxLeftBinIndex])); activityAxisRight.setMaximum((float) Math.log(rightBins[maxRightBinIndex])); } else { activityAxisLeft.setMaximum(leftBins[maxLeftBinIndex]); activityAxisRight.setMaximum(rightBins[maxRightBinIndex]); } } else { log.warning("bins==null"); } } catch (Exception e) { log.warning("while displaying bins chart caught " + e); } } }; isiFrame.setPreferredSize(new Dimension(200, 100)); Container pane = isiFrame.getContentPane(); chart = new XYChart(); activitySeriesLeft = new Series(2, nBins); activitySeriesRight = new Series(2, nBins); binAxis = new Axis(0, nBins); binAxis.setTitle("bin"); binAxis.setUnit(String.format("%d,%d us", minIsiUs, maxIsiUs)); activityAxisLeft = new Axis(0, 1); // will be normalized activityAxisLeft.setTitle("left count"); activityAxisRight = new Axis(0, 1); // will be normalized activityAxisRight.setTitle("right count"); activityCategoryLeft = new Category(activitySeriesLeft, new Axis[]{binAxis, activityAxisLeft}); activityCategoryLeft.setColor(new float[]{0f, 1f, 0f}); // green for left activityCategoryLeft.setLineWidth(3f); activityCategoryRight = new Category(activitySeriesRight, new Axis[]{binAxis, activityAxisRight}); activityCategoryRight.setColor(new float[]{1f, 0f, 0f}); // red for right activityCategoryRight.setLineWidth(3f); chart = new XYChart("ISIs"); chart.setBackground(Color.black); chart.setForeground(Color.white); chart.setGridEnabled(false); chart.addCategory(activityCategoryLeft); chart.addCategory(activityCategoryRight); pane.setLayout(new BorderLayout()); pane.add(chart, BorderLayout.CENTER); isiFrame.setVisible(yes); } } /** * @return the logPlotEnabled */ public boolean isLogPlotEnabled() { return logPlotEnabled; } /** * @param logPlotEnabled the logPlotEnabled to set */ public void setLogPlotEnabled(boolean logPlotEnabled) { this.logPlotEnabled = logPlotEnabled; getPrefs().putBoolean("logPlotEnabled", logPlotEnabled); } public boolean isUseLeftEar() { return this.useLeftEar; } public void setUseLeftEar(boolean useLeftEar) { getPrefs().putBoolean("useLeftEar", useLeftEar); this.useLeftEar = useLeftEar; } public boolean isUseRightEar() { return this.useRightEar; } public void setUseRightEar(boolean useRightEar) { getPrefs().putBoolean("useRightEar", useRightEar); this.useRightEar = useRightEar; } public boolean isSameChannelAndNeuron() { return this.sameChannelAndNeuron; } public void setSameChannelAndNeuron(boolean sameChannelAndNeuron) { getPrefs().putBoolean("sameChannelAndNeuron", sameChannelAndNeuron); this.sameChannelAndNeuron = sameChannelAndNeuron; } /** * @return the useChannels */ public String getUseChannels() { return this.useChannels; } /** * @param useChannels the channels to use */ public void setUseChannels(String useChannels) { getSupport().firePropertyChange("useChannels", this.useChannels, useChannels); this.useChannels = useChannels; getPrefs().put("useChannels", useChannels); parseUseChannel(); } public float[] getLeftBins() { return leftBins; } public float getLeftMaxBin() { return leftBins[maxLeftBinIndex]; } public float[] getRightBins() { return rightBins; } public float getRightMaxBin() { return rightBins[maxRightBinIndex]; } private void parseUseChannel() { for (int i = 0; i < 64; i++) { useChannelsBool[i] = false; } String[] temp = useChannels.split(";"); for (int i = 0; i < temp.length; i++) { String[] temp2 = temp[i].split("-"); if (temp2.length == 1) { useChannelsBool[Integer.parseInt(temp2[0])] = true; } else if (temp2.length == 2) { for (int j = Integer.parseInt(temp2[0]) - 1; j < Integer.parseInt(temp2[1]); j++) { useChannelsBool[j] = true; } } } } }
SensorsINI/jaer
src/ch/unizh/ini/jaer/projects/speakerid/ISIFilterTwoEars.java
Java
lgpl-2.1
18,944
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library 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. * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 */ package org.opencms.ade.galleries.client.preview.ui; import org.opencms.ade.galleries.client.Messages; import org.opencms.ade.galleries.client.preview.CmsPreviewUtil; import org.opencms.ade.galleries.client.preview.I_CmsPreviewHandler; import org.opencms.ade.galleries.shared.CmsResourceInfoBean; import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants.GalleryMode; import org.opencms.gwt.client.ui.CmsConfirmDialog; import org.opencms.gwt.client.ui.CmsPushButton; import org.opencms.gwt.client.ui.CmsTabbedPanel; import org.opencms.gwt.client.ui.CmsTabbedPanel.CmsTabbedPanelStyle; import org.opencms.gwt.client.ui.I_CmsConfirmDialogHandler; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; /** * Provides a widget skeleton for the preview dialog.<p> * * This widget contains a panel with the resource preview and * a set of tabs with resource information under the preview panel.<p> * * @param <T> the resource info bean type * * @since 8.0. */ public abstract class A_CmsPreviewDialog<T extends CmsResourceInfoBean> extends Composite { /** * @see com.google.gwt.uibinder.client.UiBinder */ protected interface I_CmsPreviewDialogUiBinder extends UiBinder<Widget, A_CmsPreviewDialog<?>> { // GWT interface, nothing to do here } /** The ui-binder instance for this class. */ private static I_CmsPreviewDialogUiBinder uiBinder = GWT.create(I_CmsPreviewDialogUiBinder.class); /** The button panel. */ @UiField protected FlowPanel m_buttonBar; /** The select button. */ @UiField protected CmsPushButton m_closePreview; /** The dialog height. */ protected int m_dialogHeight; /** The dialog width. */ protected int m_dialogWidth; /** The dialog mode of the gallery. */ protected GalleryMode m_galleryMode; /** The parent panel of the preview dialog. */ @UiField protected FlowPanel m_parentPanel; /** The preview height. */ protected int m_previewHeight; /** The preview placeholder panel. */ @UiField protected FlowPanel m_previewHolder; /** The preview panel of preview dialog. */ @UiField protected SimplePanel m_previewPanel; /** The select button. */ @UiField protected CmsPushButton m_selectButton; /** The tabbed panel of the preview dialog. */ protected CmsTabbedPanel<Widget> m_tabbedPanel; /** The tabs placeholder panel. */ @UiField protected FlowPanel m_tabsHolder; /** The min height for the preview panel. */ private final int m_minPreviewHeight = 362; /** * The constructor.<p> * * @param dialogMode the gallery dialog mode (view, widget, ade, editor, ...) * @param dialogHeight the dialog height to set * @param dialogWidth the dialog width to set */ public A_CmsPreviewDialog(GalleryMode dialogMode, int dialogHeight, int dialogWidth) { initWidget(uiBinder.createAndBindUi(this)); m_galleryMode = dialogMode; m_dialogHeight = dialogHeight; m_dialogWidth = dialogWidth; m_previewHeight = m_minPreviewHeight; int detailsHeight = m_dialogHeight - m_previewHeight - 7; m_previewHolder.getElement().getStyle().setHeight(m_previewHeight, Unit.PX); m_tabsHolder.getElement().getStyle().setHeight(detailsHeight, Unit.PX); m_tabbedPanel = new CmsTabbedPanel<Widget>(CmsTabbedPanelStyle.classicTabs); m_tabsHolder.add(m_tabbedPanel); m_selectButton.setText(Messages.get().key(Messages.GUI_PREVIEW_BUTTON_SELECT_0)); m_selectButton.setVisible(false); m_closePreview.setText(Messages.get().key(Messages.GUI_PREVIEW_CLOSE_BUTTON_0)); // buttons switch (m_galleryMode) { case editor: m_selectButton.setVisible(CmsPreviewUtil.shouldShowSelectButton()); m_closePreview.setText(Messages.get().key(Messages.GUI_PREVIEW_CLOSE_GALLERY_BUTTON_0)); m_buttonBar.getElement().getStyle().setBottom(94, Unit.PX); m_buttonBar.getElement().getStyle().setRight(1, Unit.PX); break; case widget: m_selectButton.setVisible(true); m_closePreview.setText(Messages.get().key(Messages.GUI_PREVIEW_CLOSE_GALLERY_BUTTON_0)); break; case ade: case view: default: break; } } /** * Displays a confirm save changes dialog with the given message. * May insert individual message before the given one for further information.<p> * Will call the appropriate command after saving/cancel.<p> * * @param message the message to display * @param onConfirm the command executed after saving * @param onCancel the command executed on cancel */ public void confirmSaveChanges(String message, final Command onConfirm, final Command onCancel) { CmsConfirmDialog confirmDialog = new CmsConfirmDialog("Confirm", message); confirmDialog.setHandler(new I_CmsConfirmDialogHandler() { /** * @see org.opencms.gwt.client.ui.I_CmsCloseDialogHandler#onClose() */ public void onClose() { if (onCancel != null) { onCancel.execute(); } } /** * @see org.opencms.gwt.client.ui.I_CmsConfirmDialogHandler#onOk() */ public void onOk() { if (onConfirm != null) { onConfirm.execute(); } } }); confirmDialog.center(); } /** * Fills the content of the tabs panel.<p> * * @param resourceInfo the bean containing the parameter */ public abstract void fillContent(T resourceInfo); /** * Returns the gallery mode.<p> * * @return the gallery mode */ public GalleryMode getGalleryMode() { return m_galleryMode; } /** * Returns if there are any changes that need saving, before the preview may be closed.<p> * * @return <code>true</code> if changed */ public abstract boolean hasChanges(); /** * Will be triggered, when the select button is clicked.<p> * * @param event the click event */ @UiHandler("m_closePreview") public void onCloseClick(ClickEvent event) { saveChanges(null); getHandler().closePreview(); } /** * Will be triggered, when the select button is clicked.<p> * * @param event the click event */ @UiHandler("m_selectButton") public void onSelectClick(ClickEvent event) { if (m_galleryMode == GalleryMode.editor) { // note: the select button isn't necessarily visible in editor mode (depending on the WYSIWYG editor), but // if it is, we want it to save the data and close the gallery dialog if (getHandler().setDataInEditor()) { // do this after a delay, so we don't get ugly Javascript errors when the iframe is closed. Timer timer = new Timer() { @Override public void run() { CmsPreviewUtil.closeDialog(); } }; timer.schedule(1); } } else { saveChanges(null); getHandler().selectResource(); } } /** * Removes the preview.<p> */ public void removePreview() { removeFromParent(); } /** * Saves the changes for this dialog.<p> * * @param afterSaveCommand the command to execute after saving the changes */ public abstract void saveChanges(Command afterSaveCommand); /** * Returns the preview handler.<p> * * @return the preview handler */ protected abstract I_CmsPreviewHandler<T> getHandler(); }
serrapos/opencms-core
src-gwt/org/opencms/ade/galleries/client/preview/ui/A_CmsPreviewDialog.java
Java
lgpl-2.1
9,619
/* * Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Samatar HASSAN. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package org.pentaho.di.trans.steps.dynamicsqlrow; import java.util.List; import java.util.Map; import org.w3c.dom.Node; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.DatabaseImpact; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; public class DynamicSQLRowMeta extends BaseStepMeta implements StepMetaInterface { /** database connection */ private DatabaseMeta databaseMeta; /** SQL Statement */ private String sql; private String sqlfieldname; /** Number of rows to return (0=ALL) */ private int rowLimit; /** false: don't return rows where nothing is found true: at least return one source row, the rest is NULL */ private boolean outerJoin; private boolean replacevars; public boolean queryonlyonchange; public DynamicSQLRowMeta() { super(); // allocate BaseStepMeta } /** * @return Returns the database. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * @param database The database to set. */ public void setDatabaseMeta(DatabaseMeta database) { this.databaseMeta = database; } /** * @return Returns the outerJoin. */ public boolean isOuterJoin() { return outerJoin; } /** * @param outerJoin The outerJoin to set. */ public void setOuterJoin(boolean outerJoin) { this.outerJoin = outerJoin; } /** * @return Returns the replacevars. */ public boolean isVariableReplace() { return replacevars; } /** * @param replacevars The replacevars to set. */ public void setVariableReplace(boolean replacevars) { this.replacevars = replacevars; } /** * @return Returns the queryonlyonchange. */ public boolean isQueryOnlyOnChange() { return queryonlyonchange; } /** * @param queryonlyonchange The queryonlyonchange to set. */ public void setQueryOnlyOnChange(boolean queryonlyonchange) { this.queryonlyonchange = queryonlyonchange; } /** * @return Returns the rowLimit. */ public int getRowLimit() { return rowLimit; } /** * @param rowLimit The rowLimit to set. */ public void setRowLimit(int rowLimit) { this.rowLimit = rowLimit; } /** * @return Returns the sql. */ public String getSql() { return sql; } /** * @param sql The sql to set. */ public void setSql(String sql) { this.sql = sql; } /** * @return Returns the sqlfieldname. */ public String getSQLFieldName() { return sqlfieldname; } /** * @param sql The sqlfieldname to set. */ public void setSQLFieldName(String sqlfieldname) { this.sqlfieldname = sqlfieldname; } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { readData(stepnode, databases); } public Object clone() { DynamicSQLRowMeta retval = (DynamicSQLRowMeta)super.clone(); return retval; } private void readData(Node stepnode, List<DatabaseMeta> databases) throws KettleXMLException { try { String con = XMLHandler.getTagValue(stepnode, "connection"); //$NON-NLS-1$ databaseMeta = DatabaseMeta.findDatabase(databases, con); sql = XMLHandler.getTagValue(stepnode, "sql"); //$NON-NLS-1$ outerJoin = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "outer_join")); //$NON-NLS-1$ //$NON-NLS-2$ replacevars = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "replace_vars")); queryonlyonchange = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "query_only_on_change")); rowLimit = Const.toInt(XMLHandler.getTagValue(stepnode, "rowlimit"), 0); //$NON-NLS-1$ sqlfieldname = XMLHandler.getTagValue(stepnode, "sql_fieldname"); //$NON-NLS-1$ } catch(Exception e) { throw new KettleXMLException(Messages.getString("DynamicSQLRowMeta.Exception.UnableToLoadStepInfo"), e); //$NON-NLS-1$ } } public void setDefault() { databaseMeta = null; rowLimit = 0; sql = ""; //$NON-NLS-1$ outerJoin=false; replacevars=false; sqlfieldname=null; queryonlyonchange=false; } public void getFields(RowMetaInterface row, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { if (databaseMeta==null) return; Database db = new Database(databaseMeta); databases = new Database[] { db }; // Keep track of this one for cancelQuery // First try without connecting to the database... (can be S L O W) // See if it's in the cache... RowMetaInterface add =null; String realSQL=sql; if(replacevars) realSQL=space.environmentSubstitute(realSQL); try { add = db.getQueryFields(realSQL, false); } catch(KettleDatabaseException dbe) { throw new KettleStepException(Messages.getString("DynamicSQLRowMeta.Exception.UnableToDetermineQueryFields")+Const.CR+sql, dbe); //$NON-NLS-1$ } if (add!=null) // Cache hit, just return it this... { for (int i=0;i<add.size();i++) { ValueMetaInterface v=add.getValueMeta(i); v.setOrigin(name); } row.addRowMeta( add ); } else // No cache hit, connect to the database, do it the hard way... try { db.connect(); add = db.getQueryFields(realSQL, false); for (int i=0;i<add.size();i++) { ValueMetaInterface v=add.getValueMeta(i); v.setOrigin(name); } row.addRowMeta( add ); db.disconnect(); } catch(KettleDatabaseException dbe) { throw new KettleStepException(Messages.getString("DynamicSQLRowMeta.Exception.ErrorObtainingFields"), dbe); //$NON-NLS-1$ } } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(" "+XMLHandler.addTagValue("connection", databaseMeta==null?"":databaseMeta.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" "+XMLHandler.addTagValue("rowlimit", rowLimit)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("sql", sql)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("outer_join", outerJoin)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("replace_vars", replacevars)); retval.append(" "+XMLHandler.addTagValue("sql_fieldname", sqlfieldname)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("query_only_on_change", queryonlyonchange)); //$NON-NLS-1$ //$NON-NLS-2$ return retval.toString(); } public void readRep(Repository rep, long id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { long id_connection = rep.getStepAttributeInteger(id_step, "id_connection"); //$NON-NLS-1$ databaseMeta = DatabaseMeta.findDatabase( databases, id_connection); rowLimit = (int)rep.getStepAttributeInteger(id_step, "rowlimit"); //$NON-NLS-1$ sql = rep.getStepAttributeString (id_step, "sql"); //$NON-NLS-1$ outerJoin = rep.getStepAttributeBoolean(id_step, "outer_join"); //$NON-NLS-1$ replacevars = rep.getStepAttributeBoolean(id_step, "replace_vars"); sqlfieldname = rep.getStepAttributeString (id_step, "sql_fieldname"); //$NON-NLS-1$ queryonlyonchange = rep.getStepAttributeBoolean (id_step, "query_only_on_change"); //$NON-NLS-1$ } catch(Exception e) { throw new KettleException(Messages.getString("DynamicSQLRowMeta.Exception.UnexpectedErrorReadingStepInfo"), e); //$NON-NLS-1$ } } public void saveRep(Repository rep, long id_transformation, long id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "id_connection", databaseMeta==null?-1:databaseMeta.getID()); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "rowlimit", rowLimit); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "sql", sql); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "outer_join", outerJoin); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "replace_vars", replacevars); rep.saveStepAttribute(id_transformation, id_step, "sql_fieldname", sqlfieldname); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "query_only_on_change", queryonlyonchange); // Also, save the step-database relationship! if (databaseMeta!=null) rep.insertStepDatabase(id_transformation, id_step, databaseMeta.getID()); } catch(Exception e) { throw new KettleException(Messages.getString("DynamicSQLRowMeta.Exception.UnableToSaveStepInfo")+id_step, e); //$NON-NLS-1$ } } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepinfo, RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info) { CheckResult cr; String error_message = ""; //$NON-NLS-1$ // See if we have input streams leading to this step! if (input.length>0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("DynamicSQLRowMeta.CheckResult.ReceivingInfo"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("DynamicSQLRowMeta.CheckResult.NoInputReceived"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } // Check for SQL field if(Const.isEmpty(sqlfieldname)) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("DynamicSQLRowMeta.CheckResult.SQLFieldNameMissing"), stepinfo); //$NON-NLS-1$ remarks.add(cr); }else { ValueMetaInterface vfield = prev.searchValueMeta(sqlfieldname); if(vfield==null) cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("DynamicSQLRowMeta.CheckResult.SQLFieldNotFound",sqlfieldname), stepinfo); //$NON-NLS-1$ else cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("DynamicSQLRowMeta.CheckResult.SQLFieldFound",sqlfieldname,vfield.getOrigin()), stepinfo); remarks.add(cr); } if (databaseMeta!=null) { Database db = new Database(databaseMeta); databases = new Database[] { db }; // Keep track of this one for cancelQuery try { db.connect(); if (sql!=null && sql.length()!=0) { error_message = ""; //$NON-NLS-1$ RowMetaInterface r = db.getQueryFields(sql, true); if (r!=null) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("DynamicSQLRowMeta.CheckResult.QueryOK"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } else { error_message=Messages.getString("DynamicSQLRowMeta.CheckResult.InvalidDBQuery"); //$NON-NLS-1$ cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); remarks.add(cr); } } } catch(KettleException e) { error_message = Messages.getString("DynamicSQLRowMeta.CheckResult.ErrorOccurred")+e.getMessage(); //$NON-NLS-1$ cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); remarks.add(cr); } finally { db.disconnect(); } } else { error_message = Messages.getString("DynamicSQLRowMeta.CheckResult.InvalidConnection"); //$NON-NLS-1$ cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); remarks.add(cr); } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr, Trans trans) { return new DynamicSQLRow(stepMeta, stepDataInterface, cnr, tr, trans); } public StepDataInterface getStepData() { return new DynamicSQLRowData(); } public void analyseImpact(List<DatabaseImpact> impact, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info) throws KettleStepException { RowMetaInterface out = prev.clone(); getFields(out, stepMeta.getName(), new RowMetaInterface[] { info, }, null, transMeta ); if (out!=null) { for (int i=0;i<out.size();i++) { ValueMetaInterface outvalue = out.getValueMeta(i); DatabaseImpact di = new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_READ, transMeta.getName(), stepMeta.getName(), databaseMeta.getDatabaseName(), "", //$NON-NLS-1$ outvalue.getName(), outvalue.getName(), stepMeta.getName(), sql, Messages.getString("DynamicSQLRowMeta.DatabaseImpact.Title") //$NON-NLS-1$ ); impact.add(di); } } } public DatabaseMeta[] getUsedDatabaseConnections() { if (databaseMeta!=null) { return new DatabaseMeta[] { databaseMeta }; } else { return super.getUsedDatabaseConnections(); } } public boolean supportsErrorHandling() { return true; } }
icholy/geokettle-2.0
src/org/pentaho/di/trans/steps/dynamicsqlrow/DynamicSQLRowMeta.java
Java
lgpl-2.1
14,438
/*! \file gd32f20x_cau_des.c \brief CAU_DES driver \version 2015-07-15, V1.0.0, firmware for GD32F20x \version 2017-06-05, V2.0.0, firmware for GD32F20x \version 2018-10-31, V2.1.0, firmware for GD32F20x */ /* Copyright (c) 2018, GigaDevice Semiconductor Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ #include "gd32f20x_cau.h" #define DESBUSY_TIMEOUT ((uint32_t)0x00010000U) /* DES calculate process */ static ErrStatus cau_des_calculate(uint8_t *input, uint32_t in_length, uint8_t *output); /*! \brief encrypt and decrypt using DES in ECB mode \param[in] algo_dir: algorithm direction only one parameter can be selected which is shown as below \arg CAU_ENCRYPT: encrypt \arg CAU_DECRYPT: decrypt \param[in] key: key used for DES algorithm \param[in] text: pointer to the text information struct input: pointer to the input buffer in_length: length of the input buffer, must be a multiple of 8 output: pointer to the returned buffer \param[out] none \retval ErrStatus: SUCCESS or ERROR */ ErrStatus cau_des_ecb(uint32_t algo_dir, uint8_t key[24], cau_text_struct *text) { ErrStatus ret = ERROR; cau_key_parameter_struct key_initpara; uint32_t keyaddr = (uint32_t)key; /* key structure initialization */ cau_key_parameter_init(&key_initpara); /* initialize the CAU peripheral */ cau_init(algo_dir, CAU_MODE_DES_ECB, CAU_SWAPPING_8BIT); /* key initialisation */ key_initpara.key_1_high = __REV(*(uint32_t*)(keyaddr)); keyaddr += 4U; key_initpara.key_1_low= __REV(*(uint32_t*)(keyaddr)); cau_key_init(& key_initpara); /* flush the IN and OUT FIFOs */ cau_fifo_flush(); /* enable the CAU peripheral */ cau_enable(); /* DES calculate process */ ret = cau_des_calculate(text->input, text->in_length, text->output); /* disable the CAU peripheral */ cau_disable(); return ret; } /*! \brief encrypt and decrypt using DES in CBC mode \param[in] algo_dir: algorithm direction only one parameter can be selected which is shown as below \arg CAU_ENCRYPT: encrypt \arg CAU_DECRYPT: decrypt \param[in] key: key used for DES algorithm \param[in] iv: initialization vectors used for TDES algorithm \param[in] text: pointer to the text information struct input: pointer to the input buffer in_length: length of the input buffer, must be a multiple of 8 output: pointer to the returned buffer \param[out] none \retval ErrStatus: SUCCESS or ERROR */ ErrStatus cau_des_cbc(uint32_t algo_dir, uint8_t key[24], uint8_t iv[8], cau_text_struct *text) { ErrStatus ret = ERROR; cau_key_parameter_struct key_initpara; cau_iv_parameter_struct iv_initpara; uint32_t keyaddr = (uint32_t)key; uint32_t ivaddr = (uint32_t)iv; /* key structure initialization */ cau_key_parameter_init(&key_initpara); /* initialize the CAU peripheral */ cau_init(algo_dir, CAU_MODE_DES_CBC, CAU_SWAPPING_8BIT); /* key initialisation */ key_initpara.key_1_high = __REV(*(uint32_t*)(keyaddr)); keyaddr += 4U; key_initpara.key_1_low= __REV(*(uint32_t*)(keyaddr)); cau_key_init(&key_initpara); /* vectors initialization */ iv_initpara.iv_0_high = __REV(*(uint32_t*)(ivaddr)); ivaddr += 4U; iv_initpara.iv_0_low= __REV(*(uint32_t*)(ivaddr)); cau_iv_init(&iv_initpara); /* flush the IN and OUT FIFOs */ cau_fifo_flush(); /* enable the CAU peripheral */ cau_enable(); /* DES calculate process */ ret = cau_des_calculate(text->input, text->in_length, text->output); /* disable the CAU peripheral */ cau_disable(); return ret; } /*! \brief DES calculate process \param[in] input: pointer to the input buffer \param[in] in_length: length of the input buffer, must be a multiple of 8 \param[in] output: pointer to the returned buffer \param[out] none \retval ErrStatus: SUCCESS or ERROR */ static ErrStatus cau_des_calculate(uint8_t *input, uint32_t in_length, uint8_t *output) { uint32_t inputaddr = (uint32_t)input; uint32_t outputaddr = (uint32_t)output; uint32_t i = 0U; __IO uint32_t counter = 0U; uint32_t busystatus = 0U; /* the clock is not enabled or there is no embeded CAU peripheral */ if(DISABLE == cau_enable_state_get()){ return ERROR; } for(i = 0U; i < in_length; i += 8U){ /* write data to the IN FIFO */ cau_data_write(*(uint32_t*)(inputaddr)); inputaddr += 4U; cau_data_write(*(uint32_t*)(inputaddr)); inputaddr += 4U; /* wait until the complete message has been processed */ counter = 0U; do{ busystatus = cau_flag_get(CAU_FLAG_BUSY); counter++; }while((DESBUSY_TIMEOUT != counter) && (RESET != busystatus)); if(RESET != busystatus){ return ERROR; }else{ /* read the output block from the output FIFO */ *(uint32_t*)(outputaddr) = cau_data_read(); outputaddr += 4U; *(uint32_t*)(outputaddr) = cau_data_read(); outputaddr += 4U; } } return SUCCESS; }
prefetchnta/crhack
src/naked/arm-gd32/gd32f20x/gd32f20x_cau_des.c
C
lgpl-2.1
7,168
namespace GASS.CUDA { using System; public enum cudaError { cudaErrorAddressOfConstant = 0x16, cudaErrorApiFailureBase = 0x2710, cudaErrorCudartUnloading = 0x1d, cudaErrorInitializationError = 3, cudaErrorInsufficientDriver = 0x23, cudaErrorInvalidChannelDescriptor = 20, cudaErrorInvalidConfiguration = 9, cudaErrorInvalidDevice = 10, cudaErrorInvalidDeviceFunction = 8, cudaErrorInvalidDevicePointer = 0x11, cudaErrorInvalidFilterSetting = 0x1a, cudaErrorInvalidHostPointer = 0x10, cudaErrorInvalidMemcpyDirection = 0x15, cudaErrorInvalidNormSetting = 0x1b, cudaErrorInvalidPitchValue = 12, cudaErrorInvalidResourceHandle = 0x21, cudaErrorInvalidSymbol = 13, cudaErrorInvalidTexture = 0x12, cudaErrorInvalidTextureBinding = 0x13, cudaErrorInvalidValue = 11, cudaErrorLaunchFailure = 4, cudaErrorLaunchOutOfResources = 7, cudaErrorLaunchTimeout = 6, cudaErrorMapBufferObjectFailed = 14, cudaErrorMemoryAllocation = 2, cudaErrorMemoryValueTooLarge = 0x20, cudaErrorMissingConfiguration = 1, cudaErrorMixedDeviceExecution = 0x1c, cudaErrorNoDevice = 0x25, cudaErrorNotReady = 0x22, cudaErrorNotYetImplemented = 0x1f, cudaErrorPriorLaunchFailure = 5, cudaErrorSetOnActiveProcess = 0x24, cudaErrorStartupFailure = 0x7f, cudaErrorSynchronizationError = 0x19, cudaErrorTextureFetchFailed = 0x17, cudaErrorTextureNotBound = 0x18, cudaErrorUnknown = 30, cudaErrorUnmapBufferObjectFailed = 15, cudaErrorIncompatibleDriverContext = 49,// NK210211 cudaSuccess = 0 } }
KarimLUCCIN/Cudafy
3p/cuda.net3.0.0_win/src/CUDA.NET_3.0_Source/GASS.CUDA/cudaError.cs
C#
lgpl-2.1
1,804
/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved * * The contents of this file is dual-licensed under 2 * alternative Open Source/Free licenses: LGPL 2.1 or later and * Apache License 2.0. (starting with JNA version 4.0.0). * * You can freely decide which license you want to apply to * the project. * * You may obtain a copy of the LGPL License at: * * http://www.gnu.org/licenses/licenses.html * * A copy is also included in the downloadable source code package * containing JNA, in file "LGPL2.1". * * You may obtain a copy of the Apache License at: * * http://www.apache.org/licenses/ * * A copy is also included in the downloadable source code package * containing JNA, in file "AL2.0". */ package com.sun.jna.platform.win32; import java.util.List; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.win32.W32APITypeMapper; /** * Ported from AccCtrl.h. Microsoft Windows SDK 7.1 * * @author amarcionek[at]gmail.com */ public abstract class Winnetwk { /** * The scope of the enumeration. This member can be one of the following * values defined in the Winnetwk.h header file. NOTE: This are for the * dwScope member of NetResource. NOTE: Certain functions allow different * values of the scope parameter. Consult MSDN for more info. */ public class RESOURCESCOPE { /** * Enumerate currently connected resources. The dwUsage member cannot be * specified. */ public static final int RESOURCE_CONNECTED = 1; /** * Enumerate all resources on the network. The dwUsage member is * specified. */ public static final int RESOURCE_GLOBALNET = 2; /** * Enumerate remembered (persistent) connections. The dwUsage member * cannot be specified. */ public static final int RESOURCE_REMEMBERED = 3; /** * NOTE: Definition for this is not defined in Windows Kits nor on MSDN */ public static final int RESOURCE_RECENT = 4; /** * Enumerate only resources in the network context of the caller. * Specify this value for a Network Neighborhood view. The function * ignores the dwUsage parameter. */ public static final int RESOURCE_CONTEXT = 5; } /** * The type of resource. This member can be one of the following values * defined in the Winnetwk.h header file. NOTE: This are for the dwType * member of NetResource */ public class RESOURCETYPE { /** * All resources */ public static final int RESOURCETYPE_ANY = 0; /** * Disk resources */ public static final int RESOURCETYPE_DISK = 1; /** * Print resources */ public static final int RESOURCETYPE_PRINT = 2; /** * NOTE: Definition for this is not defined in Windows Kits nor on MSDN */ public static final int RESOURCETYPE_RESERVED = 8; /** * The WNetEnumResource function can also return the value * RESOURCETYPE_UNKNOWN if a resource is neither a disk nor a print * resource. */ public static final int RESOURCETYPE_UNKNOWN = 0xFFFFFFFF; } /** * The type of resource. This member can be one of the following values * defined in the Winnetwk.h header file. NOTE: This are for the dwScope * member of NetResource */ public class RESOURCEDISPLAYTYPE { /** * The method used to display the object does not matter. */ public static final int RESOURCEDISPLAYTYPE_GENERIC = 0; /** * The object should be displayed as a domain. */ public static final int RESOURCEDISPLAYTYPE_DOMAIN = 1; /** * The object should be displayed as a server. */ public static final int RESOURCEDISPLAYTYPE_SERVER = 2; /** * The object should be displayed as a share. */ public static final int RESOURCEDISPLAYTYPE_SHARE = 3; /** * The object should be displayed as a file. */ public static final int RESOURCEDISPLAYTYPE_FILE = 4; // TODO: Add the others } /** * A set of bit flags describing how the resource can be used. Note that * this member can be specified only if the dwScope member is equal to * RESOURCE_GLOBALNET. This member can be one of the following values * defined in the Winnetwk.h header file. NOTE: This are for the dwUsage * member of NetResource */ public class RESOURCEUSAGE { /** * The resource is a connectable resource; the name pointed to by the * lpRemoteName member can be passed to the WNetAddConnection function * to make a network connection. */ public static final int RESOURCEUSAGE_CONNECTABLE = 0x00000001; /** * The resource is a container resource; the name pointed to by the * lpRemoteName member can be passed to the WNetOpenEnum function to * enumerate the resources in the container. */ public static final int RESOURCEUSAGE_CONTAINER = 0x00000002; /** * The resource is not a local device. */ public static final int RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004; /** * The resource is a sibling. This value is not used by Windows. */ public static final int RESOURCEUSAGE_SIBLING = 0x00000008; /** * The resource must be attached. This value specifies that a function * to enumerate resource this should fail if the caller is not * authenticated, even if the network permits enumeration without * authentication. */ public static final int RESOURCEUSAGE_ATTACHED = 0x00000010; /** * Setting this value is equivalent to setting * RESOURCEUSAGE_CONNECTABLE, RESOURCEUSAGE_CONTAINER, and * RESOURCEUSAGE_ATTACHED. */ public static final int RESOURCEUSAGE_ALL = RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED; } /** * A set of bit flags describing how the resource can be used. Note that * this member can be specified only if the dwScope member is equal to * RESOURCE_GLOBALNET. This member can be one of the following values * defined in the Winnetwk.h header file. NOTE: This are for the dwUsage * member of NetResource */ public class ConnectFlag { /** * This flag instructs the operating system to store the network * resource connection. If this bit flag is set, the operating system * automatically attempts to restore the connection when the user logs * on. The system remembers only successful connections that redirect * local devices. It does not remember connections that are unsuccessful * or deviceless connections. (A deviceless connection occurs when * lpLocalName is NULL or when it points to an empty string.) If this * bit flag is clear, the operating system does not automatically * restore the connection at logon. */ public static final int CONNECT_UPDATE_PROFILE = 0x00000001; /** * If this flag is set, the operating system may interact with the user * for authentication purposes. */ public static final int CONNECT_INTERACTIVE = 0x00000008; /** * This flag instructs the system not to use any default settings for * user names or passwords without offering the user the opportunity to * supply an alternative. This flag is ignored unless * CONNECT_INTERACTIVE is also set. */ public static final int CONNECT_PROMPT = 0x00000010; /** * This flag forces the redirection of a local device when making the * connection. If the lpLocalName member of NETRESOURCE specifies a * local device to redirect, this flag has no effect, because the * operating system still attempts to redirect the specified device. * When the operating system automatically chooses a local device, the * dwType member must not be equal to RESOURCETYPE_ANY. If this flag is * not set, a local device is automatically chosen for redirection only * if the network requires a local device to be redirected. Windows XP: * When the system automatically assigns network drive letters, letters * are assigned beginning with Z:, then Y:, and ending with C:. This * reduces collision between per-logon drive letters (such as network * drive letters) and global drive letters (such as disk drives). Note * that previous releases assigned drive letters beginning with C: and * ending with Z:. */ public static final int CONNECT_REDIRECT = 0x00000080; /** * If this flag is set, the connection was made using a local device * redirection. If the lpAccessName parameter points to a buffer, the * local device name is copied to the buffer. */ public static final int CONNECT_LOCALDRIVE = 0x00000100; /** * If this flag is set, the operating system prompts the user for * authentication using the command line instead of a graphical user * interface (GUI). This flag is ignored unless CONNECT_INTERACTIVE is * also set. Windows 2000/NT and Windows Me/98/95: This value is not * supported. */ public static final int CONNECT_COMMANDLINE = 0x00000800; /** * If this flag is set, and the operating system prompts for a * credential, the credential should be saved by the credential manager. * If the credential manager is disabled for the caller's logon session, * or if the network provider does not support saving credentials, this * flag is ignored. This flag is also ignored unless you set the * CONNECT_COMMANDLINE flag. Windows 2000/NT and Windows Me/98/95: This * value is not supported. */ public static final int CONNECT_CMD_SAVECRED = 0x00001000; } /** * The NETRESOURCE structure contains information about a network resource. */ public static class NETRESOURCE extends Structure { public static class ByReference extends NETRESOURCE implements Structure.ByReference { public ByReference() { } public ByReference(Pointer memory) { super(memory); } } public static final List<String> FIELDS = createFieldsOrder( "dwScope", "dwType", "dwDisplayType", "dwUsage", "lpLocalName", "lpRemoteName", "lpComment", "lpProvider"); /** * The scope of the enumeration. This member can be one of the values * defined in class NetResourceSope. */ public int dwScope; /** * The type of resource. This member can be one of first 3 values * defined in the NetResourceType. */ public int dwType; /** * The display options for the network object in a network browsing user * interface. This member can be one of the values defined in the * NetResourceDisplayType. */ public int dwDisplayType; /** * A set of bit flags describing how the resource can be used. */ public int dwUsage; /** * If the dwScope member is equal to RESOURCE_CONNECTED or * RESOURCE_REMEMBERED, this member is a pointer to a null-terminated * character string that specifies the name of a local device. This * member is NULL if the connection does not use a device. */ public String lpLocalName; /** * If the entry is a network resource, this member is a pointer to a * null-terminated character string that specifies the remote network * name. * * If the entry is a current or persistent connection, lpRemoteName * member points to the network name associated with the name pointed to * by the lpLocalName member. * * The string can be MAX_PATH characters in length, and it must follow * the network provider's naming conventions */ public String lpRemoteName; /** * A pointer to a NULL-terminated string that contains a comment * supplied by the network provider. */ public String lpComment; /** * A pointer to a NULL-terminated string that contains the name of the * provider that owns the resource. This member can be NULL if the * provider name is unknown. To retrieve the provider name, you can call * the WNetGetProviderName function. */ public String lpProvider; public NETRESOURCE() { super(W32APITypeMapper.DEFAULT); } public NETRESOURCE(Pointer address) { super(address, Structure.ALIGN_DEFAULT, W32APITypeMapper.DEFAULT); read(); } @Override protected List<String> getFieldOrder() { return FIELDS; } } // // Universal Naming. // public static int UNIVERSAL_NAME_INFO_LEVEL = 0x00000001; public static int REMOTE_NAME_INFO_LEVEL = 0x00000002; /** * The UNIVERSAL_NAME_INFO structure contains a pointer to a Universal * Naming Convention (UNC) name string for a network resource. */ public static class UNIVERSAL_NAME_INFO extends Structure { public static class ByReference extends REMOTE_NAME_INFO implements Structure.ByReference { public ByReference() { super(); } public ByReference(Pointer memory) { super(memory); } } public static final List<String> FIELDS = createFieldsOrder("lpUniversalName"); /** * Pointer to the null-terminated UNC name string that identifies a * network resource. */ public String lpUniversalName; public UNIVERSAL_NAME_INFO() { super(W32APITypeMapper.DEFAULT); } public UNIVERSAL_NAME_INFO(Pointer address) { super(address, Structure.ALIGN_DEFAULT, W32APITypeMapper.DEFAULT); read(); } @Override protected List<String> getFieldOrder() { return FIELDS; } } /** * The REMOTE_NAME_INFO structure contains path and name information for a * network resource. The structure contains a member that points to a * Universal Naming Convention (UNC) name string for the resource, and two * members that point to additional network connection information strings. */ public static class REMOTE_NAME_INFO extends Structure { public static class ByReference extends REMOTE_NAME_INFO implements Structure.ByReference { public ByReference() { } public ByReference(Pointer memory) { super(memory); } } public static final List<String> FIELDS = createFieldsOrder("lpUniversalName", "lpConnectionName", "lpRemainingPath"); /** * Pointer to the null-terminated UNC name string that identifies a * network resource. */ public String lpUniversalName; /** * Pointer to a null-terminated string that is the name of a network * connection. */ public String lpConnectionName; /** * Pointer to a null-terminated name string. */ public String lpRemainingPath; public REMOTE_NAME_INFO() { super(W32APITypeMapper.DEFAULT); } public REMOTE_NAME_INFO(Pointer address) { super(address, Structure.ALIGN_DEFAULT, W32APITypeMapper.DEFAULT); read(); } @Override protected List<String> getFieldOrder() { return FIELDS; } } }
trejkaz/jna
contrib/platform/src/com/sun/jna/platform/win32/Winnetwk.java
Java
lgpl-2.1
16,439
package de.fiduciagad.anflibrary.anFReceiver.anFHandling.anFNotificationTrigger; import android.content.Context; import android.content.Intent; import android.os.SystemClock; /** * Created by Felix Schiefer on 23.01.2016. */ class ContextAwaitRunnable implements Runnable { private Context context; public ContextAwaitRunnable(Context context) { this.context = context; } @Override public void run() { SystemClock.sleep(ControllerConstants.MESSAGE_WAIT_TIME); Intent notificationController = new Intent(context, InstantMessageTriggerService.class); context.startService(notificationController); } }
fiduciagad/active-notification-framework
src/main/java/de/fiduciagad/anflibrary/anFReceiver/anFHandling/anFNotificationTrigger/ContextAwaitRunnable.java
Java
lgpl-2.1
661
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2011 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library 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. 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.feature.persistence.sql.insert; import java.util.HashMap; import java.util.Map; import org.deegree.commons.jdbc.SQLIdentifier; import org.deegree.feature.persistence.sql.id.KeyPropagation; /** * A reference from an {@link InsertRow} to a parent {@link InsertRow}. * <p> * The parent provides values for foreign key columns. * </p> * * @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ class ParentRowReference { private final InsertRow parent; private final KeyPropagation propagation; private final Map<InsertRow, SQLIdentifier> hrefingRows = new HashMap<InsertRow, SQLIdentifier>(); ParentRowReference( InsertRow parent, KeyPropagation propagation ) { this.parent = parent; this.propagation = propagation; } InsertRow getTarget() { return parent; } /** * Returns the {@link KeyPropagation} from the parent {@link InsertRow}. * * @return key propagation, never <code>null</code> */ KeyPropagation getKeyPropagation() { return propagation; } void addHrefingRow( InsertRow row, SQLIdentifier hrefCol ) { hrefingRows.put( row, hrefCol ); } boolean isHrefed( InsertRow childInsertRow ) { return hrefingRows.containsKey( childInsertRow ); } SQLIdentifier getHrefColum( InsertRow childInsertRow ) { return hrefingRows.get( childInsertRow ); } }
deegree/deegree3
deegree-datastores/deegree-featurestores/deegree-featurestore-sql/src/main/java/org/deegree/feature/persistence/sql/insert/ParentRowReference.java
Java
lgpl-2.1
2,813
#include "VtkWriter.h" #include <cassert> #include <cstdlib> using namespace cigma; // --------------------------------------------------------------------------- VtkWriter::VtkWriter() { fp = NULL; } VtkWriter::~VtkWriter() { close(); } // --------------------------------------------------------------------------- int VtkWriter::open(const char *filename) { fp = fopen(filename, "w"); if (fp == NULL) { return -1; } this->write_header(); return 0; } int VtkWriter::close() { if (fp != NULL) { fclose(fp); fp = NULL; } return 0; } // --------------------------------------------------------------------------- void VtkWriter::write_header() { assert(fp != NULL); fprintf(fp, "# vtk DataFile Version 3.0\n"); fprintf(fp, "This line is a comment\n"); fprintf(fp, "ASCII\n"); fprintf(fp, "DATASET UNSTRUCTURED_GRID\n"); } void VtkWriter::write_points(double *points, int npts, int ndim) { assert(fp != NULL); assert(ndim > 1); fprintf(fp, "POINTS %d double\n", npts); for (int i = 0; i < npts; i++) { fprintf(fp, " %g", points[ndim*i + 0]); fprintf(fp, " %g", points[ndim*i + 1]); if (ndim == 3) fprintf(fp, " %g", points[ndim*i + 2]); else fprintf(fp, " 0.0"); fprintf(fp, "\n"); } } void VtkWriter::write_cells(int *cells, int nel, int ndofs) { assert(fp != NULL); fprintf(fp, "CELLS %d %d\n", nel, nel*(1 + ndofs)); for (int i = 0; i < nel; i++) { fprintf(fp, " %d", ndofs); for (int j = 0; j < ndofs; j++) { fprintf(fp, " %d", cells[ndofs*i + j]); } fprintf(fp, "\n"); } } void VtkWriter::write_cell_types(int nsd, int nel, int ndofs) { assert(fp != NULL); fprintf(fp, "CELL_TYPES %d\n", nel); int vtkType = 0; if (nsd == 3) { switch (ndofs) { case 4: vtkType = 10; break; // VTK_TETRA=10 case 8: vtkType = 12; break; // VTK_HEXAHEDRON=12 case 6: vtkType = 13; break; // VTK_WEDGE=13 case 5: vtkType = 14; break; // VTK_PYRAMID=14 case 10: vtkType = 24; break; // VTK_QUADRATIC_TETRA=24 case 20: vtkType = 25; break; // VTK_QUADRATIC_HEXAHEDRON=25 } } else if (nsd == 2) { switch (ndofs) { case 3: vtkType = 5; break; // VTK_TRIANGLE=5 case 4: vtkType = 9; break; // VTK_QUAD=9 case 6: vtkType = 22; break; // VTK_QUADRATIC_TRIANGLE=22 case 8: vtkType = 23; break; // VTK_QUADRATIC_QUAD=23 } } assert(vtkType > 0); for (int i = 0; i < nel; i++) { fprintf(fp, "%d\n", vtkType); } } void VtkWriter::write_point_data(const char *name, double *data, int nno, int ndim) { assert(fp != NULL); fprintf(fp, "POINT_DATA %d\n", nno); if (ndim == 1) { fprintf(fp, "SCALARS %s double 1\n", name); fprintf(fp, "LOOKUP_TABLE default\n"); for (int i = 0; i < nno; i++) { fprintf(fp, "%g\n", data[i]); } return; } else if ((ndim == 2) || (ndim == 3)) { fprintf(fp, "VECTORS %s double\n", name); for (int i = 0; i < nno; i++) { fprintf(fp, " %g", data[ndim*i + 0]); fprintf(fp, " %g", data[ndim*i + 1]); if (ndim == 3) fprintf(fp, " %g\n", data[ndim*i + 2]); else fprintf(fp, " 0.0\n"); } } else if (ndim == 9) { fprintf(fp, "TENSORS %s double\n", name); for (int i = 0; i < nno; i++) { for (int j = 0; j < ndim; j++) { fprintf(fp, " %g", data[ndim*i + j]); } fprintf(fp, "\n"); } } } void VtkWriter::write_cell_data(const char *name, double *data, int nel, int ndim) { assert(fp != NULL); fprintf(fp, "CELL_DATA %d\n", nel); if (ndim == 1) { fprintf(fp, "SCALARS %s float 1\n", name); fprintf(fp, "LOOKUP_TABLE default\n"); for (int i = 0; i < nel; i++) fprintf(fp, "%g\n", data[i]); } else if ((ndim == 2) || (ndim == 3)) { fprintf(fp, "VECTORS %s float\n", name); for (int i = 0; i < nel; i++) { fprintf(fp, " %g", data[ndim*i + 0]); fprintf(fp, " %g", data[ndim*i + 1]); if (ndim == 3) fprintf(fp, " %g\n", data[ndim*i + 2]); else fprintf(fp, " 0.0\n"); } } else if (ndim == 9) { fprintf(fp, "TENSORS %s float\n", name); for (int i = 0; i < nel; i++) { for (int j = 0; j < ndim; j++) { fprintf(fp, " %g", data[ndim*i + j]); } fprintf(fp, "\n"); } } } // --------------------------------------------------------------------------- int VtkWriter::write_coordinates(const char *loc, double *data, int nno, int ndim) { this->write_points(data, nno, ndim); } int VtkWriter::write_dataset(const char *loc, double *data, int nno, int ndim) { this->write_point_data(loc, data, nno, ndim); } // ---------------------------------------------------------------------------
geodynamics/cigma
src/VtkWriter.cpp
C++
lgpl-2.1
5,340
(function($,v){ v=xe.getApp('validator')[0];if(!v)return; v.cast('ADD_RULE', ['signed_number', /-?[0-9]+/]); v.cast('ADD_FILTER',['insertModuleSetup', {'module_srls':{required:true},'module_category_srl':{rule:'number'},'layout_srl':{rule:'signed_number'}}]); v.cast('ADD_MESSAGE',['isnull','%s 값은 필수입니다.']); v.cast('ADD_MESSAGE',['outofrange','%s의 글자 수를 맞추어 주세요.']); v.cast('ADD_MESSAGE',['equalto','%s이(가) 잘못되었습니다.']); v.cast('ADD_MESSAGE',['invalid','%s의 값이 올바르지 않습니다.']); v.cast('ADD_MESSAGE',['invalid_email','%s의 값은 올바른 메일 주소가 아닙니다.']); v.cast('ADD_MESSAGE',['invalid_userid','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']); v.cast('ADD_MESSAGE',['invalid_user_id','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']); v.cast('ADD_MESSAGE',['invalid_homepage','%s의 형식이 잘못되었습니다.(예: http://www.xpressengine.com)']); v.cast('ADD_MESSAGE',['invalid_url','%s의 형식이 잘못되었습니다.(예: http://www.xpressengine.com)']); v.cast('ADD_MESSAGE',['invalid_korean','%s의 형식이 잘못되었습니다. 한글로만 입력해야 합니다.']); v.cast('ADD_MESSAGE',['invalid_korean_number','%s의 형식이 잘못되었습니다. 한글과 숫자로만 입력해야 합니다.']); v.cast('ADD_MESSAGE',['invalid_alpha','%s의 형식이 잘못되었습니다. 영문으로만 입력해야 합니다.']); v.cast('ADD_MESSAGE',['invalid_alpha_number','%s의 형식이 잘못되었습니다. 영문과 숫자로만 입력해야 합니다.']); v.cast('ADD_MESSAGE',['invalid_mid','%s의 형식이 잘못되었습니다. 첫 글자는 영문으로 시작해야 하며 \'영문+숫자+_\'로만 입력해야 합니다.']); v.cast('ADD_MESSAGE',['invalid_number','%s의 형식이 잘못되었습니다. 숫자로만 입력해야 합니다.']); })(jQuery);
umjinsun12/dngshin
files/cache/ruleset/a0eca23a020d7bad0734c31fc17645fb.ko.js
JavaScript
lgpl-2.1
1,970
/* this file is part of libccc, criawips' cairo-based canvas * * AUTHORS * Sven Herzberg <herzi@gnome-de.org> * * Copyright (C) 2005 Sven Herzberg * * This program 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. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 */ #ifndef FIFTEEN_GRID_H #define FIFTEEN_GRID_H #include <ccc/cc-rectangle.h> G_BEGIN_DECLS typedef struct _FifteenGrid FifteenGrid; typedef struct _CcRectangleClass FifteenGridClass; #define FIFTEEN_TYPE_GRID (fifteen_grid_get_type()) #define FIFTEEN_GRID(i) (G_TYPE_CHECK_INSTANCE_CAST((i), FIFTEEN_TYPE_GRID, FifteenGrid)) #define FIFTEEN_GRID_CLASS(c) (G_TYPE_CHECK_CLASS_CAST((c), FIFTEEN_TYPE_GRID, FifteenGridClass)) #define FIFTEEN_IS_GRID(i) (G_TYPE_CHECK_INSTANCE_TYPE((i), FIFTEEN_TYPE_GRID)) #define FIFTEEN_IS_GRID_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE((c), FIFTEEN_TYPE_GRID)) #define FIFTEEN_GRID_GET_CLASS(i) (G_TYPE_INSTANCE_GET_CLASS((i), FIFTEEN_TYPE_GRID, FifteenGridClass)) GType fifteen_grid_get_type(void); CcItem* fifteen_grid_new (PangoFontDescription* desc); void fifteen_grid_scramble(FifteenGrid* self); struct _FifteenGrid { CcRectangle base_instance; CcItem * elements[16]; PangoFontDescription* font_description; }; G_END_DECLS #endif /* !FIFTEEN_GRID_H */
herzi/ccc
demo/fifteen-grid.h
C
lgpl-2.1
1,971
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @package cms_lib * @subpackage filter * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: CompressInterface.php 387 2010-10-04 11:11:49Z llemoullec $ */ interface CMS_Filter_Compress_CompressInterface { /** * Compresses $value with the defined settings * * @param string $value Data to compress * @return string The compressed data */ public function compress($value); /** * Decompresses $value with the defined settings * * @param string $value Data to decompress * @return string The decompressed data */ public function decompress($value); /** * Return the adapter name * * @return string */ public function toString(); }
flamant-bleu-studio/aidoo_core
current_version/library/CMS/Filter/Compress/CompressInterface.php
PHP
lgpl-2.1
1,330
//* This file is part of Zapdos, an open-source //* application for the simulation of plasmas //* https://github.com/shannon-lab/zapdos //* //* Zapdos is powered by the MOOSE Framework //* https://www.mooseframework.org //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ElectronTemperatureDirichletBC.h" registerMooseObject("ZapdosApp", ElectronTemperatureDirichletBC); template <> InputParameters validParams<ElectronTemperatureDirichletBC>() { InputParameters params = validParams<NodalBC>(); params.addRequiredParam<Real>("value", "Value of the BC"); params.addRequiredCoupledVar("em", "The electron density."); params.addParam<Real>("penalty_value", 1.0, "The penalty value for the Dirichlet BC."); params.addClassDescription("Electron temperature boundary condition"); return params; } ElectronTemperatureDirichletBC::ElectronTemperatureDirichletBC(const InputParameters & parameters) : NodalBC(parameters), _em(coupledValue("em")), _em_id(coupled("em")), _value(getParam<Real>("value")), _penalty_value(getParam<Real>("penalty_value")) { } Real ElectronTemperatureDirichletBC::computeQpResidual() { return _penalty_value * (2.0 / 3 * std::exp(_u[_qp] - _em[_qp]) - _value); } Real ElectronTemperatureDirichletBC::computeQpJacobian() { return _penalty_value * (2.0 / 3 * std::exp(_u[_qp] - _em[_qp])); } Real ElectronTemperatureDirichletBC::computeQpOffDiagJacobian(unsigned int jvar) { if (jvar == _em_id) return _penalty_value * (-2.0 / 3 * std::exp(_u[_qp] - _em[_qp])); else return 0.; }
lindsayad/zapdos
src/bcs/ElectronTemperatureDirichletBC.C
C++
lgpl-2.1
1,621
/******************************************************************** * Description: motion.h * Data structures used throughout emc2. * * Author: * License: GPL Version 2 * System: Linux * * Copyright (c) 2004 All rights reserved * * Last change: ********************************************************************/ /* jmk says: This file is a mess! */ /* Misc ramblings: The terms axis and joint are used inconsistently throughout EMC. For all new code, the usages are as follows: axis - one of the nine degrees of freedom, x, y, z, a, b, c, u, v, w these refer to axes in Cartesian space, which may or may not match up with joints (see below). On Cartesian machines they do match up, but for hexapods, robots, and other non-Cartesian machines they don't. joint - one of the physical degrees of freedom of the machine these might be linear (leadscrews) or rotary (rotary tables, robot arm joints). There can be any number of joints. The kinematics code is responsible for translating from axis space to joint space and back. There are three main kinds of data needed by the motion controller 1) data shared with higher level stuff - commands, status, etc. 2) data that is local to the motion controller 3) data shared with lower level stuff - hal pins In addition, some internal data (2) should be shared for trouble shooting purposes, even though it is "internal" to the motion controller. Depending on the type of data, it can either be treated as type (1), and made available to the higher level code, or it can be treated as type (3), and made available to the hal, so that halscope can monitor it. This file should ONLY contain structures and declarations for type (1) items - those that are shared with higher level code. Type (2) items should be declared in mot_priv.h, along with type (3) items. In the interest of retaining my sanity, I'm not gonna attempt to move everything to its proper location yet.... However, all new items will be defined in the proper place, and some existing items may be moved from one struct definition to another. */ /* the following line can be used to control where some of the "internal" motion controller data is stored. By default, it is stored in staticlly allocated kernel memory. However, if STRUCTS_IN_SHMEM is defined, it will be stored in the emcmotStruct shared memory area, for debugging purposes. */ #define STRUCTS_IN_SHMEM #ifndef MOTION_H #define MOTION_H #include "posemath.h" /* PmCartesian, PmPose, pmCartMag() */ #include "emcpos.h" /* EmcPose */ #include "cubic.h" /* CUBIC_STRUCT, CUBIC_COEFF */ #include "emcmotcfg.h" /* EMCMOT_MAX_JOINTS */ #include "kinematics.h" #include "rtapi_limits.h" #include <stdarg.h> // define a special value to denote an invalid motion ID // NB: do not ever generate a motion id of MOTION_INVALID_ID // this should be really be tested for in command.c #define MOTION_INVALID_ID INT_MIN #define MOTION_ID_VALID(x) ((x) != MOTION_INVALID_ID) #ifdef __cplusplus extern "C" { #endif typedef struct _EMC_TELEOP_DATA { EmcPose currentVel; EmcPose currentAccel; EmcPose desiredVel; EmcPose desiredAccel; } EMC_TELEOP_DATA; /* This enum lists all the possible commands */ typedef enum { EMCMOT_ABORT = 1, /* abort all motion */ EMCMOT_AXIS_ABORT, /* abort one axis */ //FIXME-AJ: replace command name to EMCMOT_JOINT_ABORT EMCMOT_ENABLE, /* enable servos for active joints */ EMCMOT_DISABLE, /* disable servos for active joints */ EMCMOT_ENABLE_AMPLIFIER, /* enable amp outputs */ EMCMOT_DISABLE_AMPLIFIER, /* disable amp outputs */ EMCMOT_ENABLE_WATCHDOG, /* enable watchdog sound, parport */ EMCMOT_DISABLE_WATCHDOG, /* enable watchdog sound, parport */ EMCMOT_ACTIVATE_JOINT, /* make joint active */ EMCMOT_DEACTIVATE_JOINT, /* make joint inactive */ EMCMOT_PAUSE, /* pause motion */ EMCMOT_RESUME, /* resume motion */ EMCMOT_STEP, /* resume motion until id encountered */ EMCMOT_FREE, /* set mode to free (joint) motion */ EMCMOT_COORD, /* set mode to coordinated motion */ EMCMOT_TELEOP, /* set mode to teleop */ EMCMOT_SPINDLE_SCALE, /* set scale factor for spindle speed */ EMCMOT_SS_ENABLE, /* enable/disable scaling the spindle speed */ EMCMOT_FEED_SCALE, /* set scale factor for feedrate */ EMCMOT_RAPID_SCALE, /* set scale factor for rapids */ EMCMOT_FS_ENABLE, /* enable/disable scaling feedrate */ EMCMOT_FH_ENABLE, /* enable/disable feed_hold */ EMCMOT_AF_ENABLE, /* enable/disable adaptive feedrate */ EMCMOT_OVERRIDE_LIMITS, /* temporarily ignore limits until jog done */ EMCMOT_HOME, /* home a joint or all joints */ EMCMOT_UNHOME, /* unhome a joint or all joints*/ EMCMOT_JOG_CONT, /* continuous jog */ EMCMOT_JOG_INCR, /* incremental jog */ EMCMOT_JOG_ABS, /* absolute jog */ EMCMOT_SET_LINE, /* queue up a linear move */ EMCMOT_SET_CIRCLE, /* queue up a circular move */ EMCMOT_SET_TELEOP_VECTOR, /* Move at a given velocity but in world cartesian coordinates, not in joint space like EMCMOT_JOG_* */ EMCMOT_CLEAR_PROBE_FLAGS, /* clears probeTripped flag */ EMCMOT_PROBE, /* go to pos, stop if probe trips, record trip pos */ EMCMOT_RIGID_TAP, /* go to pos, with sync to spindle speed, then return to initial pos */ EMCMOT_SET_POSITION_LIMITS, /* set the joint position +/- limits */ EMCMOT_SET_BACKLASH, /* set the joint backlash */ EMCMOT_SET_MIN_FERROR, /* minimum following error, input units */ EMCMOT_SET_MAX_FERROR, /* maximum following error, input units */ EMCMOT_SET_VEL, /* set the velocity for subsequent moves */ EMCMOT_SET_VEL_LIMIT, /* set the max vel for all moves (tooltip) */ EMCMOT_SET_JOINT_VEL_LIMIT, /* set the max joint vel */ EMCMOT_SET_JOINT_ACC_LIMIT, /* set the max joint accel */ EMCMOT_SET_ACC, /* set the max accel for moves (tooltip) */ EMCMOT_SET_TERM_COND, /* set termination condition (stop, blend) */ EMCMOT_SET_NUM_AXES, /* set the number of joints */ //FIXME-AJ: function needs to get renamed EMCMOT_SET_WORLD_HOME, /* set pose for world home */ EMCMOT_SET_HOMING_PARAMS, /* sets joint homing parameters */ EMCMOT_SET_DEBUG, /* sets the debug level */ EMCMOT_SET_DOUT, /* sets or unsets a DIO, this can be imediate or synched with motion */ EMCMOT_SET_AOUT, /* sets or unsets a AIO, this can be imediate or synched with motion */ EMCMOT_SET_SPINDLESYNC, /* syncronize motion to spindle encoder */ EMCMOT_SPINDLE_ON, /* start the spindle */ EMCMOT_SPINDLE_OFF, /* stop the spindle */ EMCMOT_SPINDLE_INCREASE, /* spindle faster */ EMCMOT_SPINDLE_DECREASE, /* spindle slower */ EMCMOT_SPINDLE_BRAKE_ENGAGE, /* engage the spindle brake */ EMCMOT_SPINDLE_BRAKE_RELEASE, /* release the spindle brake */ EMCMOT_SPINDLE_ORIENT, /* orient the spindle */ EMCMOT_SET_MOTOR_OFFSET, /* set the offset between joint and motor */ EMCMOT_SET_JOINT_COMP, /* set a compensation triplet for a joint (nominal, forw., rev.) */ EMCMOT_SET_OFFSET, /* set tool offsets */ EMCMOT_SET_MAX_FEED_OVERRIDE, EMCMOT_SETUP_ARC_BLENDS, } cmd_code_t; /* this enum lists the possible results of a command */ typedef enum { EMCMOT_COMMAND_OK = 0, /* cmd honored */ EMCMOT_COMMAND_UNKNOWN_COMMAND, /* cmd not understood */ EMCMOT_COMMAND_INVALID_COMMAND, /* cmd can't be handled now */ EMCMOT_COMMAND_INVALID_PARAMS, /* bad cmd params */ EMCMOT_COMMAND_BAD_EXEC /* error trying to initiate */ } cmd_status_t; /* termination conditions for queued motions */ #define EMCMOT_TERM_COND_STOP 1 #define EMCMOT_TERM_COND_BLEND 2 #define EMCMOT_TERM_COND_TANGENT 3 /********************************* COMMAND STRUCTURE *********************************/ /* This is the command structure. There is one of these in shared memory, and all commands from higher level code come thru it. */ typedef struct emcmot_command_t { unsigned char head; /* flag count for mutex detect */ cmd_code_t command; /* command code (enum) */ int commandNum; /* increment this for new command */ double motor_offset; /* offset from joint to motor position */ double maxLimit; /* pos value for position limit, output */ double minLimit; /* neg value for position limit, output */ EmcPose pos; /* line/circle endpt, or teleop vector */ PmCartesian center; /* center for circle */ PmCartesian normal; /* normal vec for circle */ int turn; /* turns for circle or which rotary to unlock for a line */ double vel; /* max velocity */ double ini_maxvel; /* max velocity allowed by machine constraints (the ini file) */ int motion_type; /* this move is because of traverse, feed, arc, or toolchange */ double spindlesync; /* user units per spindle revolution, 0 = no sync */ double acc; /* max acceleration */ double backlash; /* amount of backlash */ int id; /* id for motion */ int termCond; /* termination condition */ double tolerance; /* tolerance for path deviation in CONTINUOUS mode */ int axis; /* which index to use for below */ //FIXME-AJ: replace with joint double scale; /* velocity scale or spindle_speed scale arg */ double offset; /* input, output, or home offset arg */ double home; /* joint home position */ double home_final_vel; /* joint velocity for moving from OFFSET to HOME */ double search_vel; /* home search velocity */ double latch_vel; /* home latch velocity */ int flags; /* homing config flags, other boolean args */ int home_sequence; /* order in homing sequence */ int volatile_home; /* joint should get unhomed when we get unhome -2 (generated by task upon estop, etc) */ double minFerror; /* min following error */ double maxFerror; /* max following error */ int wdWait; /* cycle to wait before toggling wd */ int debug; /* debug level, from DEBUG in .ini file */ unsigned char now, out, start, end; /* these are related to synched AOUT/DOUT. now=wether now or synched, out = which gets set, start=start value, end=end value */ unsigned char mode; /* used for turning overrides etc. on/off */ double comp_nominal, comp_forward, comp_reverse; /* compensation triplet, nominal, forward, reverse */ unsigned char probe_type; /* ~1 = error if probe operation is unsuccessful (ngc default) |1 = suppress error, report in # instead ~2 = move until probe trips (ngc default) |2 = move until probe clears */ EmcPose tool_offset; /* TLO */ double orientation; /* angle for spindle orient */ char direction; /* CANON_DIRECTION flag for spindle orient */ double timeout; /* of wait for spindle orient to complete */ unsigned char tail; /* flag count for mutex detect */ int arcBlendOptDepth; int arcBlendEnable; int arcBlendFallbackEnable; int arcBlendGapCycles; double arcBlendRampFreq; double arcBlendTangentKinkRatio; double maxFeedScale; } emcmot_command_t; /*! \todo FIXME - these packed bits might be replaced with chars memory is cheap, and being able to access them without those damn macros would be nice */ /* motion flag type */ typedef unsigned short EMCMOT_MOTION_FLAG; /* motion status flag structure-- looks like: MSB LSB v---------------v------------------v | | | | T | CE | C | IP | EN | ^---------------^------------------^ where: EN is 1 if calculations are enabled, 0 if not IP is 1 if all joints in position, 0 if not C is 1 if coordinated mode, 0 if in free mode CE is 1 if coordinated mode error, 0 if not T is 1 if we are in teleop mode. */ /* bit masks */ #define EMCMOT_MOTION_ENABLE_BIT 0x0001 #define EMCMOT_MOTION_INPOS_BIT 0x0002 #define EMCMOT_MOTION_COORD_BIT 0x0004 #define EMCMOT_MOTION_ERROR_BIT 0x0008 #define EMCMOT_MOTION_TELEOP_BIT 0x0010 /* joint flag type */ typedef unsigned short EMCMOT_JOINT_FLAG; /* joint status flag structure-- looks like: MSB LSB ----------v-----------------v--------------------v-------------------v | AF | FE | AH | HD | H | HS | NHL | PHL | - | - | ER | IP | AC | EN | ----------^-----------------^--------------------^-------------------^ x = unused where: EN is 1 if joint amplifier is enabled, 0 if not AC is 1 if joint is active for calculations, 0 if not IP is 1 if joint is in position, 0 if not (free mode only) ER is 1 if joint has an error, 0 if not PHL is 1 if joint is on maximum hardware limit, 0 if not NHL is 1 if joint is on minimum hardware limit, 0 if not HS is 1 if joint home switch is tripped, 0 if not H is 1 if joint is homing, 0 if not HD is 1 if joint has been homed, 0 if not AH is 1 if joint is at home position, 0 if not FE is 1 if joint exceeded following error, 0 if not AF is 1 if amplifier is faulted, 0 if not Suggestion: Split this in to an Error and a Status flag register.. Then a simple test on each of the two flags can be performed rather than testing each bit... Saving on a global per joint fault and ready status flag. */ /* bit masks */ #define EMCMOT_JOINT_ENABLE_BIT 0x0001 #define EMCMOT_JOINT_ACTIVE_BIT 0x0002 #define EMCMOT_JOINT_INPOS_BIT 0x0004 #define EMCMOT_JOINT_ERROR_BIT 0x0008 #define EMCMOT_JOINT_MAX_HARD_LIMIT_BIT 0x0040 #define EMCMOT_JOINT_MIN_HARD_LIMIT_BIT 0x0080 #define EMCMOT_JOINT_HOME_SWITCH_BIT 0x0100 #define EMCMOT_JOINT_HOMING_BIT 0x0200 #define EMCMOT_JOINT_HOMED_BIT 0x0400 /*! \todo FIXME - I'm not sure AT_HOME is being reported correctly. AT_HOME is cleared when you jog in free mode, but not if you do a coordinated move... perhaps that is the intended behavior. */ #define EMCMOT_JOINT_AT_HOME_BIT 0x0800 #define EMCMOT_JOINT_FERROR_BIT 0x1000 #define EMCMOT_JOINT_FAULT_BIT 0x2000 /*! \todo FIXME - the terms "teleop", "coord", and "free" are poorly documented. This is my feeble attempt to understand exactly what they mean. According to Fred, teleop is never used with machine tools, although that may not be true for machines with non-trivial kinematics. "coord", or coordinated mode, means that all the joints are synchronized, and move together as commanded by the higher level code. It is the normal mode when machining. In coordinated mode, commands are assumed to be in the cartesean reference frame, and if the machine is non-cartesean, the commands are translated by the kinematics to drive each joint in joint space as needed. "free" mode means commands are interpreted in joint space. It is used for jogging individual joints, although it does not preclude multiple joints moving at once (I think). Homing is also done in free mode, in fact machines with non-trivial kinematics must be homed before they can go into either coord or teleop mode. 'teleop' is what you probably want if you are 'jogging' a hexapod. The jog commands as implemented by the motion controller are joint jogs, which work in free mode. But if you want to jog a hexapod or similar machine along one particular cartesean axis, you need to operate more than one joint. That's what 'teleop' is for. */ /* compensation structures */ typedef struct { double nominal; /* nominal (command) position */ float fwd_trim; /* correction for forward movement */ float rev_trim; /* correction for reverse movement */ float fwd_slope; /* slopes between here and next pt */ float rev_slope; } emcmot_comp_entry_t; #define EMCMOT_COMP_SIZE 256 typedef struct { int entries; /* number of entries in the array */ emcmot_comp_entry_t *entry; /* current entry in array */ emcmot_comp_entry_t array[EMCMOT_COMP_SIZE+2]; /* +2 because array has -HUGE_VAL and +HUGE_VAL entries at the ends */ } emcmot_comp_t; /* motion controller states */ typedef enum { EMCMOT_MOTION_DISABLED = 0, EMCMOT_MOTION_FREE, EMCMOT_MOTION_TELEOP, EMCMOT_MOTION_COORD } motion_state_t; /* states for homing */ typedef enum { HOME_IDLE = 0, HOME_START, // 1 HOME_UNLOCK, // 2 HOME_UNLOCK_WAIT, // 3 HOME_INITIAL_BACKOFF_START, // 4 HOME_INITIAL_BACKOFF_WAIT, // 5 HOME_INITIAL_SEARCH_START, // 6 HOME_INITIAL_SEARCH_WAIT, // 7 HOME_SET_COARSE_POSITION, // 8 HOME_FINAL_BACKOFF_START, // 9 HOME_FINAL_BACKOFF_WAIT, // 10 HOME_RISE_SEARCH_START, // 11 HOME_RISE_SEARCH_WAIT, // 12 HOME_FALL_SEARCH_START, // 13 HOME_FALL_SEARCH_WAIT, // 14 HOME_SET_SWITCH_POSITION, // 15 HOME_INDEX_ONLY_START, // 16 HOME_INDEX_SEARCH_START, // 17 HOME_INDEX_SEARCH_WAIT, // 18 HOME_SET_INDEX_POSITION, // 19 HOME_FINAL_MOVE_START, // 20 HOME_FINAL_MOVE_WAIT, // 21 HOME_LOCK, // 22 HOME_LOCK_WAIT, // 23 HOME_FINISHED, // 24 HOME_ABORT // 25 } home_state_t; typedef enum { HOME_SEQUENCE_IDLE = 0, HOME_SEQUENCE_START, HOME_SEQUENCE_START_JOINTS, HOME_SEQUENCE_WAIT_JOINTS, } home_sequence_state_t; typedef enum { EMCMOT_ORIENT_NONE = 0, EMCMOT_ORIENT_IN_PROGRESS, EMCMOT_ORIENT_COMPLETE, EMCMOT_ORIENT_FAULTED, } orient_state_t; /* flags for homing */ #define HOME_IGNORE_LIMITS 1 #define HOME_USE_INDEX 2 #define HOME_IS_SHARED 4 #define HOME_UNLOCK_FIRST 8 /* flags for enabling spindle scaling, feed scaling, adaptive feed, and feed hold */ #define SS_ENABLED 0x01 #define FS_ENABLED 0x02 #define AF_ENABLED 0x04 #define FH_ENABLED 0x08 /* This structure contains all of the data associated with a single joint. Note that this structure does not need to be in shared memory (but it can, if desired for debugging reasons). The portions of this structure that are considered "status" and need to be made available to user space are copied to a much smaller struct called emcmot_joint_status_t which is located in shared memory. */ typedef struct { /* configuration info - changes rarely */ int type; /* 0 = linear, 1 = rotary */ double max_pos_limit; /* upper soft limit on joint pos */ double min_pos_limit; /* lower soft limit on joint pos */ double max_jog_limit; /* jog limits change when not homed */ double min_jog_limit; double vel_limit; /* upper limit of joint speed */ double acc_limit; /* upper limit of joint accel */ double min_ferror; /* zero speed following error limit */ double max_ferror; /* max speed following error limit */ double home_search_vel; /* dir/spd to look for home switch */ double home_final_vel; /* speed to travel from OFFSET to HOME position */ double home_latch_vel; /* dir/spd to latch switch/index pulse */ double home_offset; /* dir/dist from switch to home point */ double home; /* joint coordinate of home point */ int home_flags; /* flags for various homing options */ int volatile_home; /* joint should get unhomed when we get unhome -2 (generated by task upon estop, etc) */ double backlash; /* amount of backlash */ int home_sequence; /* Order in homing sequence */ emcmot_comp_t comp; /* leadscrew correction data */ /* status info - changes regularly */ /* many of these need to be made available to higher levels */ /* they can either be copied to the status struct, or an array of joint structs can be made part of the status */ EMCMOT_JOINT_FLAG flag; /* see above for bit details */ double coarse_pos; /* trajectory point, before interp */ double pos_cmd; /* commanded joint position */ double vel_cmd; /* comanded joint velocity */ double backlash_corr; /* correction for backlash */ double backlash_filt; /* filtered backlash correction */ double backlash_vel; /* backlash velocity variable */ double motor_pos_cmd; /* commanded position, with comp */ double motor_pos_fb; /* position feedback, with comp */ double pos_fb; /* position feedback, comp removed */ double ferror; /* following error */ double ferror_limit; /* limit depends on speed */ double ferror_high_mark; /* max following error */ double free_pos_cmd; /* position command for free mode TP */ double free_vel_lim; /* velocity limit for free mode TP */ int free_tp_enable; /* if zero, joint stops ASAP */ int free_tp_active; /* if non-zero, move in progress */ int kb_jog_active; /* non-zero during a keyboard jog */ int wheel_jog_active; /* non-zero during a wheel jog */ /* internal info - changes regularly, not usually accessed from user space */ CUBIC_STRUCT cubic; /* cubic interpolator data */ int on_pos_limit; /* non-zero if on limit */ int on_neg_limit; /* non-zero if on limit */ double home_sw_pos; /* latched position of home sw */ int home_pause_timer; /* used to delay between homing states */ int index_enable; /* current state of index enable pin */ home_state_t home_state; /* state machine for homing */ double motor_offset; /* diff between internal and motor pos, used to set position to zero during homing */ int old_jog_counts; /* prior value, used for deltas */ /* stuff moved from the other structs that might be needed (or might not!) */ double big_vel; /* used for "debouncing" velocity */ } emcmot_joint_t; /* This structure contains only the "status" data associated with a joint. "Status" data is that data that should be reported to user space on a continuous basis. An array of these structs is part of the main status structure, and is filled in with data copied from the emcmot_joint_t structs every servo period. For now this struct contains more data than it really needs, but paring it down will take time (and probably needs to be done one or two items at a time, with much testing). My main goal right now is to get get the large joint struct out of status. */ typedef struct { EMCMOT_JOINT_FLAG flag; /* see above for bit details */ double pos_cmd; /* commanded joint position */ double pos_fb; /* position feedback, comp removed */ double vel_cmd; /* current velocity */ double ferror; /* following error */ double ferror_high_mark; /* max following error */ /*! \todo FIXME - the following are not really "status", but taskintf.cc expects them to be in the status structure. I don't know how or if they are used by the user space code. Ideally they will be removed from here, but each one will need to be investigated individually. */ double backlash; /* amount of backlash */ double max_pos_limit; /* upper soft limit on joint pos */ double min_pos_limit; /* lower soft limit on joint pos */ double min_ferror; /* zero speed following error limit */ double max_ferror; /* max speed following error limit */ double home_offset; /* dir/dist from switch to home point */ } emcmot_joint_status_t; typedef struct { double speed; // spindle speed in RPMs double css_factor; double xoffset; int direction; // 0 stopped, 1 forward, -1 reverse int brake; // 0 released, 1 engaged int locked; // spindle lock engaged after orient int orient_fault; // fault code from motion.spindle-orient-fault int orient_state; // orient_state_t } spindle_status; /********************************* STATUS STRUCTURE *********************************/ /* This is the status structure. There is one of these in shared memory, and it reports motion controller status to higher level code in user space. For the most part, this structure contains higher level variables - low level stuff is made visible to the HAL and troubleshooting, etc, is done using the HAL oscilliscope. */ /*! \todo FIXME - this struct is broken into two parts... at the top are structure members that I understand, and that are needed for emc2. Other structure members follow. All the later ones need to be evaluated - either they move up, or they go away. */ typedef struct emcmot_status_t { unsigned char head; /* flag count for mutex detect */ /* these three are updated only when a new command is handled */ cmd_code_t commandEcho; /* echo of input command */ int commandNumEcho; /* echo of input command number */ cmd_status_t commandStatus; /* result of most recent command */ /* these are config info, updated when a command changes them */ double feed_scale; /* velocity scale factor for all motion but rapids */ double rapid_scale; /* velocity scale factor for rapids */ double spindle_scale; /* velocity scale factor for spindle speed */ unsigned char enables_new; /* flags for FS, SS, etc */ /* the above set is the enables in effect for new moves */ /* the rest are updated every cycle */ double net_feed_scale; /* net scale factor for all motion */ double net_spindle_scale; /* net scale factor for spindle */ unsigned char enables_queued; /* flags for FS, SS, etc */ /* the above set is the enables in effect for the currently executing move */ motion_state_t motion_state; /* operating state: FREE, COORD, etc. */ EMCMOT_MOTION_FLAG motionFlag; /* see above for bit details */ EmcPose carte_pos_cmd; /* commanded Cartesian position */ int carte_pos_cmd_ok; /* non-zero if command is valid */ EmcPose carte_pos_fb; /* actual Cartesian position */ int carte_pos_fb_ok; /* non-zero if feedback is valid */ EmcPose world_home; /* cartesean coords of home position */ int homing_active; /* non-zero if any joint is homing */ home_sequence_state_t homingSequenceState; emcmot_joint_status_t joint_status[EMCMOT_MAX_JOINTS]; /* all joint status data */ int on_soft_limit; /* non-zero if any joint is on soft limit */ int probeVal; /* debounced value of probe input */ int probeTripped; /* Has the probe signal changed since start of probe command? */ int probing; /* Currently looking for a probe signal? */ unsigned char probe_type; EmcPose probedPos; /* Axis positions stored as soon as possible after last probeTripped */ int spindle_index_enable; /* hooked to a canon encoder index-enable */ int spindleSync; /* we are doing spindle-synced motion */ double spindleRevs; /* position of spindle in revolutions */ double spindleSpeedIn; /* velocity of spindle in revolutions per minute */ spindle_status spindle; /* data types for spindle status */ int synch_di[EMCMOT_MAX_DIO]; /* inputs to the motion controller, queried by g-code */ int synch_do[EMCMOT_MAX_DIO]; /* outputs to the motion controller, queried by g-code */ double analog_input[EMCMOT_MAX_AIO]; /* inputs to the motion controller, queried by g-code */ double analog_output[EMCMOT_MAX_AIO]; /* outputs to the motion controller, queried by g-code */ /*! \todo FIXME - all structure members beyond this point are in limbo */ /* dynamic status-- changes every cycle */ unsigned int heartbeat; int config_num; /* incremented whenever configuration changed. */ double computeTime; int id; /* id for executing motion */ int depth; /* motion queue depth */ int activeDepth; /* depth of active blend elements */ int queueFull; /* Flag to indicate the tc queue is full */ int paused; /* Flag to signal motion paused */ int overrideLimitMask; /* non-zero means one or more limits ignored */ /* 1 << (joint-num*2) = ignore neg limit */ /* 2 << (joint-num*2) = ignore pos limit */ /* static status-- only changes upon input commands, e.g., config */ double vel; /* scalar max vel */ double acc; /* scalar max accel */ int level; int motionType; double distance_to_go; /* in this move */ EmcPose dtg; double current_vel; double requested_vel; unsigned int tcqlen; EmcPose tool_offset; int atspeed_next_feed; /* at next feed move, wait for spindle to be at speed */ int spindle_is_atspeed; /* hal input */ unsigned char tail; /* flag count for mutex detect */ } emcmot_status_t; /********************************* CONFIG STRUCTURE *********************************/ /* This is the config structure. This is currently in shared memory, but I have no idea why... there are commands to set most of the items in this structure. It seems we should either put the struct in private memory and manipulate it with commands, or we should put it in shared memory and manipulate it directly - not both. The structure contains static or rarely changed information that describes the machine configuration. later: I think I get it now - the struct is in shared memory so user space can read the config at any time, but commands are used to change the config so they only take effect when the realtime code processes the command. */ /*! \todo FIXME - this struct is broken into two parts... at the top are structure members that I understand, and that are needed for emc2. Other structure members follow. All the later ones need to be evaluated - either they move up, or they go away. */ typedef struct emcmot_config_t { unsigned char head; /* flag count for mutex detect */ /*! \todo FIXME - all structure members beyond this point are in limbo */ int config_num; /* Incremented everytime configuration changed, should match status.config_num */ int numJoints; /* The number of joints in the system (which must be between 1 and EMCMOT_MAX_JOINTS, inclusive). Allegedly, holds a copy of the global num_joints - seems daft to maintain duplicates ! */ double trajCycleTime; /* the rate at which the trajectory loop runs.... (maybe) */ double servoCycleTime; /* the rate of the servo loop - Not the same as the traj time */ int interpolationRate; /* grep control.c for an explanation.... approx line 50 */ double limitVel; /* scalar upper limit on vel */ KINEMATICS_TYPE kinematics_type; int debug; /* copy of DEBUG, from .ini file */ unsigned char tail; /* flag count for mutex detect */ int arcBlendOptDepth; int arcBlendEnable; int arcBlendFallbackEnable; int arcBlendGapCycles; double arcBlendRampFreq; double arcBlendTangentKinkRatio; double maxFeedScale; } emcmot_config_t; /********************************* INTERNAL STRUCTURE *********************************/ /* This is the internal structure. It contains stuff that is used internally by the motion controller that does not need to be in shared memory. It will wind up with a lot of the stuff that got tossed into the debug structure. FIXME - so far most if the stuff that was tossed in here got moved back out, maybe don't need it after all? */ typedef struct emcmot_internal_t { unsigned char head; /* flag count for mutex detect */ int probe_debounce_cntr; unsigned char tail; /* flag count for mutex detect */ } emcmot_internal_t; /* error structure - A ring buffer used to pass formatted printf stings to usr space */ typedef struct emcmot_error_t { unsigned char head; /* flag count for mutex detect */ char error[EMCMOT_ERROR_NUM][EMCMOT_ERROR_LEN]; int start; /* index of oldest error */ int end; /* index of newest error */ int num; /* number of items */ unsigned char tail; /* flag count for mutex detect */ } emcmot_error_t; /* function prototypes for emcmot code */ /* error ring buffer access functions */ extern int emcmotErrorInit(emcmot_error_t * errlog); extern int emcmotErrorPut(emcmot_error_t * errlog, const char *error); extern int emcmotErrorPutfv(emcmot_error_t * errlog, const char *fmt, va_list ap); extern int emcmotErrorPutf(emcmot_error_t * errlog, const char *fmt, ...); extern int emcmotErrorGet(emcmot_error_t * errlog, char *error); #ifdef __cplusplus } #endif #endif /* MOTION_H */
bmwiedemann/linuxcnc-mirror
src/emc/motion/motion.h
C
lgpl-2.1
32,030
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyliblo - Python bindings for the liblo OSC library # # Copyright (C) 2007-2011 Dominic Sacré <dominic.sacre@gmx.de> # # 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. # import unittest import re import time import sys import liblo def approx(a, b, e = 0.0002): return abs(a - b) < e def matchHost(host, regex): r = re.compile(regex) return r.match(host) != None class Arguments: def __init__(self, path, args, types, src, data): self.path = path self.args = args self.types = types self.src = src self.data = data class ServerTestCaseBase(unittest.TestCase): def setUp(self): self.cb = None def callback(self, path, args, types, src, data): self.cb = Arguments(path, args, types, src, data) def callback_dict(self, path, args, types, src, data): if self.cb == None: self.cb = { } self.cb[path] = Arguments(path, args, types, src, data) class ServerTestCase(ServerTestCaseBase): def setUp(self): ServerTestCaseBase.setUp(self) self.server = liblo.Server('1234') def tearDown(self): del self.server def testPort(self): assert self.server.get_port() == 1234 def testURL(self): assert matchHost(self.server.get_url(), 'osc\.udp://.*:1234/') def testSendInt(self): self.server.add_method('/foo', 'i', self.callback, "data") self.server.send('1234', '/foo', 123) assert self.server.recv() == True assert self.cb.path == '/foo' assert self.cb.args[0] == 123 assert self.cb.types == 'i' assert self.cb.data == "data" assert matchHost(self.cb.src.get_url(), 'osc\.udp://.*:1234/') def testSendBlob(self): self.server.add_method('/blob', 'b', self.callback) self.server.send('1234', '/blob', [4, 8, 15, 16, 23, 42]) assert self.server.recv() == True if sys.hexversion < 0x03000000: assert list(self.cb.args[0]) == [4, 8, 15, 16, 23, 42] else: assert self.cb.args[0] == b'\x04\x08\x0f\x10\x17\x2a' def testSendVarious(self): self.server.add_method('/blah', 'ihfdscb', self.callback) if sys.hexversion < 0x03000000: self.server.send(1234, '/blah', 123, 2**42, 123.456, 666.666, "hello", ('c', 'x'), (12, 34, 56)) else: self.server.send(1234, '/blah', 123, ('h', 2**42), 123.456, 666.666, "hello", ('c', 'x'), (12, 34, 56)) assert self.server.recv() == True assert self.cb.types == 'ihfdscb' assert len(self.cb.args) == len(self.cb.types) assert self.cb.args[0] == 123 assert self.cb.args[1] == 2**42 assert approx(self.cb.args[2], 123.456) assert approx(self.cb.args[3], 666.666) assert self.cb.args[4] == "hello" assert self.cb.args[5] == 'x' if sys.hexversion < 0x03000000: assert list(self.cb.args[6]) == [12, 34, 56] else: assert self.cb.args[6] == b'\x0c\x22\x38' def testSendOthers(self): self.server.add_method('/blubb', 'tmSTFNI', self.callback) self.server.send(1234, '/blubb', ('t', 666666.666), ('m', (1, 2, 3, 4)), ('S', 'foo'), True, ('F',), None, ('I',)) assert self.server.recv() == True assert self.cb.types == 'tmSTFNI' assert approx(self.cb.args[0], 666666.666) assert self.cb.args[1] == (1, 2, 3, 4) assert self.cb.args[2] == 'foo' assert self.cb.args[3] == True assert self.cb.args[4] == False assert self.cb.args[5] == None assert self.cb.args[6] == float('inf') def testSendMessage(self): self.server.add_method('/blah', 'is', self.callback) m = liblo.Message('/blah', 42, 'foo') self.server.send(1234, m) assert self.server.recv() == True assert self.cb.types == 'is' assert self.cb.args[0] == 42 assert self.cb.args[1] == 'foo' def testSendBundle(self): self.server.add_method('/foo', 'i', self.callback_dict) self.server.add_method('/bar', 's', self.callback_dict) self.server.send(1234, liblo.Bundle( liblo.Message('/foo', 123), liblo.Message('/bar', "blubb") )) assert self.server.recv(100) == True assert self.cb['/foo'].args[0] == 123 assert self.cb['/bar'].args[0] == "blubb" def testSendTimestamped(self): self.server.add_method('/blubb', 'i', self.callback) d = 1.23 t1 = time.time() b = liblo.Bundle(liblo.time() + d) b.add('/blubb', 42) self.server.send(1234, b) while not self.cb: self.server.recv(1) t2 = time.time() assert approx(t2 - t1, d, 0.01) def testSendInvalid(self): try: self.server.send(1234, '/blubb', ('x', 'y')) except TypeError as e: pass else: assert False def testRecvTimeout(self): t1 = time.time() assert self.server.recv(500) == False t2 = time.time() assert t2 - t1 < 0.666 def testRecvImmediate(self): t1 = time.time() assert self.server.recv(0) == False t2 = time.time() assert t2 - t1 < 0.01 class ServerCreationTestCase(unittest.TestCase): def testNoPermission(self): try: s = liblo.Server('22') except liblo.ServerError as e: pass else: assert False def testRandomPort(self): s = liblo.Server() assert 1024 <= s.get_port() <= 65535 def testPort(self): s = liblo.Server(1234) t = liblo.Server('5678') assert s.port == 1234 assert t.port == 5678 assert matchHost(s.url, 'osc\.udp://.*:1234/') def testPortProto(self): s = liblo.Server(1234, liblo.TCP) assert matchHost(s.url, 'osc\.tcp://.*:1234/') class ServerTCPTestCase(ServerTestCaseBase): def setUp(self): ServerTestCaseBase.setUp(self) self.server = liblo.Server('1234', liblo.TCP) def tearDown(self): del self.server def testSendReceive(self): self.server.add_method('/foo', 'i', self.callback) liblo.send(self.server.url, '/foo', 123) assert self.server.recv() == True assert self.cb.path == '/foo' assert self.cb.args[0] == 123 assert self.cb.types == 'i' def testNotReachable(self): try: self.server.send('osc.tcp://192.168.23.42:4711', '/foo', 23, 42) except IOError: pass else: assert False class ServerThreadTestCase(ServerTestCaseBase): def setUp(self): ServerTestCaseBase.setUp(self) self.server = liblo.ServerThread('1234') def tearDown(self): del self.server def testSendAndReceive(self): self.server.add_method('/foo', 'i', self.callback) self.server.send('1234', '/foo', 42) self.server.start() time.sleep(0.2) self.server.stop() assert self.cb.args[0] == 42 class DecoratorTestCase(unittest.TestCase): class TestServer(liblo.Server): def __init__(self): liblo.Server.__init__(self, 1234) @liblo.make_method('/foo', 'ibm') def foo_cb(self, path, args, types, src, data): self.cb = Arguments(path, args, types, src, data) def setUp(self): self.server = self.TestServer() def tearDown(self): del self.server def testSendReceive(self): liblo.send(1234, '/foo', 42, ('b', [4, 8, 15, 16, 23, 42]), ('m', (6, 6, 6, 0))) assert self.server.recv() == True assert self.server.cb.path == '/foo' assert len(self.server.cb.args) == 3 class AddressTestCase(unittest.TestCase): def testPort(self): a = liblo.Address(1234) b = liblo.Address('5678') assert a.port == 1234 assert b.port == 5678 assert a.url == 'osc.udp://localhost:1234/' def testUrl(self): a = liblo.Address('osc.udp://foo:1234/') assert a.url == 'osc.udp://foo:1234/' assert a.hostname == 'foo' assert a.port == 1234 assert a.protocol == liblo.UDP def testHostPort(self): a = liblo.Address('foo', 1234) assert a.url == 'osc.udp://foo:1234/' def testHostPortProto(self): a = liblo.Address('foo', 1234, liblo.TCP) assert a.url == 'osc.tcp://foo:1234/' if __name__ == "__main__": unittest.main()
gesellkammer/pyliblo
test/unit.py
Python
lgpl-2.1
8,818
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library 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. * * 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * 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 * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1.1.1 $ | | Description: | This file defines classes for describing or extracting | detail information about a node kit. | | | The details contains a pointer to the node, a pointer to the | child part within the node, and the name of the child part. | | Classes: | SoNodeKitDetail | | Author(s) : Paul Isaacs | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ package jscenegraph.database.inventor.details; import jscenegraph.database.inventor.SbName; import jscenegraph.database.inventor.SoType; import jscenegraph.database.inventor.nodes.SoNode; import jscenegraph.nodekits.inventor.nodekits.SoBaseKit; /** * @author Yves Boyadjian * */ //////////////////////////////////////////////////////////////////////////////// //! Stores detail information about a nodekit. /*! \class SoNodeKitDetail \ingroup Details This class contains detail information about a nodekit. This consists of a pointer to the nodekit, a pointer to the child part within the nodekit, and the name of the child part. During a pick action, each nodekit along the picked path creates its own SoNodeKitDetail. Together, the full set of details gives you complete picture of the pickpath. Since nodekits have hidden children (See the reference page for SoBaseKit), a regular SoPath ends at the topmost nodekit in the path. If you cast the pickpath from an SoPath pointer to an SoNodeKitPath pointer, you can then retrieve all nodekits along the path and examine their corresponding details. \par See Also \par SoBaseKit, SoNodeKitPath, SoDetail, SoPickedPoint */ //////////////////////////////////////////////////////////////////////////////// public class SoNodeKitDetail extends SoDetail { private static final SoType classTypeId = new SoType(); //!< Type identifier //! Returns type identifier for this class. public static SoType getClassTypeId() { return new SoType(classTypeId); } /* (non-Javadoc) * @see jscenegraph.database.inventor.details.SoDetail#getTypeId() */ @Override public SoType getTypeId() { return classTypeId; } protected SoBaseKit myNodeKit; protected SoNode myPart; protected final SbName myPartName = new SbName(); //////////////////////////////////////////////////////////////////////// // // Description: // Constructors. // // Use: public // //////////////////////////////////////////////////////////////////////// public SoNodeKitDetail() { myNodeKit = null; myPart = null; myPartName.copyFrom(""); } //////////////////////////////////////////////////////////////////////// // // Description: // Destructor // // Use: public public void destructor() // //////////////////////////////////////////////////////////////////////// { if ( myNodeKit !=null) myNodeKit.unref(); if ( myPart !=null) myPart.unref(); super.destructor(); } //! Returns an instance that is a copy of this instance. The caller //! is responsible for deleting the copy when done. /* (non-Javadoc) * @see jscenegraph.database.inventor.details.SoDetail#copy() */ @Override public SoDetail copy() { SoNodeKitDetail newDetail = new SoNodeKitDetail(); newDetail.myNodeKit = myNodeKit; newDetail.myPart = myPart; newDetail.myPartName.copyFrom(myPartName); if (myNodeKit != null) myNodeKit.ref(); if (myPart != null) myPart.ref(); return newDetail; } //////////////////////////////////////////////////////////////////////// // // Description: // Set the the nodekit. // public void setNodeKit( SoBaseKit theNodeKit ) // //////////////////////////////////////////////////////////////////////// { theNodeKit.ref(); if ( myNodeKit != null) myNodeKit.unref(); myNodeKit = theNodeKit; } //////////////////////////////////////////////////////////////////////// // // Description: // Set the the part node within the nodekit. // public void setPart( SoNode thePart ) // //////////////////////////////////////////////////////////////////////// { thePart.ref(); if ( myPart != null) myPart.unref(); myPart = thePart; } public void setPartName( final SbName theName ) { myPartName.copyFrom(theName); } //////////////////////////////////////////////////////////////////////// // // Class initialization // // SoINTERNAL public // public static void initClass() // //////////////////////////////////////////////////////////////////////// { //SO_DETAIL_INIT_CLASS(SoNodeKitDetail.class, SoDetail.class); classTypeId.copyFrom(SoType.createType(SoDetail.getClassTypeId(), new SbName("SoNodeKitDetail"), null)); } }
YvesBoyadjian/jSceneGraph
src/jscenegraph/database/inventor/details/SoNodeKitDetail.java
Java
lgpl-2.1
6,560
package fr.toss.common.player.classes; import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; import fr.toss.common.command.ChatColor; import fr.toss.common.player.spells.rogue.Critic_1; import fr.toss.common.player.spells.rogue.FeatherFalling_6; import fr.toss.common.player.spells.rogue.Invisible_3; import fr.toss.common.player.spells.rogue.Poison_4; import fr.toss.common.player.spells.rogue.Speed_2; import fr.toss.common.player.spells.rogue.Vision_5; public class ClasseFusilier extends Classe { public ClasseFusilier() { super(); } @Override public String getName() { return I18n.format("Fusilier"); } @Override public ChatColor getColor() { return ChatColor.YELLOW; } @Override /** definis tous les sorts de la classe */ public void defineClasseSpells() { this.CLASSE_SPELL.clear(); this.CLASSE_SPELL.add(new Critic_1()); this.CLASSE_SPELL.add(new Speed_2()); this.CLASSE_SPELL.add(new Invisible_3()); this.CLASSE_SPELL.add(new Poison_4()); this.CLASSE_SPELL.add(new Vision_5()); this.CLASSE_SPELL.add(new FeatherFalling_6()); } @Override public EnumType getType() { return EnumType.DPS; } @Override public int getBaseEnergyRegen() { return 1; } @Override public ResourceLocation getTexture() { return (Fusilier); } }
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/common/player/classes/ClasseFusilier.java
Java
lgpl-2.1
1,330
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.jpa.test.graphs; import javax.persistence.Entity; import javax.persistence.EntityGraph; import javax.persistence.EntityManager; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Subgraph; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.TypedQuery; import java.util.Date; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.TestForIssue; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * @author Baris Cubukcuoglu */ public class EntityGraphUsingFetchGraphTest extends BaseEntityManagerFunctionalTestCase { @Override protected Class<?>[] getAnnotatedClasses() { return new Class[] {CustomerOrder.class, OrderPosition.class, Product.class, Address.class}; } @Test @TestForIssue( jiraKey = "HHH-9392") public void fetchSubGraphFromSubgraph() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Address address = new Address(); address.city = "TestCity"; CustomerOrder customerOrder = new CustomerOrder(); customerOrder.shippingAddress = address; Product product = new Product(); OrderPosition orderPosition = new OrderPosition(); orderPosition.product = product; customerOrder.orderPosition = orderPosition; em.persist( address ); em.persist( orderPosition ); em.persist( product ); em.persist( customerOrder ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); final EntityGraph<CustomerOrder> entityGraph = em.createEntityGraph( CustomerOrder.class ); //entityGraph.addAttributeNodes( "shippingAddress", "orderDate" ); entityGraph.addAttributeNodes( "shippingAddress" ); final Subgraph<OrderPosition> orderProductsSubgraph = entityGraph.addSubgraph( "orderPosition" ); //orderProductsSubgraph.addAttributeNodes( "amount" ); final Subgraph<Product> productSubgraph = orderProductsSubgraph.addSubgraph( "product" ); //productSubgraph.addAttributeNodes( "productName" ); TypedQuery<CustomerOrder> query = em.createQuery( "SELECT o FROM EntityGraphUsingFetchGraphTest$CustomerOrder o", CustomerOrder.class ); query.setHint( "javax.persistence.loadgraph", entityGraph ); final List<CustomerOrder> results = query.getResultList(); assertTrue( Hibernate.isInitialized( results ) ); em.getTransaction().commit(); em.close(); } @Test @TestForIssue( jiraKey = "HHH-9392") public void fetchAttributeNodeFromSubgraph() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Address address = new Address(); address.city = "TestCity"; CustomerOrder customerOrder = new CustomerOrder(); customerOrder.shippingAddress = address; Product product = new Product(); OrderPosition orderPosition = new OrderPosition(); orderPosition.product = product; customerOrder.orderPosition = orderPosition; em.persist( address ); em.persist( orderPosition ); em.persist( product ); em.persist( customerOrder ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); final EntityGraph<CustomerOrder> entityGraph = em.createEntityGraph( CustomerOrder.class ); entityGraph.addAttributeNodes( "shippingAddress", "orderDate" ); entityGraph.addAttributeNodes( "shippingAddress" ); final Subgraph<OrderPosition> orderProductsSubgraph = entityGraph.addSubgraph( "orderPosition" ); orderProductsSubgraph.addAttributeNodes( "amount" ); orderProductsSubgraph.addAttributeNodes( "product" ); final Subgraph<Product> productSubgraph = orderProductsSubgraph.addSubgraph( "product" ); productSubgraph.addAttributeNodes( "productName" ); TypedQuery<CustomerOrder> query = em.createQuery( "SELECT o FROM EntityGraphUsingFetchGraphTest$CustomerOrder o", CustomerOrder.class ); query.setHint( "javax.persistence.loadgraph", entityGraph ); final List<CustomerOrder> results = query.getResultList(); assertTrue( Hibernate.isInitialized( results ) ); em.getTransaction().commit(); em.close(); } @Test @TestForIssue( jiraKey = "HHH-9392") public void fetchUsingHql() { // This test is here only for comparison with results from fetchAttributeNodeFromSubgraph. // At the time this was written, the generated SQL from the HQL is the same as that generated with the // query hint in fetchAttributeNodeFromSubgraph. I am leaving this here for future debugging purposes. EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Address address = new Address(); address.city = "TestCity"; CustomerOrder customerOrder = new CustomerOrder(); customerOrder.shippingAddress = address; Product product = new Product(); OrderPosition orderPosition = new OrderPosition(); orderPosition.product = product; customerOrder.orderPosition = orderPosition; em.persist( address ); em.persist( orderPosition ); em.persist( product ); em.persist( customerOrder ); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); TypedQuery<CustomerOrder> query = em.createQuery( "SELECT o FROM EntityGraphUsingFetchGraphTest$CustomerOrder o left join fetch o.orderPosition pos left join fetch pos.product left join fetch o.shippingAddress", CustomerOrder.class ); final List<CustomerOrder> results = query.getResultList(); assertTrue( Hibernate.isInitialized( results ) ); em.getTransaction().commit(); em.close(); } @Entity @Table(name = "customerOrder") public static class CustomerOrder { @Id @GeneratedValue public Long id; @OneToOne public OrderPosition orderPosition; @Temporal(TemporalType.TIMESTAMP) public Date orderDate; @OneToOne public Address shippingAddress; } @Entity @Table(name = "address") public static class Address { @Id @GeneratedValue public Long id; public String city; } @Entity @Table(name = "orderPosition") public static class OrderPosition { @Id @GeneratedValue public Long id; public Integer amount; @ManyToOne @JoinColumn(name = "product") public Product product; } @Entity @Table(name = "product") public static class Product { @Id @GeneratedValue public Long id; public String productName; } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/graphs/EntityGraphUsingFetchGraphTest.java
Java
lgpl-2.1
6,746
//////////////////////////////////////////////////////////////// // // Copyright (C) 2005 Affymetrix, Inc. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License (version 2) as // published by the Free Software Foundation. // // 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 // //////////////////////////////////////////////////////////////// #ifndef __SDKSTATSTEST_H_ #define __SDKSTATSTEST_H_ #include <cppunit/extensions/HelperMacros.h> class SdkStatsTest : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE( SdkStatsTest ); CPPUNIT_TEST(test_pnorm); CPPUNIT_TEST(test_psignrank); CPPUNIT_TEST(test_signedRankTest); CPPUNIT_TEST(test_pwilcox); CPPUNIT_TEST(test_ranksumTest); CPPUNIT_TEST(test_uprob); CPPUNIT_TEST(test_chisqrprob); CPPUNIT_TEST(test_PearsonCorrelation); CPPUNIT_TEST(test_CalcHWEqPValue); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void test_pnorm(); void test_psignrank(); void test_signedRankTest(); void test_pwilcox(); void test_ranksumTest(); void test_uprob(); void test_chisqrprob(); void test_PearsonCorrelation(); void test_CalcHWEqPValue(); }; #endif // __SDKSTATSTEST_H_
einon/affymetrix-power-tools
sdk/stats/CPPTest/SdkStatsTest.h
C
lgpl-2.1
1,675
<?php /** * ALIPAY API: alipay.marketing.cashvoucher.template.modify request * * @author auto create * @since 1.0, 2017-06-19 11:27:47 */ class AlipayMarketingCashvoucherTemplateModifyRequest { /** * 修改资金券模板 **/ private $bizContent; private $apiParas = array(); private $terminalType; private $terminalInfo; private $prodCode; private $apiVersion="1.0"; private $notifyUrl; private $returnUrl; private $needEncrypt=false; public function setBizContent($bizContent) { $this->bizContent = $bizContent; $this->apiParas["biz_content"] = $bizContent; } public function getBizContent() { return $this->bizContent; } public function getApiMethodName() { return "alipay.marketing.cashvoucher.template.modify"; } public function setNotifyUrl($notifyUrl) { $this->notifyUrl=$notifyUrl; } public function getNotifyUrl() { return $this->notifyUrl; } public function setReturnUrl($returnUrl) { $this->returnUrl=$returnUrl; } public function getReturnUrl() { return $this->returnUrl; } public function getApiParas() { return $this->apiParas; } public function getTerminalType() { return $this->terminalType; } public function setTerminalType($terminalType) { $this->terminalType = $terminalType; } public function getTerminalInfo() { return $this->terminalInfo; } public function setTerminalInfo($terminalInfo) { $this->terminalInfo = $terminalInfo; } public function getProdCode() { return $this->prodCode; } public function setProdCode($prodCode) { $this->prodCode = $prodCode; } public function setApiVersion($apiVersion) { $this->apiVersion=$apiVersion; } public function getApiVersion() { return $this->apiVersion; } public function setNeedEncrypt($needEncrypt) { $this->needEncrypt=$needEncrypt; } public function getNeedEncrypt() { return $this->needEncrypt; } }
ddvphp/alipay
org/aop/request/AlipayMarketingCashvoucherTemplateModifyRequest.php
PHP
lgpl-2.1
1,931
#pragma ident "$Id$" /** * @file BELogEntry.hpp * Record the unique identifying information associated * with a Broadcast Ephemeris, allow it to be ordered (i.e. map support) * and provide a string output capability. */ //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2007, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #ifndef GPSTK_BELOGENTRY_HPP #define GPSTK_BELOGENTRY_HPP #include "EngEphemeris.hpp" namespace gpstk { class BELogEntry { public: /// Default constructor BELogEntry( const gpstk::EngEphemeris ee ); /// Destructor virtual ~BELogEntry() {} std::string getStr() const; gpstk::DayTime getHOW() const; void increment(); unsigned long getKey() const; static const std::string header; protected: DayTime HOWSF1; DayTime Toe; int PRN_ID; int IODC; int count; unsigned long key; }; // class BELogEntry } // namespace #endif
ianmartin/GPSTk
apps/MDPtools/BELogEntry.hpp
C++
lgpl-2.1
2,532
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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. */ /** * @constructor * @implements {WebInspector.TabbedEditorContainerDelegate} * @implements {WebInspector.ContextMenu.Provider} * @extends {WebInspector.Panel} * @param {WebInspector.Workspace=} workspaceForTest */ WebInspector.ScriptsPanel = function(workspaceForTest) { WebInspector.Panel.call(this, "scripts"); this.registerRequiredCSS("scriptsPanel.css"); WebInspector.settings.pauseOnExceptionStateString = WebInspector.settings.createSetting("pauseOnExceptionStateString", WebInspector.ScriptsPanel.PauseOnExceptionsState.DontPauseOnExceptions); WebInspector.settings.navigatorWasOnceHidden = WebInspector.settings.createSetting("navigatorWasOnceHidden", false); WebInspector.settings.debuggerSidebarHidden = WebInspector.settings.createSetting("debuggerSidebarHidden", false); this._workspace = workspaceForTest || WebInspector.workspace; function viewGetter() { return this.visibleView; } WebInspector.GoToLineDialog.install(this, viewGetter.bind(this)); var helpSection = WebInspector.shortcutsScreen.section(WebInspector.UIString("Sources Panel")); this.debugToolbar = this._createDebugToolbar(helpSection); const initialDebugSidebarWidth = 225; const maximalDebugSidebarWidthPercent = 50; this.createSplitView(this.element, WebInspector.SplitView.SidebarPosition.Right, initialDebugSidebarWidth); this.splitView.element.id = "scripts-split-view"; this.splitView.minimalSidebarWidth = Preferences.minScriptsSidebarWidth; this.splitView.minimalMainWidthPercent = 100 - maximalDebugSidebarWidthPercent; this.sidebarElement.appendChild(this.debugToolbar); this.debugSidebarResizeWidgetElement = document.createElement("div"); this.debugSidebarResizeWidgetElement.id = "scripts-debug-sidebar-resizer-widget"; this.splitView.installResizer(this.debugSidebarResizeWidgetElement); // Create scripts navigator const initialNavigatorWidth = 225; const minimalViewsContainerWidthPercent = 50; this.editorView = new WebInspector.SplitView(WebInspector.SplitView.SidebarPosition.Left, "scriptsPanelNavigatorSidebarWidth", initialNavigatorWidth); this.editorView.element.tabIndex = 0; this.editorView.minimalSidebarWidth = Preferences.minScriptsSidebarWidth; this.editorView.minimalMainWidthPercent = minimalViewsContainerWidthPercent; this.editorView.show(this.splitView.mainElement); this._navigator = new WebInspector.ScriptsNavigator(); this._navigator.view.show(this.editorView.sidebarElement); this._editorContainer = new WebInspector.TabbedEditorContainer(this, "previouslyViewedFiles"); this._editorContainer.show(this.editorView.mainElement); this._navigatorController = new WebInspector.NavigatorOverlayController(this.editorView, this._navigator.view, this._editorContainer.view); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ScriptSelected, this._scriptSelected, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.SnippetCreationRequested, this._snippetCreationRequested, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ItemRenamingRequested, this._itemRenamingRequested, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.FileRenamed, this._fileRenamed, this); this._editorContainer.addEventListener(WebInspector.TabbedEditorContainer.Events.EditorSelected, this._editorSelected, this); this._editorContainer.addEventListener(WebInspector.TabbedEditorContainer.Events.EditorClosed, this._editorClosed, this); this.splitView.mainElement.appendChild(this.debugSidebarResizeWidgetElement); this.sidebarPanes = {}; this.sidebarPanes.watchExpressions = new WebInspector.WatchExpressionsSidebarPane(); this.sidebarPanes.callstack = new WebInspector.CallStackSidebarPane(); this.sidebarPanes.scopechain = new WebInspector.ScopeChainSidebarPane(); this.sidebarPanes.jsBreakpoints = new WebInspector.JavaScriptBreakpointsSidebarPane(WebInspector.breakpointManager, this._showSourceLine.bind(this)); this.sidebarPanes.domBreakpoints = WebInspector.domBreakpointsSidebarPane; this.sidebarPanes.xhrBreakpoints = new WebInspector.XHRBreakpointsSidebarPane(); this.sidebarPanes.eventListenerBreakpoints = new WebInspector.EventListenerBreakpointsSidebarPane(); if (Preferences.exposeWorkersInspection && !WebInspector.WorkerManager.isWorkerFrontend()) { WorkerAgent.setWorkerInspectionEnabled(true); this.sidebarPanes.workerList = new WebInspector.WorkersSidebarPane(WebInspector.workerManager); } this._debugSidebarContentsElement = document.createElement("div"); this._debugSidebarContentsElement.id = "scripts-debug-sidebar-contents"; this.sidebarElement.appendChild(this._debugSidebarContentsElement); for (var pane in this.sidebarPanes) this._debugSidebarContentsElement.appendChild(this.sidebarPanes[pane].element); this.sidebarPanes.callstack.expanded = true; this.sidebarPanes.scopechain.expanded = true; this.sidebarPanes.jsBreakpoints.expanded = true; this.sidebarPanes.callstack.registerShortcuts(helpSection, this.registerShortcut.bind(this)); var evaluateInConsoleShortcut = WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.Ctrl); helpSection.addKey(evaluateInConsoleShortcut.name, WebInspector.UIString("Evaluate selection in console")); this.registerShortcut(evaluateInConsoleShortcut.key, this._evaluateSelectionInConsole.bind(this)); var outlineShortcut = WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta | WebInspector.KeyboardShortcut.Modifiers.Shift); helpSection.addKey(outlineShortcut.name, WebInspector.UIString("Go to member")); this.registerShortcut(outlineShortcut.key, this._showOutlineDialog.bind(this)); var createBreakpointShortcut = WebInspector.KeyboardShortcut.makeDescriptor("b", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta); helpSection.addKey(createBreakpointShortcut.name, WebInspector.UIString("Toggle breakpoint")); this.registerShortcut(createBreakpointShortcut.key, this._toggleBreakpoint.bind(this)); var panelEnablerHeading = WebInspector.UIString("You need to enable debugging before you can use the Scripts panel."); var panelEnablerDisclaimer = WebInspector.UIString("Enabling debugging will make scripts run slower."); var panelEnablerButton = WebInspector.UIString("Enable Debugging"); this.panelEnablerView = new WebInspector.PanelEnablerView("scripts", panelEnablerHeading, panelEnablerDisclaimer, panelEnablerButton); this.panelEnablerView.addEventListener("enable clicked", this.enableDebugging, this); this.enableToggleButton = new WebInspector.StatusBarButton("", "enable-toggle-status-bar-item"); this.enableToggleButton.addEventListener("click", this.toggleDebugging, this); if (!Capabilities.debuggerCausesRecompilation) this.enableToggleButton.element.addStyleClass("hidden"); this._pauseOnExceptionButton = new WebInspector.StatusBarButton("", "scripts-pause-on-exceptions-status-bar-item", 3); this._pauseOnExceptionButton.addEventListener("click", this._togglePauseOnExceptions, this); this._toggleFormatSourceButton = new WebInspector.StatusBarButton(WebInspector.UIString("Pretty print"), "scripts-toggle-pretty-print-status-bar-item"); this._toggleFormatSourceButton.toggled = false; this._toggleFormatSourceButton.addEventListener("click", this._toggleFormatSource, this); this._scriptViewStatusBarItemsContainer = document.createElement("div"); this._scriptViewStatusBarItemsContainer.style.display = "inline-block"; this._debuggerEnabled = !Capabilities.debuggerCausesRecompilation; this._installDebuggerSidebarController(); this._sourceFramesByUISourceCode = new Map(); this._reset(false); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasEnabled, this._debuggerWasEnabled, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasDisabled, this._debuggerWasDisabled, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.CallFrameSelected, this._callFrameSelected, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ConsoleCommandEvaluatedInSelectedCallFrame, this._consoleCommandEvaluatedInSelectedCallFrame, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ExecutionLineChanged, this._executionLineChanged, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.BreakpointsActiveStateChanged, this._breakpointsActiveStateChanged, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._handleUISourceCodeAdded, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeReplaced, this._uiSourceCodeReplaced, this); this._workspace.addEventListener(WebInspector.UISourceCodeProvider.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); this._workspace.addEventListener(WebInspector.Workspace.Events.WorkspaceReset, this._reset.bind(this, false), this); var enableDebugger = !Capabilities.debuggerCausesRecompilation || WebInspector.settings.debuggerEnabled.get(); if (enableDebugger) WebInspector.debuggerModel.enableDebugger(); WebInspector.advancedSearchController.registerSearchScope(new WebInspector.ScriptsSearchScope(this._workspace)); WebInspector.ContextMenu.registerProvider(this); } // Keep these in sync with WebCore::ScriptDebugServer WebInspector.ScriptsPanel.PauseOnExceptionsState = { DontPauseOnExceptions : "none", PauseOnAllExceptions : "all", PauseOnUncaughtExceptions: "uncaught" }; WebInspector.ScriptsPanel.prototype = { get toolbarItemLabel() { return WebInspector.UIString("Sources"); }, get statusBarItems() { return [this.enableToggleButton.element, this._pauseOnExceptionButton.element, this._toggleFormatSourceButton.element, this._scriptViewStatusBarItemsContainer]; }, defaultFocusedElement: function() { return this._navigator.view.defaultFocusedElement(); }, get paused() { return this._paused; }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); this._debugSidebarContentsElement.insertBefore(this.sidebarPanes.domBreakpoints.element, this.sidebarPanes.xhrBreakpoints.element); this.sidebarPanes.watchExpressions.show(); this._navigatorController.wasShown(); }, willHide: function() { WebInspector.Panel.prototype.willHide.call(this); WebInspector.closeViewInDrawer(); }, /** * @param {WebInspector.Event} event */ _handleUISourceCodeAdded: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data; if (this._toggleFormatSourceButton.toggled) uiSourceCode.setFormatted(true); this._uiSourceCodeAdded(uiSourceCode); }, _loadUISourceCodes: function() { var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) this._uiSourceCodeAdded(uiSourceCodes[i]); }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _uiSourceCodeAdded: function(uiSourceCode) { this._addUISourceCode(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _addUISourceCode: function(uiSourceCode) { this._navigator.addUISourceCode(uiSourceCode); this._editorContainer.addUISourceCode(uiSourceCode); }, _uiSourceCodeRemoved: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data; this._editorContainer.removeUISourceCode(uiSourceCode); this._navigator.removeUISourceCode(uiSourceCode); this._removeSourceFrame(uiSourceCode); }, _consoleCommandEvaluatedInSelectedCallFrame: function(event) { this.sidebarPanes.scopechain.update(WebInspector.debuggerModel.selectedCallFrame()); }, _debuggerPaused: function(event) { var details = /** @type {WebInspector.DebuggerPausedDetails} */ event.data; this._paused = true; this._waitingToPause = false; this._stepping = false; this._updateDebuggerButtons(); WebInspector.inspectorView.setCurrentPanel(this); this.sidebarPanes.callstack.update(details.callFrames); if (details.reason === WebInspector.DebuggerModel.BreakReason.DOM) { this.sidebarPanes.domBreakpoints.highlightBreakpoint(details.auxData); function didCreateBreakpointHitStatusMessage(element) { this.sidebarPanes.callstack.setStatus(element); } this.sidebarPanes.domBreakpoints.createBreakpointHitStatusMessage(details.auxData, didCreateBreakpointHitStatusMessage.bind(this)); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.EventListener) { var eventName = details.auxData.eventName; this.sidebarPanes.eventListenerBreakpoints.highlightBreakpoint(details.auxData.eventName); var eventNameForUI = WebInspector.EventListenerBreakpointsSidebarPane.eventNameForUI(eventName); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a \"%s\" Event Listener.", eventNameForUI)); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.XHR) { this.sidebarPanes.xhrBreakpoints.highlightBreakpoint(details.auxData["breakpointURL"]); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a XMLHttpRequest.")); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.Exception) { this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on exception: '%s'.", details.auxData.description)); } else { function didGetUILocation(uiLocation) { var breakpoint = WebInspector.breakpointManager.findBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber); if (!breakpoint) return; this.sidebarPanes.jsBreakpoints.highlightBreakpoint(breakpoint); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a JavaScript breakpoint.")); } details.callFrames[0].createLiveLocation(didGetUILocation.bind(this)); } this._showDebuggerSidebar(); this._toggleDebuggerSidebarButton.disabled = true; window.focus(); InspectorFrontendHost.bringToFront(); }, _debuggerResumed: function() { this._paused = false; this._waitingToPause = false; this._stepping = false; this._clearInterface(); this._toggleDebuggerSidebarButton.disabled = false; }, _debuggerWasEnabled: function() { this._setPauseOnExceptions(WebInspector.settings.pauseOnExceptionStateString.get()); if (this._debuggerEnabled) return; this._debuggerEnabled = true; this._reset(true); }, _debuggerWasDisabled: function() { if (!this._debuggerEnabled) return; this._debuggerEnabled = false; this._reset(true); }, _reset: function(preserveItems) { delete this.currentQuery; this.searchCanceled(); this._debuggerResumed(); delete this._currentUISourceCode; this._navigator.reset(); this._editorContainer.reset(); this._updateScriptViewStatusBarItems(); this.sidebarPanes.jsBreakpoints.reset(); this.sidebarPanes.watchExpressions.reset(); var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) this._removeSourceFrame(uiSourceCodes[i]); this._loadUISourceCodes(); }, get visibleView() { return this._editorContainer.visibleView; }, _updateScriptViewStatusBarItems: function() { this._scriptViewStatusBarItemsContainer.removeChildren(); var sourceFrame = this.visibleView; if (sourceFrame) { var statusBarItems = sourceFrame.statusBarItems() || []; for (var i = 0; i < statusBarItems.length; ++i) this._scriptViewStatusBarItemsContainer.appendChild(statusBarItems[i]); } }, canShowAnchorLocation: function(anchor) { if (this._debuggerEnabled && anchor.uiSourceCode) return true; var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) { if (uiSourceCodes[i].url === anchor.href) { anchor.uiSourceCode = uiSourceCodes[i]; return true; } } return false; }, showAnchorLocation: function(anchor) { this._showSourceLine(anchor.uiSourceCode, anchor.lineNumber); }, showFunctionDefinition: function(functionLocation) { WebInspector.showPanelForAnchorNavigation(this); var uiLocation = WebInspector.debuggerModel.rawLocationToUILocation(functionLocation); this._showSourceLine(uiLocation.uiSourceCode, uiLocation.lineNumber); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number} lineNumber */ showUISourceCode: function(uiSourceCode, lineNumber) { this._showSourceLine(uiSourceCode, lineNumber); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number=} lineNumber */ _showSourceLine: function(uiSourceCode, lineNumber) { var sourceFrame = this._showFile(uiSourceCode); if (typeof lineNumber === "number") sourceFrame.highlightLine(lineNumber); sourceFrame.focus(); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ _showFile: function(uiSourceCode) { var sourceFrame = this._getOrCreateSourceFrame(uiSourceCode); if (this._currentUISourceCode === uiSourceCode) return sourceFrame; this._currentUISourceCode = uiSourceCode; if (this._navigator.isScriptSourceAdded(uiSourceCode)) this._navigator.revealUISourceCode(uiSourceCode); this._editorContainer.showFile(uiSourceCode); this._updateScriptViewStatusBarItems(); return sourceFrame; }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ _createSourceFrame: function(uiSourceCode) { var sourceFrame; if (uiSourceCode instanceof WebInspector.SnippetJavaScriptSource) { var snippetJavaScriptSource = /** @type {WebInspector.SnippetJavaScriptSource} */ uiSourceCode; sourceFrame = new WebInspector.SnippetJavaScriptSourceFrame(this, snippetJavaScriptSource); } else if (uiSourceCode instanceof WebInspector.JavaScriptSource) { var javaScriptSource = /** @type {WebInspector.JavaScriptSource} */ uiSourceCode; sourceFrame = new WebInspector.JavaScriptSourceFrame(this, javaScriptSource); } else sourceFrame = new WebInspector.UISourceCodeFrame(uiSourceCode); this._sourceFramesByUISourceCode.put(uiSourceCode, sourceFrame); return sourceFrame; }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ _getOrCreateSourceFrame: function(uiSourceCode) { return this._sourceFramesByUISourceCode.get(uiSourceCode) || this._createSourceFrame(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ viewForFile: function(uiSourceCode) { return this._getOrCreateSourceFrame(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _removeSourceFrame: function(uiSourceCode) { var sourceFrame = this._sourceFramesByUISourceCode.get(uiSourceCode); if (!sourceFrame) return; this._sourceFramesByUISourceCode.remove(uiSourceCode); sourceFrame.detach(); }, /** * @param {WebInspector.Event} event */ _uiSourceCodeReplaced: function(event) { var oldUISourceCode = /** @type {WebInspector.UISourceCode} */ event.data.oldUISourceCode; var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data.uiSourceCode; this._navigator.replaceUISourceCode(oldUISourceCode, uiSourceCode); this._editorContainer.replaceFile(oldUISourceCode, uiSourceCode); this._removeSourceFrame(oldUISourceCode); }, _clearCurrentExecutionLine: function() { if (this._executionSourceFrame) this._executionSourceFrame.clearExecutionLine(); delete this._executionSourceFrame; }, _executionLineChanged: function(event) { var uiLocation = event.data; this._clearCurrentExecutionLine(); if (!uiLocation) return; var sourceFrame = this._getOrCreateSourceFrame(uiLocation.uiSourceCode); sourceFrame.setExecutionLine(uiLocation.lineNumber); this._executionSourceFrame = sourceFrame; }, _revealExecutionLine: function(uiLocation) { // Some scripts (anonymous and snippets evaluations) are not added to files select by default. this._editorContainer.addUISourceCode(uiLocation.uiSourceCode); var sourceFrame = this._showFile(uiLocation.uiSourceCode); sourceFrame.revealLine(uiLocation.lineNumber); sourceFrame.focus(); }, _callFrameSelected: function(event) { var callFrame = event.data; if (!callFrame) return; this.sidebarPanes.scopechain.update(callFrame); this.sidebarPanes.watchExpressions.refreshExpressions(); this.sidebarPanes.callstack.setSelectedCallFrame(callFrame); callFrame.createLiveLocation(this._revealExecutionLine.bind(this)); }, _editorClosed: function(event) { this._navigatorController.hideNavigatorOverlay(); var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data; if (this._currentUISourceCode === uiSourceCode) delete this._currentUISourceCode; // ScriptsNavigator does not need to update on EditorClosed. this._updateScriptViewStatusBarItems(); WebInspector.searchController.resetSearch(); }, _editorSelected: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data; var sourceFrame = this._showFile(uiSourceCode); this._navigatorController.hideNavigatorOverlay(); sourceFrame.focus(); WebInspector.searchController.resetSearch(); }, _scriptSelected: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data.uiSourceCode; var sourceFrame = this._showFile(uiSourceCode); this._navigatorController.hideNavigatorOverlay(); if (sourceFrame && event.data.focusSource) sourceFrame.focus(); }, _setPauseOnExceptions: function(pauseOnExceptionsState) { pauseOnExceptionsState = pauseOnExceptionsState || WebInspector.ScriptsPanel.PauseOnExceptionsState.DontPauseOnExceptions; function callback(error) { if (error) return; if (pauseOnExceptionsState == WebInspector.ScriptsPanel.PauseOnExceptionsState.DontPauseOnExceptions) this._pauseOnExceptionButton.title = WebInspector.UIString("Don't pause on exceptions.\nClick to Pause on all exceptions."); else if (pauseOnExceptionsState == WebInspector.ScriptsPanel.PauseOnExceptionsState.PauseOnAllExceptions) this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on all exceptions.\nClick to Pause on uncaught exceptions."); else if (pauseOnExceptionsState == WebInspector.ScriptsPanel.PauseOnExceptionsState.PauseOnUncaughtExceptions) this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on uncaught exceptions.\nClick to Not pause on exceptions."); this._pauseOnExceptionButton.state = pauseOnExceptionsState; WebInspector.settings.pauseOnExceptionStateString.set(pauseOnExceptionsState); } DebuggerAgent.setPauseOnExceptions(pauseOnExceptionsState, callback.bind(this)); }, _updateDebuggerButtons: function() { if (this._debuggerEnabled) { this.enableToggleButton.title = WebInspector.UIString("Debugging enabled. Click to disable."); this.enableToggleButton.toggled = true; this._pauseOnExceptionButton.visible = true; this.panelEnablerView.detach(); } else { this.enableToggleButton.title = WebInspector.UIString("Debugging disabled. Click to enable."); this.enableToggleButton.toggled = false; this._pauseOnExceptionButton.visible = false; this.panelEnablerView.show(this.element); } if (this._paused) { this.pauseButton.addStyleClass("paused"); this.pauseButton.disabled = false; this.stepOverButton.disabled = false; this.stepIntoButton.disabled = false; this.stepOutButton.disabled = false; this.debuggerStatusElement.textContent = WebInspector.UIString("Paused"); } else { this.pauseButton.removeStyleClass("paused"); this.pauseButton.disabled = this._waitingToPause; this.stepOverButton.disabled = true; this.stepIntoButton.disabled = true; this.stepOutButton.disabled = true; if (this._waitingToPause) this.debuggerStatusElement.textContent = WebInspector.UIString("Pausing"); else if (this._stepping) this.debuggerStatusElement.textContent = WebInspector.UIString("Stepping"); else this.debuggerStatusElement.textContent = ""; } }, _clearInterface: function() { this.sidebarPanes.callstack.update(null); this.sidebarPanes.scopechain.update(null); this.sidebarPanes.jsBreakpoints.clearBreakpointHighlight(); this.sidebarPanes.domBreakpoints.clearBreakpointHighlight(); this.sidebarPanes.eventListenerBreakpoints.clearBreakpointHighlight(); this.sidebarPanes.xhrBreakpoints.clearBreakpointHighlight(); this._clearCurrentExecutionLine(); this._updateDebuggerButtons(); }, get debuggingEnabled() { return this._debuggerEnabled; }, enableDebugging: function() { if (this._debuggerEnabled) return; this.toggleDebugging(this.panelEnablerView.alwaysEnabled); }, disableDebugging: function() { if (!this._debuggerEnabled) return; this.toggleDebugging(this.panelEnablerView.alwaysEnabled); }, toggleDebugging: function(optionalAlways) { this._paused = false; this._waitingToPause = false; this._stepping = false; if (this._debuggerEnabled) { WebInspector.settings.debuggerEnabled.set(false); WebInspector.debuggerModel.disableDebugger(); } else { WebInspector.settings.debuggerEnabled.set(!!optionalAlways); WebInspector.debuggerModel.enableDebugger(); } }, _togglePauseOnExceptions: function() { var nextStateMap = {}; var stateEnum = WebInspector.ScriptsPanel.PauseOnExceptionsState; nextStateMap[stateEnum.DontPauseOnExceptions] = stateEnum.PauseOnAllExceptions; nextStateMap[stateEnum.PauseOnAllExceptions] = stateEnum.PauseOnUncaughtExceptions; nextStateMap[stateEnum.PauseOnUncaughtExceptions] = stateEnum.DontPauseOnExceptions; this._setPauseOnExceptions(nextStateMap[this._pauseOnExceptionButton.state]); }, _togglePause: function() { if (this._paused) { this._paused = false; this._waitingToPause = false; DebuggerAgent.resume(); } else { this._stepping = false; this._waitingToPause = true; DebuggerAgent.pause(); } this._clearInterface(); }, _stepOverClicked: function() { if (!this._paused) return; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepOver(); }, _stepIntoClicked: function() { if (!this._paused) return; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepInto(); }, _stepOutClicked: function() { if (!this._paused) return; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepOut(); }, _toggleBreakpointsClicked: function(event) { WebInspector.debuggerModel.setBreakpointsActive(!WebInspector.debuggerModel.breakpointsActive()); }, _breakpointsActiveStateChanged: function(event) { var active = event.data; this._toggleBreakpointsButton.toggled = active; if (active) { this._toggleBreakpointsButton.title = WebInspector.UIString("Deactivate all breakpoints."); WebInspector.inspectorView.element.removeStyleClass("breakpoints-deactivated"); this.sidebarPanes.jsBreakpoints.listElement.removeStyleClass("breakpoints-list-deactivated"); } else { this._toggleBreakpointsButton.title = WebInspector.UIString("Activate all breakpoints."); WebInspector.inspectorView.element.addStyleClass("breakpoints-deactivated"); this.sidebarPanes.jsBreakpoints.listElement.addStyleClass("breakpoints-list-deactivated"); } }, _evaluateSelectionInConsole: function() { var selection = window.getSelection(); if (selection.type === "Range" && !selection.isCollapsed) WebInspector.evaluateInConsole(selection.toString()); }, _createDebugToolbar: function(section) { var debugToolbar = document.createElement("div"); debugToolbar.className = "status-bar"; debugToolbar.id = "scripts-debug-toolbar"; var title, handler, shortcuts; var platformSpecificModifier = WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta; // Continue. title = WebInspector.UIString("Pause script execution (%s)."); handler = this._togglePause.bind(this); shortcuts = []; shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F8)); shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Slash, platformSpecificModifier)); this.pauseButton = this._createButtonAndRegisterShortcuts(section, "scripts-pause", title, handler, shortcuts, WebInspector.UIString("Pause/Continue")); debugToolbar.appendChild(this.pauseButton); // Step over. title = WebInspector.UIString("Step over next function call (%s)."); handler = this._stepOverClicked.bind(this); shortcuts = []; shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F10)); shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.SingleQuote, platformSpecificModifier)); this.stepOverButton = this._createButtonAndRegisterShortcuts(section, "scripts-step-over", title, handler, shortcuts, WebInspector.UIString("Step over")); debugToolbar.appendChild(this.stepOverButton); // Step into. title = WebInspector.UIString("Step into next function call (%s)."); handler = this._stepIntoClicked.bind(this); shortcuts = []; shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11)); shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, platformSpecificModifier)); this.stepIntoButton = this._createButtonAndRegisterShortcuts(section, "scripts-step-into", title, handler, shortcuts, WebInspector.UIString("Step into")); debugToolbar.appendChild(this.stepIntoButton); // Step out. title = WebInspector.UIString("Step out of current function (%s)."); handler = this._stepOutClicked.bind(this); shortcuts = []; shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11, WebInspector.KeyboardShortcut.Modifiers.Shift)); shortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.Shift | platformSpecificModifier)); this.stepOutButton = this._createButtonAndRegisterShortcuts(section, "scripts-step-out", title, handler, shortcuts, WebInspector.UIString("Step out")); debugToolbar.appendChild(this.stepOutButton); this._toggleBreakpointsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Deactivate all breakpoints."), "toggle-breakpoints"); this._toggleBreakpointsButton.toggled = true; this._toggleBreakpointsButton.addEventListener("click", this._toggleBreakpointsClicked, this); debugToolbar.appendChild(this._toggleBreakpointsButton.element); this.debuggerStatusElement = document.createElement("div"); this.debuggerStatusElement.id = "scripts-debugger-status"; debugToolbar.appendChild(this.debuggerStatusElement); return debugToolbar; }, _createButtonAndRegisterShortcuts: function(section, buttonId, buttonTitle, handler, shortcuts, shortcutDescription) { var button = document.createElement("button"); button.className = "status-bar-item"; button.id = buttonId; button.title = String.vsprintf(buttonTitle, [shortcuts[0].name]); button.disabled = true; button.appendChild(document.createElement("img")); button.addEventListener("click", handler, false); var shortcutNames = []; for (var i = 0; i < shortcuts.length; ++i) { this.registerShortcut(shortcuts[i].key, handler); shortcutNames.push(shortcuts[i].name); } section.addAlternateKeys(shortcutNames, shortcutDescription); return button; }, searchCanceled: function() { if (this._searchView) this._searchView.searchCanceled(); delete this._searchView; delete this._searchQuery; }, /** * @param {string} query */ performSearch: function(query) { WebInspector.searchController.updateSearchMatchesCount(0, this); if (!this.visibleView) return; // Call searchCanceled since it will reset everything we need before doing a new search. this.searchCanceled(); this._searchView = this.visibleView; this._searchQuery = query; function finishedCallback(view, searchMatches) { if (!searchMatches) return; WebInspector.searchController.updateSearchMatchesCount(searchMatches, this); view.jumpToNextSearchResult(); WebInspector.searchController.updateCurrentMatchIndex(view.currentSearchResultIndex, this); } this._searchView.performSearch(query, finishedCallback.bind(this)); }, jumpToNextSearchResult: function() { if (!this._searchView) return; if (this._searchView !== this.visibleView) { this.performSearch(this._searchQuery); return; } if (this._searchView.showingLastSearchResult()) this._searchView.jumpToFirstSearchResult(); else this._searchView.jumpToNextSearchResult(); WebInspector.searchController.updateCurrentMatchIndex(this._searchView.currentSearchResultIndex, this); return true; }, jumpToPreviousSearchResult: function() { if (!this._searchView) return false; if (this._searchView !== this.visibleView) { this.performSearch(this._searchQuery); if (this._searchView) this._searchView.jumpToLastSearchResult(); return; } if (this._searchView.showingFirstSearchResult()) this._searchView.jumpToLastSearchResult(); else this._searchView.jumpToPreviousSearchResult(); WebInspector.searchController.updateCurrentMatchIndex(this._searchView.currentSearchResultIndex, this); }, /** * @return {boolean} */ canSearchAndReplace: function() { var view = /** @type {WebInspector.SourceFrame} */ this.visibleView; return !!view && view.canEditSource(); }, /** * @param {string} text */ replaceSelectionWith: function(text) { var view = /** @type {WebInspector.SourceFrame} */ this.visibleView; view.replaceSearchMatchWith(text); }, /** * @param {string} query * @param {string} text */ replaceAllWith: function(query, text) { var view = /** @type {WebInspector.SourceFrame} */ this.visibleView; view.replaceAllWith(query, text); }, _toggleFormatSource: function() { this._toggleFormatSourceButton.toggled = !this._toggleFormatSourceButton.toggled; var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) uiSourceCodes[i].setFormatted(this._toggleFormatSourceButton.toggled); }, addToWatch: function(expression) { this.sidebarPanes.watchExpressions.addExpression(expression); }, _toggleBreakpoint: function() { var sourceFrame = this.visibleView; if (!sourceFrame) return; if (sourceFrame instanceof WebInspector.JavaScriptSourceFrame) { var javaScriptSourceFrame = /** @type {WebInspector.JavaScriptSourceFrame} */ sourceFrame; javaScriptSourceFrame.toggleBreakpointOnCurrentLine(); } }, _showOutlineDialog: function() { var uiSourceCode = this._editorContainer.currentFile(); if (!uiSourceCode) return; if (uiSourceCode instanceof WebInspector.JavaScriptSource) WebInspector.JavaScriptOutlineDialog.show(this.visibleView, uiSourceCode); else if (uiSourceCode instanceof WebInspector.StyleSource) WebInspector.StyleSheetOutlineDialog.show(this.visibleView, /** @type {WebInspector.StyleSource} */ uiSourceCode); }, _installDebuggerSidebarController: function() { this._toggleDebuggerSidebarButton = new WebInspector.StatusBarButton(WebInspector.UIString("Hide debugger"), "scripts-debugger-show-hide-button", 3); this._toggleDebuggerSidebarButton.state = "shown"; this._toggleDebuggerSidebarButton.addEventListener("click", clickHandler, this); function clickHandler() { if (this._toggleDebuggerSidebarButton.state === "shown") this._hideDebuggerSidebar(); else this._showDebuggerSidebar(); } this.editorView.element.appendChild(this._toggleDebuggerSidebarButton.element); if (WebInspector.settings.debuggerSidebarHidden.get()) this._hideDebuggerSidebar(); }, _showDebuggerSidebar: function() { if (this._toggleDebuggerSidebarButton.state === "shown") return; this._toggleDebuggerSidebarButton.state = "shown"; this._toggleDebuggerSidebarButton.title = WebInspector.UIString("Hide debugger"); this.splitView.showSidebarElement(); WebInspector.settings.debuggerSidebarHidden.set(false); }, _hideDebuggerSidebar: function() { if (this._toggleDebuggerSidebarButton.state === "hidden") return; this._toggleDebuggerSidebarButton.state = "hidden"; this._toggleDebuggerSidebarButton.title = WebInspector.UIString("Show debugger"); this.splitView.hideSidebarElement(); WebInspector.settings.debuggerSidebarHidden.set(true); }, _fileRenamed: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data.uiSourceCode; var name = /** @type {string} */ event.data.name; if (!uiSourceCode.isSnippet) return; var snippetJavaScriptSource = /** @type {WebInspector.SnippetJavaScriptSource} */ uiSourceCode; WebInspector.scriptSnippetModel.renameScriptSnippet(snippetJavaScriptSource, name); }, /** * @param {WebInspector.Event} event */ _snippetCreationRequested: function(event) { var snippetJavaScriptSource = WebInspector.scriptSnippetModel.createScriptSnippet(); this._showSourceLine(snippetJavaScriptSource); var shouldHideNavigator = !this._navigatorController.isNavigatorPinned(); if (this._navigatorController.isNavigatorHidden()) this._navigatorController.showNavigatorOverlay(); this._navigator.rename(snippetJavaScriptSource, callback.bind(this)); /** * @param {boolean} committed */ function callback(committed) { if (shouldHideNavigator) this._navigatorController.hideNavigatorOverlay(); if (!committed) { WebInspector.scriptSnippetModel.deleteScriptSnippet(snippetJavaScriptSource); return; } this._showSourceLine(snippetJavaScriptSource); } }, /** * @param {WebInspector.Event} event */ _itemRenamingRequested: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ event.data; var shouldHideNavigator = !this._navigatorController.isNavigatorPinned(); if (this._navigatorController.isNavigatorHidden()) this._navigatorController.showNavigatorOverlay(); this._navigator.rename(uiSourceCode, callback.bind(this)); /** * @param {boolean} committed */ function callback(committed) { if (shouldHideNavigator && committed) { this._navigatorController.hideNavigatorOverlay(); this._showSourceLine(uiSourceCode); } } }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _showLocalHistory: function(uiSourceCode) { WebInspector.RevisionHistoryView.showHistory(uiSourceCode); }, /** * @param {WebInspector.ContextMenu} contextMenu * @param {Object} target */ appendApplicableItems: function(contextMenu, target) { if (!(target instanceof WebInspector.UISourceCode)) return; var uiSourceCode = /** @type {WebInspector.UISourceCode} */ target; contextMenu.appendItem(WebInspector.UIString("Local modifications..."), this._showLocalHistory.bind(this, uiSourceCode)); if (uiSourceCode.resource() && uiSourceCode.resource().request) contextMenu.appendApplicableItems(uiSourceCode.resource().request); }, showGoToSourceDialog: function() { WebInspector.inspectorView.setCurrentPanel(this); WebInspector.OpenResourceDialog.show(this, this._workspace, this.editorView.mainElement); } } WebInspector.ScriptsPanel.prototype.__proto__ = WebInspector.Panel.prototype;
youfoh/webkit-efl
Source/WebCore/inspector/front-end/ScriptsPanel.js
JavaScript
lgpl-2.1
46,222
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef CIRCLEAVERAGEMATERIALPROPERTYAUX_H #define CIRCLEAVERAGEMATERIALPROPERTYAUX_H #include "AuxKernel.h" //Forward Declarations class CircleAverageMaterialPropertyAux; class CircleAverageMaterialProperty; template<> InputParameters validParams<CircleAverageMaterialPropertyAux>(); class CircleAverageMaterialPropertyAux : public AuxKernel { public: CircleAverageMaterialPropertyAux(const InputParameters & parameters); protected: virtual Real computeValue(); const CircleAverageMaterialProperty & _uo; const Real _radius; }; #endif // CIRCLEAVERAGEMATERIALPROPERTYAUX_H
jessecarterMOOSE/PRARIEDOG
include/auxkernels/CircleAverageMaterialPropertyAux.h
C
lgpl-2.1
1,461
package net.darkhax.bookshelf.registry; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.logging.log4j.Logger; import net.minecraft.item.crafting.IRecipeSerializer; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.crafting.IIngredientSerializer; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.IEventBus; public class IngredientRegistry { private final String ownerId; private final Logger logger; private final Map<ResourceLocation, IIngredientSerializer<?>> serializers; public IngredientRegistry(String ownerId, Logger logger) { this.ownerId = ownerId; this.logger = logger; this.serializers = new HashMap<>(); } public <T extends Ingredient> IIngredientSerializer<T> register (String id, IIngredientSerializer<T> serializer) { this.serializers.put(new ResourceLocation(this.ownerId, id), serializer); return serializer; } public void initialize (IEventBus bus) { if (!this.serializers.isEmpty()) { bus.addGenericListener(IRecipeSerializer.class, this::registerIngredientSerializers); } } private void registerIngredientSerializers (RegistryEvent.Register<IRecipeSerializer<?>> event) { for (final Entry<ResourceLocation, IIngredientSerializer<?>> serializer : this.serializers.entrySet()) { CraftingHelper.register(serializer.getKey(), serializer.getValue()); } this.logger.info("Registered {} ingredient serializers.", this.serializers.size()); } }
Darkhax-Minecraft/Bookshelf
src/main/java/net/darkhax/bookshelf/registry/IngredientRegistry.java
Java
lgpl-2.1
1,822
/* * Minecraft Forge * Copyright (c) 2016. * * This library 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 version 2.1 * of the License. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.fml.common; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import net.minecraft.server.MinecraftServer; import javax.annotation.Nullable; public class StartupQuery { // internal class/functionality, do not use public static boolean confirm(String text) { StartupQuery query = new StartupQuery(text, new AtomicBoolean()); query.execute(); return query.getResult(); } public static void notify(String text) { StartupQuery query = new StartupQuery(text, null); query.execute(); } public static void abort() { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); if (server != null) server.initiateShutdown(); aborted = true; // to abort loading and go back to the main menu throw new AbortedException(); // to halt the server } public static void reset() { pending = null; aborted = false; } public static boolean check() { if (pending != null) { try { FMLCommonHandler.instance().queryUser(pending); } catch (InterruptedException e) { FMLLog.warning("query interrupted"); abort(); } pending = null; } return !aborted; } private static volatile StartupQuery pending; private static volatile boolean aborted = false; private StartupQuery(String text, @Nullable AtomicBoolean result) { this.text = text; this.result = result; } @Nullable public Boolean getResult() { return result == null ? null : result.get(); } public void setResult(boolean result) { this.result.set(result); } public String getText() { return text; } public boolean isSynchronous() { return synchronous; } public void finish() { signal.countDown(); } private void execute() { String prop = System.getProperty("fml.queryResult"); if (result != null && prop != null) { FMLLog.info("Using fml.queryResult %s to answer the following query:\n%s", prop, text); if (prop.equalsIgnoreCase("confirm")) { setResult(true); return; } else if (prop.equalsIgnoreCase("cancel")) { setResult(false); return; } FMLLog.warning("Invalid value for fml.queryResult: %s, expected confirm or cancel", prop); } synchronous = false; pending = this; // let the other thread start the query // from the integrated server thread: the client will eventually check pending and execute the query // from the client thread: synchronous execution // dedicated server: command handling in mc is synchronous, execute the server-side query directly if (FMLCommonHandler.instance().getSide().isServer() || FMLCommonHandler.instance().getEffectiveSide().isClient()) { synchronous = true; check(); } try { signal.await(); reset(); } catch (InterruptedException e) { FMLLog.warning("query interrupted"); abort(); } } private String text; @Nullable private AtomicBoolean result; private CountDownLatch signal = new CountDownLatch(1); private volatile boolean synchronous; /** * Exception not being caught by the crash report generation logic. */ public static class AbortedException extends RuntimeException { private static final long serialVersionUID = -5933665223696833921L; private AbortedException() { super(); } } }
SuperUnitato/UnLonely
build/tmp/recompileMc/sources/net/minecraftforge/fml/common/StartupQuery.java
Java
lgpl-2.1
4,779
<?php namespace wcf\data\language\category; use wcf\data\DatabaseObject; /** * Represents a language category. * * @author Alexander Ebert * @copyright 2001-2016 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Data\Language\Category * * @property-read integer $languageCategoryID unique id of the language category * @property-read string $languageCategory name and textual identifier of the language category */ class LanguageCategory extends DatabaseObject { /** * @inheritDoc */ protected static $databaseTableIndexName = 'languageCategoryID'; }
0xLeon/WCF
wcfsetup/install/files/lib/data/language/category/LanguageCategory.class.php
PHP
lgpl-2.1
658
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qtpropertybrowserutils_p.h" #include <QtGui/QApplication> #include <QtGui/QPainter> #include <QtGui/QHBoxLayout> #include <QtGui/QMouseEvent> #include <QtGui/QCheckBox> #include <QtGui/QLineEdit> #include <QtGui/QMenu> #include <QtCore/QLocale> QT_BEGIN_NAMESPACE QtCursorDatabase::QtCursorDatabase() { appendCursor(Qt::ArrowCursor, QApplication::translate("QtCursorDatabase", "Arrow", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-arrow.png"))); appendCursor(Qt::UpArrowCursor, QApplication::translate("QtCursorDatabase", "Up Arrow", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-uparrow.png"))); appendCursor(Qt::CrossCursor, QApplication::translate("QtCursorDatabase", "Cross", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-cross.png"))); appendCursor(Qt::WaitCursor, QApplication::translate("QtCursorDatabase", "Wait", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-wait.png"))); appendCursor(Qt::IBeamCursor, QApplication::translate("QtCursorDatabase", "IBeam", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-ibeam.png"))); appendCursor(Qt::SizeVerCursor, QApplication::translate("QtCursorDatabase", "Size Vertical", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizev.png"))); appendCursor(Qt::SizeHorCursor, QApplication::translate("QtCursorDatabase", "Size Horizontal", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeh.png"))); appendCursor(Qt::SizeFDiagCursor, QApplication::translate("QtCursorDatabase", "Size Backslash", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizef.png"))); appendCursor(Qt::SizeBDiagCursor, QApplication::translate("QtCursorDatabase", "Size Slash", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeb.png"))); appendCursor(Qt::SizeAllCursor, QApplication::translate("QtCursorDatabase", "Size All", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeall.png"))); appendCursor(Qt::BlankCursor, QApplication::translate("QtCursorDatabase", "Blank", 0, QApplication::UnicodeUTF8), QIcon()); appendCursor(Qt::SplitVCursor, QApplication::translate("QtCursorDatabase", "Split Vertical", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-vsplit.png"))); appendCursor(Qt::SplitHCursor, QApplication::translate("QtCursorDatabase", "Split Horizontal", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-hsplit.png"))); appendCursor(Qt::PointingHandCursor, QApplication::translate("QtCursorDatabase", "Pointing Hand", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-hand.png"))); appendCursor(Qt::ForbiddenCursor, QApplication::translate("QtCursorDatabase", "Forbidden", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-forbidden.png"))); appendCursor(Qt::OpenHandCursor, QApplication::translate("QtCursorDatabase", "Open Hand", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-openhand.png"))); appendCursor(Qt::ClosedHandCursor, QApplication::translate("QtCursorDatabase", "Closed Hand", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-closedhand.png"))); appendCursor(Qt::WhatsThisCursor, QApplication::translate("QtCursorDatabase", "What's This", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-whatsthis.png"))); appendCursor(Qt::BusyCursor, QApplication::translate("QtCursorDatabase", "Busy", 0, QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-busy.png"))); } void QtCursorDatabase::clear() { m_cursorNames.clear(); m_cursorIcons.clear(); m_valueToCursorShape.clear(); m_cursorShapeToValue.clear(); } void QtCursorDatabase::appendCursor(Qt::CursorShape shape, const QString &name, const QIcon &icon) { if (m_cursorShapeToValue.contains(shape)) return; const int value = m_cursorNames.count(); m_cursorNames.append(name); m_cursorIcons.insert(value, icon); m_valueToCursorShape.insert(value, shape); m_cursorShapeToValue.insert(shape, value); } QStringList QtCursorDatabase::cursorShapeNames() const { return m_cursorNames; } QMap<int, QIcon> QtCursorDatabase::cursorShapeIcons() const { return m_cursorIcons; } QString QtCursorDatabase::cursorToShapeName(const QCursor &cursor) const { int val = cursorToValue(cursor); if (val >= 0) return m_cursorNames.at(val); return QString(); } QIcon QtCursorDatabase::cursorToShapeIcon(const QCursor &cursor) const { int val = cursorToValue(cursor); return m_cursorIcons.value(val); } int QtCursorDatabase::cursorToValue(const QCursor &cursor) const { #ifndef QT_NO_CURSOR Qt::CursorShape shape = cursor.shape(); if (m_cursorShapeToValue.contains(shape)) return m_cursorShapeToValue[shape]; #endif return -1; } #ifndef QT_NO_CURSOR QCursor QtCursorDatabase::valueToCursor(int value) const { if (m_valueToCursorShape.contains(value)) return QCursor(m_valueToCursorShape[value]); return QCursor(); } #endif QPixmap QtPropertyBrowserUtils::brushValuePixmap(const QBrush &b) { QImage img(16, 16, QImage::Format_ARGB32_Premultiplied); img.fill(0); QPainter painter(&img); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect(0, 0, img.width(), img.height(), b); QColor color = b.color(); if (color.alpha() != 255) { // indicate alpha by an inset QBrush opaqueBrush = b; color.setAlpha(255); opaqueBrush.setColor(color); painter.fillRect(img.width() / 4, img.height() / 4, img.width() / 2, img.height() / 2, opaqueBrush); } painter.end(); return QPixmap::fromImage(img); } QIcon QtPropertyBrowserUtils::brushValueIcon(const QBrush &b) { return QIcon(brushValuePixmap(b)); } QString QtPropertyBrowserUtils::colorValueText(const QColor &c) { return QApplication::translate("QtPropertyBrowserUtils", "[%1, %2, %3] (%4)", 0, QApplication::UnicodeUTF8) .arg(QString::number(c.red())) .arg(QString::number(c.green())) .arg(QString::number(c.blue())) .arg(QString::number(c.alpha())); } QPixmap QtPropertyBrowserUtils::fontValuePixmap(const QFont &font) { QFont f = font; QImage img(16, 16, QImage::Format_ARGB32_Premultiplied); img.fill(0); QPainter p(&img); p.setRenderHint(QPainter::TextAntialiasing, true); p.setRenderHint(QPainter::Antialiasing, true); f.setPointSize(13); p.setFont(f); QTextOption t; t.setAlignment(Qt::AlignCenter); p.drawText(QRect(0, 0, 16, 16), QString(QLatin1Char('A')), t); return QPixmap::fromImage(img); } QIcon QtPropertyBrowserUtils::fontValueIcon(const QFont &f) { return QIcon(fontValuePixmap(f)); } QString QtPropertyBrowserUtils::fontValueText(const QFont &f) { return QApplication::translate("QtPropertyBrowserUtils", "[%1, %2]", 0, QApplication::UnicodeUTF8) .arg(f.family()) .arg(f.pointSize()); } QString QtPropertyBrowserUtils::dateFormat() { QLocale loc; return loc.dateFormat(QLocale::ShortFormat); } QString QtPropertyBrowserUtils::timeFormat() { QLocale loc; // ShortFormat is missing seconds on UNIX. return loc.timeFormat(QLocale::LongFormat); } QString QtPropertyBrowserUtils::dateTimeFormat() { QString format = dateFormat(); format += QLatin1Char(' '); format += timeFormat(); return format; } QtBoolEdit::QtBoolEdit(QWidget *parent) : QWidget(parent), m_checkBox(new QCheckBox(this)), m_textVisible(true) { QHBoxLayout *lt = new QHBoxLayout; if (QApplication::layoutDirection() == Qt::LeftToRight) lt->setContentsMargins(4, 0, 0, 0); else lt->setContentsMargins(0, 0, 4, 0); lt->addWidget(m_checkBox); setLayout(lt); connect(m_checkBox, SIGNAL(toggled(bool)), this, SIGNAL(toggled(bool))); setFocusProxy(m_checkBox); m_checkBox->setText(tr("True")); } void QtBoolEdit::setTextVisible(bool textVisible) { if (m_textVisible == textVisible) return; m_textVisible = textVisible; if (m_textVisible) m_checkBox->setText(isChecked() ? tr("True") : tr("False")); else m_checkBox->setText(QString()); } Qt::CheckState QtBoolEdit::checkState() const { return m_checkBox->checkState(); } void QtBoolEdit::setCheckState(Qt::CheckState state) { m_checkBox->setCheckState(state); } bool QtBoolEdit::isChecked() const { return m_checkBox->isChecked(); } void QtBoolEdit::setChecked(bool c) { m_checkBox->setChecked(c); if (!m_textVisible) return; m_checkBox->setText(isChecked() ? tr("True") : tr("False")); } bool QtBoolEdit::blockCheckBoxSignals(bool block) { return m_checkBox->blockSignals(block); } void QtBoolEdit::mousePressEvent(QMouseEvent *event) { if (event->buttons() == Qt::LeftButton) { m_checkBox->click(); event->accept(); } else { QWidget::mousePressEvent(event); } } QtKeySequenceEdit::QtKeySequenceEdit(QWidget *parent) : QWidget(parent), m_num(0), m_lineEdit(new QLineEdit(this)) { QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(m_lineEdit); layout->setMargin(0); m_lineEdit->installEventFilter(this); m_lineEdit->setReadOnly(true); m_lineEdit->setFocusProxy(this); setFocusPolicy(m_lineEdit->focusPolicy()); setAttribute(Qt::WA_InputMethodEnabled); } bool QtKeySequenceEdit::eventFilter(QObject *o, QEvent *e) { if (o == m_lineEdit && e->type() == QEvent::ContextMenu) { QContextMenuEvent *c = static_cast<QContextMenuEvent *>(e); QMenu *menu = m_lineEdit->createStandardContextMenu(); const QList<QAction *> actions = menu->actions(); QListIterator<QAction *> itAction(actions); while (itAction.hasNext()) { QAction *action = itAction.next(); action->setShortcut(QKeySequence()); QString actionString = action->text(); const int pos = actionString.lastIndexOf(QLatin1Char('\t')); if (pos > 0) actionString.remove(pos, actionString.length() - pos); action->setText(actionString); } QAction *actionBefore = 0; if (actions.count() > 0) actionBefore = actions[0]; QAction *clearAction = new QAction(tr("Clear Shortcut"), menu); menu->insertAction(actionBefore, clearAction); menu->insertSeparator(actionBefore); clearAction->setEnabled(!m_keySequence.isEmpty()); connect(clearAction, SIGNAL(triggered()), this, SLOT(slotClearShortcut())); menu->exec(c->globalPos()); delete menu; e->accept(); return true; } return QWidget::eventFilter(o, e); } void QtKeySequenceEdit::slotClearShortcut() { if (m_keySequence.isEmpty()) return; setKeySequence(QKeySequence()); emit keySequenceChanged(m_keySequence); } void QtKeySequenceEdit::handleKeyEvent(QKeyEvent *e) { int nextKey = e->key(); if (nextKey == Qt::Key_Control || nextKey == Qt::Key_Shift || nextKey == Qt::Key_Meta || nextKey == Qt::Key_Alt || nextKey == Qt::Key_Super_L || nextKey == Qt::Key_AltGr) return; nextKey |= translateModifiers(e->modifiers(), e->text()); int k0 = m_keySequence[0]; int k1 = m_keySequence[1]; int k2 = m_keySequence[2]; int k3 = m_keySequence[3]; switch (m_num) { case 0: k0 = nextKey; k1 = 0; k2 = 0; k3 = 0; break; case 1: k1 = nextKey; k2 = 0; k3 = 0; break; case 2: k2 = nextKey; k3 = 0; break; case 3: k3 = nextKey; break; default: break; } ++m_num; if (m_num > 3) m_num = 0; m_keySequence = QKeySequence(k0, k1, k2, k3); m_lineEdit->setText(m_keySequence.toString(QKeySequence::NativeText)); e->accept(); emit keySequenceChanged(m_keySequence); } void QtKeySequenceEdit::setKeySequence(const QKeySequence &sequence) { if (sequence == m_keySequence) return; m_num = 0; m_keySequence = sequence; m_lineEdit->setText(m_keySequence.toString(QKeySequence::NativeText)); } QKeySequence QtKeySequenceEdit::keySequence() const { return m_keySequence; } int QtKeySequenceEdit::translateModifiers(Qt::KeyboardModifiers state, const QString &text) const { int result = 0; if ((state & Qt::ShiftModifier) && (text.size() == 0 || !text.at(0).isPrint() || text.at(0).isLetter() || text.at(0).isSpace())) result |= Qt::SHIFT; if (state & Qt::ControlModifier) result |= Qt::CTRL; if (state & Qt::MetaModifier) result |= Qt::META; if (state & Qt::AltModifier) result |= Qt::ALT; return result; } void QtKeySequenceEdit::focusInEvent(QFocusEvent *e) { m_lineEdit->event(e); m_lineEdit->selectAll(); QWidget::focusInEvent(e); } void QtKeySequenceEdit::focusOutEvent(QFocusEvent *e) { m_num = 0; m_lineEdit->event(e); QWidget::focusOutEvent(e); } void QtKeySequenceEdit::keyPressEvent(QKeyEvent *e) { handleKeyEvent(e); e->accept(); } void QtKeySequenceEdit::keyReleaseEvent(QKeyEvent *e) { m_lineEdit->event(e); } bool QtKeySequenceEdit::event(QEvent *e) { if (e->type() == QEvent::Shortcut || e->type() == QEvent::ShortcutOverride || e->type() == QEvent::KeyRelease) { e->accept(); return true; } return QWidget::event(e); } QT_END_NAMESPACE
sicily/qt4.8.4
tools/shared/qtpropertybrowser/qtpropertybrowserutils.cpp
C++
lgpl-2.1
16,711
import { FocusTools, Keyboard, Keys, Step } from '@ephox/agar'; import { UnitTest } from '@ephox/bedrock'; import { Objects } from '@ephox/boulder'; import { Arr } from '@ephox/katamari'; import * as Behaviour from 'ephox/alloy/api/behaviour/Behaviour'; import { Focusing } from 'ephox/alloy/api/behaviour/Focusing'; import { Keying } from 'ephox/alloy/api/behaviour/Keying'; import * as GuiFactory from 'ephox/alloy/api/component/GuiFactory'; import * as AlloyEvents from 'ephox/alloy/api/events/AlloyEvents'; import { Container } from 'ephox/alloy/api/ui/Container'; import * as GuiSetup from 'ephox/alloy/api/testhelpers/GuiSetup'; import * as NavigationUtils from 'ephox/alloy/test/NavigationUtils'; UnitTest.asynctest('Flat Grid Keying Test', (success, failure) => { const squares = [ 's01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10', 's11', 's12', 's13', 's14', 's15', 's16', 's17', 's18', 's19', 's20', 's21' ]; GuiSetup.setup((store, doc, body) => { const item = (classes) => { return Container.sketch({ dom: { tag: 'span', styles: { display: 'inline-block', width: '20px', height: '20px', margin: '1px', border: '1px solid black' }, classes: [ 'square' ].concat(classes) }, events: AlloyEvents.derive([ AlloyEvents.runOnExecute( store.adder('item.execute: ' + classes.join(',')) ) ]), containerBehaviours: Behaviour.derive([ Focusing.config({ }) ]) }); }; return GuiFactory.build( Container.sketch({ dom: { tag: 'div', classes: [ 'flat-grid-keying-test'], styles: { background: 'white', width: '150px', height: '200px' } }, uid: 'custom-uid', containerBehaviours: Behaviour.derive([ Keying.config({ mode: 'flatgrid', selector: '.square', initSize: { numColumns: 1, numRows: 1 } }) ]), // 4 x 6 grid size components: Arr.map(squares, (num) => { return item([ num ]); }) }) ); }, (doc, body, gui, component, store) => { const targets: any = Objects.wrapAll( Arr.map(squares, (sq) => { return { key: sq, value: { label: sq, selector: '.' + sq } }; }) ); return [ GuiSetup.mSetupKeyLogger(body), FocusTools.sSetFocus('Initial focus', gui.element(), '.s11'), Step.sync(() => { Keying.setGridSize(component, 4, 6); }), NavigationUtils.sequence( doc, Keys.down(), { }, [ targets.s17, targets.s21, targets.s03, targets.s09, targets.s15, targets.s21, targets.s03 ] ), NavigationUtils.sequence( doc, Keys.left(), { }, [ targets.s02, targets.s01, targets.s06, targets.s05, targets.s04, targets.s03, targets.s02, targets.s01, targets.s06 ] ), NavigationUtils.sequence( doc, Keys.up(), { }, [ targets.s21, targets.s15, targets.s09, targets.s03, targets.s21, targets.s15, targets.s09, targets.s03, targets.s21 ] ), NavigationUtils.sequence( doc, Keys.right(), { }, [ targets.s19, targets.s20, targets.s21, targets.s19, targets.s20, targets.s21 ] ), NavigationUtils.sequence( doc, Keys.left(), { }, [ targets.s20, targets.s19, targets.s21, targets.s20, targets.s19, targets.s21 ] ), // Test execute Keyboard.sKeydown(doc, Keys.enter(), {}), store.sAssertEq( 'Execute should have s21', [ 'item.execute: s21' ] ), GuiSetup.mTeardownKeyLogger(body, [ ]) ]; }, () => { success(); }, failure); });
FernCreek/tinymce
modules/alloy/src/test/ts/browser/behaviour/keying/FlatgridKeyingTest.ts
TypeScript
lgpl-2.1
4,431
/* -*- OpenSAF -*- * * (C) Copyright 2008 The OpenSAF Foundation * * 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. This file and program are licensed * under the GNU Lesser General Public License Version 2.1, February 1999. * The complete license can be accessed from the following location: * http://opensource.org/licenses/lgpl-license.php * See the Copying file included with the OpenSAF distribution for full * licensing terms. * * Author(s): Emerson Network Power * Ericsson AB * */ #include <saImmOm.h> #include <immutil.h> #include <logtrace.h> #include <saflog.h> #include <avd.h> #include <avd_cluster.h> #include <avd_imm.h> static NCS_PATRICIA_TREE node_name_db; /* SaNameT index */ static NCS_PATRICIA_TREE node_id_db; /* SaClmNodeIdT index */ uns32 avd_node_add_nodeid(AVD_AVND *node) { unsigned int rc; if ((avd_node_find_nodeid(node->node_info.nodeId) == NULL) && (node->node_info.nodeId != 0)) { node->tree_node_id_node.key_info = (uns8 *)&(node->node_info.nodeId); node->tree_node_id_node.bit = 0; node->tree_node_id_node.left = NCS_PATRICIA_NODE_NULL; node->tree_node_id_node.right = NCS_PATRICIA_NODE_NULL; rc = ncs_patricia_tree_add(&node_id_db, &node->tree_node_id_node); assert(rc == NCSCC_RC_SUCCESS); } return NCSCC_RC_SUCCESS; } void avd_node_delete_nodeid(AVD_AVND *node) { if (node->tree_node_id_node.key_info != NULL) (void)ncs_patricia_tree_del(&node_id_db, &node->tree_node_id_node); } void avd_node_db_add(AVD_AVND *node) { unsigned int rc; if (avd_node_get(&node->name) == NULL) { rc = ncs_patricia_tree_add(&node_name_db, &node->tree_node_name_node); assert(rc == NCSCC_RC_SUCCESS); } } AVD_AVND *avd_node_new(const SaNameT *dn) { AVD_AVND *node; if ((node = calloc(1, sizeof(AVD_AVND))) == NULL) { LOG_ER("calloc FAILED"); return NULL; } memcpy(node->name.value, dn->value, dn->length); node->name.length = dn->length; node->tree_node_name_node.key_info = (uns8 *)&(node->name); node->pg_csi_list.order = NCS_DBLIST_ANY_ORDER; node->pg_csi_list.cmp_cookie = avsv_dblist_uns32_cmp; node->saAmfNodeAdminState = SA_AMF_ADMIN_UNLOCKED; node->saAmfNodeOperState = SA_AMF_OPERATIONAL_DISABLED; node->node_state = AVD_AVND_STATE_ABSENT; node->node_info.member = SA_FALSE; node->type = AVSV_AVND_CARD_PAYLOAD; return node; } void avd_node_delete(AVD_AVND *node) { assert(node->pg_csi_list.n_nodes == 0); if (node->node_info.nodeId) avd_node_delete_nodeid(node); m_AVSV_SEND_CKPT_UPDT_ASYNC_RMV(avd_cb, node, AVSV_CKPT_AVD_NODE_CONFIG); ncs_patricia_tree_del(&node_name_db, &node->tree_node_name_node); free(node); } static void node_add_to_model(AVD_AVND *node) { TRACE_ENTER2("%s", node->node_info.nodeName.value); /* Check parent link to see if it has been added already */ if (node->cluster != NULL) { TRACE("already added"); goto done; } node->cluster = avd_cluster; avd_node_db_add(node); m_AVSV_SEND_CKPT_UPDT_ASYNC_ADD(avd_cb, node, AVSV_CKPT_AVD_NODE_CONFIG); done: TRACE_LEAVE(); } AVD_AVND *avd_node_get(const SaNameT *dn) { AVD_AVND *node; SaNameT tmp = { 0 }; tmp.length = dn->length; memcpy(tmp.value, dn->value, tmp.length); node = (AVD_AVND *)ncs_patricia_tree_get(&node_name_db, (uns8 *)&tmp); if (node != NULL) { /* Adjust the pointer */ node = (AVD_AVND *)(((char *)node) - (((char *)&(AVD_AVND_NULL->tree_node_name_node)) - ((char *)AVD_AVND_NULL))); } return node; } AVD_AVND *avd_node_find_nodeid(SaClmNodeIdT node_id) { return (AVD_AVND *)ncs_patricia_tree_get(&node_id_db, (uns8 *)&node_id); } AVD_AVND *avd_node_getnext(const SaNameT *dn) { AVD_AVND *node; SaNameT tmp = { 0 }; if (dn != NULL) { tmp.length = dn->length; memcpy(tmp.value, dn->value, tmp.length); node = (AVD_AVND *)ncs_patricia_tree_getnext(&node_name_db, (uns8 *)&tmp); } else node = (AVD_AVND *)ncs_patricia_tree_getnext(&node_name_db, (uns8 *)0); if (node != NULL) { /* Adjust the pointer */ node = (AVD_AVND *)(((char *)node) - (((char *)&(AVD_AVND_NULL->tree_node_name_node)) - ((char *)AVD_AVND_NULL))); } return node; } AVD_AVND *avd_node_getnext_nodeid(SaClmNodeIdT node_id) { return (AVD_AVND *)ncs_patricia_tree_getnext(&node_id_db, (uns8 *)&node_id); } /** * Validate configuration attributes for an AMF node object * @param node * @param opdata * * @return int */ static int is_config_valid(const SaNameT *dn, const SaImmAttrValuesT_2 **attributes, CcbUtilOperationData_t * opdata) { SaBoolT abool; SaAmfAdminStateT admstate; char *parent; SaNameT saAmfNodeClmNode; if ((parent = strchr((char *)dn->value, ',')) == NULL) { LOG_ER("No parent to '%s' ", dn->value); return 0; } if (strncmp(++parent, "safAmfCluster=", 14) != 0) { LOG_ER("Wrong parent '%s' to '%s' ", parent, dn->value); return 0; } if ((immutil_getAttr("saAmfNodeAutoRepair", attributes, 0, &abool) == SA_AIS_OK) && (abool > SA_TRUE)) { LOG_ER("Invalid saAmfNodeAutoRepair %u for '%s'", abool, dn->value); return 0; } if ((immutil_getAttr("saAmfNodeFailfastOnTerminationFailure", attributes, 0, &abool) == SA_AIS_OK) && (abool > SA_TRUE)) { LOG_ER("Invalid saAmfNodeFailfastOnTerminationFailure %u for '%s'", abool, dn->value); return 0; } if ((immutil_getAttr("saAmfNodeFailfastOnInstantiationFailure", attributes, 0, &abool) == SA_AIS_OK) && (abool > SA_TRUE)) { LOG_ER("Invalid saAmfNodeFailfastOnInstantiationFailure %u for '%s'", abool, dn->value); return 0; } if ((immutil_getAttr("saAmfNodeAdminState", attributes, 0, &admstate) == SA_AIS_OK) && !avd_admin_state_is_valid(admstate)) { LOG_ER("Invalid saAmfNodeAdminState %u for '%s'", admstate, dn->value); return 0; } if (immutil_getAttr("saAmfNodeClmNode", attributes, 0, &saAmfNodeClmNode) != SA_AIS_OK) { LOG_ER("saAmfNodeClmNode not configured for '%s'", dn->value); return 0; } return 1; } /** * Create a new Node object * @param dn * @param attributes * * @return AVD_AVND* */ static AVD_AVND *node_create(SaNameT *dn, const SaImmAttrValuesT_2 **attributes) { int rc = -1; AVD_AVND *node; TRACE_ENTER2("'%s'", dn->value); /* ** If called at new active at failover, the object is found in the DB ** but needs to get configuration attributes initialized. */ if (NULL == (node = avd_node_get(dn))) { if ((node = avd_node_new(dn)) == NULL) goto done; } else TRACE("already created, refreshing config..."); if (immutil_getAttr("saAmfNodeClmNode", attributes, 0, &node->saAmfNodeClmNode) != SA_AIS_OK) { LOG_ER("saAmfNodeClmNode not configured for '%s'", node->saAmfNodeClmNode.value); goto done; } if (immutil_getAttr("saAmfNodeSuFailOverProb", attributes, 0, &node->saAmfNodeSuFailOverProb) != SA_AIS_OK) { LOG_ER("Get saAmfNodeSuFailOverProb FAILED for '%s'", dn->value); goto done; } if (immutil_getAttr("saAmfNodeSuFailoverMax", attributes, 0, &node->saAmfNodeSuFailoverMax) != SA_AIS_OK) { LOG_ER("Get saAmfNodeSuFailoverMax FAILED for '%s'", dn->value); goto done; } if (immutil_getAttr("saAmfNodeAutoRepair", attributes, 0, &node->saAmfNodeAutoRepair) != SA_AIS_OK) { node->saAmfNodeAutoRepair = SA_TRUE; } if (immutil_getAttr("saAmfNodeFailfastOnTerminationFailure", attributes, 0, &node->saAmfNodeFailfastOnTerminationFailure) != SA_AIS_OK) { node->saAmfNodeFailfastOnTerminationFailure = SA_FALSE; } if (immutil_getAttr("saAmfNodeFailfastOnInstantiationFailure", attributes, 0, &node->saAmfNodeFailfastOnInstantiationFailure) != SA_AIS_OK) { node->saAmfNodeFailfastOnInstantiationFailure = SA_FALSE; } if (immutil_getAttr("saAmfNodeAdminState", attributes, 0, &node->saAmfNodeAdminState) != SA_AIS_OK) { /* Empty, assign default value */ node->saAmfNodeAdminState = SA_AMF_ADMIN_UNLOCKED; } rc = 0; done: if (rc != 0) { avd_node_delete(node); node = NULL; } TRACE_LEAVE(); return node; } /** * Get configuration for all AMF node objects from IMM and * create AVD internal objects. * * @return int */ SaAisErrorT avd_node_config_get(void) { SaAisErrorT error, rc = SA_AIS_ERR_FAILED_OPERATION; SaImmSearchHandleT searchHandle; SaImmSearchParametersT_2 searchParam; SaNameT dn; const SaImmAttrValuesT_2 **attributes; const char *className = "SaAmfNode"; AVD_AVND *node; TRACE_ENTER(); searchParam.searchOneAttr.attrName = "SaImmAttrClassName"; searchParam.searchOneAttr.attrValueType = SA_IMM_ATTR_SASTRINGT; searchParam.searchOneAttr.attrValue = &className; error = immutil_saImmOmSearchInitialize_2(avd_cb->immOmHandle, NULL, SA_IMM_SUBTREE, SA_IMM_SEARCH_ONE_ATTR | SA_IMM_SEARCH_GET_ALL_ATTR, &searchParam, NULL, &searchHandle); if (SA_AIS_OK != error) { LOG_ER("No objects found"); goto done1; } while (immutil_saImmOmSearchNext_2(searchHandle, &dn, (SaImmAttrValuesT_2 ***)&attributes) == SA_AIS_OK) { if (!is_config_valid(&dn, attributes, NULL)) { error = SA_AIS_ERR_FAILED_OPERATION; goto done2; } if ((node = node_create(&dn, attributes)) == NULL) { error = SA_AIS_ERR_FAILED_OPERATION; goto done2; } node_add_to_model(node); } rc = SA_AIS_OK; done2: (void)immutil_saImmOmSearchFinalize(searchHandle); done1: TRACE_LEAVE2("%u", rc); return rc; } static const char *node_state_name[] = { "ABSENT", "NO_CONFIG", "PRESENT", "GO_DOWN", "SHUTTING_DOWN", "NCS_INIT" }; void avd_node_state_set(AVD_AVND *node, AVD_AVND_STATE node_state) { assert(node_state <= AVD_AVND_STATE_NCS_INIT); TRACE_ENTER2("'%s' %s => %s", node->name.value, node_state_name[node->node_state], node_state_name[node_state]); node->node_state = node_state; m_AVSV_SEND_CKPT_UPDT_ASYNC_UPDT(avd_cb, node, AVSV_CKPT_AVND_NODE_STATE); } /** * Set AMF operational state of a node. Log & update IMM, checkpoint with standby * @param node * @param oper_state */ void avd_node_oper_state_set(AVD_AVND *node, SaAmfOperationalStateT oper_state) { if (node->saAmfNodeOperState == oper_state) return; SaAmfOperationalStateT old_state = node->saAmfNodeOperState; assert(oper_state <= SA_AMF_OPERATIONAL_DISABLED); saflog(LOG_NOTICE, amfSvcUsrName, "%s OperState %s => %s", node->name.value, avd_oper_state_name[node->saAmfNodeOperState], avd_oper_state_name[oper_state]); node->saAmfNodeOperState = oper_state; avd_saImmOiRtObjectUpdate(&node->name, "saAmfNodeOperState", SA_IMM_ATTR_SAUINT32T, &node->saAmfNodeOperState); m_AVSV_SEND_CKPT_UPDT_ASYNC_UPDT(avd_cb, node, AVSV_CKPT_AVND_OPER_STATE); /* notification */ avd_send_oper_chg_ntf(&node->name, SA_AMF_NTFID_NODE_OP_STATE, old_state, node->saAmfNodeOperState); } /***************************************************************************** * Function: node_ccb_completed_delete_hdlr * * Purpose: This routine handles delete operations on SaAmfCluster objects. * * Input : Ccb Util Oper Data. * * Returns: None. * ****************************************************************************/ static SaAisErrorT node_ccb_completed_delete_hdlr(CcbUtilOperationData_t *opdata) { SaAisErrorT rc = SA_AIS_OK; AVD_AVND *node = avd_node_get(&opdata->objectName); AVD_SU *su; SaBoolT su_exist = SA_FALSE; CcbUtilOperationData_t *t_opData; TRACE_ENTER2("'%s'", opdata->objectName.value); if (node->node_info.member) { LOG_ER("Node '%s' is still cluster member", opdata->objectName.value); return SA_AIS_ERR_BAD_OPERATION; } if (node->type == AVSV_AVND_CARD_SYS_CON) { LOG_ER("Cannot remove controller node"); return SA_AIS_ERR_BAD_OPERATION; } /* Check to see that the node is in admin locked state before delete */ if (node->saAmfNodeAdminState != SA_AMF_ADMIN_LOCKED_INSTANTIATION) { LOG_ER("Node '%s' is not locked instantiation", opdata->objectName.value); return SA_AIS_ERR_BAD_OPERATION; } /* Check to see that no SUs exists on this node */ if (node->list_of_su != NULL) { /* check whether there exists a delete operation for * each of the SU in the node list in the current CCB */ su = node->list_of_su; while (su != NULL) { t_opData = ccbutil_getCcbOpDataByDN(opdata->ccbId, &su->name); if ((t_opData == NULL) || (t_opData->operationType != CCBUTIL_DELETE)) { su_exist = SA_TRUE; break; } su = su->avnd_list_su_next; } if (su_exist == SA_TRUE) { LOG_ER("Node '%s' still has SUs", opdata->objectName.value); rc = SA_AIS_ERR_BAD_OPERATION; goto done; } } opdata->userData = node; done: TRACE_LEAVE(); return rc; } static SaAisErrorT node_ccb_completed_modify_hdlr(CcbUtilOperationData_t *opdata) { SaAisErrorT rc = SA_AIS_OK; const SaImmAttrModificationT_2 *attr_mod; int i = 0; TRACE_ENTER2("'%s'", opdata->objectName.value); while ((attr_mod = opdata->param.modify.attrMods[i++]) != NULL) { const SaImmAttrValuesT_2 *attribute = &attr_mod->modAttr; void *value = attribute->attrValues[0]; if (!strcmp(attribute->attrName, "saAmfNodeClmNode")) { LOG_ER("Modification of saAmfNodeClmNode not allowed"); rc = SA_AIS_ERR_BAD_OPERATION; goto done; } else if (!strcmp(attribute->attrName, "saAmfNodeSuFailOverProb")) { SaTimeT su_failover_prob = *((SaTimeT *)value); if (su_failover_prob == 0) { rc = SA_AIS_ERR_BAD_OPERATION; goto done; } } else if (!strcmp(attribute->attrName, "saAmfNodeAutoRepair")) { SaBoolT val = *((SaBoolT *)value); if (val > SA_TRUE) { rc = SA_AIS_ERR_BAD_OPERATION; goto done; } } else if (!strcmp(attribute->attrName, "saAmfNodeFailfastOnTerminationFailure")) { SaBoolT val = *((SaBoolT *)value); if (val > SA_TRUE) { rc = SA_AIS_ERR_BAD_OPERATION; goto done; } } else if (!strcmp(attribute->attrName, "saAmfNodeFailfastOnInstantiationFailure")) { SaBoolT val = *((SaBoolT *)value); if (val > SA_TRUE) { rc = SA_AIS_ERR_BAD_OPERATION; goto done; } } else { LOG_ER("Unknown attribute %s", attribute->attrName); rc = SA_AIS_ERR_BAD_OPERATION; goto done; } } done: TRACE_LEAVE(); return rc; } static SaAisErrorT node_ccb_completed_cb(CcbUtilOperationData_t *opdata) { SaAisErrorT rc = SA_AIS_ERR_BAD_OPERATION; TRACE_ENTER2("CCB ID %llu, '%s'", opdata->ccbId, opdata->objectName.value); switch (opdata->operationType) { case CCBUTIL_CREATE: if (is_config_valid(&opdata->objectName, opdata->param.create.attrValues, opdata)) rc = SA_AIS_OK; break; case CCBUTIL_MODIFY: rc = node_ccb_completed_modify_hdlr(opdata); break; case CCBUTIL_DELETE: rc = node_ccb_completed_delete_hdlr(opdata); break; default: assert(0); break; } TRACE_LEAVE(); return rc; } static void node_ccb_apply_delete_hdlr(AVD_AVND *node) { TRACE_ENTER2("'%s'", node->name.value); avd_node_delete_nodeid(node); avd_node_delete(node); TRACE_LEAVE(); } static void node_ccb_apply_modify_hdlr(CcbUtilOperationData_t *opdata) { AVD_AVND *node; const SaImmAttrModificationT_2 *attr_mod; int i = 0; TRACE_ENTER2("'%s'", opdata->objectName.value); node = avd_node_get(&opdata->objectName); assert(node != NULL); i = 0; /* Modifications can be done for the following parameters. */ while (((attr_mod = opdata->param.modify.attrMods[i++])) != NULL) { void *value; const SaImmAttrValuesT_2 *attribute = &attr_mod->modAttr; AVSV_PARAM_INFO param; value = attribute->attrValues[0]; if (!strcmp(attribute->attrName, "saAmfNodeSuFailOverProb")) { SaTimeT su_failover_prob; SaTimeT backup_time; su_failover_prob = *((SaTimeT *)value); SaTimeT temp_su_prob; m_NCS_OS_HTONLL_P(&temp_su_prob, su_failover_prob); su_failover_prob = temp_su_prob; memset(((uns8 *)&param), '\0', sizeof(AVSV_PARAM_INFO)); param.class_id = AVSV_SA_AMF_NODE; param.attr_id = saAmfNodeSuFailoverProb_ID; param.act = AVSV_OBJ_OPR_MOD; param.name = node->name; if (node->node_state != AVD_AVND_STATE_ABSENT) { backup_time = node->saAmfNodeSuFailOverProb; param.value_len = sizeof(SaTimeT); memcpy((char *)&param.value[0], (char *)&su_failover_prob, param.value_len); node->saAmfNodeSuFailOverProb = m_NCS_OS_NTOHLL_P(&su_failover_prob); avd_snd_op_req_msg(avd_cb, node, &param); } else { node->saAmfNodeSuFailOverProb = m_NCS_OS_NTOHLL_P(&su_failover_prob); } m_AVSV_SEND_CKPT_UPDT_ASYNC_UPDT(avd_cb, node, AVSV_CKPT_AVD_NODE_CONFIG); } else if (!strcmp(attribute->attrName, "saAmfNodeSuFailoverMax")) { uns32 back_val; uns32 failover_val; failover_val = *((SaUint32T *)value); memset(((uns8 *)&param), '\0', sizeof(AVSV_PARAM_INFO)); param.class_id = AVSV_SA_AMF_NODE; param.attr_id = saAmfNodeSuFailoverMax_ID; param.act = AVSV_OBJ_OPR_MOD; param.name = node->name; if (node->node_state != AVD_AVND_STATE_ABSENT) { back_val = node->saAmfNodeSuFailoverMax; param.value_len = sizeof(uns32); m_NCS_OS_HTONL_P(&param.value[0], failover_val); node->saAmfNodeSuFailoverMax = failover_val; avd_snd_op_req_msg(avd_cb, node, &param); } else { node->saAmfNodeSuFailoverMax = failover_val; } m_AVSV_SEND_CKPT_UPDT_ASYNC_UPDT(avd_cb, node, AVSV_CKPT_AVD_NODE_CONFIG); } else { assert(0); } } /* while (attr_mod != NULL) */ TRACE_LEAVE(); } static void node_ccb_apply_cb(CcbUtilOperationData_t *opdata) { AVD_AVND *node; TRACE_ENTER2("CCB ID %llu, '%s'", opdata->ccbId, opdata->objectName.value); switch (opdata->operationType) { case CCBUTIL_CREATE: node = node_create(&opdata->objectName, opdata->param.create.attrValues); assert(node); node_add_to_model(node); break; case CCBUTIL_MODIFY: node_ccb_apply_modify_hdlr(opdata); break; case CCBUTIL_DELETE: node_ccb_apply_delete_hdlr(opdata->userData); break; default: assert(0); break; } TRACE_LEAVE(); } /** * sets the admin state of a node * * @param node * @param admin_state */ void node_admin_state_set(AVD_AVND *node, SaAmfAdminStateT admin_state) { SaAmfAdminStateT old_state = node->saAmfNodeAdminState; assert(admin_state <= SA_AMF_ADMIN_SHUTTING_DOWN); if (0 != node->clm_pend_inv) { /* Clm operations going on, skip notifications and rt updates for node change. We are using node state as LOCKED for making CLM Admin operation going through. */ node->saAmfNodeAdminState = admin_state; m_AVSV_SEND_CKPT_UPDT_ASYNC_UPDT(avd_cb, node, AVSV_CKPT_AVND_ADMIN_STATE); } else { TRACE_ENTER2("%s AdmState %s => %s", node->name.value, avd_adm_state_name[node->saAmfNodeAdminState], avd_adm_state_name[admin_state]); saflog(LOG_NOTICE, amfSvcUsrName, "%s AdmState %s => %s", node->name.value, avd_adm_state_name[node->saAmfNodeAdminState], avd_adm_state_name[admin_state]); node->saAmfNodeAdminState = admin_state; avd_saImmOiRtObjectUpdate(&node->name, "saAmfNodeAdminState", SA_IMM_ATTR_SAUINT32T, &node->saAmfNodeAdminState); m_AVSV_SEND_CKPT_UPDT_ASYNC_UPDT(avd_cb, node, AVSV_CKPT_AVND_ADMIN_STATE); avd_send_admin_state_chg_ntf(&node->name, SA_AMF_NTFID_NODE_ADMIN_STATE, old_state, node->saAmfNodeAdminState); } TRACE_LEAVE(); } /** * Sends msg to terminate all SUs on the node as part of lock instantiation * * @param node */ uns32 avd_node_admin_lock_instantiation(AVD_AVND *node) { AVD_SU *su; uns32 rc = NCSCC_RC_SUCCESS; TRACE_ENTER2("%s", node->name.value); /* terminate all the SUs on this Node */ su = node->list_of_su; while (su != NULL) { if ((su->saAmfSUPreInstantiable == TRUE) && (su->saAmfSUPresenceState != SA_AMF_PRESENCE_UNINSTANTIATED) && (su->saAmfSUPresenceState != SA_AMF_PRESENCE_INSTANTIATION_FAILED) && (su->saAmfSUPresenceState != SA_AMF_PRESENCE_TERMINATION_FAILED)) { if (avd_snd_presence_msg(avd_cb, su, TRUE) == NCSCC_RC_SUCCESS) { m_AVD_SET_SU_TERM(avd_cb, su, TRUE); node->su_cnt_admin_oper++; } else { rc = NCSCC_RC_FAILURE; LOG_WA("Failed Termination '%s'", su->name.value); } } su = su->avnd_list_su_next; } TRACE_LEAVE2("%u, %u", rc, node->su_cnt_admin_oper); return rc; } /** * Sends msg to instantiate SUs on the node as part of unlock instantiation * * @param node */ uns32 node_admin_unlock_instantiation(AVD_AVND *node) { AVD_SU *su; uns32 rc = NCSCC_RC_SUCCESS; TRACE_ENTER2("%s", node->name.value); /* instantiate the SUs on this Node */ su = node->list_of_su; while (su != NULL) { if ((su->saAmfSUAdminState != SA_AMF_ADMIN_LOCKED_INSTANTIATION) && (su->sg_of_su->saAmfSGAdminState != SA_AMF_ADMIN_LOCKED_INSTANTIATION) && (su->saAmfSUPresenceState == SA_AMF_PRESENCE_UNINSTANTIATED)) { if (su->saAmfSUPreInstantiable == TRUE) { if (avd_snd_presence_msg(avd_cb, su, FALSE) == NCSCC_RC_SUCCESS) { m_AVD_SET_SU_TERM(avd_cb, su, FALSE); node->su_cnt_admin_oper++; } else { rc = NCSCC_RC_FAILURE; LOG_WA("Failed Instantiation '%s'", su->name.value); } } else { avd_su_oper_state_set(su, SA_AMF_OPERATIONAL_ENABLED); avd_su_readiness_state_set(su, SA_AMF_READINESS_IN_SERVICE); } } su = su->avnd_list_su_next; } TRACE_LEAVE2("%u, %u", rc, node->su_cnt_admin_oper); return rc; } /** * processes lock, unlock and shutdown admin operations on a node * * @param node * @param invocation * @param operationId */ void avd_node_admin_lock_unlock_shutdown(AVD_AVND *node, SaInvocationT invocation, SaAmfAdminOperationIdT operationId) { AVD_CL_CB *cb = (AVD_CL_CB *)avd_cb; AVD_SU *su, *su_sg; NCS_BOOL su_admin = FALSE; AVD_SU_SI_REL *curr_susi; AVD_AVND *su_node_ptr = NULL; AVD_AVND *su_sg_node_ptr = NULL; SaAmfAdminStateT new_admin_state; TRACE_ENTER2("%s", node->name.value); /* determine the new_admin_state from operation ID */ if (operationId == SA_AMF_ADMIN_SHUTDOWN) new_admin_state = SA_AMF_ADMIN_SHUTTING_DOWN; else if (operationId == SA_AMF_ADMIN_UNLOCK) new_admin_state = SA_AMF_ADMIN_UNLOCKED; else new_admin_state = SA_AMF_ADMIN_LOCKED; /* If the node is not yet operational just modify the admin state field * incase of shutdown to lock and return success as this will only cause * state filed change and no semantics need to be followed. */ if (node->saAmfNodeOperState == SA_AMF_OPERATIONAL_DISABLED && invocation != 0) { if (new_admin_state == SA_AMF_ADMIN_SHUTTING_DOWN) { node_admin_state_set(node, SA_AMF_ADMIN_LOCKED); } else { node_admin_state_set(node, new_admin_state); } immutil_saImmOiAdminOperationResult(cb->immOiHandle, invocation, SA_AIS_OK); goto end; } /* Based on the admin operation that is been done call the corresponding. * Redundancy model specific functionality for each of the SUs on * the node. */ switch (new_admin_state) { case SA_AMF_ADMIN_UNLOCKED: su = node->list_of_su; while (su != NULL) { /* if SG to which this SU belongs and has SI assignments is undergoing * su semantics return error. */ if ((su->list_of_susi != AVD_SU_SI_REL_NULL) && (su->sg_of_su->sg_fsm_state != AVD_SG_FSM_STABLE)) { /* Dont go ahead as a SG that is undergoing transition is * there related to this node. */ LOG_WA("invalid sg state %u for unlock", su->sg_of_su->sg_fsm_state); if (invocation != 0) immutil_saImmOiAdminOperationResult(cb->immOiHandle, invocation, SA_AIS_ERR_TRY_AGAIN); goto end; } /* get the next SU on the node */ su = su->avnd_list_su_next; } /* while(su != AVD_SU_NULL) */ /* For each of the SUs calculate the readiness state. This routine is called * only when AvD is in AVD_APP_STATE. call the SG FSM with the new readiness * state. */ node_admin_state_set(node, new_admin_state); su = node->list_of_su; while (su != NULL) { m_AVD_GET_SU_NODE_PTR(cb, su, su_node_ptr); if (m_AVD_APP_SU_IS_INSVC(su, su_node_ptr)) { avd_su_readiness_state_set(su, SA_AMF_READINESS_IN_SERVICE); switch (su->sg_of_su->sg_redundancy_model) { case SA_AMF_2N_REDUNDANCY_MODEL: avd_sg_2n_su_insvc_func(cb, su); break; case SA_AMF_N_WAY_REDUNDANCY_MODEL: avd_sg_nway_su_insvc_func(cb, su); break; case SA_AMF_NPM_REDUNDANCY_MODEL: avd_sg_npm_su_insvc_func(cb, su); break; case SA_AMF_N_WAY_ACTIVE_REDUNDANCY_MODEL: avd_sg_nacvred_su_insvc_func(cb, su); break; case SA_AMF_NO_REDUNDANCY_MODEL: default: avd_sg_nored_su_insvc_func(cb, su); break; } /* Since an SU has come in-service re look at the SG to see if other * instantiations or terminations need to be done. */ avd_sg_app_su_inst_func(cb, su->sg_of_su); } /* check if admin lock has caused a SG REALIGN to send admin cbk */ if (su->sg_of_su->sg_fsm_state == AVD_SG_FSM_SG_REALIGN) node->su_cnt_admin_oper++; /* get the next SU on the node */ su = su->avnd_list_su_next; } if (node->su_cnt_admin_oper == 0 && invocation != 0) immutil_saImmOiAdminOperationResult(cb->immOiHandle, invocation, SA_AIS_OK); else if (invocation != 0) { node->admin_node_pend_cbk.invocation = invocation; node->admin_node_pend_cbk.admin_oper = operationId; } break; /* case NCS_ADMIN_STATE_UNLOCK: */ case SA_AMF_ADMIN_LOCKED: case SA_AMF_ADMIN_SHUTTING_DOWN: su = node->list_of_su; while (su != NULL) { if (su->list_of_susi != AVD_SU_SI_REL_NULL) { /* verify that two assigned SUs belonging to the same SG are not * on this node */ su_sg = su->sg_of_su->list_of_su; while (su_sg != NULL) { m_AVD_GET_SU_NODE_PTR(cb, su, su_node_ptr); m_AVD_GET_SU_NODE_PTR(cb, su_sg, su_sg_node_ptr); if ((su != su_sg) && (su_node_ptr == su_sg_node_ptr) && (su_sg->list_of_susi != AVD_SU_SI_REL_NULL)) { LOG_WA("two SUs on same node"); if (invocation != 0) immutil_saImmOiAdminOperationResult(cb->immOiHandle, invocation,SA_AIS_ERR_NOT_SUPPORTED); else { saClmResponse_4(cb->clmHandle, node->clm_pend_inv, SA_CLM_CALLBACK_RESPONSE_ERROR); node->clm_pend_inv = 0; } goto end; } su_sg = su_sg->sg_list_su_next; } /* while (su_sg != AVD_SU_NULL) */ /* if SG to which this SU belongs and has SI assignments is undergoing * any semantics other than for this SU return error. */ if (su->sg_of_su->sg_fsm_state != AVD_SG_FSM_STABLE) { if ((su->sg_of_su->sg_fsm_state != AVD_SG_FSM_SU_OPER) || (node->saAmfNodeAdminState != SA_AMF_ADMIN_SHUTTING_DOWN) || (new_admin_state != SA_AMF_ADMIN_LOCKED)) { LOG_WA("invalid sg state %u for lock/shutdown", su->sg_of_su->sg_fsm_state); if (invocation != 0) immutil_saImmOiAdminOperationResult(cb->immOiHandle, invocation,SA_AIS_ERR_TRY_AGAIN); else { saClmResponse_4(cb->clmHandle, node->clm_pend_inv, SA_CLM_CALLBACK_RESPONSE_ERROR); node->clm_pend_inv = 0; } goto end; } } /*if (su->sg_of_su->sg_fsm_state != AVD_SG_FSM_STABLE) */ if (su->list_of_susi->state == SA_AMF_HA_ACTIVE) { su_admin = TRUE; } else if ((node->saAmfNodeAdminState == SA_AMF_ADMIN_SHUTTING_DOWN) && (su_admin == FALSE) && (su->sg_of_su->sg_redundancy_model == SA_AMF_N_WAY_REDUNDANCY_MODEL)) { for (curr_susi = su->list_of_susi; (curr_susi) && ((SA_AMF_HA_ACTIVE != curr_susi->state) || ((AVD_SU_SI_STATE_UNASGN == curr_susi->fsm))); curr_susi = curr_susi->su_next) ; if (curr_susi) su_admin = TRUE; } } /* if(su->list_of_susi != AVD_SU_SI_REL_NULL) */ /* get the next SU on the node */ su = su->avnd_list_su_next; } /* while(su != AVD_SU_NULL) */ node_admin_state_set(node, new_admin_state); /* Now call the SG FSM for each of the SUs that have SI assignment. */ su = node->list_of_su; while (su != NULL) { avd_su_readiness_state_set(su, SA_AMF_READINESS_OUT_OF_SERVICE); if (su->list_of_susi != AVD_SU_SI_REL_NULL) { switch (su->sg_of_su->sg_redundancy_model) { case SA_AMF_2N_REDUNDANCY_MODEL: avd_sg_2n_su_admin_fail(cb, su, node); break; case SA_AMF_N_WAY_REDUNDANCY_MODEL: avd_sg_nway_su_admin_fail(cb, su, node); break; case SA_AMF_NPM_REDUNDANCY_MODEL: avd_sg_npm_su_admin_fail(cb, su, node); break; case SA_AMF_N_WAY_ACTIVE_REDUNDANCY_MODEL: avd_sg_nacvred_su_admin_fail(cb, su, node); break; case SA_AMF_NO_REDUNDANCY_MODEL: default: avd_sg_nored_su_admin_fail(cb, su, node); break; } } /* since an SU is now OOS we need to take a relook at the SG. */ avd_sg_app_su_inst_func(cb, su->sg_of_su); if (su->sg_of_su->sg_fsm_state == AVD_SG_FSM_SG_REALIGN || su->sg_of_su->sg_fsm_state == AVD_SG_FSM_SU_OPER) node->su_cnt_admin_oper++; /* get the next SU on the node */ su = su->avnd_list_su_next; } if ((node->saAmfNodeAdminState == SA_AMF_ADMIN_SHUTTING_DOWN) && (su_admin == FALSE)) { node_admin_state_set(node, SA_AMF_ADMIN_LOCKED); } if (node->su_cnt_admin_oper == 0 && invocation != 0) immutil_saImmOiAdminOperationResult(cb->immOiHandle, invocation, SA_AIS_OK); else if (invocation != 0){ node->admin_node_pend_cbk.invocation = invocation; node->admin_node_pend_cbk.admin_oper = operationId; } break; /* case NCS_ADMIN_STATE_LOCK: case NCS_ADMIN_STATE_SHUTDOWN: */ default: assert(0); break; } end: TRACE_LEAVE(); } /** * Handle admin operations on SaAmfNode objects. * * @param immOiHandle * @param invocation * @param objectName * @param operationId * @param params */ static void node_admin_op_cb(SaImmOiHandleT immOiHandle, SaInvocationT invocation, const SaNameT *objectName, SaImmAdminOperationIdT operationId, const SaImmAdminOperationParamsT_2 **params) { AVD_AVND *node; AVD_SU *su = NULL; SaAisErrorT rc = SA_AIS_OK; TRACE_ENTER2("%llu, '%s', %llu", invocation, objectName->value, operationId); if (avd_cb->init_state != AVD_APP_STATE) { rc = SA_AIS_ERR_TRY_AGAIN; LOG_WA("AVD not in APP_STATE"); goto done; } node = avd_node_get(objectName); assert(node != AVD_AVND_NULL); if (node->admin_node_pend_cbk.admin_oper != 0) { rc = SA_AIS_ERR_TRY_AGAIN; LOG_WA("Node undergoing admin operation"); goto done; } /* Check for any conflicting admin operations */ su = node->list_of_su; while (su != NULL) { if (su->pend_cbk.admin_oper != 0) { rc = SA_AIS_ERR_TRY_AGAIN; LOG_WA("SU on this node is undergoing admin op (%s)", su->name.value); goto done; } if (su->sg_of_su->sg_fsm_state != AVD_SG_FSM_STABLE) { rc = SA_AIS_ERR_TRY_AGAIN; LOG_WA("SG of SU on this node not in STABLE state (%s)", su->name.value); goto done; } su = su->avnd_list_su_next; } if (node->clm_pend_inv != 0) { LOG_NO("Clm lock operation going on"); rc = SA_AIS_ERR_TRY_AGAIN; goto done; } switch (operationId) { case SA_AMF_ADMIN_SHUTDOWN: if (node->saAmfNodeAdminState == SA_AMF_ADMIN_SHUTTING_DOWN) { rc = SA_AIS_ERR_NO_OP; LOG_WA("Already in SHUTTING DOWN state"); goto done; } if (node->saAmfNodeAdminState != SA_AMF_ADMIN_UNLOCKED) { rc = SA_AIS_ERR_BAD_OPERATION; LOG_WA("Invalid Admin Operation in state %d", node->saAmfNodeAdminState); goto done; } if (node->node_info.member == FALSE) { node_admin_state_set(node, SA_AMF_ADMIN_LOCKED); LOG_NO("Clm lock has been already performed"); immutil_saImmOiAdminOperationResult(immOiHandle, invocation, rc); goto done; } avd_node_admin_lock_unlock_shutdown(node, invocation, operationId); break; case SA_AMF_ADMIN_UNLOCK: if (node->saAmfNodeAdminState == SA_AMF_ADMIN_UNLOCKED) { rc = SA_AIS_ERR_NO_OP; LOG_WA("Already in UNLOCKED state"); goto done; } if (node->saAmfNodeAdminState != SA_AMF_ADMIN_LOCKED) { rc = SA_AIS_ERR_BAD_OPERATION; LOG_WA("Invalid Admin Operation in state %d", node->saAmfNodeAdminState); goto done; } if (node->node_info.member == FALSE) { LOG_NO("Clm lock has been already performed"); node_admin_state_set(node, SA_AMF_ADMIN_UNLOCKED); immutil_saImmOiAdminOperationResult(immOiHandle, invocation, rc); goto done; } avd_node_admin_lock_unlock_shutdown(node, invocation, operationId); break; case SA_AMF_ADMIN_LOCK: if (node->saAmfNodeAdminState == SA_AMF_ADMIN_LOCKED) { rc = SA_AIS_ERR_NO_OP; LOG_WA("Already in LOCKED state"); goto done; } if (node->saAmfNodeAdminState == SA_AMF_ADMIN_LOCKED_INSTANTIATION) { rc = SA_AIS_ERR_BAD_OPERATION; LOG_WA("Invalid Admin Operation in state %d", node->saAmfNodeAdminState); goto done; } if (node->node_info.member == FALSE) { node_admin_state_set(node, SA_AMF_ADMIN_LOCKED); LOG_NO("Clm lock has been already performed"); immutil_saImmOiAdminOperationResult(immOiHandle, invocation, rc); goto done; } avd_node_admin_lock_unlock_shutdown(node, invocation, operationId); break; case SA_AMF_ADMIN_LOCK_INSTANTIATION: if (node->saAmfNodeAdminState == SA_AMF_ADMIN_LOCKED_INSTANTIATION) { rc = SA_AIS_ERR_NO_OP; LOG_WA("Already in LOCKED INSTANTIATION state"); goto done; } if (node->saAmfNodeAdminState != SA_AMF_ADMIN_LOCKED) { rc = SA_AIS_ERR_BAD_OPERATION; LOG_WA("Invalid Admin Operation in state %d", node->saAmfNodeAdminState); goto done; } node_admin_state_set(node, SA_AMF_ADMIN_LOCKED_INSTANTIATION); if (node->node_info.member == FALSE) { LOG_NO("Clm lock has been already performed"); immutil_saImmOiAdminOperationResult(immOiHandle, invocation, rc); goto done; } if (node->saAmfNodeOperState == SA_AMF_OPERATIONAL_DISABLED || node->list_of_su == NULL) { immutil_saImmOiAdminOperationResult(immOiHandle, invocation, SA_AIS_OK); goto done; } /* now do the lock_instantiation of the node */ if (NCSCC_RC_SUCCESS == avd_node_admin_lock_instantiation(node)) { /* Check if we have pending admin operations * Otherwise reply to IMM immediately*/ if( node->su_cnt_admin_oper != 0) { node->admin_node_pend_cbk.admin_oper = operationId; node->admin_node_pend_cbk.invocation = invocation; } else immutil_saImmOiAdminOperationResult(immOiHandle, invocation, SA_AIS_OK); } else { rc = SA_AIS_ERR_REPAIR_PENDING; LOG_WA("LOCK_INSTANTIATION FAILED"); avd_node_oper_state_set(node, SA_AMF_OPERATIONAL_DISABLED); goto done; } break; case SA_AMF_ADMIN_UNLOCK_INSTANTIATION: if (node->saAmfNodeAdminState == SA_AMF_ADMIN_LOCKED) { rc = SA_AIS_ERR_NO_OP; LOG_WA("Already in LOCKED state"); goto done; } if (node->saAmfNodeAdminState != SA_AMF_ADMIN_LOCKED_INSTANTIATION) { rc = SA_AIS_ERR_BAD_OPERATION; LOG_WA("Invalid Admin Operation in state %d", node->saAmfNodeAdminState); goto done; } node_admin_state_set(node, SA_AMF_ADMIN_LOCKED); if (node->node_info.member == FALSE) { LOG_NO("Clm lock has been already performed"); immutil_saImmOiAdminOperationResult(immOiHandle, invocation, rc); goto done; } if (node->saAmfNodeOperState == SA_AMF_OPERATIONAL_DISABLED || node->list_of_su == NULL) { immutil_saImmOiAdminOperationResult(immOiHandle, invocation, SA_AIS_OK); goto done; } /* now do the unlock_instantiation of the node */ if (NCSCC_RC_SUCCESS == node_admin_unlock_instantiation(node)) { /* Check if we have pending admin operations. * Otherwise reply to IMM immediately*/ if( node->su_cnt_admin_oper != 0) { node->admin_node_pend_cbk.admin_oper = operationId; node->admin_node_pend_cbk.invocation = invocation; } else immutil_saImmOiAdminOperationResult(immOiHandle, invocation, SA_AIS_OK); } else { rc = SA_AIS_ERR_TIMEOUT; LOG_WA("UNLOCK_INSTANTIATION FAILED"); goto done; } break; default: rc = SA_AIS_ERR_NOT_SUPPORTED; LOG_WA("UNSUPPORTED ADMIN OPERATION (%llu)", operationId); break; } done: if (rc != SA_AIS_OK) immutil_saImmOiAdminOperationResult(immOiHandle, invocation, rc); TRACE_LEAVE2("%u", rc); } void avd_node_add_su(AVD_SU *su) { if (strstr((char *)su->name.value, "safApp=OpenSAF") != NULL) { su->avnd_list_su_next = su->su_on_node->list_of_ncs_su; su->su_on_node->list_of_ncs_su = su; } else { su->avnd_list_su_next = su->su_on_node->list_of_su; su->su_on_node->list_of_su = su; } } void avd_node_remove_su(AVD_SU *su) { AVD_SU *i_su = NULL; AVD_SU *prev_su = NULL; NCS_BOOL isNcs; if ((su->sg_of_su) && (su->sg_of_su->sg_ncs_spec == SA_TRUE)) isNcs = TRUE; else isNcs = FALSE; /* For external component, there is no AvND attached, so let it return. */ if (su->su_on_node != NULL) { /* remove SU from node */ i_su = (isNcs) ? su->su_on_node->list_of_ncs_su : su->su_on_node->list_of_su; while ((i_su != NULL) && (i_su != su)) { prev_su = i_su; i_su = i_su->avnd_list_su_next; } if (i_su != su) { assert(0); } else { if (prev_su == NULL) { if (isNcs) su->su_on_node->list_of_ncs_su = su->avnd_list_su_next; else su->su_on_node->list_of_su = su->avnd_list_su_next; } else { prev_su->avnd_list_su_next = su->avnd_list_su_next; } } su->avnd_list_su_next = NULL; su->su_on_node = NULL; } } void avd_node_constructor(void) { NCS_PATRICIA_PARAMS patricia_params; patricia_params.key_size = sizeof(SaNameT); assert(ncs_patricia_tree_init(&node_name_db, &patricia_params) == NCSCC_RC_SUCCESS); patricia_params.key_size = sizeof(SaClmNodeIdT); assert(ncs_patricia_tree_init(&node_id_db, &patricia_params) == NCSCC_RC_SUCCESS); avd_class_impl_set("SaAmfNode", NULL, node_admin_op_cb, node_ccb_completed_cb, node_ccb_apply_cb); }
kenzaburo/OpenSaf-FrameWork
osaf/services/saf/avsv/avd/avd_node.c
C
lgpl-2.1
37,989
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * This library 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. * * 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. */ package com.abixen.platform.core.service; import com.abixen.platform.core.form.LayoutForm; import com.abixen.platform.core.model.impl.Layout; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; public interface LayoutService { Layout createLayout(Layout layout); Layout updateLayout(Layout layout); LayoutForm updateLayout(LayoutForm layoutForm); void deleteLayout(Long id); String htmlLayoutToJson(String htmlString); Page<Layout> findAllLayouts(Pageable pageable); Layout findLayout(Long id); Layout changeIcon(Long id, MultipartFile iconFile) throws IOException; void convertPageLayoutToJson(com.abixen.platform.core.model.impl.Page page); }
adamturski/abixen-platform
abixen-platform-core/src/main/java/com/abixen/platform/core/service/LayoutService.java
Java
lgpl-2.1
1,413
''' Often used utility functions Copyright 2020 by Massimo Del Fedele ''' import sys import uno from com.sun.star.beans import PropertyValue from datetime import date import calendar import PyPDF2 ''' ALCUNE COSE UTILI La finestra che contiene il documento (o componente) corrente: desktop.CurrentFrame.ContainerWindow Non cambia nulla se è aperto un dialogo non modale, ritorna SEMPRE il frame del documento. desktop.ContainerWindow ritorna un None -- non so a che serva Per ottenere le top windows, c'è il toolkit... tk = ctx.ServiceManager.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx) tk.getTopWindowCount() ritorna il numero delle topwindow tk.getTopWIndow(i) ritorna una topwindow dell'elenco tk.getActiveTopWindow () ritorna la topwindow attiva La topwindow attiva, per essere attiva deve, appunto, essere attiva, indi avere il focus Se si fa il debug, ad esempio, è probabile che la finestra attiva sia None Resta quindi SEMPRE il problema di capire come fare a centrare un dialogo sul componente corrente. Se non ci sono dialoghi in esecuzione, il dialogo creato prende come parent la ContainerWindow(si suppone...) e quindi viene posizionato in base a quella Se c'è un dialogo aperto e nell'event handler se ne apre un altro, l'ultimo prende come parent il precedente, e viene quindi posizionato in base a quello e non alla schermata principale. Serve quindi un metodo per trovare le dimensioni DELLA FINESTRA PARENT di un dialogo, per posizionarlo. L'oggetto UnoControlDialog permette di risalire al XWindowPeer (che non serve ad una cippa), alla XView (che mi fornisce la dimensione del dialogo ma NON la parent...), al UnoControlDialogModel, che fornisce la proprietà 'DesktopAsParent' che mi dice SOLO se il dialogo è modale (False) o non modale (True) L'unica soluzione che mi viene in mente è tentare con tk.ActiveTopWindow e, se None, prendere quella del desktop ''' def getComponentContext(): ''' Get current application's component context ''' try: if __global_context__ is not None: return __global_context__ return uno.getComponentContext() except Exception: return uno.getComponentContext() def getDesktop(): ''' Get current application's LibreOffice desktop ''' ctx = getComponentContext() return ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) def getDocument(): ''' Get active document ''' desktop = getDesktop() # try to activate current frame # needed sometimes because UNO doesnt' find the correct window # when debugging. try: desktop.getCurrentFrame().activate() except Exception: pass return desktop.getCurrentComponent() def getServiceManager(): ''' Gets the service manager ''' return getComponentContext().ServiceManager def createUnoService(serv): ''' create an UNO service ''' return getComponentContext().getServiceManager().createInstance(serv) def MRI(target): ctx = getComponentContext() mri = ctx.ServiceManager.createInstanceWithContext("mytools.Mri", ctx) mri.inspect(target) def isLeenoDocument(): ''' check if current document is a LeenO document ''' try: return getDocument().getSheets().hasByName('S2') except Exception: return False def DisableDocumentRefresh(oDoc): ''' Disabilita il refresh per accelerare le procedure ''' oDoc.lockControllers() oDoc.addActionLock() def EnableDocumentRefresh(oDoc): ''' Riabilita il refresh ''' oDoc.removeActionLock() oDoc.unlockControllers() def getGlobalVar(name): if type(__builtins__) == type(sys): bDict = __builtins__.__dict__ else: bDict = __builtins__ return bDict.get('LEENO_GLOBAL_' + name) def setGlobalVar(name, value): if type(__builtins__) == type(sys): bDict = __builtins__.__dict__ else: bDict = __builtins__ bDict['LEENO_GLOBAL_' + name] = value def initGlobalVars(dict): if type(__builtins__) == type(sys): bDict = __builtins__.__dict__ else: bDict = __builtins__ for key, value in dict.items(): bDict['LEENO_GLOBAL_' + key] = value def dictToProperties(values, unoAny=False): ''' convert a dictionary in a tuple of UNO properties if unoAny is True, return the result in an UNO Any variable otherwise use a python tuple ''' ps = tuple([PropertyValue(Name=n, Value=v) for n, v in values.items()]) if unoAny: ps = uno.Any('[]com.sun.star.beans.PropertyValue', ps) return ps def daysInMonth(dat): ''' returns days in month of date dat ''' month = dat.month + 1 year = dat.year if month > 12: month = 1 year += 1 dat2 = date(year=year, month=month, day=dat.day) t = dat2 - dat return t.days def firstWeekDay(dat): ''' returns first week day in month from dat monday is 0 ''' return calendar.weekday(dat.year, dat.month, 1) DAYNAMES = ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'] MONTHNAMES = [ 'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre' ] def date2String(dat, fmt = 0): ''' conversione data in stringa fmt = 0 25 Febbraio 2020 fmt = 1 25/2/2020 fmt = 2 25-02-2020 fmt = 3 25.02.2020 ''' d = dat.day m = dat.month if m < 10: ms = '0' + str(m) else: ms = str(m) y = dat.year if fmt == 1: return str(d) + '/' + ms + '/' + str(y) elif fmt == 2: return str(d) + '-' + ms + '-' + str(y) elif fmt == 3: return str(d) + '.' + ms + '.' + str(y) else: return str(d) + ' ' + MONTHNAMES[m - 1] + ' ' + str(y) def string2Date(s): if '.' in s: sp = s.split('.') elif '/' in s: sp = s.split('/') elif '-' in s: sp = s.split('-') else: return date.today() if len(sp) != 3: raise Exception day = int(sp[0]) month = int(sp[1]) year = int(sp[2]) return date(day=day, month=month, year=year) def countPdfPages(path): ''' Returns the number of pages in a PDF document using external PyPDF2 module ''' with open(path, 'rb') as f: pdf = PyPDF2.PdfFileReader(f) return pdf.getNumPages() def replacePatternWithField(oTxt, pattern, oField): ''' Replaces a string pattern in a Text object (for example '[PATTERN]') with the given field ''' # pattern may be there many times... repl = False pos = oTxt.String.find(pattern) while pos >= 0: #create a cursor cursor = oTxt.createTextCursor() # use it to select the pattern cursor.collapseToStart() cursor.goRight(pos, False) cursor.goRight(len(pattern), True) # remove the pattern from text cursor.String = '' # insert the field at cursor's position cursor.collapseToStart() oTxt.insertTextContent(cursor, oField, False) # next occurrence of pattern pos = oTxt.String.find(pattern) repl = True return repl
giuserpe/leeno
src/Ultimus.oxt/python/pythonpath/LeenoUtils.py
Python
lgpl-2.1
7,316
/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "qmeminputpin.h" #include "qbasefilter.h" #include "compointer.h" #include <QtCore/QDebug> QT_BEGIN_NAMESPACE namespace Phonon { namespace DS9 { QMemInputPin::QMemInputPin(QBaseFilter *parent, const QVector<AM_MEDIA_TYPE> &mt, bool transform, QPin *output) : QPin(parent, PINDIR_INPUT, mt), m_shouldDuplicateSamples(true), m_transform(transform), m_output(output) { } QMemInputPin::~QMemInputPin() { } STDMETHODIMP QMemInputPin::QueryInterface(REFIID iid, void **out) { if (!out) { return E_POINTER; } if (iid == IID_IMemInputPin) { *out = static_cast<IMemInputPin*>(this); AddRef(); return S_OK; } else { return QPin::QueryInterface(iid, out); } } STDMETHODIMP_(ULONG) QMemInputPin::AddRef() { return QPin::AddRef(); } STDMETHODIMP_(ULONG) QMemInputPin::Release() { return QPin::Release(); } STDMETHODIMP QMemInputPin::EndOfStream() { //this allows to serialize with Receive calls QMutexLocker locker(&m_mutexReceive); IPin *conn = m_output ? m_output->connected() : 0; if (conn) { conn->EndOfStream(); } return S_OK; } STDMETHODIMP QMemInputPin::BeginFlush() { //pass downstream IPin *conn = m_output ? m_output->connected() : 0; if (conn) { conn->BeginFlush(); } QMutexLocker locker(&m_mutex); m_flushing = true; return S_OK; } STDMETHODIMP QMemInputPin::EndFlush() { //pass downstream IPin *conn = m_output ? m_output->connected() : 0; if (conn) { conn->EndFlush(); } QMutexLocker locker(&m_mutex); m_flushing = false; return S_OK; } STDMETHODIMP QMemInputPin::NewSegment(REFERENCE_TIME start, REFERENCE_TIME stop, double rate) { if (m_output) m_output->NewSegment(start, stop, rate); return S_OK; } //reimplementation to set the type for the output pin //no need to make a deep copy here STDMETHODIMP QMemInputPin::ReceiveConnection(IPin *pin ,const AM_MEDIA_TYPE *mt) { HRESULT hr = QPin::ReceiveConnection(pin, mt); if (hr == S_OK && mt->majortype != MEDIATYPE_NULL && mt->subtype != MEDIASUBTYPE_NULL && mt->formattype != GUID_NULL && m_output) { //we tell the output pin that it should connect with this type hr = m_output->setAcceptedMediaType(connectedType()); } return hr; } STDMETHODIMP QMemInputPin::GetAllocator(IMemAllocator **alloc) { if (!alloc) { return E_POINTER; } *alloc = memoryAllocator(true); if (*alloc) { return S_OK; } return VFW_E_NO_ALLOCATOR; } STDMETHODIMP QMemInputPin::NotifyAllocator(IMemAllocator *alloc, BOOL readonly) { if (!alloc) { return E_POINTER; } { QMutexLocker locker(&m_mutex); m_shouldDuplicateSamples = m_transform && readonly; } setMemoryAllocator(alloc); if (m_output) { ComPointer<IMemInputPin> input(m_output, IID_IMemInputPin); input->NotifyAllocator(alloc, m_shouldDuplicateSamples); } return S_OK; } STDMETHODIMP QMemInputPin::GetAllocatorRequirements(ALLOCATOR_PROPERTIES *prop) { if (!prop) { return E_POINTER; } //we have no particular requirements return E_NOTIMPL; } STDMETHODIMP QMemInputPin::Receive(IMediaSample *sample) { QMutexLocker locker(&m_mutexReceive); if (!sample) { return E_POINTER; } if (filterState() == State_Stopped) { return VFW_E_WRONG_STATE; } if (isFlushing()) { return S_FALSE; //we are still flushing } if (!m_shouldDuplicateSamples) { //we do it just once HRESULT hr = m_parent->processSample(sample); if (!SUCCEEDED(hr)) { return hr; } } if (m_output) { IMediaSample *outSample = m_shouldDuplicateSamples ? duplicateSampleForOutput(sample, m_output->memoryAllocator()) : sample; if (m_shouldDuplicateSamples) { m_parent->processSample(outSample); } ComPointer<IMemInputPin> input(m_output->connected(), IID_IMemInputPin); if (input) { input->Receive(outSample); } if (m_shouldDuplicateSamples) { outSample->Release(); } } return S_OK; } STDMETHODIMP QMemInputPin::ReceiveMultiple(IMediaSample **samples,long count,long *nbDone) { //no need to lock here: there is no access to member data if (!samples || !nbDone) { return E_POINTER; } *nbDone = 0; //initialization while( *nbDone != count) { HRESULT hr = Receive(samples[*nbDone]); if (FAILED(hr)) { return hr; } (*nbDone)++; } return S_OK; } STDMETHODIMP QMemInputPin::ReceiveCanBlock() { //we test the output to see if it can block if (m_output) { ComPointer<IMemInputPin> meminput(m_output->connected(), IID_IMemInputPin); if (meminput && meminput->ReceiveCanBlock() != S_FALSE) { return S_OK; } } return S_FALSE; } ALLOCATOR_PROPERTIES QMemInputPin::getDefaultAllocatorProperties() const { //those values reduce buffering a lot (good for the volume effect) ALLOCATOR_PROPERTIES prop = {4096, 1, 1, 0}; return prop; } IMediaSample *QMemInputPin::duplicateSampleForOutput(IMediaSample *sample, IMemAllocator *alloc) { LONG length = sample->GetActualDataLength(); HRESULT hr = alloc->Commit(); if (hr == HRESULT(VFW_E_SIZENOTSET)) { ALLOCATOR_PROPERTIES prop = getDefaultAllocatorProperties(); prop.cbBuffer = qMax(prop.cbBuffer, length); ALLOCATOR_PROPERTIES actual; //we just try to set the properties... alloc->SetProperties(&prop, &actual); hr = alloc->Commit(); } Q_ASSERT(SUCCEEDED(hr)); IMediaSample *out; hr = alloc->GetBuffer(&out, 0, 0, AM_GBF_NOTASYNCPOINT); Q_ASSERT(SUCCEEDED(hr)); //let's copy the sample { REFERENCE_TIME start, end; sample->GetTime(&start, &end); out->SetTime(&start, &end); } hr = out->SetActualDataLength(length); Q_ASSERT(SUCCEEDED(hr)); hr = out->SetDiscontinuity(sample->IsDiscontinuity()); Q_ASSERT(SUCCEEDED(hr)); { LONGLONG start, end; hr = sample->GetMediaTime(&start, &end); if (hr != HRESULT(VFW_E_MEDIA_TIME_NOT_SET)) { hr = out->SetMediaTime(&start, &end); Q_ASSERT(SUCCEEDED(hr)); } } AM_MEDIA_TYPE *type = 0; hr = sample->GetMediaType(&type); Q_ASSERT(SUCCEEDED(hr)); hr = out->SetMediaType(type); Q_ASSERT(SUCCEEDED(hr)); hr = out->SetPreroll(sample->IsPreroll()); Q_ASSERT(SUCCEEDED(hr)); hr = out->SetSyncPoint(sample->IsSyncPoint()); Q_ASSERT(SUCCEEDED(hr)); BYTE *dest = 0, *src = 0; hr = out->GetPointer(&dest); Q_ASSERT(SUCCEEDED(hr)); hr = sample->GetPointer(&src); Q_ASSERT(SUCCEEDED(hr)); memcpy(dest, src, sample->GetActualDataLength()); return out; } } } QT_END_NAMESPACE
KDE/phonon-directshow
src/qmeminputpin.cpp
C++
lgpl-2.1
9,673
/**************************************************************************** ** ** 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 test suite of the Qt Toolkit. ** ** $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 <qtest.h> #include <QtScript> Q_DECLARE_METATYPE(QScriptContext*) Q_DECLARE_METATYPE(QScriptValue) Q_DECLARE_METATYPE(QScriptValueList) //TESTED_FILES= class TestClass : public QScriptClass { public: struct CustomProperty { QueryFlags qflags; uint id; QScriptValue::PropertyFlags pflags; QScriptValue value; CustomProperty(QueryFlags qf, uint i, QScriptValue::PropertyFlags pf, const QScriptValue &val) : qflags(qf), id(i), pflags(pf), value(val) { } }; enum CallableMode { NotCallable, CallableReturnsSum, CallableReturnsArgument, CallableReturnsInvalidVariant }; TestClass(QScriptEngine *engine); ~TestClass(); void addCustomProperty(const QScriptString &name, QueryFlags qflags, uint id, QScriptValue::PropertyFlags pflags, const QScriptValue &value); void removeCustomProperty(const QScriptString &name); QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id); QScriptValue property(const QScriptValue &object, const QScriptString &name, uint id); void setProperty(QScriptValue &object, const QScriptString &name, uint id, const QScriptValue &value); QScriptValue::PropertyFlags propertyFlags( const QScriptValue &object, const QScriptString &name, uint id); QScriptClassPropertyIterator *newIterator(const QScriptValue &object); QScriptValue prototype() const; QString name() const; bool supportsExtension(Extension extension) const; QVariant extension(Extension extension, const QVariant &argument = QVariant()); void setIterationEnabled(bool enable); bool isIterationEnabled() const; void setCallableMode(CallableMode mode); CallableMode callableMode() const; void setHasInstance(bool hasInstance); bool hasInstance() const; private: inline CustomProperty *findCustomProperty(const QScriptString &name); QHash<QScriptString, CustomProperty*> customProperties; QScriptValue m_prototype; bool m_iterationEnabled; CallableMode m_callableMode; bool m_hasInstance; }; class TestClassPropertyIterator : public QScriptClassPropertyIterator { public: TestClassPropertyIterator(const QHash<QScriptString, TestClass::CustomProperty*> &props, const QScriptValue &object); ~TestClassPropertyIterator(); bool hasNext() const; void next(); bool hasPrevious() const; void previous(); void toFront(); void toBack(); QScriptString name() const; uint id() const; QScriptValue::PropertyFlags flags() const; private: int m_index; int m_last; QHash<QScriptString, TestClass::CustomProperty*> m_props; }; TestClass::TestClass(QScriptEngine *engine) : QScriptClass(engine), m_iterationEnabled(true), m_callableMode(NotCallable), m_hasInstance(false) { m_prototype = engine->newObject(); } TestClass::~TestClass() { qDeleteAll(customProperties); } TestClass::CustomProperty* TestClass::findCustomProperty(const QScriptString &name) { QHash<QScriptString, CustomProperty*>::const_iterator it; it = customProperties.constFind(name); if (it == customProperties.constEnd()) return 0; return it.value(); } void TestClass::addCustomProperty(const QScriptString &name, QueryFlags qflags, uint id, QScriptValue::PropertyFlags pflags, const QScriptValue &value) { customProperties.insert(name, new CustomProperty(qflags, id, pflags, value)); } void TestClass::removeCustomProperty(const QScriptString &name) { CustomProperty *prop = customProperties.take(name); if (prop) delete prop; } QScriptClass::QueryFlags TestClass::queryProperty(const QScriptValue &/*object*/, const QScriptString &name, QueryFlags flags, uint *id) { CustomProperty *prop = findCustomProperty(name); if (!prop) return 0; *id = prop->id; return prop->qflags & flags; } QScriptValue TestClass::property(const QScriptValue &/*object*/, const QScriptString &name, uint /*id*/) { CustomProperty *prop = findCustomProperty(name); if (!prop) return QScriptValue(); return prop->value; } void TestClass::setProperty(QScriptValue &/*object*/, const QScriptString &name, uint /*id*/, const QScriptValue &value) { CustomProperty *prop = findCustomProperty(name); if (!prop) return; prop->value = value; } QScriptValue::PropertyFlags TestClass::propertyFlags( const QScriptValue &/*object*/, const QScriptString &name, uint /*id*/) { CustomProperty *prop = findCustomProperty(name); if (!prop) return 0; return prop->pflags; } QScriptClassPropertyIterator *TestClass::newIterator(const QScriptValue &object) { if (!m_iterationEnabled) return 0; return new TestClassPropertyIterator(customProperties, object); } QScriptValue TestClass::prototype() const { return m_prototype; } QString TestClass::name() const { return QLatin1String("TestClass"); } bool TestClass::supportsExtension(Extension extension) const { if (extension == Callable) return (m_callableMode != NotCallable); if (extension == HasInstance) return m_hasInstance; return false; } QVariant TestClass::extension(Extension extension, const QVariant &argument) { if (extension == Callable) { Q_ASSERT(m_callableMode != NotCallable); QScriptContext *ctx = qvariant_cast<QScriptContext*>(argument); if (m_callableMode == CallableReturnsSum) { qsreal sum = 0; for (int i = 0; i < ctx->argumentCount(); ++i) sum += ctx->argument(i).toNumber(); QScriptValueIterator it(ctx->thisObject()); while (it.hasNext()) { it.next(); sum += it.value().toNumber(); } return sum; } else if (m_callableMode == CallableReturnsArgument) { return qVariantFromValue(ctx->argument(0)); } else if (m_callableMode == CallableReturnsInvalidVariant) { return QVariant(); } } else if (extension == HasInstance) { Q_ASSERT(m_hasInstance); QScriptValueList args = qvariant_cast<QScriptValueList>(argument); QScriptValue obj = args.at(0); QScriptValue value = args.at(1); return value.property("foo").equals(obj.property("foo")); } return QVariant(); } void TestClass::setIterationEnabled(bool enable) { m_iterationEnabled = enable; } bool TestClass::isIterationEnabled() const { return m_iterationEnabled; } void TestClass::setCallableMode(CallableMode mode) { m_callableMode = mode; } TestClass::CallableMode TestClass::callableMode() const { return m_callableMode; } void TestClass::setHasInstance(bool hasInstance) { m_hasInstance = hasInstance; } bool TestClass::hasInstance() const { return m_hasInstance; } TestClassPropertyIterator::TestClassPropertyIterator(const QHash<QScriptString, TestClass::CustomProperty*> &props, const QScriptValue &object) : QScriptClassPropertyIterator(object) { m_props = props; toFront(); } TestClassPropertyIterator::~TestClassPropertyIterator() { } bool TestClassPropertyIterator::hasNext() const { return m_index < m_props.size(); } void TestClassPropertyIterator::next() { m_last = m_index; ++m_index; } bool TestClassPropertyIterator::hasPrevious() const { return m_index > 0; } void TestClassPropertyIterator::previous() { --m_index; m_last = m_index; } void TestClassPropertyIterator::toFront() { m_index = 0; m_last = -1; } void TestClassPropertyIterator::toBack() { m_index = m_props.size(); m_last = -1; } QScriptString TestClassPropertyIterator::name() const { return m_props.keys().value(m_last); } uint TestClassPropertyIterator::id() const { QScriptString key = m_props.keys().value(m_last); if (!key.isValid()) return 0; TestClass::CustomProperty *prop = m_props.value(key); return prop->id; } QScriptValue::PropertyFlags TestClassPropertyIterator::flags() const { QScriptString key = m_props.keys().value(m_last); if (!key.isValid()) return 0; TestClass::CustomProperty *prop = m_props.value(key); return prop->pflags; } class tst_QScriptClass : public QObject { Q_OBJECT public: tst_QScriptClass(); virtual ~tst_QScriptClass(); public slots: void init(); void cleanup(); private slots: void noSuchProperty(); void property(); void setProperty(); void propertyFlags(); void call(); void hasInstance(); void iterate(); }; tst_QScriptClass::tst_QScriptClass() { } tst_QScriptClass::~tst_QScriptClass() { } void tst_QScriptClass::init() { } void tst_QScriptClass::cleanup() { } void tst_QScriptClass::noSuchProperty() { QScriptEngine eng; TestClass cls(&eng); QScriptValue obj = eng.newObject(&cls); QString propertyName = QString::fromLatin1("foo"); QBENCHMARK { (void)obj.property(propertyName); } } void tst_QScriptClass::property() { QScriptEngine eng; TestClass cls(&eng); QScriptString foo = eng.toStringHandle("foo"); cls.addCustomProperty(foo, QScriptClass::HandlesReadAccess, /*id=*/1, /*attributes=*/0, /*value=*/123); QScriptValue obj = eng.newObject(&cls); QBENCHMARK { (void)obj.property(foo); } } void tst_QScriptClass::setProperty() { QScriptEngine eng; TestClass cls(&eng); QScriptString foo = eng.toStringHandle("foo"); cls.addCustomProperty(foo, QScriptClass::HandlesWriteAccess, /*id=*/1, /*attributes=*/0, /*value=*/123); QScriptValue obj = eng.newObject(&cls); QScriptValue value(456); QBENCHMARK { obj.setProperty(foo, value); } } void tst_QScriptClass::propertyFlags() { QScriptEngine eng; TestClass cls(&eng); QScriptString foo = eng.toStringHandle("foo"); cls.addCustomProperty(foo, QScriptClass::HandlesReadAccess, /*id=*/1, QScriptValue::ReadOnly, /*value=*/123); QScriptValue obj = eng.newObject(&cls); QBENCHMARK { (void)obj.propertyFlags(foo); } } void tst_QScriptClass::call() { QScriptEngine eng; TestClass cls(&eng); cls.setCallableMode(TestClass::CallableReturnsArgument); QScriptValue obj = eng.newObject(&cls); QScriptValue thisObject; QScriptValueList args; args.append(123); QBENCHMARK { (void)obj.call(thisObject, args); } } void tst_QScriptClass::hasInstance() { QScriptEngine eng; TestClass cls(&eng); cls.setHasInstance(true); QScriptValue obj = eng.newObject(&cls); obj.setProperty("foo", 123); QScriptValue plain = eng.newObject(); plain.setProperty("foo", obj.property("foo")); QBENCHMARK { (void)plain.instanceOf(obj); } } void tst_QScriptClass::iterate() { QScriptEngine eng; TestClass cls(&eng); cls.setIterationEnabled(true); cls.addCustomProperty(eng.toStringHandle("foo"), QScriptClass::HandlesReadAccess, /*id=*/1, /*attributes=*/0, /*value=*/123); cls.addCustomProperty(eng.toStringHandle("bar"), QScriptClass::HandlesReadAccess, /*id=*/2, /*attributes=*/0, /*value=*/456); QScriptValue obj = eng.newObject(&cls); QBENCHMARK { QScriptValueIterator it(obj); while (it.hasNext()) { it.next(); (void)it.scriptName(); } } } QTEST_MAIN(tst_QScriptClass) #include "tst_qscriptclass.moc"
radekp/qt
tests/benchmarks/qscriptclass/tst_qscriptclass.cpp
C++
lgpl-2.1
13,477
--- title: Plugin Tutorial --- ## Introduction At the heart of fwupd is a plugin loader that gets run at startup, when devices get hotplugged and when updates are done. The idea is we have lots of small plugins that each do one thing, and are ordered by dependencies against each other at runtime. Using plugins we can add support for new hardware or new policies without making big changes all over the source tree. There are broadly 3 types of plugin methods: - **Mechanism**: Upload binary data into a specific hardware device. - **Policy**: Control the system when updates are happening, e.g. preventing the user from powering-off. - **Helpers**: Providing more metadata about devices, for instance handling - device quirks. In general, building things out-of-tree isn't something that we think is a very good idea; the API and ABI *internal* to fwupd is still changing and there's a huge benefit to getting plugins upstream where they can undergo review and be ported as the API adapts. For this reason we don't install the plugin headers onto the system, although you can of course just install the `.so` binary file manually. A plugin only needs to define the vfuncs that are required, and the plugin name is taken automatically from the suffix of the `.so` file. /* * Copyright (C) 2017 Richard Hughes */ #include <fu-plugin.h> #include <fu-plugin-vfuncs.h> struct FuPluginData { gpointer proxy; }; void fu_plugin_initialize (FuPlugin *plugin) { fu_plugin_add_rule (plugin, FU_PLUGIN_RULE_RUN_BEFORE, "dfu"); fu_plugin_alloc_data (plugin, sizeof (FuPluginData)); } void fu_plugin_destroy (FuPlugin *plugin) { FuPluginData *data = fu_plugin_get_data (plugin); destroy_proxy (data->proxy); } gboolean fu_plugin_startup (FuPlugin *plugin, GError **error) { FuPluginData *data = fu_plugin_get_data (plugin); data->proxy = create_proxy (); if (data->proxy == NULL) { g_set_error (error, FWUPD_ERROR, FWUPD_ERROR_NOT_SUPPORTED, "failed to create proxy"); return FALSE; } return TRUE; } We have to define when our plugin is run in reference to other plugins, in this case, making sure we run before the `dfu` plugin. For most plugins it does not matter in what order they are run and this information is not required. ## Creating an abstract device This section shows how you would create a device which is exported to the daemon and thus can be queried and updated by the client software. The example here is all hardcoded, and a true plugin would have to derive the details about the `FuDevice` from the hardware, for example reading data from `sysfs` or `/dev`. #include <fu-plugin.h> gboolean fu_plugin_coldplug (FuPlugin *plugin, GError **error) { g_autoptr(FuDevice) dev = NULL; fu_device_set_id (dev, "dummy-1:2:3"); fu_device_add_guid (dev, "2d47f29b-83a2-4f31-a2e8-63474f4d4c2e"); fu_device_set_version (dev, "1.2.3"); fu_device_get_version_lowest (dev, "1.2.2"); fu_device_get_version_bootloader (dev, "0.1.2"); fu_device_add_icon (dev, "computer"); fu_device_add_flag (dev, FWUPD_DEVICE_FLAG_UPDATABLE); fu_plugin_device_add (plugin, dev); return TRUE; } This shows a lot of the plugin architecture in action. Some notable points: - The device ID (`dummy-1:2:3`) has to be unique on the system between all - plugins, so including the plugin name as a prefix is probably a good idea. - The GUID value can be generated automatically using `fu_device_add_guid(dev,"some-identifier")` but is quoted here explicitly. The GUID value has to match the `provides` value in the `.metainfo.xml` file for the firmware update to succeed. - Setting a display name and an icon is a good idea in case the GUI software needs to display the device to the user. Icons can be specified using a full path, although icon theme names should be preferred for most devices. - The `FWUPD_DEVICE_FLAG_UPDATABLE` flag tells the client code that the device is in a state where it can be updated. If the device needs to be in a special mode (e.g. a bootloader) then the `FWUPD_DEVICE_FLAG_NEEDS_BOOTLOADER` flag can also be used. If the update should only be allowed when there is AC power available to the computer (i.e. not on battery) then `FWUPD_DEVICE_FLAG_REQUIRE_AC` should be used as well. There are other flags and the API documentation should be used when choosing what flags to use for each kind of device. - Setting the lowest allows client software to refuse downgrading the device to specific versions. This is required in case the upgrade migrates some kind of data-store so as to be incompatible with previous versions. Similarly, setting the version of the bootloader (if known) allows the firmware to depend on a specific bootloader version, for instance allowing signed firmware to only be installable on hardware with a bootloader new enough to deploy it. ## Mechanism Plugins Although it would be a wonderful world if we could update all hardware using a standard shared protocol this is not the universe we live in. Using a mechanism like DFU or UpdateCapsule means that fwupd will just work without requiring any special code, but for the real world we need to support vendor-specific update protocols with layers of backwards compatibility. When a plugin has created a device that is `FWUPD_DEVICE_FLAG_UPDATABLE` we can ask the daemon to update the device with a suitable `.cab` file. When this is done the daemon checks the update for compatibility with the device, and then calls the vfuncs to update the device. gboolean fu_plugin_write_firmware (FuPlugin *plugin, FuDevice *dev, GBytes *blob_fw, FuProgress *progress, FwupdInstallFlags flags, GError **error) { gsize sz = 0; guint8 *buf = g_bytes_get_data (blob_fw, &sz); /* write 'buf' of size 'sz' to the hardware */ return TRUE; } It's important to note that the `blob_fw` is the binary firmware file (e.g. `.dfu`) and **not** the `.cab` binary data. If `FWUPD_INSTALL_FLAG_FORCE` is used then the usual checks done by the flashing process can be relaxed (e.g. checking for quirks), but please don't brick the users hardware even if they ask you to. ## Policy Helpers For some hardware, we might want to do an action before or after the actual firmware is squirted into the device. This could be something as simple as checking the system battery level is over a certain threshold, or it could be as complicated as ensuring a vendor-specific GPIO is asserted when specific types of hardware are updated. gboolean fu_plugin_prepare (FuPlugin *plugin, FuDevice *device, GError **error) { if (fu_device_has_flag (device, FWUPD_DEVICE_FLAG_REQUIRE_AC && !on_ac_power ()) { g_set_error_literal (error, FWUPD_ERROR, FWUPD_ERROR_AC_POWER_REQUIRED, "Cannot install update " "when not on AC power"); return FALSE; } return TRUE; } gboolean fu_plugin_cleanup (FuPlugin *plugin, FuDevice *device, GError **error) { return g_file_set_contents ("/var/lib/fwupd/something", fu_device_get_id (device), -1, error); } ## Detaching to bootloader mode Some hardware can only be updated in a special bootloader mode, which for most devices can be switched to automatically. In some cases the user to do something manually, for instance re-inserting the hardware with a secret button pressed. Before the device update is performed the fwupd daemon runs an optional `update_detach()` vfunc which switches the device to bootloader mode. After the update (or if the update fails) an the daemon runs an optional `update_attach()` vfunc which should switch the hardware back to runtime mode. Finally an optional `update_reload()` vfunc is run to get the new firmware version from the hardware. The optional vfuncs are **only** run on the plugin currently registered to handle the device ID, although the registered plugin can change during the attach and detach phases. gboolean fu_plugin_detach (FuPlugin *plugin, FuDevice *device, FuProgress *progress, GError **error) { if (hardware_in_bootloader) return TRUE; return _device_detach(device, progress, error); } gboolean fu_plugin_attach (FuPlugin *plugin, FuDevice *device, FuProgress *progress, GError **error) { if (!hardware_in_bootloader) return TRUE; return _device_attach(device, progress, error); } gboolean fu_plugin_reload (FuPlugin *plugin, FuDevice *device, GError **error) { g_autofree gchar *version = _get_version(plugin, device, error); if (version == NULL) return FALSE; fu_device_set_version(device, version); return TRUE; } ## The Plugin Object Cache The fwupd daemon provides a per-plugin cache which allows objects to be added, removed and queried using a specified key. Objects added to the cache must be `GObject`s to enable the cache objects to be properly refcounted. ## Debugging a Plugin If the fwupd daemon is started with `--plugin-verbose=$plugin` then the environment variable `FWUPD_$PLUGIN_VERBOSE` is set process-wide. This allows plugins to detect when they should output detailed debugging information that would normally be too verbose to keep in the journal. For example, using `--plugin-verbose=logitech_hidpp` would set `FWUPD_LOGITECH_HID_VERBOSE=1`. ## Using existing code to develop a plugin It is not usually possible to share a plugin codebase with firmware update programs designed for other operating systems. Matching the same rationale as the Linux kernel, trying to use one code base between projects with a compatibility shim layer in-between is real headache to maintain. The general consensus is that trying to use a abstraction layer for hardware is a very bad idea as you're not able to take advantage of the platform specific helpers -- for instance quirk files and the custom GType device creation. The time the vendor saves by creating a shim layer and importing existing source code into fwupd will be overtaken 100x by upstream maintenance costs longer term, which isn't fair. In a similar way, using C++ rather than GObject C means expanding the test matrix to include clang in C++ mode and GNU g++ too. It's also doubled the runtime requirements to now include both the C standard library as well as the C++ standard library and increases the dependency surface. Most rewritten fwupd plugins at up to x10 smaller than the standalone code as they can take advantage of helpers provided by fwupd rather than re-implementing error handling, device quirking and data chunking.
hughsie/fwupd
docs/tutorial.md
Markdown
lgpl-2.1
11,197
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library 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. * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package de.danielnaber.languagetool.rules.de; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import de.danielnaber.languagetool.AnalyzedSentence; import de.danielnaber.languagetool.AnalyzedToken; import de.danielnaber.languagetool.AnalyzedTokenReadings; import de.danielnaber.languagetool.JLanguageTool; import de.danielnaber.languagetool.rules.Category; import de.danielnaber.languagetool.rules.RuleMatch; /** * A rule that matches words for which two different spellings are used * throughout the document. Currently only implemented for German. Loads * the relevant word from <code>rules/de/coherency.txt</code>. * * <p>Note that this should not be used for language variations like * American English vs. British English or German "alte Rechtschreibung" * vs. "neue Rechtschreibung" -- that's the task of a spell checker. * * @author Daniel Naber */ public class WordCoherencyRule extends GermanRule { private static final String FILE_NAME = "/de/coherency.txt"; private static final String FILE_ENCODING = "utf-8"; private final Map<String, String> relevantWords; // e.g. "aufwendig -> aufwändig" private Map<String, RuleMatch> shouldNotAppearWord = new HashMap<String, RuleMatch>(); // e.g. aufwändig -> RuleMatch of aufwendig private final GermanLemmatizer germanLemmatizer; public WordCoherencyRule(ResourceBundle messages) throws IOException { if (messages != null) super.setCategory(new Category(messages.getString("category_misc"))); relevantWords = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream(FILE_NAME)); germanLemmatizer = new GermanLemmatizer(); } @Override public String getId() { return "DE_WORD_COHERENCY"; } @Override public String getDescription() { return "Einheitliche Schreibweise für Wörter mit mehr als einer korrekten Schreibweise"; } @Override public RuleMatch[] match(AnalyzedSentence text) { final List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>(); final AnalyzedTokenReadings[] tokens = text.getTokens(); int pos = 0; for (AnalyzedTokenReadings tmpToken : tokens) { //TODO: definitely should be changed //if the general lemmatizer is working //defaulting to the first element because the //general German lemmatizer is not (yet) there String token = tmpToken.getToken(); if (tmpToken.isWhitespace()) { // ignore } else { final String origToken = token; final List<AnalyzedToken> readings = tmpToken.getReadings(); // TODO: in theory we need to care about the other readings, too: if (readings != null && readings.size() > 0) { final String baseform = readings.get(0).getLemma(); if (baseform != null) { token = baseform; } else { // not all words are known by the Tagger (esp. compounds), so use the // file lookup: final String manualLookup = germanLemmatizer.getBaseform(origToken); if (manualLookup != null) token = manualLookup; } } if (shouldNotAppearWord.containsKey(token)) { final RuleMatch otherMatch = shouldNotAppearWord.get(token); final String otherSpelling = otherMatch.getMessage(); final String msg = "'" + token + "' und '" + otherSpelling + "' sollten nicht gleichzeitig benutzt werden"; final RuleMatch ruleMatch = new RuleMatch(this, pos, pos + origToken.length(), msg); ruleMatch.setSuggestedReplacement(otherSpelling); ruleMatches.add(ruleMatch); } else if (relevantWords.containsKey(token)) { final String shouldNotAppear = relevantWords.get(token); // only used to display this spelling variation if the other one really occurs: final RuleMatch potentialRuleMatch = new RuleMatch(this, pos, pos + origToken.length(), token); shouldNotAppearWord.put(shouldNotAppear, potentialRuleMatch); } } pos += tmpToken.getToken().length(); } return toRuleMatchArray(ruleMatches); } private Map<String, String> loadWords(InputStream file) throws IOException { final Map<String, String> map = new HashMap<String, String>(); InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(file, FILE_ENCODING); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() < 1) { continue; } if (line.charAt(0) == '#') { // ignore comments continue; } final String[] parts = line.split(";"); if (parts.length != 2) { throw new IOException("Format error in file " + JLanguageTool.getDataBroker().getFromRulesDirAsUrl(FILE_NAME) + ", line: " + line); } map.put(parts[0], parts[1]); map.put(parts[1], parts[0]); } } finally { if (br != null) br.close(); if (isr != null) isr.close(); } return map; } @Override public void reset() { shouldNotAppearWord = new HashMap<String, RuleMatch>(); } }
ManolitoOctaviano/Language-Identification
src/java/de/danielnaber/languagetool/rules/de/WordCoherencyRule.java
Java
lgpl-2.1
6,293
#******************************************************************************* # PPPPPPPP # # "@(#) $Id: Makefile,v 1.1 2011/01/19 20:55:12 tstaig Exp $" # # Makefile of ........ # # who when what # -------- -------- ---------------------------------------------- # almadev 19/01/11 created # #******************************************************************************* # This Makefile follows VLT Standards (see Makefile(5) for more). #******************************************************************************* # REMARKS # None #------------------------------------------------------------------------ # List of files to be linked LINK_FILES = # # # user definable C-compilation flags #USER_CFLAGS = # # additional include and library search paths #USER_INC = #USER_LIB = # # MODULE CODE DESCRIPTION: # ------------------------ # As a general rule: public file are "cleaned" and "installed" # local (_L) are not "installed". # # C programs (public and local) # ----------------------------- EXECUTABLES = EXECUTABLES_L = # # <brief description of xxxxx program> xxxxx_OBJECTS = xxxxx_LDFLAGS = xxxxx_LIBS = # # special compilation flags for single c sources #yyyyy_CFLAGS = # # Includes (.h) files (public only) # --------------------------------- INCLUDES = # # Libraries (public and local) # ---------------------------- LIBRARIES = LIBRARIES_L = # # <brief description of lllll library> lllll_OBJECTS = # # Scripts (public and local) # ---------------------------- SCRIPTS = SCRIPTS_L = # # TCL scripts (public and local) # ------------------------------ TCL_SCRIPTS = TCL_SCRIPTS_L = # # <brief description of tttttt tcl-script> tttttt_OBJECTS = tttttt_TCLSH = tttttt_LIBS = # # TCL libraries (public and local) # ------------------------------ TCL_LIBRARIES = TCL_LIBRARIES_L = # # <brief description of tttlll library> tttlll_OBJECTS = # # IDL Files and flags # IDL_FILES = TAO_IDLFLAGS = USER_IDL = # # Configuration Database Files # ---------------------------- CDB_SCHEMAS = # # man pages to be done # -------------------- MANSECTIONS = MAN1 = MAN3 = MAN5 = MAN7 = MAN8 = # # local man pages # --------------- MANl = # # ASCII file to be converted into Framemaker-MIF # -------------------- ASCII_TO_MIF = # # other files to be installed #---------------------------- INSTALL_FILES = # # list of all possible C-sources (used to create automatic dependencies) # ------------------------------ CSOURCENAMES = \ $(foreach exe, $(EXECUTABLES) $(EXECUTABLES_L), $($(exe)_OBJECTS)) \ $(foreach lib, $(LIBRARIES) $(LIBRARIES_L), $($(lib)_OBJECTS)) # #>>>>> END OF standard rules # # CHOSE PLATFORM # -------------- # This is a LCU Makefile, so for VxVorks applications we set: MAKE_VXWORKS = on # # INCLUDE STANDARDS # ----------------- MAKEDIRTMP := $(shell searchFile include/acsMakefile) ifneq ($(MAKEDIRTMP),\#error\#) MAKEDIR := $(MAKEDIRTMP)/include include $(MAKEDIR)/acsMakefile endif # # TARGETS # ------- all: do_all @echo " . . . 'all' done" clean : clean_all @echo " . . . clean done" clean_dist : clean_all clean_dist_all @echo " . . . clean_dist done" man : do_man @echo " . . . man page(s) done" install : install_all @echo " . . . installation done" #___oOo___
jbarriosc/ACSUFRO
LGPL/CommonSoftware/monitoring/monicd/lcu/src/Makefile
Makefile
lgpl-2.1
3,365
/* * Copyright (C) 2011 Apple Inc. All Rights Reserved. * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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. */ #ifndef WebSocketServer_h #define WebSocketServer_h #if ENABLE(INSPECTOR_SERVER) #include <wtf/Deque.h> #include <wtf/OwnPtr.h> #include <wtf/text/WTFString.h> #if PLATFORM(QT) namespace WebKit { class QtTcpServerHandler; } #endif namespace WebCore { class SocketStreamHandle; } namespace WebKit { class WebSocketServerClient; class WebSocketServerConnection; class WebSocketServer { public: enum ServerState { Closed, Listening }; WebSocketServer(WebSocketServerClient*); virtual ~WebSocketServer(); // Server operations. bool listen(const String& bindAddress, unsigned short port); String bindAddress() const { return m_bindAddress; }; unsigned short port() const { return m_port; }; ServerState serverState() const { return m_state; }; void close(); WebSocketServerClient* client() const { return m_client; } void didAcceptConnection(PassOwnPtr<WebSocketServerConnection>); private: void didCloseWebSocketServerConnection(WebSocketServerConnection*); void platformInitialize(); bool platformListen(const String& bindAddress, unsigned short port); void platformClose(); ServerState m_state; Deque<OwnPtr<WebSocketServerConnection> > m_connections; WebSocketServerClient* m_client; String m_bindAddress; unsigned short m_port; #if PLATFORM(QT) OwnPtr<QtTcpServerHandler> m_tcpServerHandler; #endif friend class WebSocketServerConnection; }; } #endif // ENABLE(INSPECTOR_SERVER) #endif // WebSocketServer_h
youfoh/webkit-efl
Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h
C
lgpl-2.1
2,910
/* Copyright (c) 2010 JOSE, Hércules S. S. et al. Este arquivo é parte do programa SIRCE. SIRCE é um software livre; você pode redistribui-lo e/ou modificá-lo dentro dos termos da Licença Pública Geral Menor GNU como publicada pela Fundação do Software Livre (FSF); na versão 2.1 da Licença. Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral Menor GNU em português para maiores detalhes. Você deve ter recebido uma cópia da Licença Pública Geral Menor GNU sob o nome de "LICENSE.TXT" junto com este programa, se não, acesse o site HSlife no endereco www.hslife.com.br ou escreva para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. Para mais informações sobre o programa SIRCE e seus autores acesse o endereço www.hslife.com.br, pelo e-mail contato@hslife.com.br ou escreva para Hércules S. S. José, Av. Ministro Lafaeyte de Andrade, 1683 - Bl. 3 Apt 404, Marco II - Nova Iguaçu, RJ, Brasil. */ package br.com.hslife.sirce.persistencia; import java.util.Date; import java.util.List; import br.com.hslife.sirce.modelo.AgendaDiaria; public class AgendaDiariaDao extends GenericDao implements InterfaceDao<AgendaDiaria> { public void salvar(AgendaDiaria obj) { // TODO Auto-generated method stub save(obj); } public void alterar(AgendaDiaria obj) { // TODO Auto-generated method stub update(obj); } public void excluir(AgendaDiaria obj) { // TODO Auto-generated method stub delete(obj); } public AgendaDiaria buscar(Integer id) { // TODO Auto-generated method stub return (AgendaDiaria) find(AgendaDiaria.class, id); } public AgendaDiaria buscar(String campo, Object valor) { // TODO Auto-generated method stub return (AgendaDiaria) find(AgendaDiaria.class, campo, valor); } public List<AgendaDiaria> listar(String campo, Object valor) { // TODO Auto-generated method stub return (List) findAll(AgendaDiaria.class, campo, valor); } public List<AgendaDiaria> listarTodos() { // TODO Auto-generated method stub Date hoje = new Date(); String sqlQuery = "select * from AgendaDiaria where data>='"+(hoje.getYear()+1900)+"-"+(hoje.getMonth()+1)+"-"+hoje.getDate()+"'" ; return (List) query(AgendaDiaria.class, sqlQuery); } public List<AgendaDiaria> procurar(String campo, Object valor) { // TODO Auto-generated method stub return (List) search("AgendaDiaria", campo, (String)valor); } }
herculeshssj/sirce
src/br/com/hslife/sirce/persistencia/AgendaDiariaDao.java
Java
lgpl-2.1
2,813