id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,532,511
mark.h
canorusmusic_canorus/src/score/mark.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef MARK_H_ #define MARK_H_ #include "score/muselement.h" class CAContext; class CAMark : public CAMusElement { public: enum CAMarkType { Undefined = -1, Text, Tempo, Ritardando, Dynamic, Crescendo, Pedal, InstrumentChange, BookMark, RehersalMark, Fermata, RepeatMark, Articulation, Fingering }; CAMark(CAMarkType type, CAMusElement* associatedElt, int timeStart = -1, int timeLength = -1); CAMark(CAMarkType type, CAContext* context, int timeStart, int timeLength); virtual ~CAMark(); virtual CAMark* clone(CAContext* context) { CAMark* c = clone(); c->setContext(context); return c; } virtual CAMark* clone(CAMusElement* elt = nullptr); virtual int compare(CAMusElement* elt); inline CAMusElement* associatedElement() { return _associatedElt; } inline void setAssociatedElement(CAMusElement* elt) { _associatedElt = elt; if (elt) _context = elt->context(); } inline CAMarkType markType() { return _markType; } inline void setMarkType(CAMarkType type) { _markType = type; } inline bool isCommon() { return _common; } static const QString markTypeToString(CAMarkType t); static CAMarkType markTypeFromString(const QString s); protected: inline void setCommon(bool c) { _common = c; } private: CAMusElement* _associatedElt; CAMarkType _markType; bool _common; // is mark assigned to a single element only or the whole chord - depends who deletes it! }; #endif /* MARK_H_ */
1,860
C++
.h
58
26.362069
107
0.675056
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,512
bookmark.h
canorusmusic_canorus/src/score/bookmark.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef BOOKMARK_H_ #define BOOKMARK_H_ #include "score/mark.h" #include <QString> class CABookMark : public CAMark { public: CABookMark(const QString text, CAMusElement* m); virtual ~CABookMark(); inline const QString text() { return _text; } inline void setText(const QString t) { _text = t; } CABookMark* clone(CAMusElement* elt = 0); int compare(CAMusElement* elt); private: QString _text; }; #endif /* BOOKMARK_H_ */
671
C++
.h
21
29.095238
76
0.728972
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,513
lyricscontext.h
canorusmusic_canorus/src/score/lyricscontext.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef LYRICSCONTEXT_H_ #define LYRICSCONTEXT_H_ #include "score/context.h" #include "score/voice.h" #include <QHash> #include <QList> class CASyllable; class CALyricsContext : public CAContext { public: CALyricsContext(const QString name, int stanzaNumber, CAVoice* v); CALyricsContext(const QString name, int stanzaNumber, CASheet* s); ~CALyricsContext(); CALyricsContext* clone(CASheet* s); void cloneLyricsContextProperties(CALyricsContext*); CAMusElement* next(CAMusElement*); CAMusElement* previous(CAMusElement*); bool remove(CAMusElement*); CAMusElement *insertEmptyElement(int timeStart); void repositionElements(); void clear(); inline const QList<CASyllable*>& syllableList() { return _syllableList; } bool addSyllable(CASyllable*, bool replace = true); // void removeSyllable( CASyllable* s ) { _syllableList.removeAll(s); } CASyllable* removeSyllableAtTimeStart(int timeStart); CASyllable* syllableAtTimeStart(int timeStart); inline CAVoice* associatedVoice() { return _associatedVoice; } void setAssociatedVoice(CAVoice* v); inline int stanzaNumber() { return _stanzaNumber; } inline void setStanzaNumber(int sn) { _stanzaNumber = sn; } inline QString customStanzaName() { return _customStanzaName; } inline void setCustomStanzaName(QString name) { _customStanzaName = name; } private: QList<CASyllable*> _syllableList; CAVoice* _associatedVoice; int _stanzaNumber; QString _customStanzaName; }; #endif /* LYRICSCONTEXT_H_ */
1,769
C++
.h
43
37.395349
79
0.755102
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,514
midinote.h
canorusmusic_canorus/src/score/midinote.h
/*! Copyright (c) 2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef MIDINOTE_H_ #define MIDINOTE_H_ #include "score/playable.h" class CAVoice; class CAMidiNote : public CAPlayable { public: CAMidiNote(int pitch, int timeStart, int timeLength, CAVoice* v); virtual ~CAMidiNote(); CAMidiNote* clone(CAVoice* voice = nullptr); int compare(CAMusElement* elt); int midiPitch() { return _midiPitch; } void setMidiPitch(int m) { _midiPitch = m; } private: int _midiPitch; }; #endif /* MIDINOTE_H_ */
683
C++
.h
21
29.619048
76
0.735069
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,515
articulation.h
canorusmusic_canorus/src/score/articulation.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef ARTICULATION_H_ #define ARTICULATION_H_ #include "score/mark.h" #include "score/note.h" class CAArticulation : public CAMark { public: enum CAArticulationType { Undefined = -1, Accent, Marcato, Staccatissimo, Espressivo, Staccato, Tenuto, Portato, UpBow, DownBow, Flageolet, Open, Stopped, Turn, ReverseTurn, Trill, Prall, Mordent, PrallPrall, PrallMordent, UpPrall, DownPrall, UpMordent, DownMordent, PrallDown, PrallUp, LinePrall, Breath }; CAArticulation(CAArticulationType t, CANote* n); virtual ~CAArticulation(); CAArticulation* clone(CAMusElement* elt); int compare(CAMusElement* elt); inline CANote* associatedNote() { return static_cast<CANote*>(associatedElement()); } inline void* setAssociatedNote(CANote* n) { setAssociatedElement(n); return n; } inline CAArticulationType articulationType() { return _articulationType; } inline void setArticulationType(CAArticulationType t) { _articulationType = t; } static const QString articulationTypeToString(CAArticulationType t); static CAArticulationType articulationTypeFromString(const QString s); private: CAArticulationType _articulationType; }; #endif /* ARTICULATION_H_ */
1,667
C++
.h
59
21.932203
89
0.670632
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,516
context.h
canorusmusic_canorus/src/score/context.h
/*! Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef CONTEXT_H_ #define CONTEXT_H_ #include <QString> class CASheet; class CAMusElement; class CAContext { public: CAContext(const QString name, CASheet* s); virtual ~CAContext(); virtual CAContext* clone(CASheet*) = 0; enum CAContextType { Staff, LyricsContext, FunctionMarkContext, FiguredBassContext, ChordNameContext }; const QString name() { return _name; } void setName(const QString name) { _name = name; } CAContextType contextType() { return _contextType; } CASheet* sheet() { return _sheet; } void setSheet(CASheet* sheet) { _sheet = sheet; } virtual void clear() = 0; virtual CAMusElement* next(CAMusElement* elt) = 0; virtual CAMusElement* previous(CAMusElement* elt) = 0; virtual bool remove(CAMusElement* elt) = 0; virtual CAMusElement *insertEmptyElement(int timeStart) = 0; virtual void repositionElements() = 0; protected: void setContextType(CAContextType t) { _contextType = t; } CASheet* _sheet; QString _name; CAContextType _contextType; }; #endif /* CONTEXT_H_ */
1,336
C++
.h
40
29
72
0.705378
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,517
barline.h
canorusmusic_canorus/src/score/barline.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef BARLINE_H_ #define BARLINE_H_ #include "score/muselement.h" class CAStaff; class CAContext; class CABarline : public CAMusElement { public: enum CABarlineType { Undefined = -1, Single, Double, End, RepeatOpen, RepeatClose, RepeatCloseOpen, Dotted }; CABarline(CABarlineType type, CAStaff* staff, int startTime); virtual ~CABarline(); CABarline* clone(CAContext* context = 0); int compare(CAMusElement* elt); CABarlineType barlineType() { return _barlineType; } void setBarlineType(CABarlineType t) { _barlineType = t; } static const QString barlineTypeToString(CABarlineType); static CABarlineType barlineTypeFromString(const QString); private: CABarlineType _barlineType; }; #endif /* BARLINE_H_ */
1,044
C++
.h
34
26.147059
76
0.719
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,518
ritardando.h
canorusmusic_canorus/src/score/ritardando.h
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef RITARDANDO_H_ #define RITARDANDO_H_ #include "score/mark.h" class CAPlayable; class CARitardando : public CAMark { public: enum CARitardandoType { Ritardando, Accellerando }; CARitardando(int finalTempo, CAPlayable* p, int timeLength, CARitardandoType t = Ritardando); virtual ~CARitardando(); CARitardando* clone(CAMusElement* elt = nullptr); int compare(CAMusElement*); inline int finalTempo() { return _finalTempo; } inline void setFinalTempo(const int t) { _finalTempo = t; } inline CARitardandoType ritardandoType() { return _ritardandoType; } inline void setRitardandoType(CARitardandoType t) { _ritardandoType = t; } static const QString ritardandoTypeToString(CARitardandoType t); static CARitardandoType ritardandoTypeFromString(const QString r); private: int _finalTempo; // tempo bpm at the end CARitardandoType _ritardandoType; }; #endif /* RITARDANDO_H_ */
1,174
C++
.h
30
35.266667
97
0.752868
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,519
crescendo.h
canorusmusic_canorus/src/score/crescendo.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef CRESCENDO_H_ #define CRESCENDO_H_ #include "score/mark.h" class CANote; class CACrescendo : public CAMark { public: enum CACrescendoType { Crescendo, Decrescendo }; CACrescendo(int finalVolume, CANote* note, CACrescendoType t = Crescendo, int timeStart = -1, int timeLength = -1); virtual ~CACrescendo(); CACrescendo* clone(CAMusElement* elt = nullptr); int compare(CAMusElement*); inline int finalVolume() { return _finalVolume; } inline void setFinalVolume(const int v) { _finalVolume = v; } inline CACrescendoType crescendoType() { return _crescendoType; } inline void setCrescendoType(CACrescendoType t) { _crescendoType = t; } static const QString crescendoTypeToString(CACrescendoType t); static CACrescendoType crescendoTypeFromString(const QString r); private: int _finalVolume; // volume percantage - from 0% to 100% CACrescendoType _crescendoType; }; #endif /* CRESCENDO_H_ */
1,191
C++
.h
30
35.833333
119
0.742609
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,520
sheet.h
canorusmusic_canorus/src/score/sheet.h
/*! Copyright (c) 2006-2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef SHEET_H_ #define SHEET_H_ #include <QList> #include <QString> #include "score/context.h" #include "score/staff.h" class CADocument; class CAPlayable; class CATempo; class CANoteCheckerError; class CASheet { public: CASheet(const QString name, CADocument* doc); ~CASheet(); CASheet* clone(CADocument* doc); inline CASheet* clone() { return clone(document()); } inline const QList<CAContext*>& contextList() { return _contextList; } CAContext* findContext(const QString name); inline void insertContext(int pos, CAContext* c) { _contextList.insert(pos, c); } void insertContextAfter(CAContext* after, CAContext* c); inline void addContext(CAContext* c) { _contextList << c; } inline void removeContext(CAContext* c) { _contextList.removeAll(c); } QString findUniqueContextName(QString mask); CAStaff* addStaff(); QList<CAStaff*> staffList(); // generated list QList<CAVoice*> voiceList(); // generated list QList<CAPlayable*> getChord(int time); CATempo* getTempo(int time); inline CADocument* document() { return _document; } inline void setDocument(CADocument* doc) { _document = doc; } inline const QString name() { return _name; } inline void setName(const QString name) { _name = name; } inline void addNoteCheckerError(CANoteCheckerError* nce) { _noteCheckerErrorList << nce; } void clearNoteCheckerErrors(); inline QList<CANoteCheckerError*>& noteCheckerErrorList() { return _noteCheckerErrorList; } void clear(); private: QList<CAContext*> _contextList; CADocument* _document; QList<CANoteCheckerError*> _noteCheckerErrorList; QString _name; }; #endif /*SHEET_H_*/
1,924
C++
.h
48
36.375
95
0.731865
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,521
fermata.h
canorusmusic_canorus/src/score/fermata.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef FERMATA_H_ #define FERMATA_H_ #include "score/mark.h" class CAPlayable; class CABarline; class CAFermata : public CAMark { public: enum CAFermataType { NormalFermata, ShortFermata, LongFermata, VeryLongFermata }; CAFermata(CAPlayable* m, CAFermataType t = NormalFermata); CAFermata(CABarline* b, CAFermataType t = NormalFermata); virtual ~CAFermata(); CAFermata* clone(CAMusElement* elt = nullptr); int compare(CAMusElement*); inline CAFermataType fermataType() { return _fermataType; } inline void setFermataType(CAFermataType t) { _fermataType = t; } static const QString fermataTypeToString(CAFermataType t); static CAFermataType fermataTypeFromString(const QString r); private: CAFermataType _fermataType; }; #endif /* FERMATA_H_ */
1,049
C++
.h
31
29.806452
76
0.743793
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,522
figuredbassmark.h
canorusmusic_canorus/src/score/figuredbassmark.h
/*! Copyright (c) 2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef FIGUREDBASSMARK_H_ #define FIGUREDBASSMARK_H_ #include "score/muselement.h" #include <QHash> #include <QList> class CAFiguredBassContext; class CAFiguredBassMark : public CAMusElement { public: CAFiguredBassMark(CAFiguredBassContext* c, int timeStart, int timeLength); ~CAFiguredBassMark(); CAMusElement* clone(CAContext* context = nullptr); int compare(CAMusElement* elt); void addNumber(int number); void addNumber(int number, int accs); void removeNumber(int number); QList<int>& numbers() { return _numbers; } QHash<int, int>& accs() { return _accs; } private: void insertNumber(int number); QList<int> _numbers; // sorted numbers in the figured bass mark QHash<int, int> _accs; }; #endif /* FIGUREDBASSMARK_H_ */
998
C++
.h
28
32.428571
78
0.745568
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,523
tuplet.h
canorusmusic_canorus/src/score/tuplet.h
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef TUPLET_H_ #define TUPLET_H_ #include "score/muselement.h" class CAContext; class CAVoice; class CASlur; class CATuplet : public CAMusElement { public: CATuplet(int number, int actualNumber, QList<CAPlayable*> noteList); CATuplet(int number, int actualNumber); virtual ~CATuplet(); CATuplet* clone(CAContext* context = nullptr); CATuplet* clone(QList<CAPlayable*> newList); int compare(CAMusElement*); inline int number() { return _number; } inline void setNumber(int n) { _number = n; } inline int actualNumber() { return _actualNumber; } inline void setActualNumber(int n) { _actualNumber = n; } inline const QList<CAPlayable*>& noteList() const { return _noteList; } void addNote(CAPlayable* p); inline void addNotes(QList<CAPlayable*> l) { _noteList << l; } inline void removeNote(CAPlayable* p) { _noteList.removeAll(p); } CAPlayable* firstNote(); CAPlayable* lastNote(); inline bool containsNote(CAPlayable* p) { return noteList().contains(p); } CAPlayable* nextTimed(CAPlayable* p); int timeLength() const; int timeStart() const; void assignTimes(); private: void resetTimes(); QList<QList<CASlur*>> getNoteSlurs(); void assignNoteSlurs(QList<QList<CASlur*>>); int _number; int _actualNumber; QList<CAPlayable*> _noteList; }; #endif /* TUPLET_H_ */
1,599
C++
.h
43
33.255814
78
0.71512
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,524
functionmark.h
canorusmusic_canorus/src/score/functionmark.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICNESE.GPL for details. */ #ifndef FUNCTIONMARK_H_ #define FUNCTIONMARK_H_ #include <QList> #include <QString> #include "score/diatonickey.h" #include "score/functionmarkcontext.h" #include "score/muselement.h" class CAFunctionMark : public CAMusElement { public: enum CAFunctionType { Undefined = 0, // no degree - extend the previous one I = 1, // 1st II = 2, // 2nd III = 3, // 3rd IV = 4, // 4th V = 5, // 5th VI = 6, // 6th VII = 7, // 7th T = 8, // Tonic S = 9, // Subdominant D = 10, // Dominant F = 11, // Phrygian (F for Frigio in Italian) N = 12, // Napolitan L = 13, // Lidian K = 14 // Cadenze chord (see http://en.wikipedia.org/wiki/Cadence_%28music%29) }; // addedDegrees and alteredDegrees are generated from alterations parameter CAFunctionMark(CAFunctionType function, bool minor, const CADiatonicKey key, CAFunctionMarkContext* context, int timeStart, int timeLength, CAFunctionType chordArea = Undefined, bool chordAreaMinor = false, CAFunctionType tonicDegree = T, bool tonicDegreeMinor = false, const QString alterations = "", bool ellipseSequence = false); CAFunctionMark* clone(CAContext* context = nullptr); void clear(); // same as in CASyllable ~CAFunctionMark(); inline CAFunctionMarkContext* fmContext() { return static_cast<CAFunctionMarkContext*>(context()); } CAFunctionType function() { return _function; } CADiatonicKey key() { return _key; } CAFunctionType chordArea() { return _chordArea; } CAFunctionType tonicDegree() { return _tonicDegree; } QList<int> alteredDegrees() { return _alteredDegrees; } QList<int> addedDegrees() { return _addedDegrees; } void setFunction(CAFunctionType function) { _function = function; } void setKey(CADiatonicKey key) { _key = key; } void setChordArea(CAFunctionType chordArea) { _chordArea = chordArea; } void setChordAreaMinor(bool minor) { _chordAreaMinor = minor; } void setTonicDegree(CAFunctionType tonicDegree) { _tonicDegree = tonicDegree; } void setTonicDegreeMinor(bool minor) { _tonicDegreeMinor = minor; } void setAlteredDegrees(QList<int> degrees) { _alteredDegrees = degrees; } void setAddedDegrees(QList<int> degrees) { _addedDegrees = degrees; } void setMinor(bool minor) { _minor = minor; } void setEllipse(bool ellipse) { _ellipseSequence = ellipse; } void setAlterations(const QString alterations); inline bool isEmpty() { return (function() == Undefined && chordArea() == Undefined && tonicDegree() == T && !alteredDegrees().size() && !addedDegrees().size()); } bool isSideDegree(); bool isMinor() { return _minor; } bool isChordAreaMinor() { return _chordAreaMinor; } bool isTonicDegreeMinor() { return _tonicDegreeMinor; } bool isPartOfEllipse() { return _ellipseSequence; } int compare(CAMusElement* function); static const QString functionTypeToString(CAFunctionType); static CAFunctionType functionTypeFromString(const QString); private: CAFunctionType _function; // Function name CADiatonicKey _key; // C for C-Major, g for g-minor, bes for b-flat-minor, Fis for F-sharp-Major etc. CAFunctionType _chordArea; // Side degrees have undetermined chord locations (eg. 6th can be treated as chord of Subdominant or Tonic) bool _chordAreaMinor; // Is chord area minor? CAFunctionType _tonicDegree; // Used when doing tonicization (see http://en.wikipedia.org/wiki/Tonicization). This value is always set if the function name is set. bool _tonicDegreeMinor; // Is tonic degree minor? QList<int> _alteredDegrees; // Degree of the chord which are altered according to the current key. These marks are usually written below the function name, eg. -3, -7 for German chord QList<int> _addedDegrees; // Degrees of the chord which are added to or substracted from the basic. eg. sixte ajoutée in cadence bool _minor; // Should the function have a circle drawn? bool _ellipseSequence; // Function is part of ellipse? }; #endif /* FUNCTIONMARK_H_ */
4,329
C++
.h
76
51.842105
336
0.711489
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,525
staff.h
canorusmusic_canorus/src/score/staff.h
/*! Copyright (c) 2006-2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef STAFF_H_ #define STAFF_H_ #include <QList> #include <QString> class QPainter; #include "score/context.h" #include "score/muselement.h" class CASheet; class CAContext; class CAVoice; class CANote; class CATempo; class CAStaff : public CAContext { public: CAStaff(const QString name, CASheet* s, int numberOfLines = 5); ~CAStaff(); inline int numberOfLines() { return _numberOfLines; } inline void setNumberOfLines(int val) { _numberOfLines = val; } void clear(); CAStaff* clone(CASheet* s); inline const QList<CAVoice*>& voiceList() { return _voiceList; } inline void addVoice(CAVoice* voice) { _voiceList << voice; } inline void insertVoice(int idx, CAVoice* voice) { _voiceList.insert(idx, voice); } CAVoice* addVoice(); inline void removeVoice(CAVoice* voice) { _voiceList.removeAll(voice); } CAVoice* findVoice(const QString name); CAMusElement* next(CAMusElement* elt); CAMusElement* previous(CAMusElement* elt); bool remove(CAMusElement* elt, bool updateSignTimes); bool remove(CAMusElement* elt) { return remove(elt, true); } CAMusElement *insertEmptyElement(int timeStart); void repositionElements() {} int lastTimeEnd(); QList<CAMusElement*> getEltByType(CAMusElement::CAMusElementType type, int startTime); CAMusElement* getOneEltByType(CAMusElement::CAMusElementType type, int startTime); QList<CAPlayable*> getChord(int time); CATempo* getTempo(int time); bool synchronizeVoices(); static bool placeAutoBar(CAPlayable* elt); // Functions to keep list of references of signature events for a faster look up. inline QList<CAMusElement*>& clefRefs() { return _clefList; } inline QList<CAMusElement*>& keySignatureRefs() { return _keySignatureList; } inline QList<CAMusElement*>& timeSignatureRefs() { return _timeSignatureList; } inline QList<CAMusElement*>& barlineRefs() { return _barlineList; } private: QList<CAVoice*> _voiceList; int _numberOfLines; QList<CAMusElement*> _clefList; QList<CAMusElement*> _keySignatureList; QList<CAMusElement*> _timeSignatureList; QList<CAMusElement*> _barlineList; }; #endif /* STAFF_H_ */
2,424
C++
.h
58
37.948276
90
0.74063
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,526
clef.h
canorusmusic_canorus/src/score/clef.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef CLEF_H_ #define CLEF_H_ #include <QString> #include "score/muselement.h" #include "score/staff.h" class CAContext; class CAClef : public CAMusElement { public: enum CAPredefinedClefType { Undefined = -1, Treble, Bass, French, Soprano, Mezzosoprano, Alto, Tenor, Baritone, Varbaritone, Subbass, Percussion, Tablature }; enum CAClefType { F, G, C, PercussionHigh, PercussionLow, Tab }; CAClef(CAPredefinedClefType type, CAStaff* staff, int time, int offsetInterval = 0); CAClef(CAClefType type, int c1, CAStaff* staff, int time, int offset = 0); CAClef* clone(CAContext* context = nullptr); CAStaff* staff() { return static_cast<CAStaff*>(context()); } void setPredefinedType(CAPredefinedClefType type); CAClefType clefType() { return _clefType; } int c1() { return _c1; } int centerPitch() { return _centerPitch; } int compare(CAMusElement* elt); void setClefType(CAClefType type); inline void setOffset(int offset) { _c1 += _offset; _c1 -= (_offset = offset); } inline int offset() { return _offset; } static const QString clefTypeToString(CAClefType); static CAClefType clefTypeFromString(const QString); static int offsetFromReadable(const int offsetInterval); static int offsetToReadable(const int offset); private: CAClefType _clefType; int _c1; // Location of middle C in the staff from the bottom line up int _centerPitch; // Location of the clefs physical center (where the clef's glyph is going to be rendered) int _offset; }; #endif /* CLEF_H_ */
1,968
C++
.h
63
25.650794
111
0.670545
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,527
notecheckererror.h
canorusmusic_canorus/src/score/notecheckererror.h
/*! Copyright (c) 2015, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef NOTECHECKERERROR_H_ #define NOTECHECKERERROR_H_ #include <QString> class CAMusElement; class CANoteCheckerError { public: CANoteCheckerError(CAMusElement* targetElement, QString message); ~CANoteCheckerError(); private: CAMusElement* _targetElement; QString _message; }; #endif /* NOTECHECKERERROR_H_ */
547
C++
.h
18
28
76
0.787763
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,528
figuredbasscontext.h
canorusmusic_canorus/src/score/figuredbasscontext.h
/*! Copyright (c) 2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef FIGUREDBASSCONTEXT_H_ #define FIGUREDBASSCONTEXT_H_ #include "score/context.h" #include <QList> class CAFiguredBassMark; class CAFiguredBassContext : public CAContext { public: CAFiguredBassContext(QString name, CASheet* sheet); ~CAFiguredBassContext(); CAContext* clone(CASheet*); void clear(); CAMusElement* next(CAMusElement* elt); CAMusElement* previous(CAMusElement* elt); bool remove(CAMusElement* elt); CAMusElement *insertEmptyElement(int timeStart); void repositionElements(); QList<CAFiguredBassMark*>& figuredBassMarkList() { return _figuredBassMarkList; } CAFiguredBassMark* figuredBassMarkAtTimeStart(int timeStart); void addFiguredBassMark(CAFiguredBassMark*, bool replace = true); private: QList<CAFiguredBassMark*> _figuredBassMarkList; }; #endif /* FIGUREDBASSCONTEXT_H_ */
1,074
C++
.h
28
35.035714
85
0.779923
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,529
instrumentchange.h
canorusmusic_canorus/src/score/instrumentchange.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef INSTRUMENTCHANGE_H_ #define INSTRUMENTCHANGE_H_ #include "score/mark.h" #include <QString> class CANote; class CAInstrumentChange : public CAMark { public: CAInstrumentChange(int instrument, CANote* note); virtual ~CAInstrumentChange(); CAInstrumentChange* clone(CAMusElement* elt = nullptr); int compare(CAMusElement*); inline int instrument() { return _instrument; } inline void setInstrument(const int instrument) { _instrument = instrument; } private: int _instrument; }; #endif /* INSTRUMENTCHANGE_H_ */
767
C++
.h
22
32.045455
81
0.764946
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,530
text.h
canorusmusic_canorus/src/score/text.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef TEXT_H_ #define TEXT_H_ #include "score/mark.h" #include <QString> class CAText : public CAMark { public: CAText(const QString text, CAPlayable* m); virtual ~CAText(); inline const QString text() { return _text; } inline void setText(const QString t) { _text = t; } CAText* clone(CAMusElement* elt = nullptr); int compare(CAMusElement* elt); private: QString _text; }; #endif /* TEXT_H_ */
647
C++
.h
21
27.952381
76
0.718447
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,531
repeatmark.h
canorusmusic_canorus/src/score/repeatmark.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef REPEATMARK_H_ #define REPEATMARK_H_ #include "score/mark.h" class CABarline; class CARepeatMark : public CAMark { public: enum CARepeatMarkType { Undefined = 0, Volta = 1, Segno = 2, Coda = 3, VarCoda = 4, DalSegno = 5, DalCoda = 6, DalVarCoda = 7 }; CARepeatMark(CABarline* b, CARepeatMarkType t, int voltaNumber = 0); virtual ~CARepeatMark(); CARepeatMark* clone(CAMusElement* elt = nullptr); int compare(CAMusElement*); inline CARepeatMarkType repeatMarkType() { return _repeatMarkType; } inline void setRepeatMarkType(CARepeatMarkType t) { _repeatMarkType = t; } inline int voltaNumber() { return _voltaNumber; } inline void setVoltaNumber(int n) { _voltaNumber = n; } static const QString repeatMarkTypeToString(CARepeatMarkType t); static CARepeatMarkType repeatMarkTypeFromString(const QString r); private: CARepeatMarkType _repeatMarkType; int _voltaNumber; }; #endif /* REPEATMARK_H_ */
1,249
C++
.h
36
29.944444
78
0.711907
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,532
keysignature.h
canorusmusic_canorus/src/score/keysignature.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef KEYSIGNATURE_H_ #define KEYSIGNATURE_H_ #include <QString> #include "score/diatonickey.h" #include "score/muselement.h" #include "score/staff.h" class CAContext; class CAKeySignature : public CAMusElement { public: enum CAKeySignatureType { MajorMinor, // Marks the standard 7-level Major/Minor Modus, Custom }; enum CAModus { Ionian, Dorian, Phrygian, Lydian, Mixolydian, Aeolian, Locrian, Hypodorian, Hypolydian, Hypomixolydian, Hypophrygian }; CAKeySignature(CADiatonicKey k, CAStaff* staff, int timeStart); CAKeySignature(CAModus m, CAStaff* staff, int timeStart); ~CAKeySignature(); CAKeySignature* clone(CAContext* context = nullptr); CAStaff* staff() { return static_cast<CAStaff*>(context()); } inline CAKeySignatureType keySignatureType() { return _keySignatureType; } inline void setKeySignatureType(CAKeySignatureType type) { _keySignatureType = type; } CADiatonicKey diatonicKey() { return _diatonicKey; } CAModus modus() { return _modus; } void setDiatonicKey(CADiatonicKey k) { _diatonicKey = k; updateAccidentals(); } void setModus(CAModus modus) { _modus = modus; } QList<int>& accidentals() { return _accidentals; } int compare(CAMusElement* elt); static const QString keySignatureTypeToString(CAKeySignatureType); static CAKeySignatureType keySignatureTypeFromString(const QString); static const QString modusToString(CAModus); static CAModus modusFromString(const QString); private: void updateAccidentals(); CAKeySignatureType _keySignatureType; CAModus _modus; CADiatonicKey _diatonicKey; QList<int> _accidentals; // Accidentals matrix }; #endif /* KEYSIGNATURE_H_ */
2,072
C++
.h
61
28.704918
90
0.714142
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,533
resource.h
canorusmusic_canorus/src/score/resource.h
/*! Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef RESOURCE_H_ #define RESOURCE_H_ #include <QUrl> #include <memory> class CADocument; class CAResource #ifndef SWIG : public std::enable_shared_from_this<CAResource> #endif { public: enum CAResourceType { Undefined = -1, // error Image, // vector or bitmap image or an icon Sound, // sound sample, midi etc. Movie, // movie clip Document, // Canorus, pdf or other score document Other // other resources }; CAResource(QUrl fileName, QString name, bool linked = false, CAResourceType t = Other, CADocument* c = nullptr); virtual ~CAResource(); inline void setName(const QString n) { _name = n; } inline const QString name() { return _name; } inline void setDescription(const QString n) { _description = n; } inline const QString description() { return _description; } inline void setUrl(const QUrl url) { _url = url; } inline const QUrl url() { return _url; } inline void setResourceType(const CAResourceType t) { _resType = t; } inline CAResourceType resourceType() { return _resType; } inline void setLinked(bool l) { _linked = l; } inline bool isLinked() { return _linked; } inline void setDocument(CADocument* d) { _document = d; } inline CADocument* document() { return _document; } bool copy(QString fileName); static QString resourceTypeToString(CAResourceType type); static CAResourceType resourceTypeFromString(QString type); private: QString _name; QString _description; QUrl _url; // Absolute path to resource. Becomes relative if "file:" scheme when saved. CAResourceType _resType; bool _linked; CADocument* _document; }; #endif /* RESOURCE_H_ */
1,958
C++
.h
50
34.58
116
0.700687
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,534
playablelength.h
canorusmusic_canorus/src/score/playablelength.h
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef PLAYABLELENGTH_H_ #define PLAYABLELENGTH_H_ #include <QString> class CABarline; class CATimeSignature; class CAPlayableLength { public: enum CAMusicLength { Undefined = -1, Breve = 0, Whole = 1, Half = 2, Quarter = 4, Eighth = 8, Sixteenth = 16, ThirtySecond = 32, SixtyFourth = 64, HundredTwentyEighth = 128 }; CAPlayableLength(); CAPlayableLength(CAMusicLength l, int dotted = 0); inline CAMusicLength musicLength() { return _musicLength; } inline int dotted() { return _dotted; } inline void setMusicLength(const CAMusicLength l) { _musicLength = l; } inline void setDotted(const int d) { _dotted = d; } bool operator==(CAPlayableLength); bool operator!=(CAPlayableLength); static const QString musicLengthToString(CAMusicLength length); static CAMusicLength musicLengthFromString(const QString length); static int playableLengthToTimeLength(CAPlayableLength length); inline static int musicLengthToTimeLength(CAMusicLength l) { return playableLengthToTimeLength(CAPlayableLength(l)); } static QList<CAPlayableLength> timeLengthToPlayableLengthList(int timeLength, bool longNotesFirst = true, int dotsLimit = 4); static QList<CAPlayableLength> matchToBars(CAPlayableLength len, int timeStart, CABarline* lastBarline, CATimeSignature* ts, int dotsLimit = 4); static QList<CAPlayableLength> matchToBars(int timeLength, int timeStart, CABarline* lastBarline, CATimeSignature* ts, int dotsLimit = 4, int separiationTime = 0); private: CAMusicLength _musicLength; // note, rest length (half, whole, quarter) int _dotted; // number of dots }; #endif /* PLAYABLELENGTH_H_ */
1,976
C++
.h
47
37.06383
167
0.732916
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,535
sourceview.h
canorusmusic_canorus/src/widgets/sourceview.h
/*! Copyright (c) 2006, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef SOURCEVIEW_H_ #define SOURCEVIEW_H_ #include <QTextEdit> #include "widgets/view.h" class QPushButton; class QGridLayout; class CADocument; class CAVoice; class CALyricsContext; class CASourceView : public CAView { Q_OBJECT enum CASourceViewType { LilyPond, CanorusML }; public: CASourceView(CADocument* doc, QWidget* parent = nullptr); CASourceView(CAVoice* voice, QWidget* parent = nullptr); CASourceView(CALyricsContext* lc, QWidget* parent = nullptr); virtual ~CASourceView(); CASourceView* clone(); CASourceView* clone(QWidget* parent); inline CASourceViewType sourceViewType() { return _sourceViewType; } inline void setSourceViewType(CASourceViewType t) { _sourceViewType = t; } inline CADocument* document() { return _document; } inline CAVoice* voice() { return _voice; } inline CALyricsContext* lyricsContext() { return _lyricsContext; } inline void setDocument(CADocument* doc) { _document = doc; } inline void setVoice(CAVoice* voice) { _voice = voice; } inline void setLyricsContext(CALyricsContext* c) { _lyricsContext = c; } inline void selectAll() { _textEdit->selectAll(); } signals: void CACommit(QString documentString); public slots: void rebuild(); private slots: void on_commit_clicked(); private: void setupUI(); class CATextEdit; friend class CASourceView::CATextEdit; ///////////// // Widgets // ///////////// QTextEdit* _textEdit; QPushButton* _commit; QPushButton* _revert; QGridLayout* _layout; //////////////// // Properties // //////////////// CASourceViewType _sourceViewType; CADocument* _document; CAVoice* _voice; CALyricsContext* _lyricsContext; }; #endif /* SOURCEVIEW_H_ */
2,015
C++
.h
62
28.419355
78
0.698914
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,536
scoreview.h
canorusmusic_canorus/src/widgets/scoreview.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef SCOREVIEW_H_ #define SCOREVIEW_H_ #include <QBrush> #include <QLineEdit> #include <QList> #include <QMultiMap> #include <QPen> #include <QRect> #include <QTimer> #include "layout/kdtree.h" #include "score/note.h" #include "widgets/view.h" class QScrollBar; class QMouseEvent; class QWheelEvent; class QTimer; class QGridLayout; class CADrawable; class CADrawableMusElement; class CADrawableContext; class CADrawableNote; class CADrawableBarline; class CAMusElement; class CAContext; class CASheet; class CAStaff; class CALyricsContext; class CADrawableNoteCheckerError; class CATextEdit : public QLineEdit { Q_OBJECT public: CATextEdit(QWidget* parent = nullptr); ~CATextEdit(); signals: void CAKeyPressEvent(QKeyEvent*); public slots: void keyPressEvent(QKeyEvent*); }; class CAScoreView : public CAView { Q_OBJECT public: enum CAScrollBarVisibility { ScrollBarAlwaysVisible, ScrollBarAlwaysHidden, ScrollBarShowIfNeeded }; /////////////////// // Basic methods // /////////////////// CAScoreView(QWidget* parent = nullptr); CAScoreView(CASheet* sheet, QWidget* parent = nullptr); virtual ~CAScoreView(); CAScoreView* clone(); CAScoreView* clone(QWidget* parent); inline CASheet* sheet() { return _sheet; } inline void setSheet(CASheet* sheet) { _sheet = sheet; } //////////////////////////////////////////// // Addition, removal of drawable elements // //////////////////////////////////////////// void addMElement(CADrawableMusElement* elt, bool select = false); void addCElement(CADrawableContext* elt, bool select = false); void addDrawableNoteCheckerError(CADrawableNoteCheckerError* dnce); void importElements(CAKDTree<CADrawableMusElement*>* drawableMList, CAKDTree<CADrawableContext*>* drawableCList); /////////////// // Selection // /////////////// inline const QList<CADrawableMusElement*>& selection() { return _selection; } QList<CAMusElement*> musElementSelection(); QList<CADrawableMusElement*> musElementsAt(double x, double y); CADrawableContext* selectCElement(double x, double y); CADrawableMusElement* selectMElement(CAMusElement* elt); CADrawableContext* selectContext(CAContext* context); inline QPoint lastMousePressCoords() { return _lastMousePressCoords; } void setLastMousePressCoordsAfter(const QList<CAMusElement*> list); inline CADrawableContext* currentContext() { return _currentContext; } inline void setCurrentContext(CADrawableContext* c) { _currentContext = c; } void selectAll(); void selectAllCurBar(); void selectAllCurContext(); void invertSelection(); inline void clearSelection() { _selection.clear(); emit selectionChanged(); } // Note Reinhard: This code does not make sense inline bool removeFromSelection(CADrawableMusElement* elt) { return _selection.removeAll(elt); emit selectionChanged(); } void addToSelection(CADrawableMusElement* elt, bool triggerSignal = true); void addToSelection(const QList<CADrawableMusElement*> list, bool selectableOnly = true); CADrawableMusElement* addToSelection(CAMusElement* elt); void addToSelection(const QList<CAMusElement*> elts); CADrawableMusElement* selectNextMusElement(bool append = false); CADrawableMusElement* selectPrevMusElement(bool append = false); CADrawableMusElement* selectUpMusElement(); CADrawableMusElement* selectDownMusElement(); inline const QList<QRect>& selectionRegionList() const { return _selectionRegionList; } inline void addSelectionRegion(QRect r) { _selectionRegionList << r; } inline void removeSelectionRegion(QRect r) { _selectionRegionList.removeAll(r); } inline void clearSelectionRegionList() { _selectionRegionList.clear(); } inline CADrawable::CADirection resizeDirection() { return _resizeDirection; } bool mouseDragActivated(); bool clickTimerActivated(); ///////////////////////////////////////////////////////////////////// // Music elements and contexts query, space calculation and access // ///////////////////////////////////////////////////////////////////// CADrawableMusElement* findMElement(CAMusElement*); CADrawableContext* findCElement(CAContext*); QList<CADrawableContext*> findContextsInRegion(QRect& reg); CADrawableMusElement* nearestLeftElement(double x, double y, CADrawableContext* context = nullptr); CADrawableMusElement* nearestLeftElement(double x, double y, CAVoice* voice); CADrawableMusElement* nearestRightElement(double x, double y, CADrawableContext* context = nullptr); CADrawableMusElement* nearestRightElement(double x, double y, CAVoice* voice); int coordsToTime(double x); double timeToCoords(int time); double timeToCoordsSimpleVersion(int time); static bool musElementTimeLessThan(const CAMusElement* a, const int b); static bool timeMusElementLessThan(const int a, const CAMusElement* b); CADrawableContext* nearestUpContext(double x, double y); CADrawableContext* nearestDownContext(double x, double y); int calculateTime(double x, double y); QMap<int, CADrawableBarline*> computeBarlinePositions(bool dotted = false); CAContext* contextCollision(double x, double y); //////////////// // Scrollbars // //////////////// inline void setManualScroll(bool scroll) { _allowManualScroll = scroll; } inline bool manualScroll() { return _allowManualScroll; } void checkScrollBars(); inline CAScrollBarVisibility isScrollBarVisible() { return _scrollBarVisible; } void setScrollBarVisible(CAScrollBarVisibility status); ////////////////////////////////////////////// // Scene appearance, properties and actions // ////////////////////////////////////////////// void rebuild(); void setMouseTracking(bool); // reimplemented! inline int drawableWidth() { return _canvas->width(); } inline int drawableHeight() { return _canvas->height(); } void setWorldX(double x, bool animate = false, bool force = false); void setWorldY(double y, bool animate = false, bool force = false); void setWorldWidth(double w, bool force = false); void setWorldHeight(double h, bool force = false); inline double worldX() { return _worldX; } inline double worldY() { return _worldY; } inline double worldWidth() { return _worldW; } inline double worldHeight() { return _worldH; } inline const QRectF worldCoords() { return QRectF(worldX(), worldY(), worldWidth(), worldHeight()); } inline float zoom() { return _zoom; } void setWorldCoords(const QRectF r, bool animate = false, bool force = false); void setWorldCoords(double x, double y, double w, double h, bool animate = false, bool force = false) { setWorldCoords(QRect(x, y, w, h), animate, force); } void setCenterCoords(double x, double y, bool animate = false, bool force = false); void setZoom(float z, double x = 0, double y = 0, bool animate = false, bool force = false); void setZoom(float z, QPoint p, bool animate = false, bool force = false) { setZoom(z, p.x(), p.y(), animate, force); } void zoomToSelection(bool animate = false, bool force = false); void zoomToWidth(bool animate = false, bool force = false); void zoomToHeight(bool animate = false, bool force = false); void zoomToFit(bool animate = false, bool force = false); bool grabTabKey() { return _grabTabKey; } void setGrabTabKey(bool g) { _grabTabKey = g; } void setBorder(const QPen pen); void unsetBorder(); inline QPen border() { return _borderPen; } inline QColor backgroundColor() { return _backgroundColor; } inline void setBackgroundColor(const QColor c) { _backgroundColor = c; } inline QColor foregroundColor() { return _foregroundColor; } inline void setForegroundColor(const QColor c) { _foregroundColor = c; } inline QColor selectionColor() { return _selectionColor; } inline void setSelectionColor(const QColor c) { _selectionColor = c; } inline QColor selectionAreaColor() { return _selectionAreaColor; } inline void setSelectionAreaColor(const QColor c) { _selectionAreaColor = c; } inline QColor selectedContextColor() { return _selectedContextColor; } inline void setSelectedContextColor(const QColor c) { _selectedContextColor = c; } inline QColor hiddenElementsColor() { return _hiddenElementsColor; } inline void setHiddenElementsColor(const QColor c) { _hiddenElementsColor = c; } inline QColor disabledElementsColor() { return _disabledElementsColor; } inline void setDisabledElementsColor(const QColor c) { _disabledElementsColor = c; } inline bool playing() { return _playing; } inline void setPlaying(bool playing) { _playing = playing; } inline void setRepaintArea(QRect* area) { _repaintArea = area; } inline void clearRepaintArea() { if (_repaintArea) delete _repaintArea; _repaintArea = nullptr; } inline CAVoice* selectedVoice() { return _selectedVoice; } inline void setSelectedVoice(CAVoice* selectedVoice) { _selectedVoice = selectedVoice; } inline bool shadowNoteVisible() { return _shadowNoteVisible; } inline void setShadowNoteVisible(bool visible) { _shadowNoteVisible = visible; setShadowNoteVisibleOnLeave(visible); } inline bool drawShadowNoteAccs() { return _drawShadowNoteAccs; } inline void setDrawShadowNoteAccs(bool draw) { _drawShadowNoteAccs = draw; } inline int shadowNoteAccs() { return _shadowNoteAccs; } inline void setShadowNoteAccs(int accs) { _shadowNoteAccs = accs; } void setShadowNoteLength(CAPlayableLength); CATextEdit* createTextEdit(CADrawableMusElement* elt); inline CATextEdit* textEdit() { return _textEdit; } void removeTextEdit(); inline bool textEditVisible() { return _textEditVisible; } bool noteNameVisible() { return _noteNameVisible; } void setNoteNameVisible(bool v) { _noteNameVisible = v; } QString noteName() { return _noteName; } void setNoteName(QString n) { _noteName = n; } void updateHelpers(); // method for updating shadow notes, syllable edits and other post-engrave elements coordinates and sizes when zoom level is changed etc. private slots: void mousePressEvent(QMouseEvent* e); void mouseMoveEvent(QMouseEvent* e); void mouseReleaseEvent(QMouseEvent* e); void wheelEvent(QWheelEvent* e); void keyPressEvent(QKeyEvent* e); void HScrollBarEvent(int val); void VScrollBarEvent(int val); void resizeEvent(QResizeEvent* e); void paintEvent(QPaintEvent* p); void leaveEvent(QEvent* e); void enterEvent(QEvent* e); void on_animationTimer_timeout(); void on_clickTimer_timeout(); signals: void CATripleClickEvent(QMouseEvent* e, QPoint p); void CADoubleClickEvent(QMouseEvent* e, QPoint p); void CAMousePressEvent(QMouseEvent* e, QPoint p); void CAMouseReleaseEvent(QMouseEvent* e, QPoint p); void CAMouseMoveEvent(QMouseEvent* e, QPoint p); void CAWheelEvent(QWheelEvent* e, QPoint p); void CAKeyPressEvent(QKeyEvent* e); void selectionChanged(); protected: bool event(QEvent* event); private: void initScoreView(CASheet* s); inline void clearMElements() { _drawableMList.clear(true); } inline void clearCElements() { _drawableCList.clear(true); } inline bool isSelected(CADrawableMusElement* elt) { return (_selection.contains(elt)); } ////////////////// // Core Widgets // ////////////////// QGridLayout* _layout; // Grid layout for placing the scrollbars at the right and the bottom. QWidget* _canvas; // Virtual canvas which represents the size of the drawable area. All its signals are forwarded to CAView. QScrollBar *_hScrollBar, *_vScrollBar; // Horizontal/vertical scrollbars //////////////////////// // General properties // //////////////////////// CAKDTree<CADrawableMusElement*> _drawableMList; // The list of music elements stored in a tree for faster lookup and other operations. Every view has its own list of drawable elements and drawable objects themselves! CAKDTree<CADrawableContext*> _drawableCList; // The list of context drawable elements (staffs, lyrics etc.). Every view has its own list of drawable elements and drawable objects themselves! CAKDTree<CADrawableNoteCheckerError*> _drawableNCEList; // The list of drawable note checker errors QMultiMap<void*, CADrawable*> _mapDrawable; // Mapping of all music elements/contexts in the score -> drawable elements on canvas CASheet* _sheet; // Pointer to the CASheet which the view represents. QList<CADrawableMusElement*> _selection; // The set of elements being selected. CADrawableContext* _currentContext; // The pointer to the currently active context (staff, lyrics). static const int RIGHT_EXTRA_SPACE; // Extra space at the right end to insert new music static const int BOTTOM_EXTRA_SPACE; // Extra space at the bottom end to insert new music static const int RULER_HEIGHT; // Ruler height in pixels template <typename T> double getMaxXExtended(CAKDTree<T>& v); // Make the viewable World a little bigger (stuffed) to make inserting at the end easier template <typename T> double getMaxYExtended(CAKDTree<T>& v); // Make the viewable World a little bigger (stuffed) to make inserting below easies double _worldX, _worldY, _worldW, _worldH; // Absolute world coordinates of the area the view is currently showing. QPoint _lastMousePressCoords; // Used in multiple selection - coordinates of the upper-left point of the rectangle the user drags in world coordinates inline void setLastMousePressCoords(QPoint p) { _lastMousePressCoords = p; } double _zoom; // Zoom level of the view (1.0 = 100%, 1.5 = 150% etc.). CAVoice* _selectedVoice; // Voice to be drawn normal colors, others are shaded ///////////// // Helpers // ///////////// // Shadow note bool _shadowNoteVisible; // Should the shadow notes be rendered or not bool _shadowNoteVisibleOnLeave; // When you leave the view, shadow note is always turned off. This property holds the value, if shadow note was enabled before you left the view. inline bool shadowNoteVisibleOnLeave() { return _shadowNoteVisibleOnLeave; } inline void setShadowNoteVisibleOnLeave(bool v) { _shadowNoteVisibleOnLeave = v; } int _shadowNoteAccs; // Number of accidentals - 0 - natural, 1 - sharp, -1 flat bool _drawShadowNoteAccs; // Draw shadow note accs? QList<CANote*> _shadowNote; // List of all shadow notes - one shadow note per drawable staff QList<CADrawableNote*> _shadowDrawableNote; // List of drawable shadow notes // QLineEdit for editing or creating a lyrics syllable CATextEdit* _textEdit; inline void setTextEdit(CATextEdit* e) { _textEdit = e; } QRect _textEditGeometry; inline QRect textEditGeometry() { return _textEditGeometry; } inline void setTextEditGeometry(const QRect r) { _textEditGeometry = r; } bool _textEditVisible; inline void setTextEditVisible(bool v) { _textEditVisible = v; } inline void setResizeDirection(CADrawable::CADirection r) { _resizeDirection = r; } CADrawable::CADirection _resizeDirection; // Is the current scalable music element in drag-drop resizing mode? // Selection regions QList<QRect> _selectionRegionList; void drawSelectionRegion(QPainter* p, CADrawSettings s); public: static const int SELECTION_REGION_THRESHOLD; // Threshold in px for mouse move until the selection region is activated private: //////////////// // Appearance // //////////////// bool _grabTabKey; // Pass the tab key to keyPressEvent() or treat it like the next item key bool _drawBorder; // Should the border be drawn or not. QRect* _repaintArea; // Area to be repainted on paintEvent(). QPen _borderPen; // Pen which the border is drawn by. QColor _backgroundColor; // Color which the background is filled. QColor _foregroundColor; // Color which the music elements are painted. QColor _selectionColor; // Color which the selected music elements are painted. QColor _selectionAreaColor; // Color which the selection area background is filled. QColor _selectedContextColor; // Color which the current context is painted. QColor _disabledElementsColor; // Color which the elements in non-selected voice are painted. QColor _hiddenElementsColor; // Color which the invisible elements are painted in current-voice-only mode. bool _noteNameVisible; // Is the written note name visible QString _noteName; // Name of the note to be inserted. eg. c', Des, /////////////// // Animation // /////////////// QTimer* _animationTimer; // Timer used to animate scroll/zoom behaviour. static const int ANIMATION_STEPS; // Number of steps used in animation int _animationStep; // Current step in the animation double _targetWorldX, _targetWorldY, _targetWorldW, _targetWorldH; // Absolute world coordinates of the area the view is currently showing. double _targetZoom; // Zoom level of the view (1.0 = 100%, 1.5 = 150% etc.). void startAnimationTimer(); /////////////////////// // Widgets behaviour // /////////////////////// CAScrollBarVisibility _scrollBarVisible; // Are the scrollbars always visible/never/if needed. Use CAView::ScrollBarAlwaysVisible, CAView::ScrollBarAlwaysHidden or CAView::ScrollBarShowIfNeeded. bool _allowManualScroll; // Does the scrollbars actually react on user actions - sometimes we only want the scrollbars to show the current location of the score and don't do anything ///////////////////////// // Internal properties // ///////////////////////// double _oldWorldX, _oldWorldY, _oldWorldW, _oldWorldH; // Old coordinates used before the repaint. This is needed so only the new part of the view gets repainted when panning. bool _playing; // Set to on, when in Playback mode QTimer* _clickTimer; // Used for measuring doubleClick and tripleClick int _numberOfClicks; // Used for measuring doubleClick and tripleClick double _xCursor, _yCursor; // Mouse cursor position in absolute world coords. bool _holdRepaint; // Flag to prevent multiple repaintings. bool _checkScrollBarsDeadLock; // Flag to prevent recursive checkScrollBars() calls. bool _hScrollBarDeadLock; // Flag to prevent recursive scrollbar calls when its value is manually changed. bool _vScrollBarDeadLock; // Flag to prevent recursive scrollbar calls when its value is manually changed. }; #endif /*SCOREVIEW_H_*/
19,022
C++
.h
345
50.318841
220
0.714992
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,537
helpbrowser.h
canorusmusic_canorus/src/widgets/helpbrowser.h
/*! Copyright (c) 2009, Itay Perl, Canorus development team Copyright (c) 2016, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef HELPBROWSER_H_ #define HELPBROWSER_H_ #include <QtWebEngineWidgets/QWebEngineView> class CAHelpBrowser : public QWebEngineView { Q_OBJECT public: CAHelpBrowser(QWidget* parent = nullptr); ~CAHelpBrowser() {} }; #endif /* HELPBROWSER_H_ */
544
C++
.h
17
29.176471
79
0.758621
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,538
undotoolbutton.h
canorusmusic_canorus/src/widgets/undotoolbutton.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef UNDOTOOLBUTTON_H_ #define UNDOTOOLBUTTON_H_ #include "widgets/toolbutton.h" #include <QListWidget> class QUndoStack; class CAUndoToolButton : public CAToolButton { Q_OBJECT public: enum CAUndoToolButtonType { Undo, Redo }; CAUndoToolButton(QIcon icon, CAUndoToolButtonType t, QWidget* parent); ~CAUndoToolButton(); void setDefaultAction(QAction*); inline CAUndoToolButtonType undoType() { return _type; } inline void setUndoType(CAUndoToolButtonType type) { _type = type; } void showButtons(); public slots: void onListWidgetItemClicked(QListWidgetItem*); void onListWidgetItemEntered(QListWidgetItem*); protected: void wheelEvent(QWheelEvent*); private: QListWidget* _listWidget; CAUndoToolButtonType _type; QIcon _icon; }; #endif /* UNDOTOOLBUTTON_H_ */
1,062
C++
.h
34
27.529412
74
0.75665
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,539
toolbutton.h
canorusmusic_canorus/src/widgets/toolbutton.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef TOOLBUTTON_H_ #define TOOLBUTTON_H_ #include <QToolButton> #include "widgets/toolbuttonpopup.h" class QWidget; class CAMainWin; class CAToolButton : public QToolButton { Q_OBJECT public: CAToolButton(QWidget* parent); virtual ~CAToolButton(); inline int currentId() { return _currentId; } virtual void setCurrentId(int id) { _currentId = id; } inline bool buttonsVisible() { return (_popupWidget) ? _popupWidget->isVisible() : 0; } // Is the popup widget visible or not void setDefaultAction(QAction*); virtual void showButtons(); virtual void hideButtons(); private slots: void handleToggled(bool checked); void handleTriggered(); signals: void toggled(bool checked, int id); protected: inline CAMainWin* mainWin() { return _mainWin; } inline void setMainWin(CAMainWin* m) { _mainWin = m; } inline void setPopupWidget(QWidget* w) { _popupWidget->setWidget(w); } virtual void wheelEvent(QWheelEvent*) = 0; void mousePressEvent(QMouseEvent*); QPoint calculateTopLeft(QSize widgetSize); CAMainWin* _mainWin; // Pointer to the main window for toolbar location polling etc. int _currentId; // current ID of the button CAToolButtonPopup* _popupWidget; // container for the floating widget }; #endif /* TOOLBUTTON_H_ */
1,527
C++
.h
39
35.615385
129
0.73916
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,540
tabwidget.h
canorusmusic_canorus/src/widgets/tabwidget.h
/*! Copyright (c) 2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef TABWIDGET_H_ #define TABWIDGET_H_ #include <QTabWidget> class QMouseEvent; class CATabWidget : public QTabWidget { Q_OBJECT public: CATabWidget(QWidget* parent = nullptr); virtual ~CATabWidget(); signals: void CANewTab(); void CAMoveTab(int from, int to); protected slots: void mouseDoubleClickEvent(QMouseEvent* event); protected: void tabInserted(int); void tabRemoved(int); }; #endif /* TABWIDGET_H_ */
664
C++
.h
24
24.833333
72
0.755943
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,541
menutoolbutton.h
canorusmusic_canorus/src/widgets/menutoolbutton.h
/*! Copyright (c) 2006-2007, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef MENUTOOLBUTTON_H_ #define MENUTOOLBUTTON_H_ #include "widgets/toolbutton.h" #include <QButtonGroup> #include <QGridLayout> #include <QGroupBox> #include <QHash> class CAMainWin; class CAGroupBoxToolButton : public QToolButton { Q_OBJECT public: CAGroupBoxToolButton(QWidget* w) : QToolButton(w) { } protected: void paintEvent(QPaintEvent*); }; class CAMenuToolButton : public CAToolButton { Q_OBJECT public: CAMenuToolButton(QString title, int numIconsRow = 4, QWidget* parent = nullptr); ~CAMenuToolButton() override; void addButton(const QIcon icon, int buttonId, const QString toolTip = ""); inline QAbstractButton* getButton(int buttonId) { return _buttonGroup->button(buttonId); } inline const QList<QToolButton*>& buttonList() const { return _buttonList; } inline int spacing() { return _spacing; } inline int layoutMargin() { return _layoutMargin; } inline int margin() { return _margin; } inline int numIconsPerRow() { return _numIconsRow; } inline void setSpacing(int spacing) { _spacing = spacing; } inline void setLayoutMargin(int margin) { _layoutMargin = margin; } inline void setMargin(int margin) { _margin = margin; } inline void setNumIconsPerRow(int numIconsRow) { _numIconsRow = numIconsRow; } void setCurrentId(int id) override { setCurrentId(id, false); } void setCurrentId(int id, bool triggerSignal); void showButtons() override; public slots: void onButtonPressed(int); private: void wheelEvent(QWheelEvent*) override; QButtonGroup* _buttonGroup; // Abstract group for the button actions QGroupBox* _groupBox; // Group box containing title and buttons QGridLayout* _boxLayout; // Layout for the group box QGridLayout* _menuLayout; // Layout for the button menu QList<QToolButton*> _buttonList; // List of created buttons in button box QHash<QString, int> _buttonIds; // hash of IDs of buttons int _buttonXPos; // X position of next button int _buttonYPos; // Y position of next button int _numIconsRow; // Number of icons per row int _spacing; // Space between buttons int _margin; // Margin around the buttons int _layoutMargin; // Margin of layout }; #endif /* MENUTOOLBUTTON_H_ */
2,515
C++
.h
60
38.1
94
0.734945
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,542
toolbuttonpopup.h
canorusmusic_canorus/src/widgets/toolbuttonpopup.h
/*! Copyright (c) 2007, Itay Perl, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef TOOLBUTTONPOPUP_H_ #define TOOLBUTTONPOPUP_H_ #include <QWidget> class CAToolButtonPopup : public QWidget { Q_OBJECT public: CAToolButtonPopup(QWidget* parent = nullptr); ~CAToolButtonPopup() { /* widget is not destroyed! */ } inline void setWidget(QWidget* w) { _widget = w; w->setParent(this); } inline QWidget* widget() { return _widget; } inline QSize sizeHint() const { return (_widget) ? _widget->sizeHint() : QSize(0, 0); } protected: void mousePressEvent(QMouseEvent* e); QWidget* _widget; }; #endif /* TOOLBUTTONPOPUP_H_ */
815
C++
.h
27
26.444444
91
0.697823
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,543
midirecorderview.h
canorusmusic_canorus/src/widgets/midirecorderview.h
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef MIDIRECORDERVIEW_H_ #define MIDIRECORDERVIEW_H_ #include <QDockWidget> #include <QTimer> #include "ui_midirecorder.h" class QAction; class QLabel; class QSlider; class QWidget; class CAMidiRecorder; class CAMidiRecorderView : public QDockWidget, private Ui::uiMidiRecorder { Q_OBJECT public: CAMidiRecorderView(CAMidiRecorder* recorder, QWidget* parent = nullptr); virtual ~CAMidiRecorderView(); void setMidiRecorder(CAMidiRecorder* r) { _midiRecorder = r; } CAMidiRecorder* midiRecorder() { return _midiRecorder; } enum CARecorderStatus { Idle, Pause, Recording }; private slots: void on_uiRecord_clicked(bool); void on_uiPause_clicked(bool); void on_uiStop_clicked(bool); void onTimerTimeout(); private: void setupCustomUi(); QTimer* _timer; CAMidiRecorder* _midiRecorder; CARecorderStatus _status; }; #endif /* MIDIRECORDERVIEW_H_ */
1,157
C++
.h
39
26.051282
76
0.74796
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,544
view.h
canorusmusic_canorus/src/widgets/view.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef VIEW_H #define VIEW_H #include <QWidget> class QCloseEvent; class CAView : public QWidget { Q_OBJECT public: CAView(QWidget* parent = nullptr); virtual ~CAView(); enum CAViewType { ScoreView, SourceView }; inline CAViewType viewType() { return _viewType; } virtual CAView* clone() = 0; virtual CAView* clone(QWidget* parent) = 0; virtual void rebuild() = 0; static const int DEFAULT_VIEW_WIDTH; static const int DEFAULT_VIEW_HEIGHT; protected slots: void mousePressEvent(QMouseEvent* e); inline void closeEvent(QCloseEvent*) { emit closed(this); } signals: void clicked(); void closed(CAView*); protected: inline void setViewType(CAViewType t) { _viewType = t; } //////////////////////// // General properties // //////////////////////// CAViewType _viewType; }; #endif
1,104
C++
.h
38
25.026316
72
0.674286
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,545
progressstatusbar.h
canorusmusic_canorus/src/widgets/progressstatusbar.h
/*! Copyright (c) 2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef PROGRESSSTATUSBAR_H_ #define PROGRESSSTATUSBAR_H_ #include <QStatusBar> class QLabel; class QPushButton; class QProgressBar; class CAProgressStatusBar : public QStatusBar { Q_OBJECT public: CAProgressStatusBar(QWidget* parent); ~CAProgressStatusBar(); public slots: void setProgress(QString label, int value); void setProgress(int value); void setProgress(QString label); signals: void cancelButtonClicked(bool); private slots: void on_cancelButton_clicked(bool); private: QLabel* _progressLabel; QProgressBar* _progressBar; QPushButton* _cancelButton; }; #endif /* PROGRESSSTATUSBAR_H_ */
866
C++
.h
30
25.933333
76
0.778182
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,546
viewcontainer.h
canorusmusic_canorus/src/widgets/viewcontainer.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Itay Perl, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef VIEWCONTAINER_H #define VIEWCONTAINER_H #include <QHash> #include <QSplitter> class CAView; class CASheet; class CAViewContainer : public QSplitter { Q_OBJECT public: CAViewContainer(QWidget* p); ~CAViewContainer(); void addView(CAView* v, QSplitter* s = nullptr); void removeView(CAView* v); CAView* splitHorizontally(CAView* v = nullptr); CAView* splitVertically(CAView* v = nullptr); CAView* unsplit(CAView* v = nullptr); QList<CAView*> unsplitAll(); inline bool contains(CAView* v) { return _viewMap.contains(v); } inline const QList<CAView*> viewList() { return _viewMap.keys(); } inline void setCurrentView(CAView* v) { _currentView = v; } inline CAView* currentView() { return _currentView; } private: QHash<CAView*, QSplitter*> _viewMap; CAView* _currentView; CASheet* _sheet; }; #endif
1,103
C++
.h
32
31.03125
78
0.726415
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,547
resourceview.h
canorusmusic_canorus/src/widgets/resourceview.h
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef RESOURCEVIEW_H_ #define RESOURCEVIEW_H_ #include <QMap> #include <QTreeWidget> #include <memory> class QWidget; class CADocument; class CAResource; class CAResourceView : public QTreeWidget { Q_OBJECT public: CAResourceView(CADocument* doc, QWidget* parent = nullptr); ~CAResourceView(); void rebuildUi(); void setDocument(CADocument* doc) { _document = doc; rebuildUi(); } CADocument* document() { return _document; } protected slots: void on_itemChanged(QTreeWidgetItem* i, int column); private: void showEvent(QShowEvent*); void closeEvent(QCloseEvent*); void contextMenuEvent(QContextMenuEvent* e); CADocument* _document; QMap<QTreeWidgetItem*, std::shared_ptr<CAResource> > _items; }; #endif /* RESOURCEVIEW_H_ */
1,021
C++
.h
35
25.657143
72
0.735868
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,548
actionseditor.h
canorusmusic_canorus/src/widgets/actionseditor.h
/*! Copyright (c) 2009, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. This code is based on smplayer, GUI front-end for mplayer, v0.6.7. Copyright (C) 2006-2009 Ricardo Villalba <rvm@escomposlinux.org> which again based it on qq14-actioneditor-code.zip from Qt and heavily adapted to our needs. */ #ifndef _CAACTIONSEDITOR_H_ #define _CAACTIONSEDITOR_H_ #include "ui/singleaction.h" #include <QDialog> #include <QList> #include <QStringList> class QTableWidget; class QTableWidgetItem; class CASingleAction; class QSettings; class QLineEdit; class QPushButton; class CAActionsEditor : public QWidget { Q_OBJECT public: // Definition of file type enum fileType { //FT_COMPLETE = 0, // All together like when stored in settings FT_SHORTCUT = 1, // Keyboard shortcut FT_MIDI = 2, // Midi command FT_MIDISCUT = 3 // Requires Midi and Shortcut at one time to be used }; // Constructor // Parameters are standard QWidget parameters CAActionsEditor(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr); // Destructor ~CAActionsEditor(); // Clear the actionlist void clear(); // There are no actions yet? bool isEmpty(); // See QWidget documentation void addActions(const QList<CASingleAction*>& actionList); // Static functions static CASingleAction* findAction(QWidget* widget, const QString& name); static QStringList actionsNames(QWidget* widget); static void saveToConfig(QWidget* widget, QSettings* set); static void loadFromConfig(QWidget* widget, QSettings* set); //#if USE_MULTIPLE_SHORTCUTS // static QString shortcutsToString(QList <QKeySequence> shortcuts_list); // static QList <QKeySequence> stringToShortcuts(QString shortcuts); //#endif public slots: // save changes from editing (shortcut or midi command) void applyChanges(); // Get file type from suffix enum fileType getFType(const QString& suffix); // save action profile (shortcuts or midi commands) separately to disc void saveActionsTable(); bool saveActionsTable(const QString& filename, enum fileType type = FT_SHORTCUT); // load action profile (shortcuts or midi commands) separately from disc void loadActionsTable(); bool loadActionsTable(const QString& filename, enum fileType type = FT_SHORTCUT); // Add all actions to the table widget void updateView(); protected: // Translate strings dynamically // Adapts save buttons according to column focus virtual void retranslateStrings(); virtual void changeEvent(QEvent* event); // Find in table, not in actionslist (command, shortcut or midi) int findActionCommand(const QString& name); int findActionAccel(const QString& accel, int ignoreRow = -1); int findActionMidi(const QString& midi, int ignoreRow = -1); // Check for Conflicts of shortcut or midi command bool hasConflicts(bool bMidi = false); protected slots: //#if !USE_SHORTCUTGETTER // Start recording (save current Text) void recordAction(QTableWidgetItem*); // Easy check of edited shortcut / midi command void validateAction(QTableWidgetItem*); //#else void editShortcut(); //#endif private: QTableWidget* actionsTable; QList<CASingleAction*> m_actionsList; QPushButton* saveButton; QPushButton* loadButton; QString latest_dir; //#if USE_SHORTCUTGETTER QPushButton* editButton; //#else QString oldAccelText; QString oldMidiText; bool dont_validate; // Lock validate during update //#endif }; class ShortcutGetter : public QDialog { Q_OBJECT public: ShortcutGetter(QWidget* parent = nullptr); int exec() override { return QDialog::exec(); } QString exec(const QString& s); protected slots: void setCaptureKeyboard(bool b); protected: bool captureKeyboard() { return capture; } bool event(QEvent* e) override; bool eventFilter(QObject* o, QEvent* e) override; void setText(); private: bool bStop; QLineEdit* leKey; QStringList lKeys; bool capture; }; #endif
4,315
C++
.h
119
31.806723
88
0.726662
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,549
pyconsole.h
canorusmusic_canorus/src/widgets/pyconsole.h
/*! Copyright (c) 2006-2008, Štefan Sakalík, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PYCONSOLE_H_ #define PYCONSOLE_H_ #include "score/document.h" #include <QMutex> #include <QObject> #include <QTextEdit> #include <QToolBar> #include <QWaitCondition> class CAPyConsole : public QTextEdit { Q_OBJECT public: enum TxtType { txtNormal, txtStdout, txtStderr }; CAPyConsole(CADocument* doc, QWidget* parent = nullptr); QString asyncBufferedInput(QString prompt); void asyncBufferedOutput(QString bufInp, bool bStdErr); void asyncPluginInit(); void asyncKeyboardInterrupt(); protected: void keyPressEvent(QKeyEvent* e); private slots: void txtAppend(const QString& text, TxtType txtType = txtNormal); void on_txtChanged(); void on_posChanged(); void on_selChanged(); void on_fmtChanged(); void syncPluginInit(); signals: void sig_txtAppend(const QString& text, TxtType stdType); void sig_syncPluginInit(); private: enum HistLay { histPrev, histNext }; struct TxtFragment { QString text; TxtType type; }; // void txtAppend(...) -> is in signals void txtRevert(); QString txtGetInput(bool bReadText = false); void txtSetInput(QString input, bool bUpdateText = true); void histAdd(); void histGet(HistLay histLay); // text in the console QTextCursor _curInput, _curNew; int _iCurStart, _iCurNowOld, _iCurNow; bool _bIgnTxtChange; TxtFragment* _tf; QList<TxtFragment*> _txtFixed; QString _strInput; // history int _histIndex; QList<QString> _histList; QString _histOldInput; // old _strInput QTextCharFormat _fmtNormal; QTextCharFormat _fmtStdout; QTextCharFormat _fmtStderr; // thread QString _bufSend; QMutex* _thrWaitMut; QWaitCondition* _thrWait; QMutex* _thrIntrWaitMut; QWaitCondition* _thrIntrWait; // pyconsole '/' commands bool cmdIntern(QString strCmd); QString _strEntryFunc; // rarely used CADocument* _canorusDoc; QWidget* _parent; }; #endif /* PYCONSOLE_H_ */
2,327
C++
.h
81
24.08642
101
0.705221
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,550
lcdnumber.h
canorusmusic_canorus/src/widgets/lcdnumber.h
/** @file widgets/numberdisplay.h * * 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; version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; (See "LICENSE.GPL"). If not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * *--------------------------------------------------------------------------- * * Copyright (c) 2006, Reinhard Katzmann, Canorus development team * All Rights Reserved. See AUTHORS for a complete list of authors. * */ #ifndef NUMBERDISPLAY_H #define NUMBERDISPLAY_H #include <QContextMenuEvent> #include <QLCDNumber> class QAction; // LCD Number enhanced with the possibility to limit the number displayed in the LCD class CALCDNumber : public QLCDNumber { Q_OBJECT public: /** * Constructs the number display * * @param iMin minimal number * @param iMax maximal number * @param oToolTipText text to be displayed as tool tip * @param oShortCut shortcut for a quick change of the number * @param poParent parent widget * @param oText name of the widget * */ CALCDNumber(int iMin, int iMax, QWidget* poParent = nullptr, QString oText = ""); /** * Sets the current value of the number display * * @param iVal new value to be set * */ void setRealValue(int val); /** * Gets the current value of the number display * */ int getRealValue(); /** * Sets the minimum value of the number display * * @param iMin new minimum value to be set * */ void setMin(int iMin); /** * Sets the maximum value of the number display * * @param iMax new maximum value to be set * */ void setMax(int iMax); /** * Checks if the value is 0 (or false if LCD number wasn't plugged) * */ bool isZero(); signals: /** * Actually sends out the changed value if triggered via mouse press event * * @param iVal new value * */ void valChanged(int iVal); protected: /** * Event being performed when a mouse button was pressed * * @param poEvt Necessary information about the event * */ virtual void mousePressEvent(QMouseEvent* poEvt); /** * Event being performed when a wheel was moved * * @param poEvt Necessary information about the event * */ virtual void wheelEvent(QWheelEvent* poEvt); /*! * Overrides QMainWindow::contextMenuEvent() to prevent showing the context menu when the LCD widget is right-clicked (in a toolbar). * * \param poEvt Pointer to event info. * */ virtual inline void contextMenuEvent(QContextMenuEvent*) {} private: int min_, max_; QAction* numDisplay_; int realValue_; QString toolTipText_; }; #endif /* NUMBERDISPLAY_H */
3,768
C++
.h
111
26.018018
134
0.579265
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,552
zip.h
canorusmusic_canorus/src/zip/zip.h
/* * 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 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. */ #pragma once #ifndef ZIP_H #define ZIP_H #include <string.h> #ifdef __cplusplus extern "C" { #endif #ifndef MAX_PATH #define MAX_PATH 32767 /* # chars in a path name including NULL */ #endif #define ZIP_DEFAULT_COMPRESSION_LEVEL 6 /* This data structure is used throughout the library to represent zip archive - forward declaration. */ struct zip_t; /* Opens zip archive with compression level using the given mode. Args: zipname: zip archive file name. level: compression level (0-9 are the standard zlib-style levels). mode: file access mode. 'r': opens a file for reading/extracting (the file must exists). 'w': creates an empty file for writing. 'a': appends to an existing archive. Returns: The zip archive handler or NULL on error */ extern struct zip_t* zip_open(const char* zipname, int level, char mode); /* Closes the zip archive, releases resources - always finalize. Args: zip: zip archive handler. */ extern void zip_close(struct zip_t* zip); /* Opens an entry by name in the zip archive. For zip archive opened in 'w' or 'a' mode the function will append a new entry. In readonly mode the function tries to locate the entry in global dictionary. Args: zip: zip archive handler. entryname: an entry name in local dictionary. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_open(struct zip_t* zip, const char* entryname); /* Opens a new entry by index in the zip archive. This function is only valid if zip archive was opened in 'r' (readonly) mode. Args: zip: zip archive handler. index: index in local dictionary. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_openbyindex(struct zip_t* zip, int index); /* Closes a zip entry, flushes buffer and releases resources. Args: zip: zip archive handler. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_close(struct zip_t* zip); /* Returns a local name of the current zip entry. The main difference between user's entry name and local entry name is optional relative path. Following .ZIP File Format Specification - the path stored MUST not contain a drive or device letter, or a leading slash. All slashes MUST be forward slashes '/' as opposed to backwards slashes '\' for compatibility with Amiga and UNIX file systems etc. Args: zip: zip archive handler. Returns: The pointer to the current zip entry name, or NULL on error. */ extern const char* zip_entry_name(struct zip_t* zip); /* Returns an index of the current zip entry. Args: zip: zip archive handler. Returns: The index on success, negative number (< 0) on error. */ extern int zip_entry_index(struct zip_t* zip); /* Determines if the current zip entry is a directory entry. Args: zip: zip archive handler. Returns: The return code - 1 (true), 0 (false), negative number (< 0) on error. */ extern int zip_entry_isdir(struct zip_t* zip); /* Returns an uncompressed size of the current zip entry. Args: zip: zip archive handler. Returns: The uncompressed size in bytes. */ extern unsigned long long zip_entry_size(struct zip_t* zip); /* Returns CRC-32 checksum of the current zip entry. Args: zip: zip archive handler. Returns: The CRC-32 checksum. */ extern unsigned int zip_entry_crc32(struct zip_t* zip); /* Compresses an input buffer for the current zip entry. Args: zip: zip archive handler. buf: input buffer. bufsize: input buffer size (in bytes). Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_write(struct zip_t* zip, const void* buf, size_t bufsize); /* Compresses a file for the current zip entry. Args: zip: zip archive handler. filename: input file. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_fwrite(struct zip_t* zip, const char* filename); /* Extracts the current zip entry into output buffer. The function allocates sufficient memory for a output buffer. Args: zip: zip archive handler. buf: output buffer. bufsize: output buffer size (in bytes). Note: - remember to release memory allocated for a output buffer. - for large entries, please take a look at zip_entry_extract function. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_read(struct zip_t* zip, void** buf, size_t* bufsize); /* Extracts the current zip entry into a memory buffer using no memory allocation. Args: zip: zip archive handler. buf: preallocated output buffer. bufsize: output buffer size (in bytes). Note: - ensure supplied output buffer is large enough. - zip_entry_size function (returns uncompressed size for the current entry) can be handy to estimate how big buffer is needed. - for large entries, please take a look at zip_entry_extract function. Returns: The return code - 0 on success, negative number (< 0) on error (e.g. bufsize is not large enough). */ extern int zip_entry_noallocread(struct zip_t* zip, void* buf, size_t bufsize); /* Extracts the current zip entry into output file. Args: zip: zip archive handler. filename: output file. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_fread(struct zip_t* zip, const char* filename); /* Extracts the current zip entry using a callback function (on_extract). Args: zip: zip archive handler. on_extract: callback function. arg: opaque pointer (optional argument, which you can pass to the on_extract callback) Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_entry_extract(struct zip_t* zip, size_t (*on_extract)(void* arg, unsigned long long offset, const void* data, size_t size), void* arg); /* Returns the number of all entries (files and directories) in the zip archive. Args: zip: zip archive handler. Returns: The return code - the number of entries on success, negative number (< 0) on error. */ extern int zip_total_entries(struct zip_t* zip); /* Creates a new archive and puts files into a single zip archive. Args: zipname: zip archive file. filenames: input files. len: number of input files. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_create(const char* zipname, const char* filenames[], size_t len); /* Extracts a zip archive file into directory. If on_extract_entry is not NULL, the callback will be called after successfully extracted each zip entry. Returning a negative value from the callback will cause abort and return an error. The last argument (void *arg) is optional, which you can use to pass data to the on_extract_entry callback. Args: zipname: zip archive file. dir: output directory. on_extract_entry: on extract callback. arg: opaque pointer. Returns: The return code - 0 on success, negative number (< 0) on error. */ extern int zip_extract(const char* zipname, const char* dir, int (*on_extract_entry)(const char* filename, void* arg), void* arg); #ifdef __cplusplus } #endif #endif
7,961
C++
.h
235
30.425532
81
0.723724
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,553
mainwin.h
canorusmusic_canorus/src/ui/mainwin.h
/*! Copyright (c) 2006-2007, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef MAINWIN_H_ #define MAINWIN_H_ #include <QFileDialog> #include <QHash> #include <QObject> #include <QTime> #include <QTimer> #include "ui_mainwin.h" #include "control/mainwinprogressctl.h" #include "core/notechecker.h" #include "score/clef.h" #include "score/document.h" #include "score/muselement.h" #include "score/note.h" #include "interface/playback.h" #include "interface/pyconsoleinterface.h" #include "widgets/resourceview.h" #include "widgets/scoreview.h" #include "widgets/viewcontainer.h" // std::unique_ptr for old Qt LTS 5.9.x #include <iostream> // verbose stuff #include <memory> class QKeyEvent; class QSlider; class QSpinBox; class QToolBar; class QLabel; class QLineEdit; class QComboBox; class QCheckBox; class QAction; class CAKeySignatureUI; #ifdef QT_WEBENGINEWIDGETS_LIB class CAHelpBrowser; #endif class CAMenuToolButton; class CAUndoToolButton; class CALCDNumber; class CASheet; class CAScoreView; class CASourceView; class CAMusElementFactory; class CAPrintPreviewCtl; class CAPrintCtl; class CAPreviewCtl; class CAPyConsole; class CATransposeView; class CAJumpToView; class CAMidiRecorderView; class CAKeybdInput; class CAExport; class CAActionStorage; class CAImport; class CAMainWin : public QMainWindow, private Ui::uiMainWindow { Q_OBJECT friend class CAMainWinProgressCtl; friend class CAActionDelegate; friend class CAActionStorage; public: enum CAMode { NoDocumentMode, ProgressMode, InsertMode, EditMode, ReadOnlyMode }; CAMainWin(QMainWindow* oParent = nullptr); ~CAMainWin(); void clearUI(); void rebuildUI(CASheet* sheet, bool repaint = true); void rebuildUI(bool repaint = true); inline bool rebuildUILock() { return _rebuildUILock; } void updateWindowTitle(); void newDocument(); void addSheet(CASheet* s); void removeSheet(CASheet* s); bool insertMusElementAt(const QPoint coords, CAScoreView* v); void restartTimeEditedTime() { _timeEditedTime = 0; } void deleteSelection(CAScoreView* v, bool deleteSyllable, bool deleteNotes, bool undo); void copySelection(CAScoreView* v); void pasteAt(const QPoint coords, CAScoreView* v); CADocument* openDocument(const QString& fileName); CADocument* openDocument(CADocument* doc); bool saveDocument(QString fileName); void setMode(CAMode mode, const QString& oModeHash); inline CAMode mode() { return _mode; } inline QFileDialog* saveDialog() { return uiSaveDialog.get(); } inline QFileDialog* openDialog() { return uiOpenDialog.get(); } inline QFileDialog* exportDialog() { return uiExportDialog.get(); } inline QFileDialog* importDialog() { return uiImportDialog.get(); } inline CAResourceView* resourceView() { return _resourceView; } inline QAction* resourceViewAction() { return uiResourceView; } inline CAMidiRecorderView* midiRecorderView() { return _midiRecorderView; } inline void setMidiRecorderView(CAMidiRecorderView* v) { _midiRecorderView = v; } inline CAView* currentView() { return _currentView; } inline void removeView(CAView* v) { _viewList.removeAll(v); } inline const QList<CAView*>& viewList() const { return _viewList; } inline CAScoreView* currentScoreView() { if (currentView() && currentView()->viewType()==CAView::ScoreView) return static_cast<CAScoreView*>(currentView()); else return nullptr; } CASheet* currentSheet(); inline CAStaff* currentStaff() { CAContext* context = currentContext(); if (context && context->contextType() == CAContext::Staff) return static_cast<CAStaff*>(context); else return nullptr; } CAContext* currentContext(); void setCurrentVoice(CAVoice*); CAVoice* currentVoice(); inline CAViewContainer* currentViewContainer() { return _currentViewContainer; } inline CADocument* document() { return _document; } inline void setDocument(CADocument* document) { _document = document; _resourceView->setDocument(document); } inline bool isInsertKeySigChecked() { return uiInsertKeySig->isChecked(); } // Dialogs, Windows std::unique_ptr<QFileDialog> uiSaveDialog; std::unique_ptr<QFileDialog> uiOpenDialog; std::unique_ptr<QFileDialog> uiExportDialog; std::unique_ptr<QFileDialog> uiImportDialog; // Python Console CAPyConsole* pyConsole; CAPyConsoleInterface* pyConsoleIface; QDockWidget* helpDock() { return uiHelpDock; } #ifdef QT_WEBENGINEWIDGETS_LIB CAHelpBrowser* helpWidget() { return uiHelpWidget; } #endif private slots: /////////////////////////// // ToolBar/Menus actions // /////////////////////////// void closeEvent(QCloseEvent* event); // File void on_uiNewDocument_triggered(); void on_uiOpenDocument_triggered(); bool on_uiSaveDocument_triggered(); bool on_uiSaveDocumentAs_triggered(); void on_uiCloseDocument_triggered(); void on_uiExportDocument_triggered(); void on_uiImportDocument_triggered(); void on_uiExportToPdf_triggered(); void on_uiOpenRecent_aboutToShow(); void onUiOpenRecentDocumentTriggered(); // Edit void on_uiUndo_toggled(bool, int); void on_uiRedo_toggled(bool, int); void on_uiCopy_triggered(); void on_uiCut_triggered(); void on_uiPaste_triggered(); void on_uiSelectAll_triggered(); void on_uiInvertSelection_triggered(); void on_uiDocumentProperties_triggered(); // Insert void on_uiEditMode_toggled(bool); void on_uiNewSheet_triggered(); void on_uiNewVoice_triggered(); void on_uiContextType_toggled(bool, int); void on_uiClefType_toggled(bool, int); void on_uiTimeSigType_toggled(bool, int); void on_uiBarlineType_toggled(bool, int); void on_uiInsertPlayable_toggled(bool); void on_uiSlurType_toggled(bool, int); void on_uiMarkType_toggled(bool, int); void on_uiArticulationType_toggled(bool, int); void on_uiInsertSyllable_toggled(bool); void on_uiInsertFBM_toggled(bool); void on_uiInsertFM_toggled(bool); void on_uiInsertChordName_toggled(bool); // View void on_uiFullscreen_toggled(bool); void on_uiLockScrollPlayback_toggled(bool); void on_uiZoomToSelection_triggered(); void on_uiZoomToFit_triggered(); void on_uiZoomToWidth_triggered(); void on_uiZoomToHeight_triggered(); void on_uiScoreView_triggered(); void on_uiLilyPondSource_triggered(); void on_uiCanorusMLSource_triggered(); void on_uiResourceView_toggled(bool); void on_uiShowRuler_toggled(bool); // Sheet void on_uiRemoveSheet_triggered(); void on_uiSheetName_editingFinished(); void on_uiSheetProperties_triggered(); // Context void on_uiContextName_editingFinished(); void on_uiRemoveContext_triggered(); void on_uiStanzaNumber_valueChanged(int); void on_uiAssociatedVoice_activated(int); void on_uiContextProperties_triggered(); // Playback void on_uiPlayFromSelection_toggled(bool); // Playable void on_uiPlayableLength_toggled(bool, int); void on_uiTupletType_toggled(bool, int); void on_uiTupletNumber_valueChanged(int); void on_uiTupletActualNumber_valueChanged(int); void on_uiNoteStemDirection_toggled(bool, int); void on_uiHiddenRest_toggled(bool checked); void onMidiInEvent(QVector<unsigned char> message); // Time Signature void on_uiTimeSigBeats_valueChanged(int); void on_uiTimeSigBeat_valueChanged(int); // Clef void on_uiClefOffset_valueChanged(int); // Lyrics void onTextEditKeyPressEvent(QKeyEvent*); void confirmTextEdit(CAScoreView* v, CATextEdit* textEdit, CAMusElement* elt); // Function marks void on_uiFMFunction_toggled(bool, int); void on_uiFMChordArea_toggled(bool, int); void on_uiFMTonicDegree_toggled(bool, int); void on_uiFMEllipse_toggled(bool); // Figured bass marks void on_uiFBMNumber_toggled(bool, int); void on_uiFBMAccs_toggled(bool, int); // Dynamic marks void on_uiDynamicText_toggled(bool, int); void on_uiDynamicVolume_valueChanged(int); void on_uiDynamicCustomText_editingFinished(); // Instrument change void on_uiInstrumentChange_activated(int); // Fermata void on_uiFermataType_toggled(bool, int); // Repeat Mark void on_uiRepeatMarkType_toggled(bool, int); // Fingering void on_uiFinger_toggled(bool checked, int t); void on_uiFingeringOriginal_toggled(bool checked); // Tempo void on_uiTempoBeat_toggled(bool, int); void on_uiTempoBpm_editingFinished(); // Tools void on_uiSettings_triggered(); void on_uiTranspose_triggered(); void on_uiJumpTo_triggered(); void on_uiMidiRecorder_triggered(); // Voice void on_uiVoiceNum_valChanged(int); void on_uiVoiceName_editingFinished(); void on_uiVoiceInstrument_activated(int); void on_uiRemoveVoice_triggered(); void on_uiVoiceStemDirection_toggled(bool, int); void on_uiVoiceProperties_triggered(); // Window void on_uiSplitHorizontally_triggered(); void on_uiSplitVertically_triggered(); void on_uiUnsplitAll_triggered(); void on_uiCloseCurrentView_triggered(); void on_uiNewView_triggered(); void on_uiNewWindow_triggered(); // Help public slots: void on_uiUsersGuide_triggered(); private slots: void on_uiAboutCanorus_triggered(); void on_uiAboutQt_triggered(); ////////////////////////////////// // Handle other widgets signals // ////////////////////////////////// void keyPressEvent(QKeyEvent*); void on_uiTabWidget_currentChanged(int); void on_uiTabWidget_CANewTab(); void on_uiTabWidget_CAMoveTab(int from, int to); void viewClicked(); void scoreViewMousePress(QMouseEvent* e, const QPoint coords); void scoreViewMouseMove(QMouseEvent* e, const QPoint coords); void scoreViewMouseRelease(QMouseEvent* e, const QPoint coords); void scoreViewDoubleClick(QMouseEvent* e, const QPoint coords); void scoreViewTripleClick(QMouseEvent* e, const QPoint coords); void scoreViewWheel(QWheelEvent* e, const QPoint coords); void scoreViewKeyPress(QKeyEvent* e); void sourceViewCommit(QString inputString); void floatViewClosed(CAView*); void onTimeEditedTimerTimeout(); void playbackFinished(); void onScoreViewSelectionChanged(); void onRepaintTimerTimeout(); //////////////////////////////// // Handle progress bar events // //////////////////////////////// void onImportDone(int status); void onExportDone(int status); private: void playImmediately(QList<CAMusElement*> elements); //////////////////////// // General properties // //////////////////////// CADocument* _document; CAMode _mode; CAPreviewCtl* _poPrintPreviewCtl; CAPrintCtl* _poPrintCtl; CAExport* _poExp; // abstract export instance CAResourceView* _resourceView; CATransposeView* _transposeView; CAJumpToView* _jumpToView; CAMidiRecorderView* _midiRecorderView; QStatusBar* _permanentStatusBar; CAMainWinProgressCtl _mainWinProgressCtl; void setMode(CAMode mode); QString createModeHash(); inline void setCurrentView(CAView* view) { _currentView = view; } inline void setCurrentViewContainer(CAViewContainer* vpc) { _currentViewContainer = vpc; } CAViewContainer* _currentViewContainer; QList<CAViewContainer*> _viewContainerList; QList<CAView*> _viewList; QHash<CAViewContainer*, CASheet*> _sheetMap; QHash<QString, int> _modeHash; int _iNumAllowed; CAView* _currentView; CAView* _playbackView; QList<CADrawableMusElement*> _prePlaybackSelection; QTimer* _repaintTimer; bool _rebuildUILock; inline void setRebuildUILock(bool l) { _rebuildUILock = l; } CAPlayback* _playback; QTimer _timeEditedTimer; unsigned int _timeEditedTime; CAMusElementFactory* _musElementFactory; CANoteChecker _noteChecker; std::unique_ptr<CAImport> _importFile; public: inline CAMusElementFactory* musElementFactory() { return _musElementFactory; } private: inline bool stopPlayback() { if (_playback && _playback->isRunning()) _playback->stopNow(); return true; } bool handleUnsavedChanges(); CAKeybdInput* _keybdInput; /////////////////////////////////////////////////////////////////////////// // Pure user interface - widgets that weren't created by Qt Designer yet // /////////////////////////////////////////////////////////////////////////// void createCustomActions(); void setupCustomUi(); void initView(CAView*); void updateUndoRedoButtons(); void updateToolBars(); void updateSheetToolBar(); void updateContextToolBar(); void updateVoiceToolBar(); void updateInsertToolBar(); void updatePlayableToolBar(); void updateTimeSigToolBar(); void updateClefToolBar(); void updateFBMToolBar(); void updateFMToolBar(); void updateDynamicToolBar(); void updateInstrumentToolBar(); void updateTempoToolBar(); void updateFermataToolBar(); void updateRepeatMarkToolBar(); void updateFingeringToolBar(); ///////////////////// // Toolbar section // ///////////////////// // Standard toolbar //QToolBar *uiStandardToolBar; CAUndoToolButton* uiUndo; CAUndoToolButton* uiRedo; // Insert toolbar QToolBar* uiInsertToolBar; QActionGroup* uiInsertGroup; // Group for mutual exclusive selection of music elements // QAction *uiNewSheet; // made by Qt Designer CAMenuToolButton* uiContextType; // QAction *uiInsertPlayable; // made by Qt Designer CAMenuToolButton* uiClefType; // QAction *uiInsertKeySig; // made by Qt Designer CAMenuToolButton* uiTimeSigType; // made by Qt Designer CAMenuToolButton* uiBarlineType; CAMenuToolButton* uiMarkType; CAMenuToolButton* uiArticulationType; // QAction *uiInsertSyllable; // made by Qt Designer // QAction *uiInsertFBM; // made by Qt Designer // QAction *uiInsertFM; // made by Qt Designer QToolBar* uiSheetToolBar; // QAction *uiNewSheet; // made by Qt Designer QLineEdit* uiSheetName; // QAction *uiRemoveSheet; // made by Qt Designer // QAction *uiSheetProperties; // made by Qt Designer QToolBar* uiContextToolBar; // CAContext QLineEdit* uiContextName; //QAction *uiRemoveContext; // made by Qt Designer //QAction *uiContextProperties; // made by Qt Designer // CAStaff // CALyricsContext QSpinBox* uiStanzaNumber; QAction* uiStanzaNumberAction; QComboBox* uiAssociatedVoice; QAction* uiAssociatedVoiceAction; // CAFunctionMarkContext QToolBar* uiVoiceToolBar; // QAction *uiNewVoice; // made by Qt Designer CALCDNumber* uiVoiceNum; QLineEdit* uiVoiceName; QComboBox* uiVoiceInstrument; // QAction *uiRemoveVoice; // made by Qt Designer CAMenuToolButton* uiVoiceStemDirection; // QAction *uiVoiceProperties; // made by Qt Designer QToolBar* uiPlayableToolBar; // note and rest properties are merged for the time being // Note properties CAMenuToolButton* uiPlayableLength; CAMenuToolButton* uiNoteAccs; CAMenuToolButton* uiSlurType; public: // Because CAKeyboardInput (input with midi keyboard) needs to operate these widgets to // provide gui feedback, these, probably even more, should become public. // Some clean interface would be appropriate. CAMenuToolButton* uiTupletType; QSpinBox* uiTupletNumber; QSpinBox* uiTupletActualNumber; private: QAction* uiTupletNumberAction; QLabel* uiTupletInsteadOf; QAction* uiTupletInsteadOfAction; QAction* uiTupletActualNumberAction; // QAction *uiNoteAccsVisible; // made by Qt Designer CAMenuToolButton* uiNoteStemDirection; CAActionStorage* actionStorage; // Rest properties // CAMenuToolButton *uiPlayableLength; // same as note properties // QLabel *uiPlayableDotted; // same as note properties // QAction *uiHiddenRest; // made by Qt Designer CAKeySignatureUI* _poKeySignatureUI; // Key signature UI parts QToolBar* uiClefToolBar; QSpinBox* uiClefOffset; int oldUiClefOffsetValue; QToolBar* uiTimeSigToolBar; QSpinBox* uiTimeSigBeats; QLabel* uiTimeSigSlash; QSpinBox* uiTimeSigBeat; // CAMenuToolButton *uiTimeSigStyle; /// \todo Implement it. -Matevz QToolBar* uiFBMToolBar; // figured bass tool bar CAMenuToolButton* uiFBMNumber; CAMenuToolButton* uiFBMAccs; QToolBar* uiFMToolBar; // function mark tool bar CAMenuToolButton* uiFMFunction; CAMenuToolButton* uiFMChordArea; CAMenuToolButton* uiFMTonicDegree; QComboBox* uiFMKeySig; //QSpinBox *uiKeySigNumberOfAccs; // defined in uiKeySigToolBar //QComboBox *uiKeySigGender; // defined in uiKeySigToolBar //QAction *uiFMEllipse; // made by Qt Designer // Marks tool bars: QToolBar* uiDynamicToolBar; CAMenuToolButton* uiDynamicText; QSpinBox* uiDynamicVolume; QLineEdit* uiDynamicCustomText; QToolBar* uiInstrumentToolBar; QComboBox* uiInstrumentChange; QToolBar* uiTempoToolBar; CAMenuToolButton* uiTempoBeat; QLabel* uiTempoEquals; QLineEdit* uiTempoBpm; QToolBar* uiFermataToolBar; CAMenuToolButton* uiFermataType; QToolBar* uiRepeatMarkToolBar; CAMenuToolButton* uiRepeatMarkType; QToolBar* uiFingeringToolBar; CAMenuToolButton* uiFinger; QCheckBox* uiFingeringOriginal; // Python console QDockWidget* uiPyConsoleDock; // Help widget QDockWidget* uiHelpDock; #ifdef QT_WEBENGINEWIDGETS_LIB CAHelpBrowser* uiHelpWidget; #endif }; #endif /* MAINWIN_H_ */
18,342
C++
.h
492
32.463415
95
0.711986
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,554
singleaction.h
canorusmusic_canorus/src/ui/singleaction.h
/*! Copyright (c) 2009, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef _CASINGLEACTION_H_ #define _CASINGLEACTION_H_ #include <QAction> #include <QShortcut> class QString; // One action based on QAction, Midi and QString. Contains all // information (including description) for one control command class CASingleAction { public: // Constructor / Desctructor CASingleAction(QObject*); virtual ~CASingleAction(); // Getter methods for all single action parameters inline QString getCommandName(bool ampersand = false) { return ampersand ? _oCommandNameNoAmpersand : _oCommandName; } inline QString getDescription() { return _oDescription; } inline QString getShortCutAsString() { return _oShortCut; } inline QString getMidiKeySequence() { return _oMidiKeySequence; } inline bool getMidiShortCutCombined() { return _bMidiShortCutCombined; } // Application-specific Getter (Refs, so no Setter required) inline QAction* getAction() { return _pAction; } inline QKeySequence& getSysShortCut() { return _oSysShortCut; } inline QList<int>& getMidiKeyParameters() { return _oMidiKeyParameters; } // Setter methods void setCommandName(QString oCommandName); void setDescription(QString oDescription); void setShortCutAsString(QString oShortCut); void setMidiKeySequence(QString oMidiKeySequence, bool combined = false); //void setAction(QAction *pAction); QAction* newAction(QObject* parent = nullptr); static void fromQAction(const QAction& action, CASingleAction& sAction); protected: // Action parameters to be stored / loaded via Settings Dialog QString _oCommandName; QString _oCommandNameNoAmpersand; QString _oDescription; QString _oShortCut; QString _oMidiKeySequence; bool _bMidiShortCutCombined; QAction* _pAction; // ShortCut, Midi Key Sequence for the application QKeySequence _oSysShortCut; QList<int> _oMidiKeyParameters; bool m_localCreated = false; }; #endif // _CASINGLEACTION_H_
2,197
C++
.h
50
40.04
122
0.762284
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,555
transposeview.h
canorusmusic_canorus/src/ui/transposeview.h
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef TRANSPOSEVIEW_H_ #define TRANSPOSEVIEW_H_ #include "ui_transposeview.h" class CAMainWin; class QAbstractButton; class CATransposeView : public QDockWidget, private Ui::uiTransposeView { Q_OBJECT public: CATransposeView(CAMainWin* parent); virtual ~CATransposeView(); public slots: void show(); private slots: void updateUi(bool); void on_uiApply_clicked(QAbstractButton* b); void on_uiIntervalQuantity_currentIndexChanged(int); private: void setupCustomUi(); void updateKeySig1(); }; #endif /* TRANSPOSEVIEW_H_ */
777
C++
.h
26
27
73
0.77193
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,556
propertiesdialog.h
canorusmusic_canorus/src/ui/propertiesdialog.h
/*! Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PROPERTIESDIALOG_H_ #define PROPERTIESDIALOG_H_ #include "ui_chordnamecontextproperties.h" #include "ui_documentproperties.h" #include "ui_functionmarkcontextproperties.h" #include "ui_lyricscontextproperties.h" #include "ui_propertiesdialog.h" #include "ui_sheetproperties.h" #include "ui_staffproperties.h" #include "ui_voiceproperties.h" class QTreeWidgetItem; class CADocument; class CASheet; class CAStaff; class CAContext; class CAVoice; class CALyricsContext; class CAFunctionMarkContext; class CAChordNameContext; class CADocumentProperties : public QWidget, public Ui::uiDocumentProperties { Q_OBJECT public: CADocumentProperties(CADocument* doc, QWidget* parent = nullptr) : QWidget(parent) { _document = doc; setupUi(this); } public slots: void on_uiComposer_editingFinished(); private: CADocument* _document; }; class CASheetProperties : public QWidget, public Ui::uiSheetProperties { public: CASheetProperties(QWidget* parent = nullptr) : QWidget(parent) { setupUi(this); } }; class CAStaffProperties : public QWidget, public Ui::uiStaffProperties { public: CAStaffProperties(QWidget* parent = nullptr) : QWidget(parent) { setupUi(this); } }; class CAVoiceProperties : public QWidget, public Ui::uiVoiceProperties { public: CAVoiceProperties(QWidget* parent = nullptr) : QWidget(parent) { setupUi(this); } }; class CALyricsContextProperties : public QWidget, public Ui::uiLyricsContextProperties { public: CALyricsContextProperties(QWidget* parent = nullptr) : QWidget(parent) { setupUi(this); } }; class CAFunctionMarkContextProperties : public QWidget, public Ui::uiFunctionMarkContextProperties { public: CAFunctionMarkContextProperties(QWidget* parent = nullptr) : QWidget(parent) { setupUi(this); } }; class CAChordNameContextProperties : public QWidget, public Ui::uiChordNameContextProperties { public: CAChordNameContextProperties(QWidget* parent = nullptr) : QWidget(parent) { setupUi(this); } }; class CAPropertiesDialog : public QDialog, private Ui::uiPropertiesDialog { Q_OBJECT public: CAPropertiesDialog(CADocument* doc, QWidget* parent = nullptr); virtual ~CAPropertiesDialog(); static void documentProperties(CADocument* doc, QWidget* parent); static void sheetProperties(CASheet* sheet, QWidget* parent); static void contextProperties(CAContext* context, QWidget* parent); static void voiceProperties(CAVoice* voice, QWidget* parent); inline CADocument* document() { return _document; } inline QTreeWidgetItem* documentItem() { return _documentItem; } inline QHash<QTreeWidgetItem*, CASheet*>& sheetItem() { return _sheetItem; } inline QHash<QTreeWidgetItem*, CAContext*>& contextItem() { return _contextItem; } inline QHash<QTreeWidgetItem*, CAVoice*>& voiceItem() { return _voiceItem; } public slots: void on_uiDocumentTree_currentItemChanged(QTreeWidgetItem* cur, QTreeWidgetItem* prev); void on_uiButtonBox_clicked(QAbstractButton*); void on_uiUp_clicked(bool); void on_uiDown_clicked(bool); private: void buildTree(); void applyProperties(); void createDocumentFromTree(); void updateDocumentProperties(CADocument*); void updateSheetProperties(CASheet*); void updateStaffProperties(CAStaff*); void updateVoiceProperties(CAVoice*); void updateLyricsContextProperties(CALyricsContext*); void updateFunctionMarkContextProperties(CAFunctionMarkContext*); void updateChordNameContextProperties(CAChordNameContext*); CADocument* _document; QTreeWidgetItem* _documentItem; // Document => Document properties widget QWidget* _documentPropertiesWidget; // Document item in tree widget => Document QHash<CASheet*, QWidget*> _sheetPropertiesWidget; // Sheet => Sheet properties widget QHash<QTreeWidgetItem*, CASheet*> _sheetItem; // Sheet item in tree widget => Sheet QHash<CAContext*, QWidget*> _contextPropertiesWidget; // Context => Context properties widget QHash<QTreeWidgetItem*, CAContext*> _contextItem; // Context item in tree widget => Context QHash<CAVoice*, QWidget*> _voicePropertiesWidget; // Voice => Voice properties widget QHash<QTreeWidgetItem*, CAVoice*> _voiceItem; // Voice item in tree widget => Voice }; #endif /* PROPERTIESDIALOG_H_ */
4,684
C++
.h
127
32.889764
100
0.753086
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,557
settingsdialog.h
canorusmusic_canorus/src/ui/settingsdialog.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef MIDISETUPDIALOG_H_ #define MIDISETUPDIALOG_H_ #include <QColorDialog> #include <QPoint> #include <QWidget> // Parent of Settings #include "mainwin.h" #include "ui_settingsdialog.h" class CASheet; class CAActionsEditor; class CASettingsDialog : public QDialog, private Ui::uiSettingsDialog { Q_OBJECT public: enum CASettingsPage { UndefinedSettings = -1, EditorSettings = 0, AppearanceSettings = 1, ActionSettings = 2, LoadSaveSettings = 3, PlaybackSettings = 4, PrintingSettings = 5, }; CASettingsDialog(CASettingsPage currentPage, CAMainWin* parent = nullptr); ~CASettingsDialog(); private slots: void on_uiButtonBox_clicked(QAbstractButton*); void on_uiSettingsList_currentItemChanged(QListWidgetItem*, QListWidgetItem*); void on_uiDocumentsDirectoryBrowse_clicked(bool); void on_uiDocumentsDirectoryRevert_clicked(bool); void on_uiBackgroundColor_clicked(bool); void on_uiBackgroundRevert_clicked(bool); void on_uiForegroundColor_clicked(bool); void on_uiForegroundRevert_clicked(bool); void on_uiSelectionColor_clicked(bool); void on_uiSelectionRevert_clicked(bool); void on_uiSelectionAreaColor_clicked(bool); void on_uiSelectionAreaRevert_clicked(bool); void on_uiSelectedContextColor_clicked(bool); void on_uiSelectedContextRevert_clicked(bool); void on_uiHiddenElementsColor_clicked(bool); void on_uiHiddenElementsRevert_clicked(bool); void on_uiDisabledElementsColor_clicked(bool); void on_uiDisabledElementsRevert_clicked(bool); void on_uiTypesetterBrowse_clicked(bool); void on_uiPdfViewerBrowse_clicked(bool); void on_uiTypesetterDefault_toggled(bool); void on_uiPdfViewerDefault_toggled(bool); private: void setupPages(CASettingsPage currentPage = EditorSettings); void buildPreviewSheet(); void buildActionsEditorPage(); void applySettings(); // Pages temporary variables CASheet* _previewSheet; CAActionsEditor* _commandsEditor; QMap<int, QString> _midiInPorts; QMap<int, QString> _midiOutPorts; CAMainWin* _mainWin; // access to file dialogs instances }; #endif /* MIDISETUPDIALOG_H_ */
2,444
C++
.h
65
33.184615
82
0.761844
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,558
actionstorage.h
canorusmusic_canorus/src/ui/actionstorage.h
/*! Copyright (c) 2015, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef ACTIONSTORAGE_H_ #define ACTIONSTORAGE_H_ #include <QAction> #include <QString> // Helper class to reduce code ballast in mainwin class // Action instances from childs in CAMainWin are stored here for access // their default keyboard information (like shortcut) class CAMainWin; class CAActionDelegate; class CASingleAction; class CAActionStorage { public: CAActionStorage(); ~CAActionStorage(); void storeActionsFromMainWindow(CAMainWin& mainWin); void storeAction(QAction* action); void addWinActions(); protected: QWidget _actionWidget; CAActionDelegate* _actionDelegate; // Requires parts of main win, so needs to be a member }; #endif // ACTIONSTORAGE_H_
944
C++
.h
27
32.148148
93
0.778634
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,559
jumptoview.h
canorusmusic_canorus/src/ui/jumptoview.h
/*! Copyright (c) 2018, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef JUMPTOVIEW_H_ #define JUMPTOVIEW_H_ #include <QDialog> #include "ui_jumptoview.h" class CAMainWin; class CAJumpToView : public QDialog, private Ui::uiJumpToView { Q_OBJECT public: CAJumpToView(CAMainWin* parent); virtual ~CAJumpToView(); public slots: void show(); void accept(); private: void setupCustomUi(); }; #endif /* JUMPTOVIEW_H_ */
591
C++
.h
22
24.227273
72
0.751786
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,560
plugin.h
canorusmusic_canorus/src/interface/plugin.h
/*! Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PLUGIN_H_ #define PLUGIN_H_ #include <QHash> #include <QList> #include <QLocale> #include <QString> class QPoint; class QEvent; class QMenu; class CAMainWin; class CADocument; class CAPluginAction; class CAPlugin { public: CAPlugin(); CAPlugin(QString name, QString author, QString version, QString date, QString dirName, QString homeUrl, QString updateUrl); ~CAPlugin(); /** * This function is called when an event was triggered in a program and a plugin connected to this event is triggered. * It calls all the plugin's actions having the given onAction. * * @param onAction String describing action name. eg. onScoreClick, onDocumentClose * @param mainWin Pointer to the current application main window. * @param document Pointer to the current document. * @param evt Pointer to the Mouse/Key/Wheel event, if it happened. * @param coords Pointer to the coords in absolute world units, if a click on Score happened. * @return True, if all the actions were successfully called, False otherwise. */ bool action(QString onAction, CAMainWin* mainWin = nullptr, CADocument* document = nullptr, QEvent* evt = nullptr, QPoint* coords = nullptr); /** * This function calls a specific action. This is used for export, import and custom actions which aren't called by Canorus automatically. * @param action Pointer to the action to be called. * @param mainWin Pointer to the current application main window. * @param document Pointer to the current document. * @param evt Pointer to the Mouse/Key/Wheel event, if it happened. * @param coords Pointer to the coords in absolute world units, if a click on Score happened. * @return True, if the action succeeded, False otherwise. */ bool callAction(CAPluginAction* action, CAMainWin* mainWin = nullptr, CADocument* document = nullptr, QEvent* evt = nullptr, QPoint* coords = nullptr, QString filename = ""); /** * Adds an action to the plugin, if the actionName&action aren't present yet. * * @param onAction Name of the Canorus's action the plugin reacts on. * @param lang Type of the action (ruby, python, library etc.). * @param fileName File name of the script/library which is to be run on Canorus event. * @param function Name of the function to be run. * @param args List of arguments expected by the function. */ void addAction(CAPluginAction* action); void addMenu(QString name, QMenu* menu) { _menuMap[name] = menu; } void setEnabled(bool enabled) { _enabled = enabled; } bool isEnabled() { return _enabled; } QString name() { return _name; } QString author() { return _author; } QString version() { return _version; } QString date() { return _date; } QString dirName() { return _dirName; } QString homeUrl() { return _homeUrl; } QString updateUrl() { return _updateUrl; } QString description(QString lang) { return _descMap[lang]; } QString localDescription() { if (_descMap.contains(QLocale::system().name())) return description(QLocale::system().name()); else return description(""); } QMenu* menu(QString menuName) { return _menuMap[menuName]; } void setName(QString name) { _name = name; } void setDescription(QString desc, QString lang = QString("")) { _descMap[lang] = desc; } void setAuthor(QString author) { _author = author; } void setVersion(QString version) { _version = version; } void setDate(QString date) { _date = date; } void setDirName(QString dirName) { _dirName = dirName; } void setHomeUrl(QString homeUrl) { _homeUrl = homeUrl; } void setUpdateUrl(QString updateUrl) { _updateUrl = updateUrl; } /** * Return a list of all the actions the plugin is connected to. * * @return List of actions in QList QString format. */ QList<QString> actionList() { return _actionMap.keys(); } private: QString _name; QHash<QString, QString> _descMap; /// LOCALE description of the plugin, key means the language code, value is the translation. Empty string key is the key of universal non-translated description. QString _author; QString _version; QString _date; QString _dirName; /// ABSOLUTE Name of directory where the plugin is located - plugin only stores the relative one, Canorus changes it to absolute one QString _homeUrl; QString _updateUrl; bool _enabled; QMultiHash<QString, CAPluginAction*> _actionMap; /// Key: onAction, Value: plugin's action QHash<QString, QMenu*> _menuMap; /// Map of plugin menu name -> Canorus menu object }; #endif /*PLUGIN_H_*/
4,869
C++
.h
101
43.950495
199
0.715278
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,561
rtmididevice.h
canorusmusic_canorus/src/interface/rtmididevice.h
/*! Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef RTMIDIDEVICE_H_ #define RTMIDIDEVICE_H_ #include "interface/mididevice.h" #include <sstream> class RtMidiOut; class RtMidiIn; #ifndef SWIG void rtMidiInCallback(double deltatime, std::vector<unsigned char>* message, void* userData); #endif class CARtMidiDevice : public CAMidiDevice { public: CARtMidiDevice(); virtual ~CARtMidiDevice(); QMap<int, QString> getOutputPorts(); QMap<int, QString> getInputPorts(); bool openOutputPort(int port); // return true on success, false otherwise bool openInputPort(int port); // return true on success, false otherwise void closeOutputPort(); void closeInputPort(); void send(QVector<unsigned char> message, int time); void sendMetaEvent(int, char, char, char, int) {} private: RtMidiOut* _out; RtMidiIn* _in; bool _outOpen; bool _inOpen; qint64 _pid; std::stringstream _midiNameIn; std::stringstream _midiNameOut; }; #endif /* RTMIDIDEVICE_H_ */
1,187
C++
.h
36
29.694444
93
0.744737
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,562
playback.h
canorusmusic_canorus/src/interface/playback.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PLAYBACK_H_ #define PLAYBACK_H_ #include <QList> #include <QThread> class CAMidiDevice; class CASheet; class CAMusElement; class CAPlayable; class CANote; class CATempo; class CAPlayback : public QThread { #ifndef SWIG Q_OBJECT #endif public: CAPlayback(CASheet*, CAMidiDevice*); CAPlayback(CAMidiDevice*); ~CAPlayback(); void run(); void stop(); void playImmediately(QList<CAMusElement*> elts, int port); inline int getInitTimeStart() { return _initTimeStart; } inline void setInitTimeStart(int t) { _initTimeStart = t; } inline CAMidiDevice* midiDevice() { return _midiDevice; } inline CASheet* sheet() { return _sheet; } inline void setSheet(CASheet* s) { _sheet = s; } inline QList<CAPlayable*>& curPlaying() { return _curPlaying; } #ifndef SWIG public slots: #else public: #endif void stopNow(); #ifndef SWIG signals: void playbackFinished(); #endif private: void initPlayback(); void initStreams(CASheet* sheet); void loopUntilPlayable(int i, bool ignoreRepeats = false); void playSelectionImpl(); void updateSleepFactor(CATempo* t); inline QList<CAMusElement*>& streamAt(int idx) { return _streamList[idx]; } inline const QList<QList<CAMusElement*>>& streamList() { return _streamList; } inline int& streamIdx(int i) { return _streamIdx[i]; } inline int& lastRepeatOpenIdx(int i) { return _lastRepeatOpenIdx[i]; } inline bool stopLock() { return _stopLock; } inline void setStopLock(bool lock) { _stopLock = lock; } CASheet* _sheet; CAMidiDevice* _midiDevice; inline void setMidiDevice(CAMidiDevice* d) { _midiDevice = d; } inline void setStop(bool stop) { _stop = stop; } bool _stop; bool _stopLock; bool _playSelectionOnly; QList<CAMusElement*> _selection; int _initTimeStart; float _sleepFactor; QList<QList<CAMusElement*>> _streamList; QList<CAPlayable*> _curPlaying; // list of currently playing notes and rests int* _streamIdx; bool _repeating; int* _lastRepeatOpenIdx; int _curTime; }; #endif /* PLAYBACK_H_ */
2,335
C++
.h
72
28.777778
82
0.719126
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,563
plugins_swig.h
canorusmusic_canorus/src/interface/plugins_swig.h
/*! Copyright (c) 2009-2020, Štefan Sakalík, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include "interface/pyconsoleinterface.h" #include "score/document.h" #include "score/sheet.h" #include <QObject> class CAMainWin { //: public QObject { // currentSheet (SHEET = OK) // CAScoreViewport(NOT_OK) {currentScoreViewport} // -> selection.size = v->selection().front()->drawableMusElement::DrawableNote? : BAD BAD BAD // -> front()->musElement (OK) // currentScoreViewport // -> musElementSelection ok // public: CAMainWin() {} CASheet* currentSheet() { //CAScoreViewPort *v = currentScoreViewPort(); //if (v) return v->sheet(); //else return 0; return nullptr; } CAPyConsoleInterface* pyConsoleIface = nullptr; }; // Needs refactoring! // Functions in this file should be moved to scripting directory and merged with // scripting code (canoruspython.i and swigpython.cpp). -Matevz class CACanorus { public: inline static QList<CAMainWin*>& mainWinList() { return _mainWinList; } private: static QList<CAMainWin*> _mainWinList; };
1,260
C++
.h
37
30.27027
101
0.704283
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,564
mididevice.h
canorusmusic_canorus/src/interface/mididevice.h
/*! Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef MIDIDEVICE_H_ #define MIDIDEVICE_H_ #include <QMap> #include <QObject> #include <QString> #include <QStringList> #include <QVector> #include "score/diatonicpitch.h" class CASheet; class CADiatonicKey; class CAMidiDevice : public QObject { #ifndef SWIG Q_OBJECT #endif friend void rtMidiInCallback(double deltatime, std::vector<unsigned char>* message, void* userData); public: enum CAMidiDeviceType { RtMidiDevice, MidiExportDevice }; CAMidiDevice(); enum midiCommands { Meta_Text = 0x01, Meta_Copyright = 0x02, Meta_SeqTrkName = 0x03, Meta_InstrName = 0x04, Meta_Lyric = 0x05, Meta_Marker = 0x06, Meta_CuePoint = 0x07, Meta_Tempo = 0x51, // len=03 tt tt tt microseconds per midi quarter note Meta_SMPTEOffs = 0x54, // len=05 hr mn se fr ff SMPTE Offset Meta_Timesig = 0x58, Meta_Keysig = 0x59, Meta_Track_End = 0x2f, Midi_Ctl_Reverb = 0x5b, Midi_Ctl_Chorus = 0x5d, Midi_Ctl_Pan = 0x0a, Midi_Ctl_Volume = 0x07, Midi_Ctl_Sustain = 0x40, Midi_Ctl_Event = 0xff, // Events with midi channel on the low nibble: Midi_Note_Off = 0x80, // 3 byte Midi_Note_On = 0x90, Midi_Prog_Change = 0xc0, // 2 byte Midi_Control_Chg = 0xb0 // 3 byte }; static QStringList gmInstrumentList() { return CAMidiDevice::GM_INSTRUMENTS; } static QString instrumentName(int midiProgram); static QStringList instrumentNames(); static unsigned char freeMidiChannel(CASheet*); virtual ~CAMidiDevice() {} inline CAMidiDeviceType midiDeviceType() { return _midiDeviceType; } bool isRealTime() { return _realTime; } virtual QMap<int, QString> getOutputPorts() = 0; virtual QMap<int, QString> getInputPorts() = 0; virtual bool openOutputPort(int port) = 0; // return true on success, false otherwise virtual bool openInputPort(int port) = 0; // return true on success, false otherwise virtual void closeOutputPort() = 0; virtual void closeInputPort() = 0; virtual void send(QVector<unsigned char> message, int time) = 0; // message and absolute canorus time (independent of tempo) virtual void sendMetaEvent(int time, char event, char a, char b, int c) = 0; // absolute time of the meta event which is meant only for midi file export #ifndef SWIG signals: void midiInEvent(QVector<unsigned char> message); #endif protected: void setRealTime(bool r) { _realTime = r; } inline void setMidiDeviceType(CAMidiDeviceType t) { _midiDeviceType = t; } CAMidiDeviceType _midiDeviceType; bool _realTime; // is the device private: static QStringList GM_INSTRUMENTS; }; #endif /* MIDIDEVICE_H_ */
3,003
C++
.h
79
32.746835
156
0.694004
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,565
pluginaction.h
canorusmusic_canorus/src/interface/pluginaction.h
/*! Copyright (c) 2007-2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PLUGINACTION_H_ #define PLUGINACTION_H_ #include <QAction> #include "interface/plugin.h" class CAPluginAction : public QAction { #ifndef SWIG Q_OBJECT #endif public: CAPluginAction(CAPlugin* plugin, QString name, QString lang, QString function, QList<QString> args, QString filename); inline CAPlugin* plugin() { return _plugin; } inline QString name() { return _name; } inline QString lang() { return _lang; } inline QString function() { return _function; } inline const QList<QString>& args() { return _args; } inline QString filename() { return _filename; } inline QString onAction() { return _onAction; } inline QString exportFilter(QString lang) { return _exportFilter[lang]; } QString localExportFilter() { if (_exportFilter.contains(QLocale::system().name())) return exportFilter(QLocale::system().name()); else return exportFilter(""); } inline QString importFilter(QString lang) { return _importFilter[lang]; } QString localImportFilter() { if (_importFilter.contains(QLocale::system().name())) return exportFilter(QLocale::system().name()); else return importFilter(""); } inline QString localeText(QString lang) { return _text[lang]; } QString localText() { if (_text.contains(QLocale::system().name())) return localeText(QLocale::system().name()); else return localeText(""); } bool refresh() { return _refresh; } void setPlugin(CAPlugin* plugin) { _plugin = plugin; } void setName(QString name) { _name = name; } void setLang(QString lang) { _lang = lang; } void setFunction(QString function) { _function = function; } void addArgument(QString arg) { _args << arg; } bool removeArgument(QString arg) { return _args.removeAll(arg); } void setFilename(QString filename) { _filename = filename; } void setOnAction(QString onAction) { _onAction = onAction; } void setExportFilter(QString lang, QString value) { _exportFilter[lang] = value; } void setExportFilters(QHash<QString, QString> f) { _exportFilter = f; } void setImportFilter(QString lang, QString value) { _importFilter[lang] = value; } void setImportFilters(QHash<QString, QString> f) { _importFilter = f; } void setLocaleText(QString lang, QString value) { _text[lang] = value; this->setText(localText()); } void setTexts(QHash<QString, QString> t) { _text = t; this->setText(localText()); } void setRefresh(bool refresh) { _refresh = refresh; } private: CAPlugin* _plugin; /// Pointer to the plugin which this action belongs to QString _name; /// Action name QString _lang; /// Scripting language QString _function; /// Function name QList<QString> _args; /// Function arguments QString _filename; /// Filename which has the function QString _onAction; /// Canorus internal action which this action reacts on QHash<QString, QString> _exportFilter; /// Text written in export dialog's filter QHash<QString, QString> _importFilter; /// Text written in import dialog's filter QHash<QString, QString> _text; /// Text written on a menu item or the toolbar button bool _refresh; /// Should the UI be rebuilt when calling the action. #ifndef SWIG private slots: void triggeredSlot(bool); /// Connected to triggered(), calls plugin->callAction() signals: void triggered(QAction*, bool); /// When the action is triggered, this signal is emitted #endif }; #endif /* PLUGINACTION_H_ */
3,848
C++
.h
90
37.511111
122
0.684548
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,566
pyconsoleinterface.h
canorusmusic_canorus/src/interface/pyconsoleinterface.h
/*! Copyright (c) 2008-2019, Štefan Sakalík, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PYCONSOLEINTERFACE_H_ #define PYCONSOLEINTERFACE_H_ #include <QString> class CAPyConsole; class CAPyConsoleInterface { public: #if !defined(SWIG) && !defined(SWIGCPP) CAPyConsoleInterface(CAPyConsole* pyConsole); // API for pycli plugin char* bufferedInput(char* prompt); // Input goes to script void bufferedOutput(char* bufInp, bool bStdErr); #else char* bufferedInput(char* prompt) { (void)prompt; return nullptr; } void bufferedOutput(char* bufInp, bool bStdErr) { (void)bufInp; (void)bStdErr; } #endif CAPyConsoleInterface() { } void pluginInit(void); // when script initializes private: #if !defined(SWIG) && !defined(SWIGCPP) CAPyConsole* _pycons; #endif }; #endif /* PYCONSOLEINTERFACE_H_ */
1,060
C++
.h
38
24.078947
101
0.721782
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,567
pluginmanager.h
canorusmusic_canorus/src/interface/pluginmanager.h
/** @file interface/pluginmanager.h * * Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team * All Rights Reserved. See AUTHORS for a complete list of authors. * * Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PLUGINMANAGER_H_ #define PLUGINMANAGER_H_ #include <QMultiHash> #include <QStack> #include <QString> #include <QXmlDefaultHandler> class CAMainWin; class CADocument; class CAPlugin; class CAPluginAction; class QEvent; class QPoint; class CAPluginManager : public QXmlDefaultHandler { public: CAPluginManager(CAMainWin* mainWin, CAPlugin* plugin); ~CAPluginManager(); static void readPlugins(); static bool enablePlugin(CAPlugin* plugin, CAMainWin* mainWin); static bool enablePlugins(CAMainWin* mainWin); static bool disablePlugin(CAPlugin* plugin); static bool disablePlugins(); static void action(QString onAction, CADocument* document, QEvent* evt, QPoint* coords, CAMainWin* mainWin); static bool exportFilterExists(const QString filter) { return _exportFilterMap.contains(filter); } static void exportAction(QString filter, CADocument* document, QString filename); static bool importFilterExists(const QString filter) { return _importFilterMap.contains(filter); } static void importAction(QString filter, CADocument* document, QString filename); static bool installPlugin(QString path); static bool removePlugin(CAPlugin* plugin); static const QList<CAPlugin*> pluginList() { return _pluginList; } // XML parser functions: bool startElement(const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& attributes); bool endElement(const QString& namespaceURI, const QString& localName, const QString& qName); bool fatalError(const QXmlParseException& exception); bool characters(const QString& ch); private: static QList<CAPlugin*> _pluginList; static QMultiHash<QString, CAPlugin*> _actionMap; static QHash<QString, CAPluginAction*> _exportFilterMap; static QHash<QString, CAPluginAction*> _importFilterMap; // non-static members needed while parsing plugin's descriptor file: CAMainWin* _mainWin; QString _curChars; QStack<QString> _tree; CAPlugin* _curPlugin; QString _curPluginCanorusVersion; QString _curPluginLocale; // <action> tag: QHash<QString, QString> _curActionText; // List of actions LOCALE texts QString _curActionName; QString _curActionLocale; // Temporary lang QString _curActionOnAction; QHash<QString, QString> _curActionExportFilter, _curActionImportFilter; QString _curActionParentMenu, _curActionParentToolbar; bool _curActionRefresh; QString _curActionLang, _curActionFunction, _curActionFilename; QList<QString> _curActionArgs; // <menu> tag: QString _curMenuName; QHash<QString, QString> _curMenuTitle; // List of menus LOCALE titles QString _curMenuLocale; // Temporary lang QString _curMenuParentMenu; // Parent menu of the menu }; #endif /*PLUGINMANAGER_H_*/
3,115
C++
.h
72
39.180556
112
0.763871
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,568
keybdinput.h
canorusmusic_canorus/src/interface/keybdinput.h
/*! Copyright (c) 2006-2008, Matevž Jekovec, Canorus development team Copyright (c) 2008, Georg Rudolph All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef KEYBDINPUT_H_ #define KEYBDINPUT_H_ #include <QList> #include <QThread> #include "ui/mainwin.h" class CAMainWin; class CAKeybdInput { public: CAKeybdInput(CAMainWin* m); ~CAKeybdInput(); void onMidiInEvent(QVector<unsigned char> m); private: CAMainWin* _mw; void midiInEventToScore(CAScoreView* v, QVector<unsigned char> m); QTimer _midiInChordTimer; //CASheet *_lastMidiInSheet; //CAStaff *_lastMidiInStaff; CAVoice* _lastMidiInVoice; CADiatonicPitch _actualKeySignature; signed char _actualKeySignatureAccs[7]; int _actualKeyAccidentalsSum; CADiatonicPitch matchPitchToKey(CAVoice* voice, CADiatonicPitch p); CAPlayable* _tupPla; CATuplet* _tup; QList<CAMusElement*> _noteLayout; }; #endif /* KEYBDINPUT_H_ */
1,042
C++
.h
33
28.242424
72
0.755
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,569
swigruby.h
canorusmusic_canorus/src/scripting/swigruby.h
/*! Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifdef USE_RUBY #ifndef SWIGRUBY_H_ #define SWIGRUBY_H_ #include <ruby.h> #include <QList> #include <QString> class CASwigRuby { public: enum CAClassType { // Qt objects String, // Canorus objects Document, Sheet, Resource, Context, Voice, MusElement, PlayableLength, // Console PyConsoleInterface, // Plugins Plugin }; static void init(); ///Initializes Ruby and loads base 'CanorusRuby' module. Call this before any other Ruby operations! Call this before calling toRubyObject() or any other conversation functions as well! /*! * Call an external Ruby function in the given module with the list of arguments and return its Ruby value. * * \param fileName Absolute path to the filename of the script * \param function Function or method name. * \param args List of arguments in Ruby's VALUE format. Use toRubyObject() to convert C++ classes to Ruby objects. * \return Ruby's function return value in Ruby VALUE format. */ static VALUE callFunction(QString fileName, QString function, QList<VALUE> args); /*! * Ruby uses different objects than C++. They are actually wrappers around the original ones, but still share different memory and structure. * Use this function to create a Ruby object out of the C++ one. * * \param object Pointer to the C++ object which the Ruby object should be derived from. * \param objectType See CAClassType. C++ doesn't support figuring out the object type from the raw pointer - you have to pass its class type as well. * \return Pointer to the Ruby object in Ruby's VALUE format. */ static VALUE toRubyObject(void* object, CAClassType type); //defined in scripting/canorusruby.i file }; #endif /*SWIGRUBY_H_*/ #endif
2,112
C++
.h
51
35.529412
209
0.694973
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,570
swigpython.h
canorusmusic_canorus/src/scripting/swigpython.h
/*! Copyright (c) 2006-2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifdef USE_PYTHON #ifndef SWIGPYTHON_H_ #define SWIGPYTHON_H_ #include <Python.h> #include <QList> #include <QString> class CASwigPython { public: enum CAClassType { // Qt objects String, // Canorus objects Document, Sheet, Resource, Context, Voice, MusElement, PlayableLength, // Console PyConsoleInterface, // Plugins Plugin }; static void init(); static PyObject* callFunction(QString fileName, QString function, QList<PyObject*> args, bool autoReload = false); static void* callPycli(void*); static PyObject* toPythonObject(void* object, CAClassType type); // defined in scripting/canoruspython.i static PyThreadState *mainThreadState, *pycliThreadState; }; #endif /*SWIGPYTHON_H_*/ #endif
1,059
C++
.h
37
23.459459
118
0.691395
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,571
printctl.h
canorusmusic_canorus/src/control/printctl.h
/*! Copyright (c) 2006-2019, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef _PRINT_CTL_H_ #define _PRINT_CTL_H_ // Includes #include <QFile> #include <QObject> #include <QPrinterInfo> #include <QStringList> #include <QVariant> #include <QVector> #include <memory> // Forward declarations class CAMainWin; class CASVGExport; class CAPrintCtl : public QObject { Q_OBJECT public: CAPrintCtl(CAMainWin* poMainWin); ~CAPrintCtl(); public slots: void on_uiPrint_triggered(); void on_uiPrintDirectly_triggered(); protected slots: void printSVG(int iExitCode); protected: void printDocument(); CAMainWin* _poMainWin; std::unique_ptr<CASVGExport> _poSVGExport; QString _oOutputSVGName; bool _showDialog; // used when printing directly }; #endif // _PRINT_CTL_H
994
C++
.h
36
24.388889
93
0.743129
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,572
mainwinprogressctl.h
canorusmusic_canorus/src/control/mainwinprogressctl.h
/*! Copyright (c) 2009, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef MAINWINPROGRESSCTL_H_ #define MAINWINPROGRESSCTL_H_ #include <QObject> #include <memory> class CAMainWin; class CAProgressStatusBar; class CAFile; class QTimer; class CAMainWinProgressCtl : public QObject { Q_OBJECT public: CAMainWinProgressCtl(CAMainWin* mainWin); ~CAMainWinProgressCtl(); void startProgress(CAFile &f); private slots: void on_updateTimer_timeout(); void on_cancelButton_clicked(bool); private: void restoreStatusBar(); CAMainWin* _mainWin; std::unique_ptr<CAProgressStatusBar> _bar; std::unique_ptr<QTimer> _updateTimer; CAFile *_file; }; #endif /* MAINWINPROGRESSCTL_H_ */
865
C++
.h
30
25.9
72
0.768204
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,573
externprogram.h
canorusmusic_canorus/src/control/externprogram.h
/*! Copyright (c) 2006-2019, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef EXTERN_PROGRAM_H #define EXTERN_PROGRAM_H // Includes #include <QObject> #include <QProcess> #include <QStringList> #include <memory> // Forward declarations // This class is used to run a program in the background // and to get it's input/output via signals // Class definition class CAExternProgram : public QObject { Q_OBJECT public: CAExternProgram(bool bRcvStdErr = true, bool bRcvStdOut = true); void setProgramName(const QString& roProgram); void setProgramPath(const QString& roPath); // Warning: Setting all parameters overwrites all // parameters added via addParameter method! void setParameters(const QStringList& roParams); void inline setParamDelimiter(QString oDelimiter = " ") { _oParamDelimiter = oDelimiter; } inline const QStringList& getParameters() { return _oParameters; } inline bool getRunning() { return _poExternProgram->state() == QProcess::Running; } inline const QString& getParamDelimiter() { return _oParamDelimiter; } int getExitState(); void addParameter(const QString& roParam, bool bAddDelimiter = true); inline void clearParameters() { _oParameters.clear(); } bool execProgram(const QString& roCwd = "."); inline bool waitForFinished(int iMSecs) { return _poExternProgram->waitForFinished(iMSecs); } signals: void nextOutput(const QByteArray& roData); void programExited(int iExitCode); protected slots: void rcvProgramStdOut() { rcvProgramOutput(_poExternProgram->readAllStandardOutput()); } void rcvProgramStdErr() { rcvProgramOutput(_poExternProgram->readAllStandardError()); } void programError(QProcess::ProcessError) { programExited(); } void programFinished(int, QProcess::ExitStatus) { programExited(); } protected: void rcvProgramOutput(const QByteArray& roData); void programExited(); // References to the real objects(!) std::unique_ptr<QProcess> _poExternProgram; // Process object running the watched program QString _oProgramName; // Program name to be run QString _oProgramPath; // Program path being added to the program name QStringList _oParameters; // List of program parameters QString _oParamDelimiter; // delimiter between the single parameters bool _bRcvStdErr; // 'true': Receive program output from stderr }; #endif // EXTERN_PROGRAM
2,629
C++
.h
60
39.55
97
0.744222
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,574
typesetctl.h
canorusmusic_canorus/src/control/typesetctl.h
/*! Copyright (c) 2006-2019, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef TYPESET_CTL_H #define TYPESET_CTL_H // Includes #include <QObject> #include <QStringList> #include <QTemporaryFile> #include <QVariant> #include <QVector> // Forward declarations class CAExternProgram; class CAExport; class CADocument; class CASheet; class CATypesetCtl : public QObject { Q_OBJECT public: CATypesetCtl(); ~CATypesetCtl(); void setTypesetter(const QString& roProgramName, const QString& roProgramPath = ""); void setPS2PDF(const QString& roProgrammName, const QString& roProgramPath = "", const QStringList& roParams = (QStringList() << QString(""))); virtual void setExpOption(const QVariant& roName, const QVariant& roValue); virtual void setTSetOption(const QVariant& roName, const QVariant& roValue, bool bSpace = false, bool bShortParam = true); inline void setPDFConversion(bool bConversion) { _bPDFConversion = bConversion; } inline void setExporter(CAExport* poExport) { _poExport = poExport; } // Attention: .pdf automatically added and removed if it was added internally void exportDocument(CADocument* poDoc); void exportSheet(CASheet* poSheet); void runTypesetter(); inline bool getPDFConversion() { return _bPDFConversion; } inline CAExport* getExporter() { return _poExport; } inline QString getTempFilePath() { return _oOutputFileName; } bool waitForFinished(int iMSecs); signals: void nextOutput(const QByteArray& roData); void nextStep(); void typesetterFinished(int iExitCode); protected slots: void rcvTypesetterOutput(const QByteArray& roData); void typsetterExited(int iExitCode); protected: bool createPDF(); CAExternProgram* _poTypesetter; // Transforms exported file to pdf / postscript CAExternProgram* _poConvPS2PDF; // Transforms postscripts files to pdf if needed CAExport* _poExport; // Transforms canorus document to typesetter format QVector<QVariant> _oExpOptList; // List of options for export QVector<QVariant> _oTSetOptList; // List of options for typesetter QTemporaryFile* _poOutputFile; // Output file for pdf (also used for exported file) QString _oOutputFileName; // Output file name for pdf (temporary file deletes it on close) bool _bPDFConversion; // Do a conversion from postscript to pdf bool _bOutputFileNameFirst; // File name as first parameter ? (Default: No) }; #endif // TYPESET_CTL_H
2,663
C++
.h
58
41.931034
126
0.753086
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,575
helpctl.h
canorusmusic_canorus/src/control/helpctl.h
/*! Copyright (c) 2009, 2016 Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef HELPCTL_H_ #define HELPCTL_H_ #include <QString> #include <QUrl> class QWidget; class CAHelpCtl { public: CAHelpCtl(); virtual ~CAHelpCtl(); bool showUsersGuide(QString chapter = "", QWidget* helpWidget = nullptr); private: QUrl _homeUrl; QUrl detectHomeUrl(); void displayHelp(QUrl url, QWidget* helpWidget); }; #endif /* HELPCTL_H_ */
613
C++
.h
21
25.47619
79
0.715266
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,576
resourcectl.h
canorusmusic_canorus/src/control/resourcectl.h
/*! Copyright (c) 2008-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef RESOURCECTL_H_ #define RESOURCECTL_H_ #include <QList> #include <QString> #include <memory> #include "score/resource.h" class CAResourceCtl { public: CAResourceCtl(); virtual ~CAResourceCtl(); static std::shared_ptr<CAResource> importResource(QString name, QString fileName, bool isLinked = false, CADocument* parent = nullptr, CAResource::CAResourceType t = CAResource::Other); static std::shared_ptr<CAResource> createEmptyResource(QString name, CADocument* parent = nullptr, CAResource::CAResourceType t = CAResource::Other); static void deleteResource(std::shared_ptr<CAResource>); }; #endif /* RESOURCECTL_H_ */
871
C++
.h
20
41
189
0.773428
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,577
previewctl.h
canorusmusic_canorus/src/control/previewctl.h
/*! Copyright (c) 2006-2019, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #ifndef PREVIEW_CTL_H #define PREVIEW_CTL_H // Includes #include <QFile> #include <QObject> #include <QStringList> #include <QVariant> #include <QVector> #include <memory> // Forward declarations class CAMainWin; class CAPDFExport; class CAPreviewCtl : public QObject { Q_OBJECT public: CAPreviewCtl(CAMainWin* poMainWin); ~CAPreviewCtl(); public slots: void on_uiPrintPreview_triggered(); protected slots: void showPDF(int iExitCode); protected: CAMainWin* _poMainWin; std::unique_ptr<CAPDFExport> _poPDFExport; QString _oOutputPDFName; }; #endif // PREVIEW_CTL_H
870
C++
.h
32
23.84375
93
0.753358
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,578
lilypondexport.h
canorusmusic_canorus/src/export/lilypondexport.h
/*! Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef LILYPONDEXPORT_H_ #define LILYPONDEXPORT_H_ #include <QString> #include <QTextStream> #include "score/barline.h" #include "score/clef.h" #include "score/document.h" #include "score/keysignature.h" #include "score/lyricscontext.h" #include "score/note.h" #include "score/playable.h" #include "score/rest.h" #include "score/syllable.h" #include "score/timesignature.h" #include "export/export.h" class CAChordNameContext; class CALilyPondExport : public CAExport { #ifndef SWIG Q_OBJECT #endif public: CALilyPondExport(QTextStream* out = 0); /////////////////////////// // Polling export status // /////////////////////////// // Setter methods are private! inline CAVoice* curVoice() { return _curVoice; } inline CASheet* curSheet() { return _curSheet; } inline CADocument* curDocument() { return _curDocument; } inline CAContext* curContext() { return _curContext; } inline int curContextIndex() { return _curContextIndex; } inline int curIndentLevel() { return _curIndentLevel; } private: void exportSheetImpl(CASheet* sheet); void exportScoreBlock(CASheet* sheet); void exportStaffVoices(CAStaff* staff); void exportVoiceImpl(CAVoice* voice); void exportLyricsContextBlock(CALyricsContext* lc); void exportLyricsContextImpl(CALyricsContext* lc); void exportChordNameContextBlock(CAChordNameContext*); void exportChordNameContextImpl(CAChordNameContext*); void exportMarksBeforeElement(CAMusElement*); void exportNoteMarks(CANote*); void exportMarksAfterElement(CAMusElement*); void exportPlayable(CAPlayable* elt); void writeDocumentHeader(); void scanForRepeats(CAStaff* staff); CADiatonicPitch writeRelativeIntro(); void doAnacrusisCheck(CATimeSignature* time); //////////////////// // Helper methods // //////////////////// const QString clefTypeToLilyPond(CAClef::CAClefType type, int c1, int offset); const QString diatonicKeyGenderToLilyPond(CADiatonicKey::CAGender gender); const QString playableLengthToLilyPond(CAPlayableLength length); const QString diatonicPitchToLilyPond(CADiatonicPitch p); const QString restTypeToLilyPond(CARest::CARestType type); const QString barlineTypeToLilyPond(CABarline::CABarlineType type); const QString syllableToLilyPond(CASyllable* s); inline const QString relativePitchToString(CANote* note, CADiatonicPitch prevPitch) { return relativePitchToString(note->diatonicPitch(), prevPitch); } const QString relativePitchToString(CADiatonicPitch p, CADiatonicPitch prevPitch); void voiceVariableName(QString& name, int staffNum, int voiceNum); void spellNumbers(QString& s); QString markupString(QString); QString escapeWeirdChars(QString); void indent(); inline void indentMore() { ++_curIndentLevel; } inline void indentLess() { --_curIndentLevel; } /////////////////////////// // Getter/Setter methods // /////////////////////////// inline void setCurVoice(CAVoice* voice) { _curVoice = voice; } inline void setCurSheet(CASheet* sheet) { _curSheet = sheet; } inline void setCurContext(CAContext* context) { _curContext = context; } inline void setCurContextIndex(int c) { _curContextIndex = c; } inline void setCurDocument(CADocument* document) { _curDocument = document; } inline void setIndentLevel(int level) { _curIndentLevel = level; } ///////////// // Members // ///////////// CAVoice* _curVoice; CASheet* _curSheet; CAContext* _curContext; CADocument* _curDocument; int _curContextIndex; int _curIndentLevel; // Voice exporting current status CADiatonicPitch _lastNotePitch; CAPlayableLength _lastPlayableLength; int _curStreamTime; bool _voltaBracketIsOpen; bool _voltaBracketOccured; void voltaFunction(void); bool _voltaFunctionWritten; bool _voltaBracketFinishAtRepeat; bool _voltaBracketFinishAtBar; static const QString _regExpVoltaRepeat; static const QString _regExpVoltaBar; bool _timeSignatureFound; }; #endif /* LILYPONDEXPORT_H_*/
4,366
C++
.h
109
35.834862
87
0.723861
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,579
canexport.h
canorusmusic_canorus/src/export/canexport.h
/*! Copyright (c) 2007-2019, Matevž Jekovec, Itay Perl, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef CANEXPORT_H_ #define CANEXPORT_H_ #include "export/export.h" class CAArchive; class CACanExport : public CAExport { public: CACanExport(QTextStream* stream = nullptr); ~CACanExport(); inline CAArchive* archive() { return _archive; } inline void setArchive(CAArchive* a) { _archive = a; } protected: void exportDocumentImpl(CADocument* doc); private: CAArchive* _archive; }; #endif /* CANEXPORT_H_ */
671
C++
.h
21
29.190476
78
0.746875
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,580
svgexport.h
canorusmusic_canorus/src/export/svgexport.h
/*! Copyright (c) 2008-2019, Reinahrd Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef SVGEXPORT_H_ #define SVGEXPORT_H_ // Includes #include "export/export.h" // Forward declarations class CATypesetCtl; // SVG Export class doing lilypond export internally // !! exportDocument does not support threading !! class CASVGExport : public CAExport { #ifndef SWIG Q_OBJECT #endif public: CASVGExport(QTextStream* stream = nullptr); ~CASVGExport(); QString getTempFilePath(); #ifndef SWIG signals: void svgIsFinished(int iExitCode); protected slots: void outputTypsetterOutput(const QByteArray& roOutput); void svgFinished(int iExitCode); private: void startExport(); void finishExport(); void exportDocumentImpl(CADocument* doc); void exportSheetImpl(CASheet* poSheet); void runTypesetter(); protected: CATypesetCtl* _poTypesetCtl; #endif }; #endif // SVGEXPORT_H_
1,082
C++
.h
38
25.710526
86
0.771318
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,581
musicxmlexport.h
canorusmusic_canorus/src/export/musicxmlexport.h
/*! Copyright (c) 2008-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef MUSICXMLEXPORT_H_ #define MUSICXMLEXPORT_H_ #include "export/export.h" #include <QDomElement> class CAContext; class CADocument; class CAVoice; class CASheet; class CAClef; class CAKeySignature; class CATimeSignature; class CANote; class CARest; class CAMusicXmlExport : public CAExport { public: CAMusicXmlExport(QTextStream* stream = nullptr); virtual ~CAMusicXmlExport(); inline CAVoice* curVoice() { return _curVoice; } inline CASheet* curSheet() { return _curSheet; } inline CADocument* curDocument() { return _curDocument; } inline CAContext* curContext() { return _curContext; } inline int curContextIndex() { return _curContextIndex; } private: void exportSheetImpl(CASheet* s); using CAExport::exportStaffImpl; void exportStaffImpl(CAStaff*, QDomElement&); void exportMeasure(QList<CAVoice*>&, int*, QDomElement&); void exportClef(CAClef*, QDomElement&); void exportTimeSig(CATimeSignature*, QDomElement&); void exportKeySig(CAKeySignature*, QDomElement&); void exportNote(CANote*, QDomElement&); void exportRest(CARest*, QDomElement&); inline void setCurVoice(CAVoice* voice) { _curVoice = voice; } inline void setCurSheet(CASheet* sheet) { _curSheet = sheet; } inline void setCurContext(CAContext* context) { _curContext = context; } inline void setCurContextIndex(int c) { _curContextIndex = c; } inline void setCurDocument(CADocument* document) { _curDocument = document; } CAVoice* _curVoice; CASheet* _curSheet; CAContext* _curContext; CADocument* _curDocument; int _curContextIndex; QDomDocument* _xmlDoc; }; #endif /* MUSICXMLEXPORT_H_ */
1,903
C++
.h
50
34.58
81
0.748913
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,582
export.h
canorusmusic_canorus/src/export/export.h
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef EXPORT_H_ #define EXPORT_H_ #include "core/file.h" #include <QString> class QTextStream; class CADocument; class CASheet; class CAStaff; class CAVoice; class CALyricsContext; class CAFunctionMarkContext; class CAExport : public CAFile { #ifndef SWIG Q_OBJECT #endif public: CAExport(QTextStream* stream = 0); virtual ~CAExport(); virtual const QString readableStatus(); void exportDocument(CADocument*, bool bStartThread = true); void exportSheet(CASheet*); void exportStaff(CAStaff*); void exportVoice(CAVoice*); void exportLyricsContext(CALyricsContext*); void exportFunctionMarkContext(CAFunctionMarkContext*); inline CADocument* exportedDocument() { return _exportedDocument; } inline CASheet* exportedSheet() { return _exportedSheet; } inline CAStaff* exportedStaff() { return _exportedStaff; } inline CAVoice* exportedVoice() { return _exportedVoice; } inline CALyricsContext* exportedLyricsContext() { return _exportedLyricsContext; } inline CAFunctionMarkContext* exportedFunctionMarkContext() { return _exportedFunctionMarkContext; } // Methods from CAFile to be called via abstract class CAAbsExport virtual void setStreamToFile(const QString filename) { CAFile::setStreamToFile(filename); } bool wait(unsigned long time = ULONG_MAX) { return CAFile::wait(time); } #ifndef SWIG signals: void documentExported(CADocument*); void sheetExported(CASheet*); void staffExported(CAStaff*); void voiceExported(CAVoice*); void lyricsContextExported(CALyricsContext*); void functionMarkContextExported(CAFunctionMarkContext*); void exportDone(int status); #endif protected: virtual void exportDocumentImpl(CADocument*) { setStatus(0); return; } virtual void exportSheetImpl(CASheet*) { setStatus(0); return; } virtual void exportStaffImpl(CAStaff*) { setStatus(0); return; } virtual void exportVoiceImpl(CAVoice*) { setStatus(0); return; } virtual void exportLyricsContextImpl(CALyricsContext*) { setStatus(0); return; } virtual void exportFunctionMarkContextImpl(CAFunctionMarkContext*) { setStatus(0); return; } inline QTextStream& out() { return *stream(); } void run(); private: inline void setExportedDocument(CADocument* doc) { _exportedDocument = doc; } inline void setExportedSheet(CASheet* sheet) { _exportedSheet = sheet; } inline void setExportedStaff(CAStaff* staff) { _exportedStaff = staff; } inline void setExportedVoice(CAVoice* voice) { _exportedVoice = voice; } inline void setExportedLyricsContext(CALyricsContext* lc) { _exportedLyricsContext = lc; } inline void setExportedFunctionMarkContext(CAFunctionMarkContext* fmc) { _exportedFunctionMarkContext = fmc; } CADocument* _exportedDocument; CASheet* _exportedSheet; CAStaff* _exportedStaff; CAVoice* _exportedVoice; CALyricsContext* _exportedLyricsContext; CAFunctionMarkContext* _exportedFunctionMarkContext; }; #endif /* EXPORT_H_ */
3,405
C++
.h
103
28.378641
114
0.731589
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,583
canorusmlexport.h
canorusmusic_canorus/src/export/canorusmlexport.h
/*! Copyright (c) 2006-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef CANORUSMLEXPORT_H_ #define CANORUSMLEXPORT_H_ #include <QColor> #include <QDomElement> #include "export/export.h" #include "score/diatonickey.h" #include "score/diatonicpitch.h" #include "score/playablelength.h" class CAMusElement; class CAFiguredBassContext; class CACanorusMLExport : public CAExport { public: CACanorusMLExport(QTextStream* stream = nullptr); virtual ~CACanorusMLExport(); void exportDocumentImpl(CADocument* doc); private: using CAExport::exportVoiceImpl; void exportVoiceImpl(CAVoice* voice, QDomElement& dVoice); void exportFiguredBass(CAFiguredBassContext* c, QDomElement& domParent); void exportMarks(CAMusElement* associatedElt, QDomElement& domParent); void exportPlayableLength(CAPlayableLength l, QDomElement& domParent); void exportDiatonicPitch(CADiatonicPitch p, QDomElement& domParent); void exportDiatonicKey(CADiatonicKey k, QDomElement& domParent); void exportColor(CAMusElement* elt, QDomElement& domParent); void exportTime(CAMusElement* elt, QDomElement& domParent); void exportResources(CADocument*, QDomElement&); QDomElement _dTuplet; QColor _color; // foreground color of elements }; #endif /* CANORUSMLEXPORT_H_ */
1,454
C++
.h
35
38.457143
76
0.792761
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,584
pdfexport.h
canorusmusic_canorus/src/export/pdfexport.h
/*! Copyright (c) 2008, Reinahrd Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef PDFEXPORT_H_ #define PDFEXPORT_H_ // Includes #include "export/export.h" // Forward declarations class CATypesetCtl; // PDF Export class doing lilypond export internally // !! exportDocument does not support threading !! class CAPDFExport : public CAExport { #ifndef SWIG Q_OBJECT #endif public: CAPDFExport(QTextStream* stream = 0); ~CAPDFExport(); QString getTempFilePath(); #ifndef SWIG signals: void pdfIsFinished(int iExitCode); protected slots: void outputTypsetterOutput(const QByteArray& roOutput); void pdfFinished(int iExitCode); private: void startExport(); void finishExport(); void exportDocumentImpl(CADocument* doc); void exportSheetImpl(CASheet* poSheet); void runTypesetter(); protected: CATypesetCtl* _poTypesetCtl; #endif }; #endif // PDFEXPORT_H_
1,070
C++
.h
38
25.421053
81
0.769833
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,585
midiexport.h
canorusmusic_canorus/src/export/midiexport.h
/*! Copyright (c) 2007-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #ifndef MIDIEXPORT_H_ #define MIDIEXPORT_H_ #include <QByteArray> #include <QList> #include <QString> #include <QTextStream> #include <QVector> #include "score/barline.h" #include "score/clef.h" #include "score/document.h" #include "score/keysignature.h" #include "score/lyricscontext.h" #include "score/note.h" #include "score/rest.h" #include "score/syllable.h" #include "score/timesignature.h" #include "export/export.h" #include "interface/mididevice.h" #include "interface/playback.h" class CAMidiExport : public CAExport, public CAMidiDevice { public: CAMidiExport(QTextStream* out = 0); /* ////////////////////////////// // Interface to file export // ////////////////////////////// */ QMap<int, QString> getOutputPorts() { return m_InputPorts; } QMap<int, QString> getInputPorts() { return m_OutputPorts; } bool openOutputPort(int) { return true; } // return true on success, false otherwise bool openInputPort(int) { return true; } // return true on success, false otherwise void closeOutputPort() {} void closeInputPort() {} void send(QVector<unsigned char> message, int time); void sendMetaEvent(int timeLength, char event, char a, char b, int c); void writeFile(); // direct access to the writing /* /////////////////////////// // Polling export status // /////////////////////////// // Setter methods are private! */ private: QByteArray writeTime(int time); void exportDocumentImpl(CADocument* doc); void exportSheetImpl(CASheet* sheet); int midiTrackCount; QByteArray trackChunk; // for the time beeing we build one big track int timeIncrement(int time); int _trackTime; // which this is the time line for QVector<QByteArray> trackChunks; // for the future QVector<int> trackTimes; void streamQByteArray(QByteArray x); // streaming binary data to midi file, possibly with print for debugging QByteArray variableLengthValue(int value); QByteArray word16(short x); QByteArray textEvent(int time, QString s); QByteArray trackEnd(void); QByteArray timeSignature(void); QByteArray keySignature(void); void setChunkLength(QByteArray* x); /* //////////////////// // Helper methods // //////////////////// /////////////////////////// // Getter/Setter methods // /////////////////////////// */ inline void setCurVoice(CAVoice* voice) { _curVoice = voice; } inline void setCurSheet(CASheet* sheet) { _curSheet = sheet; } /* ///////////// // Members // ///////////// QTextStream *_out; */ CAVoice* _curVoice; CASheet* _curSheet; // Dummy members for getOutputPorts/getInputPorts QMap<int, QString> m_InputPorts; QMap<int, QString> m_OutputPorts; /* CAContext *_curContext; int _curContextIndex; int _curIndentLevel; */ }; #endif /* MIDIEXPORT_H_*/
3,070
C++
.h
93
29.817204
113
0.669368
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,586
ymbprot.cpp
lyqdy_ymodbus/ymodbus/ymod/ymbprot.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/ymbprot.h" #include "ymod/ymbdefs.h" #include "ymblog.h" #include <memory> #include <cstring> namespace YModbus { uint8_t GetMasterMsgMinLen(uint8_t *msg) { switch (msg[1]) { case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: return 6; case kFunWriteAndReadRegisters: return 10 + 1; case kFunWriteMultiCoils: case kFunWriteMultiRegisters: return 6 + 1; case kFunWriteSingleCoil: case kFunWriteSingleRegister: return 6; case kFunMaskWriteRegister: return 8; default: return 2; } } uint8_t GetSlaveMsgMinLen(uint8_t *msg) { switch (msg[1]) { case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: return 3; case kFunWriteAndReadRegisters: return 3; case kFunWriteMultiCoils: case kFunWriteMultiRegisters: return 6; case kFunWriteSingleCoil: case kFunWriteSingleRegister: return 6; case kFunMaskWriteRegister: return 8; default: return 2; } } uint8_t GetMasterMsgMaxLen(uint8_t *msg) { switch (msg[1]) { case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: return 6; case kFunWriteAndReadRegisters: return 10 + 1 + msg[10];//id-fun-rn-ru-wa-wn-wb case kFunWriteMultiCoils: case kFunWriteMultiRegisters: return 6 + 1 + msg[6];//id-fun-wa-wn-wb case kFunWriteSingleCoil: case kFunWriteSingleRegister: return 6; case kFunMaskWriteRegister: return 8; default: return 255; } } uint8_t GetSlaveMsgMaxLen(uint8_t *msg) { switch (msg[1]) { case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: return 3 + msg[2]; case kFunWriteAndReadRegisters: return 3 + msg[2]; case kFunWriteMultiCoils: case kFunWriteMultiRegisters: return 6; case kFunWriteSingleCoil: case kFunWriteSingleRegister: return 6; case kFunMaskWriteRegister: return 8; default: return 255; } } //direct: 1: in, /master/request, 0: out, slave/response //return: offset from first byte of local format msg based 0 int Protocol::GetMasterDataOffset(uint8_t fun) { switch (fun) { case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: return 6;//id-fun-rreg-rnum case kFunWriteMultiCoils: case kFunWriteMultiRegisters: return 6 + 1;//id-fun-rreg-rnum-bytes case kFunWriteAndReadRegisters: return 10 + 1;//id-fun-rreg-rnum-wreg-wnum-bytes case kFunWriteSingleCoil: case kFunWriteSingleRegister: case kFunMaskWriteRegister: return 4;//id-fun-reg default: return 2; } } //direct: 1: in, /master/request, 0: out, slave/response //return: offset from first byte of local format msg based 0 int Protocol::GetSlaveDataOffset(uint8_t fun) { switch (fun) { case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: case kFunWriteAndReadRegisters: return 3;//id-fun-bytes case kFunWriteMultiCoils: case kFunWriteMultiRegisters: return 6;//id-fun-reg-num case kFunWriteSingleCoil: case kFunWriteSingleRegister: case kFunMaskWriteRegister: return 4; //id-fun-reg default: return 2; } } size_t Protocol::MakeMasterMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { uint8_t *pbuf = buf; *pbuf++ = inf.id; *pbuf++ = inf.fun; switch (inf.fun) { case kFunWriteSingleCoil: case kFunWriteSingleRegister: case kFunMaskWriteRegister: *pbuf++ = static_cast<uint8_t>(inf.wreg >> 8); *pbuf++ = static_cast<uint8_t>(inf.wreg & 0xff); break; case kFunWriteMultiCoils: case kFunWriteMultiRegisters: *pbuf++ = static_cast<uint8_t>(inf.wreg >> 8); *pbuf++ = static_cast<uint8_t>(inf.wreg & 0xff); *pbuf++ = static_cast<uint8_t>(inf.wnum >> 8); *pbuf++ = static_cast<uint8_t>(inf.wnum & 0xff); *pbuf++ = static_cast<uint8_t>(inf.datalen); break; case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: *pbuf++ = static_cast<uint8_t>(inf.rreg >> 8); *pbuf++ = static_cast<uint8_t>(inf.rreg & 0xff); *pbuf++ = static_cast<uint8_t>(inf.rnum >> 8); *pbuf++ = static_cast<uint8_t>(inf.rnum & 0xff); break; case kFunWriteAndReadRegisters: *pbuf++ = static_cast<uint8_t>(inf.rreg >> 8); *pbuf++ = static_cast<uint8_t>(inf.rreg & 0xff); *pbuf++ = static_cast<uint8_t>(inf.rnum >> 8); *pbuf++ = static_cast<uint8_t>(inf.rnum & 0xff); *pbuf++ = static_cast<uint8_t>(inf.wreg >> 8); *pbuf++ = static_cast<uint8_t>(inf.wreg & 0xff); *pbuf++ = static_cast<uint8_t>(inf.wnum >> 8); *pbuf++ = static_cast<uint8_t>(inf.wnum & 0xff); *pbuf++ = static_cast<uint8_t>(inf.datalen); break; default: YMB_ASSERT(false && "Function is not surpported"); break; } //data maybe has been copied, in this case, databuf is null. if (inf.databuf != nullptr) { //write or read data memmove(pbuf, inf.databuf, inf.datalen); } pbuf += inf.datalen; //datalen must always is valid! size_t msglen = static_cast<size_t>(pbuf - buf); YMB_ASSERT(bufsiz >= msglen); return msglen; } size_t Protocol::MakeSlaveMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { uint8_t *pbuf = buf; *pbuf++ = inf.id; if (inf.err == 0) { *pbuf++ = inf.fun; switch (inf.fun) { case kFunWriteSingleCoil: case kFunWriteSingleRegister: case kFunMaskWriteRegister: *pbuf++ = static_cast<uint8_t>(inf.wreg >> 8); *pbuf++ = static_cast<uint8_t>(inf.wreg & 0xff); break; case kFunWriteMultiCoils: case kFunWriteMultiRegisters: *pbuf++ = static_cast<uint8_t>(inf.wreg >> 8); *pbuf++ = static_cast<uint8_t>(inf.wreg & 0xff); *pbuf++ = static_cast<uint8_t>(inf.wnum >> 8); *pbuf++ = static_cast<uint8_t>(inf.wnum & 0xff); break; case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: case kFunWriteAndReadRegisters: *pbuf++ = static_cast<uint8_t>(inf.datalen); break; default: YMB_ASSERT(false); break; } } else { *pbuf++ = inf.fun | 0x80; *pbuf++ = inf.err; } //data maybe has been copied, in this case, databuf is null. if (inf.databuf != nullptr) { //write or read data memmove(pbuf, inf.databuf, inf.datalen); } pbuf += inf.datalen; //datalen must always is valid! size_t msglen = static_cast<size_t>(pbuf - buf); YMB_ASSERT(bufsiz >= msglen); return msglen; } //Exact message int Protocol::VerifyMasterMsg(uint8_t *msg, size_t msglen) { size_t len = 3; //id-fun-err if (msglen < len) return static_cast<int>(len - msglen); if (msg[1] & 0x80) return EOK; //exception msg len = GetMasterMsgMinLen(msg); if (msglen < len) return static_cast<int>(len - msglen); len = GetMasterMsgMaxLen(msg); if (msglen < len) return static_cast<int>(len - msglen); return EOK; } int Protocol::VerifySlaveMsg(uint8_t *msg, size_t msglen) { size_t len = 3; //id-fun-err if (msglen < len) return static_cast<int>(len - msglen); if (msg[1] & 0x80) return EOK; //exception msg len = GetSlaveMsgMinLen(msg); if (msglen < len) return static_cast<int>(len - msglen); len = GetSlaveMsgMaxLen(msg); if (msglen < len) return static_cast<int>(len - msglen); return EOK; } //Used by slave int Protocol::ParseMasterMsg(uint8_t *msg, size_t msglen, MsgInf &inf) { uint8_t *pbuf = msg; inf.id = *pbuf++; inf.fun = *pbuf++; switch (inf.fun) { case kFunWriteSingleCoil: case kFunWriteSingleRegister: case kFunMaskWriteRegister: inf.rreg = INVALID_REG; inf.rnum = INVALID_NUM; inf.wreg = *pbuf++ << 8; inf.wreg |= *pbuf++; inf.wnum = 1; inf.datalen = 2; inf.databuf = pbuf; break; case kFunWriteMultiCoils: case kFunWriteMultiRegisters: inf.rreg = INVALID_REG; inf.rnum = INVALID_NUM; inf.wreg = *pbuf++ << 8; inf.wreg |= *pbuf++; inf.wnum = *pbuf++ << 8; inf.wnum |= *pbuf++; inf.datalen = *pbuf++; inf.databuf = pbuf; break; case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: inf.wreg = INVALID_REG; inf.wnum = INVALID_NUM; inf.rreg = *pbuf++ << 8; inf.rreg |= *pbuf++; inf.rnum = *pbuf++ << 8; inf.rnum |= *pbuf++; inf.datalen = 0; inf.databuf = nullptr; break; case kFunWriteAndReadRegisters: inf.rreg = *pbuf++ << 8; inf.rreg |= *pbuf++; inf.rnum = *pbuf++ << 8; inf.rnum |= *pbuf++; inf.wreg = *pbuf++ << 8; inf.wreg |= *pbuf++; inf.wnum = *pbuf++ << 8; inf.wnum |= *pbuf++; inf.datalen = *pbuf++; inf.databuf = pbuf; break; default: YMB_ERROR("Modbus function not surpport. fun = %u\n", inf.fun); return -EBADMSG; } YMB_HEXDUMP(msg, msglen, "Master message: id = 0x%02x, fun = 0x%02x: ", inf.id, inf.fun); return EOK; } //Used by master int Protocol::ParseSlaveMsg(uint8_t *msg, size_t /*msglen*/, MsgInf &inf) { uint8_t *pbuf = msg; inf.id = *pbuf++; inf.fun = *pbuf++; if ((inf.fun & 0x80) == 0) { switch (inf.fun) { case kFunWriteSingleCoil: case kFunWriteSingleRegister: case kFunMaskWriteRegister: inf.rreg = INVALID_REG; inf.rnum = 0; inf.wreg = *pbuf++ << 8; inf.wreg |= *pbuf++; inf.wnum = 1; inf.datalen = 0; inf.databuf = nullptr; break; case kFunWriteMultiCoils: case kFunWriteMultiRegisters: inf.rreg = INVALID_REG; inf.rnum = 0; inf.wreg = *pbuf++ << 8; inf.wreg |= *pbuf++; inf.wnum = *pbuf++ << 8; inf.wnum |= *pbuf++; inf.datalen = 0; inf.databuf = nullptr; break; case kFunReadCoils: case kFunReadDiscreteInputs: case kFunReadHoldingRegisters: case kFunReadInputRegisters: inf.datalen = *pbuf++; inf.databuf = pbuf; break; case kFunWriteAndReadRegisters: inf.datalen = *pbuf++; inf.databuf = pbuf; break; default: return -EBADMSG; } } else { //exception inf.err = *pbuf++; } YMB_HEXDUMP0(msg, msglen, "Slave message: id = 0x%02x, fun = 0x%02x: ", inf.id, inf.fun); return EOK; } } //namespace YModbus
10,457
C++
.cpp
388
23.314433
74
0.684532
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,587
ymbtask.cpp
lyqdy_ymodbus/ymodbus/ymod/ymbtask.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/ymbtask.h" #include "ymblog.h" namespace YModbus { Task::Task() : init_(false) , stop_(false) { } Task::~Task() { } void Task::Start() { YMB_DEBUG("Start Task . %s\n", this->Name().c_str()); init_ = Init(); if (init_) { task_ = std::thread(&Task::task, this); } else { YMB_ERROR("Task Init failed!!! %s", this->Name().c_str()); #ifndef WIN32 abort(); #endif } } void Task::Wait() { if (task_.joinable()) task_.join(); if (init_) { Fini(); init_ = false; } } void Task::task() { ShallWeGo(); //wait for go signal YMB_DEBUG("Task start run. %s\n", this->Name().c_str()); Run(); YMB_DEBUG("Task exit run. %s\n", this->Name().c_str()); } void Task::LetUsGo(void) { go_ = true; goCond_.notify_all(); } void Task::LetUsDone(void) { running_ = false; } bool Task::ShallWeGo(void) { std::unique_lock<std::mutex> lock(goMutex_); goCond_.wait(lock, []() { return Task::go_; }); return go_; } volatile bool Task::running_ = true; volatile bool Task::go_ = false; std::mutex Task::goMutex_; std::condition_variable Task::goCond_; } //namespace YModbus
1,287
C++
.cpp
66
16.333333
61
0.610875
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,589
ymbmaster.cpp
lyqdy_ymodbus/ymodbus/ymod/master/ymbmaster.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/master/ymbmaster.h" #include "ymod/ymbtask.h" #include "ymod/ymbnet.h" #include "ymod/ymbrtu.h" #include "ymod/ymbascii.h" #include "ymod/master/ytcpconnect.h" #include "ymod/master/yserconnect.h" #include "ymod/master/yudpconnect.h" #include "ymbopts.h" #include <queue> #include <mutex> #include <condition_variable> #include <cstring> namespace YModbus { namespace { struct Request { Request(MsgInf &i) : err(0), inf(i) {} int err; //error, api or logical error MsgInf &inf; //modbus exception code is in inf.err std::mutex mutex; std::condition_variable cond; }; typedef std::shared_ptr<Request> RequestPtr; const uint32_t kDefRetries = 3; const long kDefRdTimeout = 500; //ms const long kPerReadTimeout = 10; //ms } //namespace { struct Master::Impl : public Task { public: typedef Net<IProtocol> INet; typedef Rtu<IProtocol> IRtu; typedef Ascii<IProtocol> IAscii; Impl(eThreadMode thrm) : retries_(kDefRetries) , rdto_(kDefRdTimeout) , thrm_(thrm) { if (thrm_ == TASK) this->Start(); } ~Impl() { if (thrm_ == TASK) { this->Stop(); this->Wait(); } } int Read(MsgInf &inf, uint8_t *buf, size_t bufsiz) { if (buf == nullptr) { //We don't need any response datas here. //But store will be updated after here. return this->SendRequest(inf); } //Because inf.databuf is a valid pointer of inf.pbuf //So we must guareentee inf.pbuf is valid after SendReuqest uint8_t msgbuf[kMaxMsgLen]; inf.pbuf = msgbuf; inf.bufsiz = sizeof(msgbuf); int ret = this->SendRequest(inf); if (ret == 0 && inf.datalen != 0) { //received data if (bufsiz >= inf.datalen) { YMB_ASSERT(inf.databuf != nullptr); memcpy(buf, inf.databuf, inf.datalen); ret = inf.datalen; } else { //buffer size is too small to fit data YMB_DEBUG("buffer size is too small!\n"); ret = -ENOMEM; } } return ret; } int Write(MsgInf &inf) { uint8_t sid = inf.id; uint8_t fun = inf.fun; uint16_t reg = inf.wreg; if (int ret = this->SendRequest(inf)) { YMB_DEBUG("eXecute Write failed!\n"); return ret; } if (inf.err != 0) { YMB_DEBUG("eXecute Write exception! code = %u\n", inf.err); return -EFAULT; } if (inf.id != sid || inf.fun != fun || inf.wreg != reg) { YMB_DEBUG("eXecute Write response error id/fun/reg" "send: id = %02x, fun = %02x, reg = %02x \n" "recv: id = %02x, fun = %02x, reg = %02x \n", sid, fun, reg, inf.id, inf.fun, inf.wreg); return -EBADF; } return EOK; } int SendRequest(MsgInf &inf) { uint32_t retry = 0; error = -EFAULT; do { if (retry != 0) { YMB_DEBUG0("SendRequest retry %u\n", retry); } if (thrm_ == TASK) { if (auto req = std::make_shared<Request>(inf)) { //发送请求 std::unique_lock<std::mutex> lockq(mutex_); requests_.push(req); cond_.notify_all(); lockq.unlock(); //等待执行 std::unique_lock<std::mutex> lockr(req->mutex); req->cond.wait(lockr); //错误信息存放在线程局部变量 error = req->err; } } else { //POLL, execute poll diretctly error = ExecPoll(inf); } } while (error != 0 && ++retry < retries_); return error; } void PostQuery(const MsgInf &inf) { if (thrm_ == TASK) { //提交查询,不需等待返回 std::unique_lock<std::mutex> lock(mutex_); querys_.push(inf); cond_.notify_all(); } else { //POLL mode, also need waiting for result, but only execute once error = ExecPoll(const_cast<MsgInf&>(inf)); } } const long perto_ = kPerReadTimeout; //ms 每次接收超时 uint32_t retries_; long rdto_; //read timeout eThreadMode thrm_; uint8_t msgbuf_[kMaxMsgLen]; std::weak_ptr<IMonitor> monitor_; std::weak_ptr<IStore> store_; std::unique_ptr<IProtocol> prot_; std::unique_ptr<IConnect> conn_; std::string desc_; static thread_local int error; //TMaster api operate error protected: void Run(void) override; //thread func std::string Name(void) override { return "Master Task"; } private: int ExecPoll(MsgInf &inf); int SendRecv(MsgInf &inf); std::queue<RequestPtr> requests_; std::queue<MsgInf> querys_; std::mutex mutex_; std::condition_variable cond_; }; thread_local int Master::Impl::error = 0; int Master::Impl::ExecPoll(MsgInf &inf) { bool bInnerBuf; if (inf.pbuf == nullptr) { inf.pbuf = msgbuf_; inf.bufsiz = sizeof(msgbuf_); bInnerBuf = true; } else { YMB_ASSERT(inf.bufsiz >= sizeof(msgbuf_)); bInnerBuf = false; } int ret = SendRecv(inf); auto store = store_.lock(); if (ret == EOK && inf.datalen != 0 && store) { YMB_ASSERT(inf.databuf != nullptr); if (inf.fun == kFunReadCoils || inf.fun == kFunReadDiscreteInputs) { //bit for (uint16_t i = 0; i < inf.rnum; i++) { //one bit to one register uint8_t val[] = { 0, static_cast<uint8_t>((inf.databuf[i/8] >> (i%8)) & 0x1) }; store->Set(inf.id, inf.rreg + i, val, 1); } } else { //register store->Set(inf.id, inf.rreg, inf.databuf, inf.rnum); } } if (bInnerBuf) { inf.pbuf = nullptr; inf.bufsiz = 0; } return ret; } int Master::Impl::SendRecv(MsgInf &inf) { if (!conn_->Validate()) return -ENOLINK; YMB_ASSERT(inf.pbuf != nullptr); size_t msglen = prot_->MakeMasterMsg(inf.pbuf, inf.bufsiz, inf); conn_->Purge(); //清空buffer YMB_HEXDUMP0(inf.pbuf, msglen, "send: "); if (!conn_->Send(inf.pbuf, msglen)) return -ENETRESET; if (auto monitor = monitor_.lock()) monitor->SendPacket(desc_, inf.pbuf, static_cast<int>(msglen)); msglen = 0; for (long to = 0; to < rdto_; to += perto_) { //timeout int ret = conn_->Recv(inf.pbuf + msglen, inf.bufsiz - msglen); if (ret > 0) { //received some data YMB_HEXDUMP0(inf.pbuf + msglen, ret, "recv: "); msglen += ret; ret = prot_->VerifySlaveMsg(inf.pbuf, msglen); if (ret == EOK) { //OK, msg arrived if (auto monitor = monitor_.lock()) monitor->RecvPacket(desc_, inf.pbuf, static_cast<int>(msglen)); return prot_->ParseSlaveMsg(inf.pbuf, msglen, inf); } if (ret < 0) //msg error return -EBADMSG; } if (ret < 0) //connect error return -ENETRESET; } return -EBUSY; } void Master::Impl::Run(void) { while (this->IsRunning()) { //等待操作通知 std::unique_lock<std::mutex> lock(mutex_); cond_.wait_for(lock, std::chrono::seconds(1)); while (!requests_.empty() || !querys_.empty()) { if (!requests_.empty()) { //始终优先执行请求命令 auto req = requests_.front(); lock.unlock(); req->err = ExecPoll(req->inf); req->cond.notify_all(); lock.lock(); requests_.pop(); } else if (!querys_.empty()) { auto &inf = querys_.front(); lock.unlock(); ExecPoll(inf); lock.lock(); querys_.pop(); } else { ; //assert(false); } } } //完成所有等待的请求 std::unique_lock<std::mutex> lock(mutex_); while (!requests_.empty()) { auto req = requests_.front(); lock.unlock(); req->err = ExecPoll(req->inf); req->cond.notify_all(); lock.lock(); requests_.pop(); } } //Master api implementation Master::Master(const std::string &ip, uint16_t port, eProtocol type, eThreadMode thrm) : impl_(std::make_shared<Impl>(thrm)) { switch (type) { case TCP: impl_->prot_ = std::make_unique<Impl::INet>(); impl_->conn_ = std::make_unique<TcpConnect>(ip, port); break; case TCPRTU: impl_->prot_ = std::make_unique<Impl::IRtu>(); impl_->conn_ = std::make_unique<TcpConnect>(ip, port); break; case TCPASCII: impl_->prot_ = std::make_unique<Impl::IAscii>(); impl_->conn_ = std::make_unique<TcpConnect>(ip, port); break; case UDP: impl_->prot_ = std::make_unique<Impl::INet>(); impl_->conn_ = std::make_unique<UdpConnect>(ip, port); break; case UDPRTU: impl_->prot_ = std::make_unique<Impl::IRtu>(); impl_->conn_ = std::make_unique<UdpConnect>(ip, port); break; case UDPASCII: impl_->prot_ = std::make_unique<Impl::IAscii>(); impl_->conn_ = std::make_unique<UdpConnect>(ip, port); break; default: YMB_ASSERT(false); break; } impl_->conn_->SetTimeout(impl_->perto_); impl_->conn_->Validate(); impl_->desc_ = ip + ":" + std::to_string(port); } Master::Master(const std::string &com, uint32_t baudrate, char parity, uint8_t stopbits, eProtocol type, eThreadMode thrm) : impl_(std::make_shared<Impl>(thrm)) { switch (type) { case RTU: impl_->prot_ = std::make_unique<Impl::IRtu>(); impl_->conn_ = std::make_unique<SerConnect>(com, baudrate, 8, parity, stopbits); break; case ASCII: impl_->prot_ = std::make_unique<Impl::IAscii>(); impl_->conn_ = std::make_unique<SerConnect>(com, baudrate, 7, parity, stopbits); break; default: YMB_ASSERT(false); break; } impl_->conn_->SetTimeout(impl_->perto_); impl_->conn_->Validate(); impl_->desc_ = com; } Master::~Master() { } void Master::SetMonitor(std::shared_ptr<IMonitor> monitor) { impl_->monitor_ = monitor; } std::shared_ptr<IMonitor> Master::GetMonitor(void) const { return impl_->monitor_.lock(); } void Master::SetStore(std::shared_ptr<IStore> store) { impl_->store_ = store; } std::shared_ptr<IStore> Master::GetStore(void) const { return impl_->store_.lock(); } //reties: retry count void Master::SetRetries(uint32_t retries) { impl_->retries_ = retries; } uint32_t Master::GetRetries(void) const { return impl_->retries_; } //rto: ms void Master::SetReadTimeout(long rdto) { impl_->rdto_ = rdto; } long Master::GetReadTimeout(void) const { return impl_->rdto_; } //错误信息 int Master::GetLastError(void) const { return impl_->error; } std::string Master::GetErrorString(int err) const { return std::to_string(err); } bool Master::CheckConnect(void) { YMB_ASSERT(impl_->conn_); return impl_->conn_->Validate(); } //异步抓取操作,不需返回读取的数据,也不需等待执行完成 //返回的数据通过过SetStore的对象处理 void Master::PullCoils(uint8_t sid, uint16_t reg, uint16_t num) { impl_->PostQuery({ sid, kFunReadCoils, reg, num }); } void Master::PullDiscreteInputs(uint8_t sid, uint16_t reg, uint16_t num) { impl_->PostQuery({ sid, kFunReadDiscreteInputs, reg, num }); } void Master::PullHoldingRegisters(uint8_t sid, uint16_t reg, uint16_t num) { impl_->PostQuery({ sid, kFunReadHoldingRegisters, reg, num }); } void Master::PullInputRegisters(uint8_t sid, uint16_t reg, uint16_t num) { impl_->PostQuery({ sid, kFunReadInputRegisters, reg, num }); } //IPlayer================================================================ //return: >= 0, bytes of data to return; //return: < 0, errorcode of exception //buf: data value, net order int Master::ReadCoils(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { MsgInf inf = { sid, kFunReadCoils, reg, num }; return impl_->Read(inf, buf, bufsiz); } int Master::ReadDiscreteInputs(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { MsgInf inf = { sid, kFunReadDiscreteInputs, reg, num }; return impl_->Read(inf, buf, bufsiz); } int Master::ReadInputRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { MsgInf inf = { sid, kFunReadInputRegisters, reg, num }; return impl_->Read(inf, buf, bufsiz); } int Master::ReadHoldingRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { MsgInf inf = { sid, kFunReadHoldingRegisters, reg, num }; return impl_->Read(inf, buf, bufsiz); } //return: = 0, OK; //return: < 0, errorcode of exception //values: data value, net order int Master::WriteSingleCoil(uint8_t sid, uint16_t reg, bool onoff) { uint8_t databuf[] = { static_cast<uint8_t>(onoff ? 0xff : 0x00), 0x00 }; MsgInf inf = { sid, kFunWriteSingleCoil, 0, 0, reg, 1, databuf, 2 }; return impl_->Write(inf); } int Master::WriteCoils(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *bits, uint8_t wbytes) { MsgInf inf = { sid, kFunWriteMultiCoils, 0, 0, reg, num }; inf.databuf = const_cast<uint8_t*>(bits); inf.datalen = wbytes; return impl_->Write(inf); } int Master::WriteSingleRegister(uint8_t sid, uint16_t reg, uint16_t value) { uint8_t databuf[] = { static_cast<uint8_t>(value >> 8), static_cast<uint8_t>(value & 0xff) }; MsgInf inf = { sid, kFunWriteSingleRegister, 0, 0, reg, 1, databuf, 2 }; return impl_->Write(inf); } int Master::WriteRegisters(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *values, uint8_t wbytes) { MsgInf inf = { sid, kFunWriteMultiRegisters, 0, 0, reg, num }; inf.databuf = const_cast<uint8_t*>(values); inf.datalen = wbytes; return impl_->Write(inf); } int Master::MaskWriteRegisters(uint8_t sid, uint16_t reg, uint16_t andmask, uint16_t ormask) { uint8_t databuf[] = { static_cast<uint8_t>(andmask >> 8), static_cast<uint8_t>(andmask & 0xff), static_cast<uint8_t>(ormask >> 8), static_cast<uint8_t>(ormask & 0xff) }; MsgInf inf = { sid, kFunMaskWriteRegister, 0, 0, reg, 1, databuf, 4 }; return impl_->Write(inf); } //return: >= 0, bytes of data to return //return: < 0, errorcode of exception //values/buf: data value, net order int Master::WriteReadRegisters(uint8_t sid, uint16_t wreg, uint16_t wnum, const uint8_t *values, uint8_t wbytes, uint16_t rreg, uint16_t rnum, uint8_t *buf, size_t bufsiz) { MsgInf inf = { sid, kFunWriteAndReadRegisters, rreg, rnum, wreg, wnum }; inf.databuf = const_cast<uint8_t*>(values); inf.datalen = wbytes; return impl_->Read(inf, buf, bufsiz); } //return: >= 0, OK //return: < 0, errorcode of exception int Master::ReportSlaveId(uint8_t /* maxsid */, uint8_t * /* buf */, size_t /* bufsiz*/) { YMB_DEBUG("%s%s not implementation.\n", __FILE__, __func__); return -1; } } //namespace ymodbus
14,429
C++
.cpp
497
24.696177
89
0.643048
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,590
ymbslave.cpp
lyqdy_ymodbus/ymodbus/ymod/slave/ymbslave.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/slave/ymbslave.h" #include "ymod/slave/yserlistener.h" #include "ymod/slave/ytcplistener.h" #include "ymod/slave/yudplistener.h" #include "ymod/ymbnet.h" #include "ymod/ymbrtu.h" #include "ymod/ymbascii.h" #include "ymod/ymbtask.h" #include "ymblog.h" #include "ymbopts.h" #include <vector> namespace YModbus { namespace { const long kDefListenTimeout = 1000; //ms } //namespace { struct Slave::Impl : public Task { typedef Net<IProtocol> Net; typedef Rtu<IProtocol> Rtu; typedef Ascii<IProtocol> Ascii; Impl(eThreadMode thrm) : thrm_(thrm) {} ~Impl() {} int Run(long to) { listener_->SetTimeout(to); Accept(); return err_; } int Request(MsgInf &inf, uint8_t *rspbuf, size_t bufsiz); eThreadMode thrm_; int err_ = 0; uint8_t id_ = kAnySlaveId; //slave id std::weak_ptr<IMonitor> monitor_; std::unique_ptr<IProtocol> prot_; std::shared_ptr<IPlayer> player_; std::unique_ptr<IListerner> listener_; std::vector<SessionPtr> ses_; std::string desc_; uint8_t rspbuf_[kMaxMsgLen]; size_t bufsiz_ = kMaxMsgLen; protected: virtual void Run(void) override; virtual std::string Name(void) override { return "Slave Task"; } private: void Accept(void); }; void Slave::Impl::Run(void) { while (IsRunning()) { Accept(); } } void Slave::Impl::Accept(void) { MsgInf inf; uint8_t *recvmsg; err_ = listener_->Accept(ses_); for (auto &session : ses_) { size_t msglen = session->Peek(&recvmsg); int need = prot_->VerifyMasterMsg(recvmsg, msglen); if (need < 0) { //bad msg YMB_HEXDUMP(recvmsg, msglen, "Bad master message! len = %u:\n", msglen); session->Purge(); //error, clear port data continue; } //msg has arrived if (need == 0 && prot_->ParseMasterMsg(recvmsg, msglen, inf) == EOK) { session->Purge(); if (auto monitor = monitor_.lock()) monitor->RecvPacket(desc_, recvmsg, msglen); if (inf.id == id_ || id_ == kAnySlaveId) { //token or careless id size_t roff = prot_->GetSlaveDataOffset(inf.fun); int rsp = Request(inf, rspbuf_ + roff, bufsiz_ - roff); if (rsp >= 0 && inf.id != kBroadcastId) { inf.databuf = nullptr; //The Datas have filled into rspbuf. msglen = prot_->MakeSlaveMsg(rspbuf_, bufsiz_, inf); session->Write(rspbuf_, msglen); if (auto monitor = monitor_.lock()) monitor->SendPacket(desc_, rspbuf_, msglen); YMB_HEXDUMP(rspbuf_, msglen, "Response message! len = %u: \n", msglen); } } } } } int Slave::Impl::Request(MsgInf &inf, uint8_t *rdbuf, size_t rdbufsiz) { int rsp; YMB_ASSERT(player_ != nullptr); YMB_DEBUG0("ExecRequest id = %u, fun = %u\n", inf.id, inf.fun); switch (inf.fun) { case kFunReadCoils: rsp = player_->ReadCoils(inf.id, inf.rreg, inf.rnum, rdbuf, rdbufsiz); break; case kFunReadDiscreteInputs: rsp = player_->ReadDiscreteInputs(inf.id, inf.rreg, inf.rnum, rdbuf, rdbufsiz); break; case kFunReadHoldingRegisters: rsp = player_->ReadHoldingRegisters(inf.id, inf.rreg, inf.rnum, rdbuf, rdbufsiz); break; case kFunReadInputRegisters: rsp = player_->ReadInputRegisters(inf.id, inf.rreg, inf.rnum, rdbuf, rdbufsiz); break; case kFunWriteAndReadRegisters: rsp = player_->WriteReadRegisters(inf.id, inf.wreg, inf.wnum, inf.databuf, inf.datalen, inf.rreg, inf.rnum, rdbuf, rdbufsiz); break; case kFunWriteMultiCoils: rsp = player_->WriteCoils(inf.id, inf.wreg, inf.wnum, inf.databuf, inf.datalen); break; case kFunWriteMultiRegisters: rsp = player_->WriteRegisters(inf.id, inf.wreg, inf.wnum, inf.databuf, inf.datalen); break; case kFunWriteSingleCoil: YMB_ASSERT(inf.databuf != nullptr && inf.datalen == 2); rsp = player_->WriteSingleCoil(inf.id, inf.wreg, inf.databuf[0] == 0xff && inf.databuf[1] == 0x00); if (rsp == 0) { rsp = 2; //ack the same data of request memmove(rdbuf, inf.databuf, rsp); } break; case kFunWriteSingleRegister: YMB_ASSERT(inf.databuf != nullptr && inf.datalen == 2); rsp = player_->WriteSingleRegister(inf.id, inf.wreg, static_cast<uint16_t>((inf.databuf[0] << 8) | inf.databuf[1])); if (rsp == 0) { rsp = 2; //ack the same data of request memmove(rdbuf, inf.databuf, rsp); } break; case kFunMaskWriteRegister: rsp = player_->MaskWriteRegisters(inf.id, inf.wreg, static_cast<uint16_t>((inf.databuf[0] << 8) | inf.databuf[1]), static_cast<uint16_t>((inf.databuf[2] << 8) | inf.databuf[3])); if (rsp == 0) { rsp = 4; //ack the same data of request memmove(rdbuf, inf.databuf, rsp); } break; default: rsp = -EINVAL; break; } inf.err = rsp >= 0 ? 0 : static_cast<uint8_t>(-rsp); inf.datalen = rsp > 0 ? static_cast<uint8_t>(rsp) : 0; inf.databuf = inf.datalen != 0 ? rdbuf : nullptr; YMB_DEBUG0("Exec Result rsp = %u\n", rsp); return rsp; } //YMB_RTU/YMB_ASCII Slave::Slave(const std::string& port, uint32_t baudrate, char parity, uint8_t stopbits, eProtocol prot, eThreadMode thrm) : impl_(std::make_shared<Impl>(thrm)) { switch (prot) { case RTU: impl_->listener_ = std::make_unique<SerListener>(port, baudrate, 8, parity, stopbits); impl_->prot_ = std::make_unique<Impl::Rtu>(); break; case ASCII: impl_->listener_ = std::make_unique<SerListener>(port, baudrate, 7, parity, stopbits); impl_->prot_ = std::make_unique<Impl::Ascii>(); break; default: YMB_ASSERT(false); break; } impl_->listener_->SetTimeout(kDefListenTimeout); impl_->desc_ = std::string("tcp:") + port; YMB_DEBUG("Create modbus slave server: %s: %s, mode: %s\n", impl_->listener_->GetName().c_str(), PROTNAME(prot), thrm == POLL ? "POLL" : "TASK"); } //YMB_TCP/YMB_UDP //YMB_TCP_RTU/YMB_TCP_ASCII //YMB_UDP_RTU/YMB_UDP_ASCII Slave::Slave(uint16_t port, eProtocol prot, eThreadMode thrm) : impl_(std::make_shared<Impl>(thrm)) { switch (prot) { case TCP: impl_->listener_ = std::make_unique<TcpListener>(port); impl_->prot_ = std::make_unique<Impl::Net>(); break; case TCPRTU: impl_->listener_ = std::make_unique<TcpListener>(port); impl_->prot_ = std::make_unique<Impl::Rtu>(); break; case TCPASCII: impl_->listener_ = std::make_unique<TcpListener>(port); impl_->prot_ = std::make_unique<Impl::Ascii>(); break; case UDP: impl_->listener_ = std::make_unique<UdpListener>(port); impl_->prot_ = std::make_unique<Impl::Net>(); break; case UDPRTU: impl_->listener_ = std::make_unique<UdpListener>(port); impl_->prot_ = std::make_unique<Impl::Rtu>(); break; case UDPASCII: impl_->listener_ = std::make_unique<UdpListener>(port); impl_->prot_ = std::make_unique<Impl::Ascii>(); break; default: YMB_ASSERT(false); break; } impl_->listener_->SetTimeout(kDefListenTimeout); impl_->desc_ = std::string("tcp:") + std::to_string(port); YMB_DEBUG("Create modbus slave server: %s: %s, mode: %s\n", impl_->listener_->GetName().c_str(), PROTNAME(prot), thrm == POLL ? "POLL" : "TASK"); } Slave::~Slave() { } //By default, any id will receipt(id=0) void Slave::SetSlaveId(uint8_t id) { impl_->id_ = id; } uint8_t Slave::GetSlaveId(void) const { return impl_->id_; } void Slave::SetMonitor(std::shared_ptr<IMonitor> monitor) { impl_->monitor_ = monitor; } std::shared_ptr<IMonitor> Slave::GetMonitor(void) const { return impl_->monitor_.lock(); } void Slave::SetPlayer(std::shared_ptr<IPlayer> player) { impl_->player_ = player; } std::shared_ptr<IPlayer> Slave::GetPlayer(void) const { return impl_->player_; } bool Slave::Startup(void) { if (!impl_->listener_->Listen()) { LOG(ERROR) << "Slave Listen failed."; return false; } if (impl_->thrm_ == TASK) { impl_->Start(); } return true; } void Slave::Shutdown(void) { if (impl_->thrm_ == TASK) { impl_->Stop(); impl_->Wait(); } } //for nthr = 0 to loop //to: timeout: ms //return: < 0: errorcode, = 0: no error int Slave::Run(long to) { YMB_ASSERT(impl_->thrm_ == POLL); return impl_->Run(to); } int Slave::GetLastError(void) const { return impl_->err_; } } //namespace YModbus
8,425
C++
.cpp
294
24.908163
73
0.655017
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,591
linuxsercon.cpp
lyqdy_ymodbus/ymodbus/ports/linuxsercon.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/master/yserconnect.h" #include "ymod/ymbdefs.h" #include "ymod/ymbutils.h" #include "ymblog.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <sys/time.h> #include <iomanip> namespace YModbus { struct SerConnect::Impl { Impl(const std::string &port, uint32_t baudrate, uint8_t databits, char parity, uint8_t stopbits) : fd_(-1) , t35_(1000000 * 12 * 20 / baudrate / 1000) { SetReadTimeout(10); /* Open the serial device. */ fd_ = open(port.c_str(), O_RDWR | O_NOCTTY); if (fd_ < 0) { fd_ = -1; LOG(ERROR) << "Open serial failed! " << port << ", " << baudrate << "bps, " << static_cast<int>(databits) << ", " << parity << ", " << std::setprecision(1) << stopbits / 10.0 << std::endl; return; } struct termios tio = { 0 }; tio.c_iflag |= IGNBRK | INPCK; tio.c_cflag |= CREAD | CLOCAL; switch (parity) { case kSerParityNone: break; case kSerParityEven: tio.c_cflag |= PARENB; break; case kSerParityOdd: tio.c_cflag |= PARENB | PARODD; break; default: break; } switch (databits) { case 8: tio.c_cflag |= CS8; break; case 7: tio.c_cflag |= CS7; break; default: tio.c_cflag |= CS8; break; } speed_t speed; switch (baudrate) { case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; default: speed = B9600; break; } if (cfsetispeed(&tio, speed) != 0 || cfsetospeed(&tio, speed) != 0 || tcsetattr(fd_, TCSANOW, &tio) != 0) { LOG(ERROR) << "Setup serial failed. " << port; close(fd_); fd_ = -1; } tcflush (fd_, TCIFLUSH); YMB_DEBUG("serial open success. %s,%u,%u,%c,%3.1f\n", port.c_str(), baudrate, databits, parity, stopbits/10.0); } bool SetReadTimeout(long to) { tv_.tv_sec = to / 1000; tv_.tv_usec = (to % 1000) * 1000; YMB_DEBUG("%s:%d %s timeout = %ld.%06ld\n", __FILE__, __LINE__, __func__, tv_.tv_sec, tv_.tv_usec); return true; } ~Impl() { if (fd_ != -1) { close(fd_); fd_ = -1; } } int fd_; struct timeval tv_; uint32_t t35_; //ms }; SerConnect::SerConnect(const std::string &com, uint32_t baudrate, uint8_t databits, char parity, uint8_t stopbits) : impl_(std::make_unique<Impl>(com, baudrate, databits, parity, stopbits)) { } SerConnect::~SerConnect() { } void SerConnect::SetTimeout(long to) { impl_->SetReadTimeout(to); } bool SerConnect::Validate(void) { return impl_->fd_ != -1; } void SerConnect::Purge(void) { if (impl_->fd_ != -1) { struct timeval tv = { 0, 0 }; fd_set fds; int ret; char buf[BUFSIZ]; do { FD_ZERO(&fds); FD_SET(impl_->fd_, &fds); ret = select(impl_->fd_ + 1, &fds, nullptr, nullptr, &tv); } while (ret > 0 && FD_ISSET(impl_->fd_, &fds) && read(impl_->fd_, buf, static_cast<int>(sizeof(buf))) > 0); } } bool SerConnect::Send(uint8_t *buf, size_t len) { if (impl_->fd_ != -1) { char *pbuf = reinterpret_cast<char *>(buf); int ret; do { ret = write(impl_->fd_, pbuf, len); if (ret > 0) { YMB_HEXDUMP0(pbuf, ret, "%p SerConnect::Send: ", this); len -= static_cast<size_t>(ret); pbuf += static_cast<size_t>(ret); } else { return false; } } while (len != 0); } return len == 0; } int SerConnect::Recv(uint8_t *buf, size_t len) { int recvlen = 0; if (impl_->fd_ != -1) { struct timeval tv = impl_->tv_; fd_set fds; int ret; do { FD_ZERO(&fds); FD_SET(impl_->fd_, &fds); ret = select(impl_->fd_ + 1, &fds, nullptr, nullptr, &tv); if (ret > 0 && FD_ISSET(impl_->fd_, &fds)) { ret = read(impl_->fd_, reinterpret_cast<char*>(buf) + recvlen, static_cast<int>(len) - recvlen); if (ret > 0) { YMB_HEXDUMP0(buf + recvlen, ret, "%p SerConnect::Recv: ", this); recvlen += ret; } } else { YMB_DEBUG0("SerConnect::Recv recvlen = %d, ret = %d\n", recvlen, ret); } tv.tv_sec = impl_->t35_ / 1000; tv.tv_usec = impl_->t35_ % 1000 * 1000; } while (ret > 0 && recvlen < static_cast<int>(len)); } return recvlen; } } //namespace YModbus
4,741
C++
.cpp
205
18.678049
84
0.567171
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,592
yudplistener.cpp
lyqdy_ymodbus/ymodbus/ports/yudplistener.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/slave/yudplistener.h" #include "ymod/ymbdefs.h" #include "ymbopts.h" #include "ymblog.h" #ifdef WIN32 # include <winsock2.h> # pragma comment(lib,"ws2_32.lib") #else # include <stdio.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <arpa/inet.h> # define closesocket close #endif namespace YModbus { namespace { #ifndef WIN32 typedef int SOCKET; const SOCKET INVALID_SOCKET = -1; const int SOCKET_ERROR = -1; #else typedef int socklen_t; #endif } //namesapce { struct UdpListener::Impl : public ISession { Impl(uint16_t port) : port_(port) , recvlen_(0) , alen_(sizeof(addr_)) { } virtual std::string PeerName(void); virtual int Write(uint8_t *msg, size_t msglen); virtual int Read(uint8_t *buf, size_t bufsiz); virtual size_t Peek(uint8_t **buf); virtual void Purge(void); virtual void Discard(size_t nbytes); bool Recv(void); uint16_t port_; SOCKET sock_; timeval tv_ = { 0, 0 }; char recvbuf_[kMaxMsgLen]; size_t recvlen_; sockaddr addr_; socklen_t alen_; }; std::string UdpListener::Impl::PeerName() { struct sockaddr_in addr; int addrlen = sizeof(addr); std::string peer = "tcp:"; peer += std::to_string(sock_); peer += ":connect:"; if (getpeername(sock_, reinterpret_cast<sockaddr*>(&addr), &addrlen) == 0) { peer = inet_ntoa(addr.sin_addr); peer += ":"; peer += std::to_string(ntohs(addr.sin_port)); } else { peer += "error peer"; } return peer; } int UdpListener::Impl::Write(uint8_t *msg, size_t msglen) { if (sock_ != INVALID_SOCKET) { YMB_HEXDUMP0(msg, msglen, "udp sendto sock = %d", sock_); return sendto(sock_, (char *)msg, (int)msglen, 0, &addr_, alen_); } return -1; } int UdpListener::Impl::Read(uint8_t *buf, size_t bufsiz) { if (recvlen_ < bufsiz) bufsiz = recvlen_; memcpy(buf, recvbuf_, bufsiz); recvlen_ -= bufsiz; return static_cast<int>(bufsiz); } size_t UdpListener::Impl::Peek(uint8_t **buf) { *buf = reinterpret_cast<uint8_t*>(&recvbuf_[0]); return recvlen_; } void UdpListener::Impl::Purge(void) { recvlen_ = 0; } void UdpListener::Impl::Discard(size_t nbytes) { if (recvlen_ > nbytes) { recvlen_ -= nbytes; memmove(recvbuf_, recvbuf_ + nbytes, recvlen_); } else { recvlen_ = 0; } } bool UdpListener::Impl::Recv() { int len = recvfrom(sock_, recvbuf_, sizeof(recvbuf_), 0, &addr_, &alen_); if (len > 0) { recvlen_ = len; YMB_HEXDUMP0(recvbuf_, recvlen_, "%s recvbuf, len = %u ", PeerName().c_str(), recvlen_); return true; } recvlen_ = 0; return false; } UdpListener::UdpListener(uint16_t port) : impl_(std::make_shared<Impl>(port)) { #ifdef WIN32 WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); #endif impl_->sock_ = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (impl_->sock_ == INVALID_SOCKET) { YMB_ERROR("Open udp socket failed. port = %u\n ", port); return; } int opt = 1; setsockopt(impl_->sock_, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; int ret = bind(impl_->sock_, (struct sockaddr *)&addr, sizeof(addr)); if (ret == SOCKET_ERROR) { YMB_ERROR("Udp socket bind failed. port = %u\n", port); closesocket(impl_->sock_); impl_->sock_ = INVALID_SOCKET; return; } YMB_DEBUG("Open udp listen success. port = %u\n", port); } UdpListener::~UdpListener() { if (impl_->sock_ != INVALID_SOCKET) { closesocket(impl_->sock_); impl_->sock_ = INVALID_SOCKET; } #if 0 //def WIN32 //We needn't call this function WSACleanup(); #endif } std::string UdpListener::GetName(void) { struct sockaddr_in addr; int addrlen = sizeof(addr); std::string peer = "udp:"; peer += std::to_string(impl_->sock_); peer += ":listen:"; if (getsockname(impl_->sock_, reinterpret_cast<sockaddr*>(&addr), &addrlen) == 0) { peer = inet_ntoa(addr.sin_addr); peer += ":"; peer += std::to_string(ntohs(addr.sin_port)); } else { peer += "error sock"; } return peer; } void UdpListener::SetTimeout(long to) { impl_->tv_.tv_sec = to / 1000; impl_->tv_.tv_usec = (to % 1000) * 1000; } bool UdpListener::Listen(void) { return impl_->sock_ != INVALID_SOCKET; } int UdpListener::Accept(std::vector<SessionPtr> &ses) { ses.clear(); if (impl_->sock_ != INVALID_SOCKET) { fd_set fds; FD_ZERO(&fds); FD_SET(impl_->sock_, &fds); int ret = select(impl_->sock_ + 1, &fds, nullptr, nullptr, &impl_->tv_); if (ret <= 0) return EOK; if (FD_ISSET(impl_->sock_, &fds)) { if (impl_->Recv()) { //data received, impl_ is the session ses.push_back(impl_); } return EOK; //no error } } return -1; } } //namespace YModbus
5,061
C++
.cpp
205
21.297561
75
0.640546
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,593
linuxserlistener.cpp
lyqdy_ymodbus/ymodbus/ports/linuxserlistener.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/slave/yserlistener.h" #include "ymod/ymbdefs.h" #include "ymblog.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <sys/time.h> #include <iomanip> namespace YModbus { struct SerListener::Impl : public ISession { Impl(const std::string &port) : port_(port), recvlen_(0) {} virtual std::string PeerName(void); virtual int Write(uint8_t *msg, size_t msglen); virtual int Read(uint8_t *buf, size_t bufsiz); virtual size_t Peek(uint8_t **buf); virtual void Purge(void); virtual void Discard(size_t nbytes); bool Recv(void); int fd_; timeval tv_ = { 0, 0 }; char recvbuf_[kMaxMsgLen]; size_t recvlen_; }; std::string SerListener::Impl::PeerName() { return std::string("ser:") + port_; } int SerListener::Impl::Write(uint8_t *msg, size_t msglen) { if (fd_ != -1) { int ret; size_t len = msglen; YMB_HEXDUMP0(msg, msglen, "Ser Write fd = %d", fd_); do { ret = write(fd_, msg, len); if (ret > 0) { YMB_HEXDUMP0(msg, ret, "Ser Send fd = %d", fd_); len -= ret; msg += ret; } else { return -1; //error } } while (len != 0); return msglen; } return -1; } int SerListener::Impl::Read(uint8_t *buf, size_t bufsiz) { if (recvlen_ < bufsiz) bufsiz = recvlen_; memcpy(buf, recvbuf_, bufsiz); recvlen_ -= bufsiz; return static_cast<int>(bufsiz); } size_t SerListener::Impl::Peek(uint8_t **buf) { *buf = reinterpret_cast<uint8_t*>(&recvbuf_[0]); return recvlen_; } void SerListener::Impl::Purge(void) { recvlen_ = 0; if (fd_ != -1) tcflush(fd_, TCIOFLUSH); } void SerListener::Impl::Discard(size_t nbytes) { if (recvlen_ > nbytes) { recvlen_ -= nbytes; memmove(recvbuf_, recvbuf_ + nbytes, recvlen_); } else { recvlen_ = 0; } } bool SerListener::Impl::Recv() { if (recvlen_ == sizeof(recvbuf_)) recvlen_ = 0; int len = read(fd_, &recvbuf_[recvlen_], sizeof(recvbuf_) - recvlen_); if (len > 0) { recvlen_ += len; YMB_HEXDUMP0(recvbuf_, recvlen_, "%s recvbuf, len = %u ", PeerName().c_str(), recvlen_); return true; } return false; } SerListener::SerListener(const std::string& port, uint32_t baudrate, uint8_t databits, char parity, uint8_t stopbits) : impl_(std::make_shared<Impl>(port)) { impl_->fd_ = open(port.c_str(), O_RDWR | O_NOCTTY); if (impl_->fd_ < 0) { impl_->fd_ = -1; LOG(ERROR) << "Open serial failed! " << port << ", " << baudrate << "bps, " << static_cast<int>(databits) << ", " << parity << ", " << std::setprecision(1) <<stopbits / 10.0 << std::endl; return; } struct termios tio = { 0 }; tio.c_iflag |= IGNBRK | INPCK; tio.c_cflag |= CREAD | CLOCAL; switch (parity) { case kSerParityNone: break; case kSerParityEven: tio.c_cflag |= PARENB; break; case kSerParityOdd: tio.c_cflag |= PARENB | PARODD; break; default: break; } switch (databits) { case 8: tio.c_cflag |= CS8; break; case 7: tio.c_cflag |= CS7; break; default: tio.c_cflag |= CS8; break; } speed_t speed; switch (baudrate) { case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; default: speed = B9600; break; } if (cfsetispeed(&tio, speed) != 0 || cfsetospeed(&tio, speed) != 0 || tcsetattr(impl_->fd_, TCSANOW, &tio) != 0) { LOG(ERROR) << "Setup serial failed. " << port; close(impl_->fd_); impl_->fd_ = -1; } YMB_DEBUG("serial listen open success. %s,%u,%u,%u,%3.1f\n", port.c_str(), baudrate, databits, parity, stopbits/10); } std::string SerListener::GetName(void) { return impl_->PeerName(); } void SerListener::SetTimeout(long to) { impl_->tv_.tv_sec = to / 1000; impl_->tv_.tv_usec = (to % 1000) * 1000; } bool SerListener::Listen(void) { return impl_->fd_ != -1; } int SerListener::Accept(std::vector<SessionPtr> &ses) { ses.clear(); if (impl_->fd_ != -1) { fd_set fds; FD_ZERO(&fds); FD_SET(impl_->fd_, &fds); int ret = select(impl_->fd_ + 1, &fds, nullptr, nullptr, &impl_->tv_); if (ret <= 0) return 0; if (FD_ISSET(impl_->fd_, &fds)) { if (impl_->Recv()) { //data received, impl_ is the session ses.push_back(impl_); } return 0; //no error } } return -1; } SerListener::~SerListener() { if (impl_->fd_ != -1) { close(impl_->fd_); impl_->fd_ = -1; } } } //namespace YModbus
4,927
C++
.cpp
225
18.302222
62
0.609233
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,594
winserlistener.cpp
lyqdy_ymodbus/ymodbus/ports/winserlistener.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/slave/yserlistener.h" #include "ymod/ymbdefs.h" #include "ymblog.h" #include "ymbopts.h" #include <Windows.h> #include <algorithm> #include <iomanip> namespace YModbus { struct SerListener::Impl : public ISession { Impl(const std::string &port) : port_(port), recvlen_(0) {} virtual std::string PeerName(void); virtual int Write(uint8_t *msg, size_t msglen); virtual int Read(uint8_t *buf, size_t bufsiz); virtual size_t Peek(uint8_t **buf); virtual void Purge(void); virtual void Discard(size_t nbytes); bool Recv(void); std::string port_; HANDLE file_; char recvbuf_[kMaxMsgLen]; size_t recvlen_; }; std::string SerListener::Impl::PeerName() { return std::string("ser:") + port_; } int SerListener::Impl::Write(uint8_t *msg, size_t msglen) { if (file_ != INVALID_HANDLE_VALUE) { DWORD dwWritten; size_t len = msglen; uint8_t *pbuf = msg; do { if (WriteFile(file_, pbuf, len, &dwWritten, NULL)) { len -= dwWritten; pbuf += dwWritten; FlushFileBuffers(file_); } else { return -EFAULT; //error } } while (len != 0); YMB_HEXDUMP(msg, msglen, "%s write data, len = %u: ", port_.c_str(), dwWritten); return msglen; } return -EDEV; } int SerListener::Impl::Read(uint8_t *buf, size_t bufsiz) { if (recvlen_ < bufsiz) bufsiz = recvlen_; memcpy(buf, recvbuf_, bufsiz); recvlen_ -= bufsiz; return static_cast<int>(bufsiz); } size_t SerListener::Impl::Peek(uint8_t **buf) { *buf = reinterpret_cast<uint8_t*>(&recvbuf_[0]); return recvlen_; } void SerListener::Impl::Purge(void) { recvlen_ = 0; if (file_ != INVALID_HANDLE_VALUE) ::PurgeComm(file_, PURGE_RXCLEAR | PURGE_TXCLEAR); } void SerListener::Impl::Discard(size_t nbytes) { if (recvlen_ > nbytes) { recvlen_ -= nbytes; memmove(recvbuf_, recvbuf_ + nbytes, recvlen_); } else { recvlen_ = 0; } } bool SerListener::Impl::Recv() { if (file_ != INVALID_HANDLE_VALUE) { DWORD dwRead; if (recvlen_ == sizeof(recvbuf_)) recvlen_ = 0; if (ReadFile(file_, recvbuf_ + recvlen_, sizeof(recvbuf_) - recvlen_, &dwRead, NULL)) { if (dwRead != 0) { //some bytes arrived recvlen_ += dwRead; YMB_HEXDUMP0(recvbuf_, recvlen_, "%s recvbuf, len = %u", port_.c_str(), recvlen_); return true; } } } return false; } SerListener::SerListener(const std::string& port, uint32_t baudrate, uint8_t databits, char parity, uint8_t stopbits) : impl_(std::make_shared<Impl>(port)) { DCB dcb; impl_->file_ = CreateFileA( port.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (impl_->file_ == INVALID_HANDLE_VALUE) { LOG(ERROR) << "Open serial failed! " << port << ", " << baudrate << "bps, " << static_cast<int>(databits) << ", " << parity << ", " << std::setprecision(1) << stopbits / 10.0 << std::endl; return; } dcb.DCBlength = sizeof(DCB); if (!GetCommState(impl_->file_, &dcb)) { CloseHandle(impl_->file_); impl_->file_ = INVALID_HANDLE_VALUE; LOG(ERROR) << "GetCommState failed! " << port << std::endl; return; } dcb.BaudRate = baudrate; dcb.ByteSize = databits; if (stopbits == kSerStopbits1) dcb.StopBits = ONESTOPBIT; else if (stopbits == kSerStopbits15) dcb.StopBits = ONE5STOPBITS; else dcb.StopBits = TWOSTOPBITS; if (parity == kSerParityNone) { dcb.Parity = NOPARITY; dcb.fParity = FALSE; } else if (parity == kSerParityEven) { dcb.Parity = EVENPARITY; dcb.fParity = TRUE; } else { dcb.Parity = ODDPARITY; dcb.fParity = TRUE; } dcb.fTXContinueOnXoff = TRUE; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fBinary = TRUE; dcb.fAbortOnError = FALSE; if (!SetCommState(impl_->file_, &dcb)) { CloseHandle(impl_->file_); impl_->file_ = INVALID_HANDLE_VALUE; LOG(ERROR) << "SetCommState failed! " << port << std::endl; return; } YMB_DEBUG("Open serial success! %s, %u, %u, %c, %3.1f\n", port.c_str(), baudrate, databits, parity, stopbits / 10.0); } std::string SerListener::GetName(void) { return impl_->PeerName(); } void SerListener::SetTimeout(long to) { if (impl_->file_ != INVALID_HANDLE_VALUE) { COMMTIMEOUTS cto = {0}; cto.ReadIntervalTimeout = 5; cto.ReadTotalTimeoutConstant = 5; cto.WriteTotalTimeoutMultiplier = 0; cto.WriteTotalTimeoutConstant = 1000; SetCommTimeouts(impl_->file_, &cto); } } bool SerListener::Listen(void) { return impl_->file_ != INVALID_HANDLE_VALUE; } int SerListener::Accept(std::vector<SessionPtr> &ses) { ses.clear(); if (impl_->Recv()) { //data received, impl_ is the session ses.push_back(impl_); } return EOK; //no error } SerListener::~SerListener() { if (impl_->file_ != INVALID_HANDLE_VALUE) { CloseHandle(impl_->file_); impl_->file_ = INVALID_HANDLE_VALUE; } } } //namespace YModbus
5,133
C++
.cpp
206
21.18932
62
0.645842
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,595
w32sercon.cpp
lyqdy_ymodbus/ymodbus/ports/w32sercon.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/master/yserconnect.h" #include "ymod/ymbdefs.h" #include "ymblog.h" #include <Windows.h> namespace YModbus { struct SerConnect::Impl { Impl(const std::string &com, uint32_t baudrate, uint8_t databits, char parity, uint8_t stopbits) : file_(INVALID_HANDLE_VALUE) { /* Open the serial device. */ file_ = CreateFileA(com.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (file_ == INVALID_HANDLE_VALUE) { LOG(ERROR) << "Open serial failed! " << com << ", " << baudrate << "bps, " << static_cast<int>(databits) << ", " << parity << ", " << stopbits / 10.0 << std::endl; return; } DCB dcb = {0}; dcb.DCBlength = sizeof(dcb); dcb.BaudRate = baudrate; dcb.ByteSize = databits; if (stopbits == kSerStopbits1) dcb.StopBits = ONESTOPBIT; else if (stopbits == kSerStopbits15) dcb.StopBits = ONE5STOPBITS; else dcb.StopBits = TWOSTOPBITS; if (parity == kSerParityNone) { dcb.Parity = NOPARITY; dcb.fParity = FALSE; } else if (parity == kSerParityEven) { dcb.Parity = EVENPARITY; dcb.fParity = TRUE; } else { dcb.Parity = ODDPARITY; dcb.fParity = TRUE; } dcb.fTXContinueOnXoff = TRUE; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fBinary = TRUE; dcb.fAbortOnError = FALSE; if (!SetCommState(file_, &dcb)) { CloseHandle(file_); file_ = INVALID_HANDLE_VALUE; LOG(ERROR) << "SetCommState failed! " << com << std::endl; } } bool SetReadTimeout(long to) { COMMTIMEOUTS cto; cto.ReadIntervalTimeout = 4; //modbus < 3.5ms cto.ReadTotalTimeoutConstant = static_cast<DWORD>(to); cto.ReadTotalTimeoutMultiplier = 0; cto.WriteTotalTimeoutConstant = 0; cto.WriteTotalTimeoutMultiplier = 0; return static_cast<bool>(SetCommTimeouts(file_, &cto)); } ~Impl() { if (file_ != INVALID_HANDLE_VALUE) { CloseHandle(file_); file_ = INVALID_HANDLE_VALUE; } } HANDLE file_; }; SerConnect::SerConnect(const std::string &com, uint32_t baudrate, uint8_t databits, char parity, uint8_t stopbits) : impl_(std::make_unique<Impl>(com, baudrate, databits, parity, stopbits)) { } SerConnect::~SerConnect() { } void SerConnect::SetTimeout(long to) { impl_->SetReadTimeout(to); } bool SerConnect::Validate(void) { return impl_->file_ != INVALID_HANDLE_VALUE; } void SerConnect::Purge(void) { if (impl_->file_ != INVALID_HANDLE_VALUE) { PurgeComm(impl_->file_, PURGE_RXCLEAR | PURGE_TXCLEAR); } } bool SerConnect::Send(uint8_t *buf, size_t len) { if (impl_->file_ != INVALID_HANDLE_VALUE) { char *pbuf = reinterpret_cast<char *>(buf); DWORD dwWritten; do { if (WriteFile(impl_->file_, pbuf, len, &dwWritten, NULL)) { len -= static_cast<size_t>(dwWritten); pbuf += static_cast<size_t>(dwWritten); } else { return false; } } while (len != 0); } return len == 0; } int SerConnect::Recv(uint8_t *buf, size_t len) { if (impl_->file_ != INVALID_HANDLE_VALUE) { DWORD dwRead; if (ReadFile(impl_->file_, buf, len, &dwRead, NULL)) return static_cast<int>(dwRead); } return -ENODEV; } } //namespace YModbus
3,370
C++
.cpp
129
22.085271
76
0.648759
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,596
ytcpconnect.cpp
lyqdy_ymodbus/ymodbus/ports/ytcpconnect.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/master/ytcpconnect.h" #include "ymod/ymbutils.h" #ifdef WIN32 # include <winsock2.h> # pragma comment(lib,"ws2_32.lib") #else # include <stdio.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <arpa/inet.h> # include <unistd.h> # define closesocket close #endif namespace YModbus { namespace { #ifndef WIN32 typedef int SOCKET; const SOCKET INVALID_SOCKET = -1; const int SOCKET_ERROR = -1; #else typedef int socklen_t; #endif } //namesapce { struct TcpConnect::Impl { Impl(const std::string &ip, uint16_t port) : ip_(ip), port_(port), sock_(INVALID_SOCKET) { } ~Impl() { Clear(); } void Clear(void) { if (sock_ != INVALID_SOCKET) { closesocket(sock_); sock_ = INVALID_SOCKET; } } std::string ip_; uint16_t port_; SOCKET sock_; timeval tv_; }; TcpConnect::TcpConnect(const std::string &ip, uint16_t port) : impl_(std::make_unique<Impl>(ip, port)) { #ifdef WIN32 WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); #endif } TcpConnect::~TcpConnect() { #if 0 //def WIN32 //We can't call this function WSACleanup(); #endif } void TcpConnect::SetTimeout(long to) { impl_->tv_.tv_sec = to / 1000; impl_->tv_.tv_usec = (to % 1000) * 1000; } bool TcpConnect::Validate(void) { if (impl_->sock_ != INVALID_SOCKET) return true; impl_->sock_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (impl_->sock_ == INVALID_SOCKET) { return false; } struct sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(impl_->port_); addr.sin_addr.s_addr = inet_addr(impl_->ip_.c_str()); if (connect(impl_->sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) { impl_->Clear(); return false; } return true; } void TcpConnect::Purge(void) { if (impl_->sock_ != INVALID_SOCKET) { int ret; fd_set fdsets; timeval tv = { 0 }; do { FD_ZERO(&fdsets); FD_SET(impl_->sock_, &fdsets); ret = select(impl_->sock_ + 1, &fdsets, NULL, NULL, &tv); if (ret > 0 && FD_ISSET(impl_->sock_, &fdsets)) { char buf[BUFSIZ]; ret = recv(impl_->sock_, buf, sizeof(buf), 0); if (ret == 0) { impl_->Clear(); } } } while (ret >= BUFSIZ); } } bool TcpConnect::Send(uint8_t *buf, size_t len) { int ret; char *pbuf = reinterpret_cast<char *>(buf); if (impl_->sock_ != INVALID_SOCKET) { do { ret = send(impl_->sock_, pbuf, len, 0); if (ret > 0) { len -= static_cast<uint16_t>(ret); pbuf += static_cast<uint16_t>(ret); } else if (ret < 0) { impl_->Clear(); return false; } else { // == 0 ? ;//Be not imposible } } while (len != 0); } return len == 0; } int TcpConnect::Recv(uint8_t *buf, size_t len) { int ret = -ENOLINK; if (impl_->sock_ != INVALID_SOCKET) { struct timeval tv = impl_->tv_; fd_set fdsets; FD_ZERO(&fdsets); FD_SET(impl_->sock_, &fdsets); ret = select(impl_->sock_ + 1, &fdsets, NULL, NULL, &tv); if (ret > 0 && FD_ISSET(impl_->sock_, &fdsets)) { ret = recv(impl_->sock_, reinterpret_cast<char *>(buf), len, 0); if (ret == 0) { impl_->Clear(); return -ECONNRESET; } } } return ret; } } //namespace YModbus
3,431
C++
.cpp
150
19.193333
75
0.603229
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,597
yudpconnect.cpp
lyqdy_ymodbus/ymodbus/ports/yudpconnect.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/master/yudpconnect.h" #include "ymod/ymbutils.h" #include "ymblog.h" #ifdef WIN32 # include <winsock2.h> # pragma comment(lib,"ws2_32.lib") #else # include <stdio.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <arpa/inet.h> # include <unistd.h> # define closesocket close #endif namespace YModbus { namespace { #ifndef WIN32 typedef int SOCKET; const SOCKET INVALID_SOCKET = -1; const int SOCKET_ERROR = -1; #else typedef int socklen_t; #endif } //namesapce { struct UdpConnect::Impl { Impl(const std::string &ip, uint16_t port) : ip_(ip), port_(port), sock_(INVALID_SOCKET) { } ~Impl() { Clear(); } void Clear(void) { if (sock_ != INVALID_SOCKET) { closesocket(sock_); sock_ = INVALID_SOCKET; } } std::string ip_; uint16_t port_; SOCKET sock_; timeval tv_; }; UdpConnect::UdpConnect(const std::string &ip, uint16_t port) : impl_(std::make_unique<Impl>(ip, port)) { #ifdef WIN32 WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); #endif } UdpConnect::~UdpConnect() { #if 0 //def WIN32 //We can't call this function WSACleanup(); #endif } void UdpConnect::SetTimeout(long to) { impl_->tv_.tv_sec = to / 1000; impl_->tv_.tv_usec = (to % 1000) * 1000; } bool UdpConnect::Validate(void) { if (impl_->sock_ != INVALID_SOCKET) return true; impl_->sock_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (impl_->sock_ == INVALID_SOCKET) { YMB_ERROR("Open udp socket failed!\n"); return false; } struct sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(impl_->port_); addr.sin_addr.s_addr = inet_addr(impl_->ip_.c_str()); if (connect(impl_->sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) { impl_->Clear(); return false; } return true; } void UdpConnect::Purge(void) { if (impl_->sock_ != INVALID_SOCKET) { int ret; fd_set fdsets; timeval tv = { 0 }; do { FD_ZERO(&fdsets); FD_SET(impl_->sock_, &fdsets); ret = select(impl_->sock_ + 1, &fdsets, NULL, NULL, &tv); if (ret > 0 && FD_ISSET(impl_->sock_, &fdsets)) { char buf[BUFSIZ]; ret = recv(impl_->sock_, buf, sizeof(buf), 0); if (ret == 0) { impl_->Clear(); } } } while (ret >= BUFSIZ); } } bool UdpConnect::Send(uint8_t *buf, size_t len) { int ret; char *pbuf = reinterpret_cast<char *>(buf); if (impl_->sock_ != INVALID_SOCKET) { do { ret = send(impl_->sock_, pbuf, len, 0); if (ret > 0) { len -= static_cast<uint16_t>(ret); pbuf += static_cast<uint16_t>(ret); } else if (ret < 0) { impl_->Clear(); return false; } else { // == 0 ? ;//Be not imposible } } while (len != 0); } return len == 0; } int UdpConnect::Recv(uint8_t *buf, size_t len) { int ret = -ENOLINK; if (impl_->sock_ != INVALID_SOCKET) { struct timeval tv = impl_->tv_; fd_set fdsets; FD_ZERO(&fdsets); FD_SET(impl_->sock_, &fdsets); ret = select(impl_->sock_ + 1, &fdsets, NULL, NULL, &tv); if (ret > 0 && FD_ISSET(impl_->sock_, &fdsets)) { ret = recv(impl_->sock_, reinterpret_cast<char *>(buf), len, 0); if (ret == 0) { impl_->Clear(); return -ECONNRESET; } } } return ret; } } //namespace YModbus
3,494
C++
.cpp
152
19.315789
75
0.604509
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,598
ytcplistener.cpp
lyqdy_ymodbus/ymodbus/ports/ytcplistener.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymod/slave/ytcplistener.h" #include "ymod/ymbdefs.h" #include "ymbopts.h" #include "ymblog.h" #ifdef WIN32 # include <winsock2.h> # pragma comment(lib,"ws2_32.lib") #else # include <stdio.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <arpa/inet.h> # define closesocket close #endif #include <ctime> #include <algorithm> #include <memory> namespace YModbus { namespace { #ifndef WIN32 typedef int SOCKET; const SOCKET INVALID_SOCKET = -1; const int SOCKET_ERROR = -1; #else typedef int socklen_t; #endif const int kTcpListenNum = 5; const time_t kMinIdleTime = 300; //s struct TcpSession : public ISession { TcpSession(SOCKET sock) : sock_(sock) , lrt_(time(0)) , recvlen_(0) { } ~TcpSession() { Reset(INVALID_SOCKET); } void Reset(SOCKET sock) { YMB_DEBUG("Tcp socket closed. socket = %d\n", sock_); closesocket(sock_); sock_ = sock; recvlen_ = 0; lrt_ = time(0); } virtual std::string PeerName(void); virtual int Write(uint8_t *msg, size_t msglen); virtual int Read(uint8_t *buf, size_t bufsiz); virtual size_t Peek(uint8_t **buf); virtual void Purge(void); virtual void Discard(size_t nbytes); bool Recv(void); SOCKET sock_; time_t lrt_; //last recv msg time char recvbuf_[kMaxMsgLen]; size_t recvlen_; }; std::string TcpSession::PeerName() { struct sockaddr_in addr; int addrlen = sizeof(addr); std::string peer = "tcp:"; peer += std::to_string(sock_); peer += ":connect:"; if (getpeername(sock_, reinterpret_cast<sockaddr*>(&addr), &addrlen) == 0) { peer = inet_ntoa(addr.sin_addr); peer += ":"; peer += std::to_string(ntohs(addr.sin_port)); } else { peer += "error peer"; } return peer; } int TcpSession::Write(uint8_t *msg, size_t msglen) { int len = static_cast<int>(msglen); char *pbuf = reinterpret_cast<char*>(msg); int sentlen = 0; do { sentlen = send(sock_, pbuf, len, 0); if (sentlen > 0) { pbuf += sentlen; len -= sentlen; YMB_HEXDUMP0(pbuf, sentlen, "%s write data, len = %u", PeerName().c_str(), sentlen); } } while (len > 0 && sentlen >= 0); return len == 0 ? EOK : -EFAULT; } int TcpSession::Read(uint8_t *buf, size_t bufsiz) { if (recvlen_ < bufsiz) bufsiz = recvlen_; memcpy(buf, recvbuf_, bufsiz); recvlen_ -= bufsiz; return static_cast<int>(bufsiz); } size_t TcpSession::Peek(uint8_t **buf) { *buf = reinterpret_cast<uint8_t*>(&recvbuf_[0]); return recvlen_; } void TcpSession::Purge(void) { fd_set fds; timeval tv = { 0, 0 }; int ret; do { FD_ZERO(&fds); FD_SET(sock_, &fds); ret = select(sock_ + 1, &fds, nullptr, nullptr, &tv); if (ret > 0) { if (FD_ISSET(sock_, &fds)) ret = recv(sock_, recvbuf_, sizeof(recvbuf_), 0); else ret = 0; } } while (ret > 0); recvlen_ = 0; } void TcpSession::Discard(size_t nbytes) { if (recvlen_ > nbytes) { recvlen_ -= nbytes; memmove(recvbuf_, recvbuf_ + nbytes, recvlen_); } else { recvlen_ = 0; } } bool TcpSession::Recv() { if (recvlen_ == sizeof(recvbuf_)) recvlen_ = 0; int len = recv(sock_, &recvbuf_[recvlen_], sizeof(recvbuf_) - recvlen_, 0); if (len > 0) { recvlen_ += len; lrt_ = time(0); YMB_HEXDUMP0(recvbuf_, recvlen_, "%s recvbuf, len = %u ", PeerName().c_str(), recvlen_); return true; } return false; } } //namespace { struct TcpListener::Impl { typedef std::shared_ptr<TcpSession> TcpSessionPtr; timeval tv_ = { 0, 0 }; SOCKET sock_ = INVALID_SOCKET; //listen sockets std::vector<TcpSessionPtr> ses_; bool AddSession(SOCKET sock) { if (ses_.size() < kMaxTcpSessionNum) { ses_.push_back(std::make_shared<TcpSession>(sock)); return true; } auto session = *std::min_element(ses_.begin(), ses_.end(), [](TcpSessionPtr s1, TcpSessionPtr s2) { return s1->lrt_ < s2->lrt_; //min lrt }); time_t now = time(0); if (now < session->lrt_ || now - session->lrt_ > kMinIdleTime) { session->Reset(sock); //reuse session return true; //ok, found a idle session } return false; //idle session object not found! connect refused. } }; TcpListener::TcpListener(uint16_t port) : impl_(std::make_unique<Impl>()) { #ifdef WIN32 WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); #endif impl_->sock_ = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (impl_->sock_ == INVALID_SOCKET) { YMB_ERROR("Open listen socket failed. port = %u\n ", port); return; } int opt = 1; setsockopt(impl_->sock_, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; int ret = bind(impl_->sock_, (struct sockaddr *)&addr, sizeof(addr)); if (ret == SOCKET_ERROR) { YMB_ERROR("Tcp socket bind failed. port = %u\n", port); closesocket(impl_->sock_); impl_->sock_ = INVALID_SOCKET; return; } YMB_DEBUG("Open tcp listen success. port = %u\n", port); } TcpListener::~TcpListener() { if (impl_->sock_ != INVALID_SOCKET) { closesocket(impl_->sock_); impl_->sock_ = INVALID_SOCKET; } #if 0 //def WIN32 //We needn't call this function WSACleanup(); #endif } std::string TcpListener::GetName(void) { struct sockaddr_in addr; int addrlen = sizeof(addr); std::string peer = "tcp:"; peer += std::to_string(impl_->sock_); peer += ":listen:"; if (getsockname(impl_->sock_, reinterpret_cast<sockaddr*>(&addr), &addrlen) == 0) { peer = inet_ntoa(addr.sin_addr); peer += ":"; peer += std::to_string(ntohs(addr.sin_port)); } else { peer += "error sock"; } return peer; } void TcpListener::SetTimeout(long to) { impl_->tv_.tv_sec = to / 1000; impl_->tv_.tv_usec = (to % 1000) * 1000; } bool TcpListener::Listen(void) { if (impl_->sock_ == INVALID_SOCKET) return false; int ret = listen(impl_->sock_, kTcpListenNum); if (ret == SOCKET_ERROR) { YMB_ERROR("Tcp listen socket listen failed.\n"); closesocket(impl_->sock_); impl_->sock_ = INVALID_SOCKET; return false; } return true; } int TcpListener::Accept(std::vector<SessionPtr> &ses) { ses.clear(); SOCKET maxsock = -1; fd_set fds; FD_ZERO(&fds); if (impl_->sock_ != INVALID_SOCKET) { FD_SET(impl_->sock_, &fds); maxsock = impl_->sock_; } for (const auto &s : impl_->ses_) { FD_SET(s->sock_, &fds); if (s->sock_ > maxsock) maxsock = s->sock_; } int ret = select(maxsock + 1, &fds, nullptr, nullptr, &impl_->tv_); if (ret <= 0) return EOK; //session socket for (auto it = impl_->ses_.begin(); it != impl_->ses_.end();) { if (FD_ISSET((*it)->sock_, &fds)) { if ((*it)->Recv()) { //data arrived ses.push_back(*it); ++it; } else { //error or closed it = impl_->ses_.erase(it); } } else { //!FD_ISSET ++it; } } //Listen socket if (FD_ISSET(impl_->sock_, &fds)) { sockaddr addr; socklen_t addrlen = sizeof(addr); SOCKET sock = accept(impl_->sock_, &addr, &addrlen); if (sock != SOCKET_ERROR) { sockaddr_in *addrin = (sockaddr_in*)&addr; YMB_DEBUG("New tcp connect. socket = %d, ip = %s, port = %u\n", sock, inet_ntoa(addrin->sin_addr), ntohs(addrin->sin_port)); if (!impl_->AddSession(sock)) { YMB_ERROR("Idle session object not found!connect refused." "socket = %d, ip = %s, port = %u\n", sock, inet_ntoa(addrin->sin_addr), ntohs(addrin->sin_port)); closesocket(sock); } } } return EOK; } } //namespace YModbus
7,863
C++
.cpp
308
21.831169
71
0.625624
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,599
test_yslave.cpp
lyqdy_ymodbus/ymodbus/tests/test_yslave.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ // test_yslave.cpp // #include "ymod/slave/ymbslave.h" #include "ymod/slave/yslave.h" namespace YModbus { class Player : public IPlayer { public: //return: >= 0, bytes of data to return; //return: < 0, errorcode of exception virtual int ReadCoils(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { *buf++ = 0x01; *buf++ = 0x02; return num / 8 + ((num % 8) != 0 ? 1 : 0); } virtual int ReadDiscreteInputs(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { *buf++ = 0x01; *buf++ = 0x02; return num / 8 + ((num % 8) != 0 ? 1 : 0); } virtual int ReadInputRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { *buf++ = 0x01; *buf++ = 0x02; return num * 2; } virtual int ReadHoldingRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) { *buf++ = 0x01; *buf++ = 0x02; *buf++ = 0x03; *buf++ = 0x04; *buf++ = 0x05; *buf++ = 0x06; *buf++ = 0x07; *buf++ = 0x08; return num * 2; } //return: >= 0, OK; //return: < 0, errorcode of exception virtual int WriteSingleCoil(uint8_t sid, uint16_t reg, bool onoff) { return 0; } virtual int WriteCoils(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *bits, uint8_t wbytes) { return 0; } virtual int WriteSingleRegister(uint8_t sid, uint16_t reg, uint16_t value) { return 0; } virtual int WriteRegisters(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *values, uint8_t wbytes) { return 0; } virtual int MaskWriteRegisters(uint8_t sid, uint16_t reg, uint16_t andmask, uint16_t ormask) { return 0; } //return: >= 0, bytes of data to return //return: < 0, errorcode of exception virtual int WriteReadRegisters(uint8_t sid, uint16_t wreg, uint16_t wnum, const uint8_t *values, uint8_t wbytes, uint16_t rreg, uint16_t rnum, uint8_t *buf, size_t bufsiz) { *buf++ = 0x01; *buf++ = 0x02; return rnum * 2; } //return: >= 0, OK //return: < 0, errorcode of exception virtual int ReportSlaveId(uint8_t maxsid, uint8_t *buf, size_t bufsiz) { return -1; } }; } //namespace YModbus using namespace YModbus; int main() { Slave slave1(5502, TCP, TASK); Slave slave2(5503, TCPRTU, TASK); Slave slave3(5504, TCPASCII, TASK); #ifdef WIN32 //Slave slave4("COM3", 256000, kSerParityNone, kSerStopbits1, RTU, TASK); #else Slave slave4("/dev/ttyS9", 115200, kSerParityNone, kSerStopbits1, YMB_PROT_RTU, YMB_THR_POLL); #endif TSlave<SNet, TcpListener, Player> slave5(5505, TASK); TSlave<SRtu, TcpListener, Player> slave6(5506, TASK); TSlave<SAscii, TcpListener, Player> slave7(5507, TASK); Slave slave8(5508, UDP, TASK); slave1.SetPlayer(std::make_shared<YModbus::Player>()); slave2.SetPlayer(std::make_shared<YModbus::Player>()); slave3.SetPlayer(std::make_shared<YModbus::Player>()); //slave4.SetPlayer(std::make_shared<YModbus::Player>()); slave5.SetPlayer(std::make_shared<YModbus::Player>()); slave6.SetPlayer(std::make_shared<YModbus::Player>()); slave7.SetPlayer(std::make_shared<YModbus::Player>()); slave8.SetPlayer(std::make_shared<YModbus::Player>()); slave1.Startup(); slave2.Startup(); slave3.Startup(); //slave4.Startup(); slave5.Startup(); slave6.Startup(); slave7.Startup(); slave8.Startup(); Task::LetUsGo(); while (1); return 0; }
3,571
C++
.cpp
129
24.224806
96
0.664219
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,601
test_ymaster.cpp
lyqdy_ymodbus/ymodbus/tests/test_ymaster.cpp
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #include "ymblog.h" #include "ymod/ymbutils.h" #include "ymod/ymbtask.h" #include "ymod/master/ymbmaster.h" #include "ymod/master/ymaster.h" #include <iomanip> void LOG_Init(char *prog) {} void LOG_Fini(void) {} using namespace YModbus; template<typename T> class A { public: void f(uint8_t sid, uint16_t startreg, T val) { YMB_DEBUG("AsyncRead val = %x(%u)\n", val, val); } }; using namespace std::placeholders; int main(int argc, char *argv[]) { LOG_Init(argv[0]); LOG(INFO) << "test master enter" << std::endl; Master tcpmaster("127.0.0.1", 5502, TCP, TASK); TMaster<MRtu, TcpConnect> rtumaster("127.0.0.1", 5506, TASK); TMaster<MRtu, TcpConnect> rtu2master("127.0.0.1", 5503, TASK); TMaster<MNet, UdpConnect> udpmaster("127.0.0.1", 5508, TASK); rtumaster.SetReadTimeout(1000); tcpmaster.SetReadTimeout(500); udpmaster.SetReadTimeout(500); Task::LetUsGo(); uint8_t buf[BUFSIZ]; int len; for (int i = 0; i < 500; i++) { std::shared_ptr<A<uint16_t>> a = std::make_shared<A<uint16_t>>(); udpmaster.AsyncRead<uint16_t>(1, 1, std::bind(&A<uint16_t>::f, a, _1, _2, _3)); std::shared_ptr<A<uint32_t>> b = std::make_shared<A<uint32_t>>(); udpmaster.AsyncRead<uint32_t>(1, 1, std::bind(&A<uint32_t>::f, b, _1, _2, _3)); } udpmaster.WaitAsynReader(); udpmaster.SetByteOrder(BOR_1234); { uint16_t val = 0; udpmaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_1234= %x(%u)\n", val, val); } { uint32_t val = 0; udpmaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_1234= %x(%lu)\n", val, val); } { uint64_t val = 0; udpmaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_1234= %llx(%llu)\n", val, val); } rtumaster.SetByteOrder(BOR_1234); { uint16_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_1234= %x(%u)\n", val, val); } { uint32_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_1234= %x(%lu)\n", val, val); } { uint64_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_1234= %llx(%llu)\n", val, val); } rtumaster.SetByteOrder(BOR_3412); { uint16_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_3412= %x(%u)\n", val, val); } { uint32_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_3412= %x(%lu)\n", val, val); } { uint64_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_3412= %llx(%llu)\n", val, val); } rtumaster.SetByteOrder(BOR_4321); { uint16_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_4321= %x(%u)\n", val, val); } { uint32_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_4321= %x(%lu)\n", val, val); } { uint64_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_4321= %llx(%llu)\n", val, val); } rtumaster.SetByteOrder(BOR_2143); { uint16_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_2143= %x(%u)\n", val, val); } { uint32_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_2143= %x(%lu)\n", val, val); } { uint64_t val = 0; rtumaster.ReadValue(1, 1, val); YMB_DEBUG("ReadValue BOR_2143= %llx(%llu)\n", val, val); } exit(0); len = tcpmaster.ReadHoldingRegisters(1, 1, 1, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP(buf, len, "tcpReadHoldingRegisters: "); } YMB_ASSERT(len == 2); uint32_t rcount = 0; uint32_t ecount = 0; do { rcount++; len = tcpmaster.ReadHoldingRegisters(1, 1, 10, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP0(buf, len, "tcpReadHoldingRegisters: "); } else { ecount++; } YMB_DEBUG("REQ:%u, ERR:%u\n", rcount, ecount); } while (rcount < 10000); len = tcpmaster.ReadHoldingRegisters(1, 1, 100, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP(buf, len, "tcpReadHoldingRegisters: "); } YMB_ASSERT(len == 200); len = rtumaster.ReadHoldingRegisters(1, 1, 1, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP(buf, len, "rtuReadHoldingRegisters: "); } YMB_ASSERT(len == 2); len = rtumaster.ReadHoldingRegisters(1, 1, 10, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP(buf, len, "rtuReadHoldingRegisters: "); } YMB_ASSERT(len == 20); rcount = 0; ecount = 0; do { rcount++; len = rtumaster.ReadHoldingRegisters(1, 1, 10, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP0(buf, len, "tcpReadHoldingRegisters: "); } else { ecount++; } YMB_DEBUG("REQ:%u, ERR:%u\n", rcount, ecount); } while (rcount < 10000); len = rtumaster.ReadHoldingRegisters(1, 1, 100, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP(buf, len, "rtuReadHoldingRegisters: "); } YMB_ASSERT(len == 200); len = rtu2master.ReadHoldingRegisters(1, 1, 1, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP(buf, len, "rtuReadHoldingRegisters: "); } YMB_ASSERT(len == 2); rcount = 0; ecount = 0; do { rcount++; len = rtu2master.ReadHoldingRegisters(1, 1, 10, buf, sizeof(buf)); if (len > 0) { YMB_HEXDUMP0(buf, len, "tcpReadHoldingRegisters: "); } else { ecount++; } YMB_DEBUG("REQ:%u, ERR:%u\n", rcount, ecount); } while (rcount < 10000); Task::LetUsDone(); LOG(INFO) << "test master quit" << std::endl; LOG_Fini(); return 0; }
5,567
C++
.cpp
201
23.870647
82
0.627611
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,602
ymbmonitor.h
lyqdy_ymodbus/ymodbus/ymod/ymbmonitor.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.08.11 */ #ifndef __YMODBUS_YMBMONITOR_H__ #define __YMODBUS_YMBMONITOR_H__ #include <cstdint> #include <string> namespace YModbus { //数据为大端字节序 class IMonitor { public: virtual ~IMonitor() {} virtual void SendPacket(const std::string &desc, const uint8_t *val, int len) = 0; virtual void RecvPacket(const std::string &desc, const uint8_t *val, int len) = 0; }; } //namespace YModbus #endif //__YMODBUS_YMBMONITOR_H__
524
C++
.h
20
23.8
83
0.732777
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,603
ymbrtu.h
lyqdy_ymodbus/ymodbus/ymod/ymbrtu.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBRTU_H__ #define __YMODBUS_YMBRTU_H__ #include "ymod/ymbprot.h" #include "ymod/ymbdefs.h" #include "ymod/ymbcrc.h" #include "ymblog.h" namespace YModbus { template<typename TBase> class Rtu : public TBase { public: static const char *protname; int GetMasterDataOffset(uint8_t fun) { return Protocol::GetMasterDataOffset(fun); } int GetSlaveDataOffset(uint8_t fun) { return Protocol::GetSlaveDataOffset(fun); } size_t MakeMasterMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { size_t msglen = Protocol::MakeMasterMsg(buf, bufsiz - 2, inf); YMB_ASSERT(bufsiz >= static_cast<size_t>(msglen + 2)); uint16_t crc = Crc16(buf, static_cast<uint16_t>(msglen)); buf[msglen + 0] = static_cast<uint8_t>(crc & 0xff); buf[msglen + 1] = static_cast<uint8_t>(crc >> 8); return msglen + 2; } size_t MakeSlaveMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { size_t msglen = Protocol::MakeSlaveMsg(buf, bufsiz - 2, inf); YMB_ASSERT(bufsiz >= msglen + 2); uint16_t crc = Crc16(buf, static_cast<uint16_t>(msglen)); buf[msglen + 0] = static_cast<uint8_t>(crc & 0xff); buf[msglen + 1] = static_cast<uint8_t>(crc >> 8); return msglen + 2; } //Exact message int VerifyMasterMsg(uint8_t *msg, size_t msglen) { if (msglen < kMinRtuMsgLen) return static_cast<int>(kMinRtuMsgLen - msglen); int expect = Protocol::VerifyMasterMsg(msg, msglen - 2); if (expect != 0) return expect; uint16_t crc = Crc16(msg, static_cast<uint16_t>(msglen - 2)); return crc == ((msg[msglen - 1] << 8) | msg[msglen - 2]) ? 0 : -EVAL; } int VerifySlaveMsg(uint8_t *msg, size_t msglen) { if (msglen < kMinRtuMsgLen) return static_cast<int>(kMinRtuMsgLen - msglen); int expect = Protocol::VerifySlaveMsg(msg, msglen - 2); if (expect != 0) return expect; uint16_t crc = Crc16(msg, static_cast<uint16_t>(msglen - 2)); return crc == ((msg[msglen - 1] << 8) | msg[msglen - 2]) ? 0 : -EVAL; } //Used by slave int ParseMasterMsg(uint8_t *msg, size_t msglen, MsgInf &inf) { YMB_ASSERT(msglen >= kMinRtuMsgLen); return Protocol::ParseMasterMsg(msg, msglen - 2, inf); } //Used by master int ParseSlaveMsg(uint8_t *msg, size_t msglen, MsgInf &inf) { YMB_ASSERT(msglen >= kMinRtuMsgLen); return Protocol::ParseSlaveMsg(msg, msglen - 2, inf); } private: const size_t kMinRtuMsgLen = 5; }; template<typename TBase> const char* Rtu<TBase>::protname = "RTU"; } //namespace YModbus #endif // ! __YMODBUS_YMBRTU_H__
2,691
C++
.h
83
28.53012
72
0.671507
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,604
ymbplayer.h
lyqdy_ymodbus/ymodbus/ymod/ymbplayer.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBPLAYER_H__ #define __YMODBUS_YMBPLAYER_H__ #include <cstdint> #include <cstddef> namespace YModbus { class IPlayer { public: //return: >= 0, bytes of data to return; //return: < 0, errorcode of exception //buf: data value, net order virtual int ReadCoils(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) = 0; virtual int ReadDiscreteInputs(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) = 0; virtual int ReadInputRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) = 0; virtual int ReadHoldingRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz) = 0; //return: = 0, OK; //return: < 0, errorcode of exception //values: data value, net order virtual int WriteSingleCoil(uint8_t sid, uint16_t reg, bool onoff) = 0; virtual int WriteCoils(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *bits, uint8_t wbytes) = 0; virtual int WriteSingleRegister(uint8_t sid, uint16_t reg, uint16_t value) = 0; virtual int WriteRegisters(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *values, uint8_t wbytes) = 0; virtual int MaskWriteRegisters(uint8_t sid, uint16_t reg, uint16_t andmask, uint16_t ormask) = 0; //return: >= 0, bytes of data to return //return: < 0, errorcode of exception //values/buf: data value, net order virtual int WriteReadRegisters(uint8_t sid, uint16_t wreg, uint16_t wnum, const uint8_t *values, uint8_t wbytes, uint16_t rreg, uint16_t rnum, uint8_t *buf, size_t bufsiz) = 0; //return: >= 0, OK //return: < 0, errorcode of exception virtual int ReportSlaveId(uint8_t maxsid, uint8_t *buf, size_t bufsiz) = 0; virtual ~IPlayer() {} }; } //namespace YModbus #endif // !__YMODBUS_YMBPLAYER_H__
1,939
C++
.h
49
36.244898
77
0.700214
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,605
ymbascii.h
lyqdy_ymodbus/ymodbus/ymod/ymbascii.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBASCII_H__ #define __YMODBUS_YMBASCII_H__ #include "ymod/ymbprot.h" #include "ymod/ymbdefs.h" #include "ymblog.h" #include <memory> #include <algorithm> #include <numeric> namespace YModbus { template<typename TBase> class Ascii : public TBase { public: static const char *protname; int GetMasterDataOffset(uint8_t fun) { return static_cast<int>(Protocol::GetMasterDataOffset(fun) + kRtuBufOff); } int GetSlaveDataOffset(uint8_t fun) { return static_cast<int>(Protocol::GetSlaveDataOffset(fun) + kRtuBufOff); } size_t MakeMasterMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { YMB_ASSERT(bufsiz >= kMaxAsciiMsgLen); uint8_t *pbuf = buf; uint8_t *prtu = buf + kRtuBufOff; size_t msglen = Protocol::MakeMasterMsg(prtu, bufsiz-kRtuBufOff, inf); uint8_t lrc = (uint8_t)(~std::accumulate(prtu, prtu + msglen, 0) + 1); *pbuf++ = ':'; //start char std::for_each(prtu, prtu + msglen, [&pbuf](uint8_t d) { *pbuf = static_cast<uint8_t>(d >> 4); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; *pbuf = static_cast<uint8_t>(d & 0xf); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; }); *pbuf = static_cast<uint8_t>(lrc >> 4); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; *pbuf = static_cast<uint8_t>(lrc & 0xf); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; *pbuf++ = '\r'; *pbuf++ = '\n'; msglen = static_cast<size_t>(pbuf - buf); YMB_ASSERT(bufsiz >= msglen); return msglen; } size_t MakeSlaveMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { YMB_ASSERT(bufsiz >= kMaxAsciiMsgLen); uint8_t *pbuf = buf; uint8_t *prtu = buf + kRtuBufOff; size_t msglen = Protocol::MakeSlaveMsg(prtu, bufsiz - kRtuBufOff, inf); uint8_t lrc = (uint8_t)(~std::accumulate(prtu, prtu + msglen, 0) + 1); *pbuf++ = ':'; //start char std::for_each(prtu, prtu + msglen, [&pbuf](uint8_t d) { *pbuf = static_cast<uint8_t>(d >> 4); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; *pbuf = static_cast<uint8_t>(d & 0xf); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; }); *pbuf = static_cast<uint8_t>(lrc >> 4); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; *pbuf = static_cast<uint8_t>(lrc & 0xf); *pbuf += *pbuf <= 9 ? '0' : 'A' - 0xA; pbuf++; *pbuf++ = '\r'; *pbuf++ = '\n'; msglen = static_cast<size_t>(pbuf - buf); YMB_ASSERT(bufsiz >= msglen); return msglen; } //Exact message int VerifyMasterMsg(uint8_t *msg, size_t msglen) { if (msglen < kMinAsciiMsgLen) //:-id-fun-xxx-lrc-\r\n return static_cast<int>(kMinAsciiMsgLen - msglen); //expect data if (msg[0] != ':') return -EBADMSG; if (msglen > kMaxAsciiMsgLen) return -EBADMSG; if (msg[msglen - 2] != '\r') return 2; //expect '\r\n' if (msg[msglen - 1] != '\n') return -EBADMSG; //must be '\n' return EOK; } int VerifySlaveMsg(uint8_t *msg, size_t msglen) { if (msglen < kMinAsciiMsgLen) //:-id-fun-err-lrc-\r\n return static_cast<int>(kMinAsciiMsgLen - msglen); //expect data if (msg[0] != ':') return -EBADMSG; if (msglen > kMaxAsciiMsgLen) return -EBADMSG; if (msg[msglen - 2] != '\r') return 2; //expect '\r\n' if (msg[msglen - 1] != '\n') return -EBADMSG; //must be '\n' return EOK; } //Used by slave int ParseMasterMsg(uint8_t *msg, size_t msglen, MsgInf &inf) { //Transform to base format msg uint8_t *prtu = msg; size_t i; for (i = 1; i < msglen - 4; i += 2) { *prtu = msg[i] <= '9' ? msg[i] - '0' : msg[i] - 'A' + 0xA; *prtu <<= 4; *prtu |= msg[i+1] <= '9' ? msg[i+1] - '0' : msg[i+1] - 'A' + 0xA; ++prtu; } //msg has transformed base format size_t rtulen = static_cast<size_t>(prtu - msg); uint8_t lrc = (uint8_t)(~std::accumulate(msg, msg + rtulen, 0) + 1); lrc -= (msg[i] <= '9' ? msg[i] - '0' : msg[i] - 'A' + 0xA) << 4; lrc -= msg[i + 1] <= '9' ? msg[i + 1] - '0' : msg[i + 1] - 'A' + 0xA; if (lrc == 0 && Protocol::VerifyMasterMsg(msg, rtulen) == EOK) return Protocol::ParseMasterMsg(msg, rtulen, inf); return -EBADMSG; } //Used by master int ParseSlaveMsg(uint8_t *msg, size_t msglen, MsgInf &inf) { //Transform to base format msg uint8_t *prtu = msg; size_t i; for (i = 1; i < msglen - 4; i += 2) { *prtu = msg[i] <= '9' ? msg[i] - '0' : msg[i] - 'A' + 0xA; *prtu <<= 4; *prtu |= msg[i+1] <= '9' ? msg[i+1] - '0' : msg[i+1] - 'A' + 0xA; ++prtu; } //msg has transformed base format size_t rtulen = static_cast<size_t>(prtu - msg); uint8_t lrc = (uint8_t)(~std::accumulate(msg, msg + rtulen, 0) + 1); lrc -= (msg[i] <= '9' ? msg[i] - '0' : msg[i] - 'A' + 0xA) << 4; lrc -= msg[i + 1] <= '9' ? msg[i + 1] - '0' : msg[i + 1] - 'A' + 0xA; if (lrc == 0 && Protocol::VerifySlaveMsg(msg, rtulen) == EOK) return Protocol::ParseSlaveMsg(msg, rtulen, inf); return -EBADMSG; } private: const size_t kMinAsciiMsgLen = 8; const size_t kMaxAsciiMsgLen = 513; const size_t kMaxRtuMsgLen = 254; const size_t kRtuBufOff = 513 - 254 - 1; }; template<typename TBase> const char* Ascii<TBase>::protname = "ASCII"; } //namespace YModbus #endif // ! __YMODBUS_YMBASCII_H__
5,436
C++
.h
164
28.817073
76
0.579497
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,606
ymbtask.h
lyqdy_ymodbus/ymodbus/ymod/ymbtask.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBTASK_H__ #define __YMODBUS_YMBTASK_H__ #include <string> #include <thread> #include <condition_variable> #include <mutex> namespace YModbus { class Task { public: Task(); ~Task(); virtual void Start(void); virtual void Wait(void); //用于控制单个个体 virtual void Stop(void) { stop_ = true; } //用于全部继承本类型的对象 static void LetUsGo(void); static void LetUsDone(void); protected: bool IsRunning(void) { return running_ && !stop_; } virtual void Run(void) = 0; virtual std::string Name(void) = 0; private: virtual bool Init(void) { return true; } virtual void Fini(void) {} void task(void); static bool ShallWeGo(void); bool init_; bool stop_; //用于个体 std::thread task_; //用于全部继承本类型的对象 static volatile bool running_; static volatile bool go_; static std::mutex goMutex_; static std::condition_variable goCond_; }; } //namespace YModbus #endif // __YMODBUS_YMBTASK_H__
1,134
C++
.h
44
20.863636
53
0.697769
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,607
ymbcrc.h
lyqdy_ymodbus/ymodbus/ymod/ymbcrc.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBCRC_H__ #define __YMODBUS_YMBCRC_H__ #include <cstdint> namespace YModbus { uint16_t Crc16(uint8_t *msg, uint16_t len); } //namespace YModbus #endif // ! __YMODBUS_YMBCRC_H__
314
C++
.h
12
22.75
52
0.684211
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,608
ymbnet.h
lyqdy_ymodbus/ymodbus/ymod/ymbnet.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBNET_H__ #define __YMODBUS_YMBNET_H__ #include "ymod/ymbdefs.h" #include "ymod/ymbprot.h" #include "ymblog.h" #include <memory> namespace YModbus { template<typename TBase> class Net : public TBase { public: static const char *protname; int GetMasterDataOffset(uint8_t fun) { return Protocol::GetMasterDataOffset(fun) + kHdrSiz; } int GetSlaveDataOffset(uint8_t fun) { return Protocol::GetSlaveDataOffset(fun) + kHdrSiz; } size_t MakeMasterMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { tid_++; //tid buf[0] = static_cast<uint8_t>(tid_ >> 8); buf[1] = static_cast<uint8_t>(tid_ & 0xff); //protocol type buf[2] = buf[3] = 0; size_t msglen = Protocol::MakeMasterMsg(buf + kHdrSiz, bufsiz - kHdrSiz, inf); YMB_ASSERT(bufsiz >= msglen + kHdrSiz); //Now, we got the msg's length buf[4] = static_cast<uint8_t>((msglen) >> 8); buf[5] = static_cast<uint8_t>((msglen) & 0xff); return msglen + kHdrSiz; } size_t MakeSlaveMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) { //tid buf[0] = static_cast<uint8_t>(tid_ >> 8); buf[1] = static_cast<uint8_t>(tid_ & 0xff); //protocol type buf[2] = buf[3] = 0; size_t msglen = Protocol::MakeSlaveMsg(buf + kHdrSiz, bufsiz - kHdrSiz, inf); YMB_ASSERT(bufsiz >= msglen + kHdrSiz); //fill length field buf[4] = static_cast<uint8_t>((msglen) >> 8); buf[5] = static_cast<uint8_t>((msglen) & 0xff); return msglen + kHdrSiz; } int VerifyMasterMsg(uint8_t *msg, size_t msglen) { if (msglen >= kHdrSiz) return Protocol::VerifyMasterMsg(msg + kHdrSiz, msglen - kHdrSiz); return static_cast<int>(kHdrSiz - msglen); } int VerifySlaveMsg(uint8_t *msg, size_t msglen) { if (msglen >= kHdrSiz) return Protocol::VerifySlaveMsg(msg + kHdrSiz, msglen - kHdrSiz); return static_cast<int>(kHdrSiz - msglen); } //Used by slave int ParseMasterMsg(uint8_t *msg, size_t msglen, MsgInf &inf) { //Buffer the tid for rsp msg tid_ = (msg[0] << 8) | msg[1]; return Protocol::ParseMasterMsg(msg + kHdrSiz, msglen - kHdrSiz, inf); } //Used by master int ParseSlaveMsg(uint8_t *msg, size_t msglen, MsgInf &inf) { uint16_t tid = (msg[0] << 8) | msg[1]; if (tid_ == tid) return Protocol::ParseSlaveMsg(msg + kHdrSiz, msglen - kHdrSiz, inf); return -EBADMSG; } private: const uint8_t kHdrSiz = 6; uint16_t tid_; }; template<typename TBase> const char* Net<TBase>::protname = "NET"; } //namespace YModbus #endif // ! __YMODBUS_YMBNET_H__
2,710
C++
.h
89
26.404494
81
0.661695
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,609
ymbprot.h
lyqdy_ymodbus/ymodbus/ymod/ymbprot.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YPROTOCOL_H__ #define __YMODBUS_YPROTOCOL_H__ #include <cstdint> #include <cstddef> #include <memory> namespace YModbus { struct MsgInf { MsgInf() { } MsgInf(uint8_t i, uint8_t f, uint16_t r, uint16_t n) : id(i) , fun(f) , rreg(r) , rnum(n) , wreg(0) , wnum(0) , databuf(nullptr) , datalen(0) , pbuf(nullptr) , bufsiz(0) , err(0) { } MsgInf(uint8_t i, uint8_t f, uint16_t r, uint16_t n, uint16_t wr, uint16_t wn) : id(i) , fun(f) , rreg(r) , rnum(n) , wreg(wr) , wnum(wn) , databuf(nullptr) , datalen(0) , pbuf(nullptr) , bufsiz(0) , err(0) { } MsgInf(uint8_t i, uint8_t f, uint16_t r, uint16_t n, uint16_t wr, uint16_t wn, uint8_t *d, uint8_t l) : id(i) , fun(f) , rreg(r) , rnum(n) , wreg(wr) , wnum(wn) , databuf(d) , datalen(l) , pbuf(nullptr) , bufsiz(0) , err(0) { } uint8_t id; uint8_t fun; uint16_t rreg; uint16_t rnum; uint16_t wreg; uint16_t wnum; uint8_t *databuf; uint8_t datalen; uint8_t *pbuf; size_t bufsiz; uint8_t err; }; class IProtocol { public: //Master----------------------------------------------------------------- //direct: 1: in, request, 0: out, response virtual int GetMasterDataOffset(uint8_t fun) = 0; //Used by master virtual size_t MakeMasterMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) = 0; //Used by slave //If msg OK, return 0, else return bytes of data expected virtual int VerifyMasterMsg(uint8_t *msg, size_t msglen) = 0; //Used by slave virtual int ParseMasterMsg(uint8_t *msg, size_t msglen, MsgInf &inf) = 0; //Slave------------------------------------------------------------------ //direct: 1: in, request, 0: out, response virtual int GetSlaveDataOffset(uint8_t fun) = 0; //Used by slave virtual size_t MakeSlaveMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf) = 0; //Used by master //If msg OK, return 0, else return bytes of data expected //tid_ will be checked... virtual int VerifySlaveMsg(uint8_t *msg, size_t msglen) = 0; //Used by master virtual int ParseSlaveMsg(uint8_t *msg, size_t msglen, MsgInf &inf) = 0; ~IProtocol() {} }; class Protocol { public: //Master----------------------------------------------------------------- //direct: 1: in, request, 0: out, response static int GetMasterDataOffset(uint8_t fun); //Used by master static size_t MakeMasterMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf); //Used by slave //If msg OK, return 0, else return bytes of data expected static int VerifyMasterMsg(uint8_t *msg, size_t msglen); //Used by slave static int ParseMasterMsg(uint8_t *msg, size_t msglen, MsgInf &inf); //Slave------------------------------------------------------------------ //direct: 1: in, request, 0: out, response static int GetSlaveDataOffset(uint8_t fun); //Used by slave static size_t MakeSlaveMsg(uint8_t *buf, size_t bufsiz, MsgInf &inf); //Used by master //If msg OK, return 0, else return bytes of data expected //tid_ will be checked... static int VerifySlaveMsg(uint8_t *msg, size_t msglen); //Used by master static int ParseSlaveMsg(uint8_t *msg, size_t msglen, MsgInf &inf); }; } //namespace YModbus #endif // ! __YMODBUS_YPROTOCOL_H__
3,489
C++
.h
137
21.824818
77
0.601824
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,610
ymbstore.h
lyqdy_ymodbus/ymodbus/ymod/ymbstore.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBSTORE_H__ #define __YMODBUS_YMBSTORE_H__ #include <cstdint> namespace YModbus { //数据为大端字节序 class IStore { public: //更新缓存的寄存器数据,同时更新生命值为最大, num:寄存器数目 val:网络序 virtual void Set(uint8_t sid, uint16_t reg, const uint8_t *val, uint16_t num) = 0; //获取缓存的寄存器数据,如不存在或失效则返回失败 virtual bool Get(uint8_t sid, uint16_t reg, uint8_t *val, uint16_t num) const = 0; //保存缓存的寄存器数据,同时更新生命值为永久 virtual void Save(uint8_t sid, uint16_t reg, const uint8_t *val, uint16_t num) = 0; //强行加载,无论是否存在对应的设备,用于加载配置 virtual void Load(uint8_t sid, uint16_t reg, const uint8_t *val, uint16_t num) = 0; virtual ~IStore() {} }; } //namespace YModbus #endif //__YMODBUS_YMBSTORE_H__
1,019
C++
.h
25
29.2
85
0.705497
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,611
ymbutils.h
lyqdy_ymodbus/ymodbus/ymod/ymbutils.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBUTILS_H__ #define __YMODBUS_YMBUTILS_H__ #include "ymod/ymbdefs.h" #include "ymblog.h" #include <algorithm> namespace YModbus { inline bool IsLittleEndian(void) { static unsigned long x = 0x12345678; return *reinterpret_cast<unsigned char*>(&x) == 0x78; } template<typename T> inline void YExchangeByteOrder(T &val) { char *p = reinterpret_cast<char*>(&val); ::std::reverse(p, p + sizeof(val)); } //template<typename T> //inline void YNetToHost(T &val, eByteOrder bor) //T may be integral or float/double type, such as int, uint64_t... //If you have some custom structs defined by yourself, // you must override the function template for your own struct. //Example: // struct A { // uint16_t len; // char name[MAX_NAME_LEN]; // }; // template<> // inline void YNetToHost<A>(A &val, eByteOrder bor) // { // //Nothing to do for raw data or your custom codes. // YNetToHost(val.len, bor); // } // A a; // if (master.ReadValue(sid, startreg, a)) { // .... // } // template<typename T> inline void YNetToHost(T &val, eByteOrder bor) { if (IsLittleEndian()) { //host is little endian switch (bor) { case BOR_1234: //Big-endian //0x01020304=>{0x01,0x02,0x03,0x04}=>{0x04,0x03,0x02,0x01} YExchangeByteOrder(val); break; case BOR_3412: { //Little-endian byte swap //0x01020304=>{0x03,0x04,0x01,0x02}=>{0x04,0x03,0x02,0x01} uint16_t *p = reinterpret_cast<uint16_t*>(&val); std::for_each(p, p + sizeof(val) / 2, [](uint16_t &v) { YExchangeByteOrder(v); }); break; } case BOR_4321: //Little-endian //0x01020304=>{0x04,0x03,0x02,0x01}=>{0x04,0x03,0x02,0x01} //Nothing to do break; case BOR_2143: { // Big-endian byte swap //0x01020304=>{0x02,0x01,0x04,0x03}=>{0x04,0x03,0x02,0x01} uint16_t *p = reinterpret_cast<uint16_t*>(&val); std::reverse(p, p + sizeof(val) / 2); break; } default: YMB_ASSERT(false); break; } //switch (bor) } //host is little-endian else { //host is big-endian switch (bor) { case BOR_1234: //Big-endian //0x01020304=>{0x01,0x02,0x03,0x04}=>{0x01,0x02,0x03,0x04} //Nothing to do break; case BOR_3412: { //Little-endian byte swap //0x01020304=>{0x03,0x04,0x01,0x02}=>{0x01,0x02,0x03,0x04} uint16_t *p = reinterpret_cast<uint16_t*>(&val); std::reverse(p, p + sizeof(val) / 2); break; } case BOR_4321: //Little endian //0x01020304=>{0x04,0x03,0x02,0x01}=>{0x01,0x02,0x03,0x04} YExchangeByteOrder(val); break; case BOR_2143: { // big-endian byte swap //0x01020304=>{0x02,0x01,0x04,0x03}=>{0x01,0x02,0x03,0x04} uint16_t *p = reinterpret_cast<uint16_t*>(&val); std::for_each(p, p + sizeof(val) / 2, [](uint16_t &v) { YExchangeByteOrder(v); }); break; } default: YMB_ASSERT(false); break; } //switch (bor) } //host is big-endian } #define YHostToNet YNetToHost inline void YNetToHost(uint8_t *buf, int bufsiz, eByteOrder bor) { switch (bor) { case BOR_1234: //Big-endian //0x01020304=>{0x01,0x02,0x03,0x04}=>{0x04,0x03,0x02,0x01} ::std::reverse(buf, buf + bufsiz); break; case BOR_3412: { //Little-endian byte swap //0x01020304=>{0x03,0x04,0x01,0x02}=>{0x04,0x03,0x02,0x01} YMB_ASSERT((bufsiz % 2) == 0); for (int i = 0; i < bufsiz; i += 2) ::std::swap(buf[i], buf[i+1]); break; } case BOR_4321: //Little-endian //0x01020304=>{0x04,0x03,0x02,0x01}=>{0x04,0x03,0x02,0x01} //Nothing to do break; case BOR_2143: { // Big-endian byte swap //0x01020304=>{0x02,0x01,0x04,0x03}=>{0x04,0x03,0x02,0x01} //TODO break; } default: YMB_ASSERT(false); break; } //switch (bor) } } //namesapce YModbus #if defined(__GNUC__) && __GNUC__ < 5 //for std::make_unique #include <type_traits> #include <memory> namespace std { template<class T, class... Args> inline typename enable_if<!is_array<T>::value, unique_ptr<T>>::type make_unique(Args&&... args) { return unique_ptr<T>(new T(std::forward<Args>(args)...)); } template<class T> inline typename enable_if<is_array<T>::value && extent<T>::value == 0, unique_ptr<T>>::type make_unique(size_t size) { typedef typename remove_extent<T>::type U; return unique_ptr<T>(new U[size]()); } template<class T, class... Args> typename enable_if<extent<T>::value != 0, void>::type make_unique(Args&&...) = delete; } //namespace std #else # include <memory> #endif namespace YModbus { //for function argue type template<int index, typename FuntionType> struct ArgTypeAt; template<typename ResultType, typename FirstArgType, typename... ArgsType> struct ArgTypeAt<0, ResultType(FirstArgType, ArgsType...)> { using type = FirstArgType; }; template<int index, typename ResultType, typename FirstArgType, typename... ArgsType> struct ArgTypeAt<index, ResultType(FirstArgType, ArgsType...)> { using type = typename ArgTypeAt<index - 1, ResultType(ArgsType...)>::type; }; } //namespace YModbus #endif //__YMODBUS_YMBUTILS_H__
5,202
C++
.h
167
27.520958
86
0.660237
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,612
ymbdefs.h
lyqdy_ymodbus/ymodbus/ymod/ymbdefs.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBDEFS_H__ #define __YMODBUS_YMBDEFS_H__ #include <cstdint> #include <cstddef> #define kSerParityNone 'N' /*!< No parity. */ #define kSerParityOdd 'O' /*!< Odd parity. */ #define kSerParityEven 'E' /*!< Even parity. */ #define kSerStopbits1 10 // NESTOPBIT #define kSerStopbits15 15 // ONE5STOPBITS #define kSerStopbits2 20 // TWOSTOPBITS #define kMaxRegNum 125 #define kAnySlaveId 0 #define kBroadcastId 0 namespace YModbus { typedef enum { RTU, ASCII, TCP, TCPRTU, TCPASCII, UDP, UDPRTU, UDPASCII, } eProtocol; #define PROTNAME(prot) \ ((prot == RTU ? "RTU" : \ (prot == ASCII ? "ASCII" : \ (prot == TCP ? "TCP" : \ (prot == TCPRTU ? "TCPRTU" : \ (prot == TCPASCII ? "TCPASCII" : \ (prot == UDP ? "UDP" : \ (prot == UDPRTU ? "UDPRTU" : \ (prot == UDPASCII ? "UDPASCII" : "ERROR"))))))))) typedef enum { POLL = 0, TASK = 1, } eThreadMode; typedef enum { SLAVE = 0, MASTER = 1, } eMsgDirect; typedef enum { EOK = 0, EFUN, EREG, EVAL, EDEV, EACK, EYBUSY, } eModbusError; typedef enum { BOR_1234, //0x01020304=>{ 0x01, 0x02, 0x03, 0x04 } big-endian BOR_3412, //0x01020304=>{ 0x03, 0x04, 0x01, 0x02 } little-endian byte swap BOR_4321, //0x01020304=>{ 0x04, 0x03, 0x02, 0x01 } little-endian BOR_2143, //0x01020304=>{ 0x02, 0x01, 0x04, 0x03 } big-endian byte swap } eByteOrder; typedef enum { SM_OriginalOctetStream, SM_XchangedByteStream } eStringMode; const uint8_t kFunReadCoils = 0x01; const uint8_t kFunReadDiscreteInputs = 0x02; const uint8_t kFunReadHoldingRegisters = 0x03; const uint8_t kFunReadInputRegisters = 0x04; const uint8_t kFunWriteSingleCoil = 0x05; const uint8_t kFunWriteSingleRegister = 0x06; const uint8_t kFunWriteMultiCoils = 0x0F; const uint8_t kFunWriteMultiRegisters = 0x10; const uint8_t kFunMaskWriteRegister = 0x16; const uint8_t kFunWriteAndReadRegisters = 0x17; #define INVALID_REG 0xffff #define INVALID_NUM 0xffff } //namespace YModbus #endif //__YMODBUS_YMBDEFS_H__
2,220
C++
.h
79
24.810127
76
0.677958
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,613
ymbmaster.h
lyqdy_ymodbus/ymodbus/ymod/master/ymbmaster.h
/** * ymodbus * Copyright © 2019-2019 liuyongqing<lyqdy1@163.com> * v1.0.1 2019.05.04 */ #ifndef __YMODBUS_YMBMASTER_H__ #define __YMODBUS_YMBMASTER_H__ #include "ymod/ymbdefs.h" #include "ymod/ymbstore.h" #include "ymod/ymbmonitor.h" #include "ymod/ymbplayer.h" #include "ymod/ymbutils.h" #include <string> #include <vector> #include <memory> namespace YModbus { class Master : public IPlayer { public: Master(const std::string &ip, uint16_t port, eProtocol type, eThreadMode thrm); Master(const std::string &com, uint32_t baudrate, char parity, uint8_t stopbits, eProtocol type, eThreadMode thrm); Master() = delete; Master(const Master&) = default; Master &operator = (const Master &t) = default; Master(Master &&t) = default; Master &operator = (Master &&t) = default; ~Master(void); void SetMonitor(std::shared_ptr<IMonitor> monitor); std::shared_ptr<IMonitor> GetMonitor(void) const; void SetStore(std::shared_ptr<IStore> store); std::shared_ptr<IStore> GetStore(void) const; //reties: retry count void SetRetries(uint32_t retries); uint32_t GetRetries(void) const; //rto: ms void SetReadTimeout(long rdto); long GetReadTimeout(void) const; //错误信息,线程相关,每个线程独立 int GetLastError(void) const; std::string GetErrorString(int err) const; //检查连接状态,如未连接尝试连接一次 bool CheckConnect(void); //异步抓取操作,不需返回读取的数据,也不需等待执行完成 //返回的数据通过过SetStore的对象处理 void PullCoils(uint8_t sid, uint16_t reg, uint16_t num); void PullDiscreteInputs(uint8_t sid, uint16_t reg, uint16_t num); void PullHoldingRegisters(uint8_t sid, uint16_t reg, uint16_t num); void PullInputRegisters(uint8_t sid, uint16_t reg, uint16_t num); //IPlayer================================================================ //return: >= 0, bytes of data to return; //return: < 0, errorcode of exception //buf: data value, net order virtual int ReadCoils(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz); virtual int ReadDiscreteInputs(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz); virtual int ReadInputRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz); virtual int ReadHoldingRegisters(uint8_t sid, uint16_t reg, uint16_t num, uint8_t *buf, size_t bufsiz); //return: = 0, OK; //return: < 0, errorcode of exception //values: data value, net order virtual int WriteSingleCoil(uint8_t sid, uint16_t reg, bool onoff); virtual int WriteCoils(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *bits, uint8_t wbytes); virtual int WriteSingleRegister(uint8_t sid, uint16_t reg, uint16_t value); virtual int WriteRegisters(uint8_t sid, uint16_t reg, uint16_t num, const uint8_t *values, uint8_t wbytes); virtual int MaskWriteRegisters(uint8_t sid, uint16_t reg, uint16_t andmask, uint16_t ormask); //return: >= 0, bytes of data to return //return: < 0, errorcode of exception //values/buf: data value, net order virtual int WriteReadRegisters(uint8_t sid, uint16_t wreg, uint16_t wnum, const uint8_t *values, uint8_t wbytes, uint16_t rreg, uint16_t rnum, uint8_t *buf, size_t bufsiz); //return: >= 0, OK //return: < 0, errorcode of exception virtual int ReportSlaveId(uint8_t maxsid, uint8_t *buf, size_t bufsiz); private: struct Impl; std::shared_ptr<Impl> impl_; }; } //namespace YModbus #endif //__YMODBUS_YMBMASTER_H__
3,602
C++
.h
89
35.41573
75
0.710027
lyqdy/ymodbus
34
39
2
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false