id
int64
0
755k
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
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 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
20,460
LeftRightNav.h
LMMS_lmms/include/LeftRightNav.h
/* * LeftRightNav.h - side-by-side left-facing and right-facing arrows for navigation (looks like < > ) * * Copyright (c) 2015 Colin Wallace <wallacoloo/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_LEFT_RIGHT_NAV_H #define LMMS_GUI_LEFT_RIGHT_NAV_H #include "PixmapButton.h" namespace lmms::gui { class LeftRightNav : public QWidget { Q_OBJECT public: LeftRightNav(QWidget *parent=nullptr); PixmapButton* getLeftBtn(); PixmapButton* getRightBtn(); void setShortcuts(const QKeySequence &leftShortcut=Qt::Key_Minus, const QKeySequence &rightShortcut=Qt::Key_Plus); signals: void onNavLeft(); void onNavRight(); private: QHBoxLayout m_layout; PixmapButton m_leftBtn; PixmapButton m_rightBtn; }; } // namespace lmms::gui #endif // LMMS_GUI_LEFT_RIGHT_NAV_H
1,554
C++
.h
46
31.913043
115
0.765333
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
20,461
PeakIndicator.h
LMMS_lmms/include/PeakIndicator.h
/* * PeakIndicator.h - Peak indicator widget * * Copyright (c) 2024- Michael Gregorius * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_PEAKINDICATOR_H #define LMMS_GUI_PEAKINDICATOR_H #include "lmms_export.h" #include <QLabel> namespace lmms::gui { class LMMS_EXPORT PeakIndicator : public QLabel { Q_OBJECT public: PeakIndicator(QWidget* parent); void resetPeakToMinusInf(); public slots: void updatePeak(float peak); protected: void mousePressEvent(QMouseEvent* e) override; private: void updatePeakDisplay(); private: float m_peak; } ; } // namespace lmms::gui #endif // LMMS_GUI_PEAKINDICATOR_H
1,387
C++
.h
46
28.195652
70
0.767898
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,462
VstSyncData.h
LMMS_lmms/include/VstSyncData.h
/* * VstSyncData.h - type declarations needed for VST to lmms host sync * * Copyright (c) 2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * Copyright (c) 2013 Mike Choi <rdavidian71/at/gmail/dot/com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_VST_SYNC_DATA_H #define LMMS_VST_SYNC_DATA_H namespace lmms { // VST sync frequency (in ms), how often will be VST plugin synced // keep it power of two if possible (not used by now) //#define VST_SNC_TIMER 1 // When defined, latency should be subtracted from song PPQ position //#define VST_SNC_LATENCY struct VstSyncData { double ppqPos; int timeSigNumer; int timeSigDenom; bool isPlaying; bool isCycle; float cycleStart; float cycleEnd; bool m_playbackJumped; int m_bufferSize; int m_sampleRate; int m_bpm; #ifdef VST_SNC_LATENCY float m_latency; #endif } ; } // namespace lmms #endif // LMMS_VST_SYNC_DATA_H
1,655
C++
.h
52
29.923077
72
0.761157
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,463
SweepOscillator.h
LMMS_lmms/include/SweepOscillator.h
/* * SweepOscillator.h - sweeping oscillator * * Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_SWEEP_OSCILLATOR_H #define LMMS_SWEEP_OSCILLATOR_H #include "Oscillator.h" #include "DspEffectLibrary.h" namespace lmms { template<class FX = DspEffectLibrary::StereoBypass> class SweepOscillator { public: SweepOscillator( const FX & _fx = FX() ) : m_phase( 0.0f ), m_FX( _fx ) { } virtual ~SweepOscillator() = default; void update( SampleFrame* buf, const fpp_t frames, const float freq1, const float freq2, const float sampleRate ) { const float df = freq2 - freq1; for( fpp_t frame = 0; frame < frames; ++frame ) { const sample_t s = Oscillator::sinSample( m_phase ); buf[frame][0] = s; buf[frame][1] = s; m_FX.nextSample( buf[frame][0], buf[frame][1] ); m_phase += ( freq1 + ( frame * df / frames ) ) / sampleRate; } } private: float m_phase; FX m_FX; // inline sample_t getSample( const float _sample ); // inline void recalcPhase(); } ; } // namespace lmms #endif // LMMS_SWEEP_OSCILLATOR_H
1,880
C++
.h
59
29.661017
114
0.722345
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
20,464
ClipView.h
LMMS_lmms/include/ClipView.h
/* * ClipView.h - declaration of ClipView class * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_CLIP_VIEW_H #define LMMS_GUI_CLIP_VIEW_H #include <optional> #include <QVector> #include "ModelView.h" #include "Rubberband.h" #include "Clip.h" class QMenu; class QContextMenuEvent; namespace lmms { class DataFile; class Clip; namespace gui { class TextFloat; class TrackView; class ClipView : public selectableObject, public ModelView { Q_OBJECT // theming qproperties Q_PROPERTY( QColor mutedColor READ mutedColor WRITE setMutedColor ) Q_PROPERTY( QColor mutedBackgroundColor READ mutedBackgroundColor WRITE setMutedBackgroundColor ) Q_PROPERTY( QColor selectedColor READ selectedColor WRITE setSelectedColor ) Q_PROPERTY( QColor textColor READ textColor WRITE setTextColor ) Q_PROPERTY( QColor textBackgroundColor READ textBackgroundColor WRITE setTextBackgroundColor ) Q_PROPERTY( QColor textShadowColor READ textShadowColor WRITE setTextShadowColor ) Q_PROPERTY( QColor patternClipBackground READ patternClipBackground WRITE setPatternClipBackground ) Q_PROPERTY( bool gradient READ gradient WRITE setGradient ) // We have to use a QSize here because using QPoint isn't supported. // width -> x, height -> y Q_PROPERTY( QSize mouseHotspotHand MEMBER m_mouseHotspotHand ) Q_PROPERTY( QSize mouseHotspotKnife MEMBER m_mouseHotspotKnife ) public: const static int BORDER_WIDTH = 2; ClipView( Clip * clip, TrackView * tv ); ~ClipView() override; bool fixedClips(); inline Clip * getClip() { return m_clip; } inline TrackView * getTrackView() { return m_trackView; } // qproperty access func QColor mutedColor() const; QColor mutedBackgroundColor() const; QColor selectedColor() const; QColor textColor() const; QColor textBackgroundColor() const; QColor textShadowColor() const; QColor patternClipBackground() const; bool gradient() const; void setMutedColor( const QColor & c ); void setMutedBackgroundColor( const QColor & c ); void setSelectedColor( const QColor & c ); void setTextColor( const QColor & c ); void setTextBackgroundColor( const QColor & c ); void setTextShadowColor( const QColor & c ); void setPatternClipBackground(const QColor& c); void setGradient( const bool & b ); // access needsUpdate member variable bool needsUpdate(); void setNeedsUpdate( bool b ); // Method to get a QVector of Clips to be affected by a context menu action QVector<ClipView *> getClickedClips(); // Methods to remove, copy, cut, paste and mute a QVector of Clip views void copy( QVector<ClipView *> clipvs ); void cut( QVector<ClipView *> clipvs ); void paste(); // remove and toggleMute are static because they don't depend // being called from a particular Clip view, but can be called anywhere as long // as a valid Clip view list is given, while copy/cut require an instance for // some metadata to be written to the clipboard. static void remove( QVector<ClipView *> clipvs ); static void toggleMute( QVector<ClipView *> clipvs ); static void mergeClips(QVector<ClipView*> clipvs); // Returns true if selection can be merged and false if not static bool canMergeSelection(QVector<ClipView*> clipvs); QColor getColorForDisplay( QColor ); void inline setMarkerPos(int x) { m_markerPos = x; } void inline setMarkerEnabled(bool e) { m_marker = e; } public slots: virtual bool close(); void remove(); void update() override; void selectColor(); void randomizeColor(); void resetColor(); protected: enum class ContextMenuAction { Remove, Cut, Copy, Paste, Mute, Merge }; TrackView * m_trackView; TimePos m_initialClipPos; TimePos m_initialClipEnd; bool m_marker = false; int m_markerPos = 0; virtual void constructContextMenu( QMenu * ) { } void contextMenuEvent( QContextMenuEvent * cme ) override; void contextMenuAction( ContextMenuAction action ); void dragEnterEvent( QDragEnterEvent * dee ) override; void dropEvent( QDropEvent * de ) override; void mousePressEvent( QMouseEvent * me ) override; void mouseMoveEvent( QMouseEvent * me ) override; void mouseReleaseEvent( QMouseEvent * me ) override; void resizeEvent( QResizeEvent * re ) override { m_needsUpdate = true; selectableObject::resizeEvent( re ); } bool unquantizedModHeld( QMouseEvent * me ); TimePos quantizeSplitPos( TimePos, bool shiftMode ); float pixelsPerBar(); DataFile createClipDataFiles(const QVector<ClipView *> & clips) const; virtual void paintTextLabel(QString const & text, QPainter & painter); auto hasCustomColor() const -> bool; protected slots: void updateLength(); void updatePosition(); private: enum class Action { None, Move, MoveSelection, Resize, ResizeLeft, Split, CopySelection, ToggleSelected } ; static TextFloat * s_textFloat; Clip * m_clip; Action m_action; QPoint m_initialMousePos; QPoint m_initialMouseGlobalPos; QVector<TimePos> m_initialOffsets; TextFloat * m_hint; // qproperty fields QColor m_mutedColor; QColor m_mutedBackgroundColor; QColor m_selectedColor; QColor m_textColor; QColor m_textBackgroundColor; QColor m_textShadowColor; QColor m_patternClipBackground; bool m_gradient; QSize m_mouseHotspotHand; // QSize must be used because QPoint QSize m_mouseHotspotKnife; // isn't supported by property system QCursor m_cursorHand; QCursor m_cursorKnife; bool m_cursorSetYet; bool m_needsUpdate; inline void setInitialPos( QPoint pos ) { m_initialMousePos = pos; m_initialMouseGlobalPos = mapToGlobal( pos ); m_initialClipPos = m_clip->startPosition(); m_initialClipEnd = m_initialClipPos + m_clip->length(); } void setInitialOffsets(); bool mouseMovedDistance( QMouseEvent * me, int distance ); TimePos draggedClipPos( QMouseEvent * me ); int knifeMarkerPos( QMouseEvent * me ); void setColor(const std::optional<QColor>& color); //! Return true iff the clip could be split. Currently only implemented for samples virtual bool splitClip( const TimePos pos ){ return false; }; void updateCursor(QMouseEvent * me); } ; } // namespace gui } // namespace lmms #endif // LMMS_GUI_CLIP_VIEW_H
6,962
C++
.h
206
31.592233
101
0.777479
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,465
volume.h
LMMS_lmms/include/volume.h
/* * volume.h - declaration of some constants and types, concerning the volume * of a note * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_VOLUME_H #define LMMS_VOLUME_H #include "lmms_basics.h" namespace lmms { constexpr volume_t MinVolume = 0; constexpr volume_t MaxVolume = 200; constexpr volume_t DefaultVolume = 100; struct StereoVolumeVector { float vol[2]; }; } // namespace lmms #endif // LMMS_VOLUME_H
1,273
C++
.h
38
31.657895
77
0.753056
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,466
FileDialog.h
LMMS_lmms/include/FileDialog.h
/* * FileDialog.h - declaration of class FileDialog * * Copyright (c) 2014 Lukas W <lukaswhl/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_FILE_DIALOG_H #define LMMS_GUI_FILE_DIALOG_H #include <QFileDialog> #include "lmms_export.h" namespace lmms::gui { class LMMS_EXPORT FileDialog : public QFileDialog { Q_OBJECT public: explicit FileDialog( QWidget *parent = 0, const QString &caption = QString(), const QString &directory = QString(), const QString &filter = QString() ); static QString getExistingDirectory(QWidget *parent, const QString &caption, const QString &directory, QFileDialog::Options options = QFileDialog::ShowDirsOnly); static QString getOpenFileName(QWidget *parent = 0, const QString &caption = QString(), const QString &directory = QString(), const QString &filter = QString(), QString *selectedFilter = 0); void clearSelection(); }; } // namespace lmms::gui #endif // LMMS_GUI_FILE_DIALOG_H
1,791
C++
.h
49
33.142857
78
0.72806
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,467
AudioAlsa.h
LMMS_lmms/include/AudioAlsa.h
/* * AudioAlsa.h - device-class that implements ALSA-PCM-output * * Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_AUDIO_ALSA_H #define LMMS_AUDIO_ALSA_H #include "lmmsconfig.h" #ifdef LMMS_HAVE_ALSA // older ALSA-versions might require this #define ALSA_PCM_NEW_HW_PARAMS_API #include <alsa/asoundlib.h> #include <QThread> #include "AudioDevice.h" namespace lmms { class AudioAlsa : public QThread, public AudioDevice { Q_OBJECT public: /** * @brief Contains the relevant information about available ALSA devices */ class DeviceInfo { public: DeviceInfo(QString const & deviceName, QString const & deviceDescription) : m_deviceName(deviceName), m_deviceDescription(deviceDescription) {} ~DeviceInfo() = default; QString const & getDeviceName() const { return m_deviceName; } QString const & getDeviceDescription() const { return m_deviceDescription; } private: QString m_deviceName; QString m_deviceDescription; }; using DeviceInfoCollection = std::vector<DeviceInfo>; public: AudioAlsa( bool & _success_ful, AudioEngine* audioEngine ); ~AudioAlsa() override; inline static QString name() { return QT_TRANSLATE_NOOP( "AudioDeviceSetupWidget", "ALSA (Advanced Linux Sound Architecture)" ); } static QString probeDevice(); static DeviceInfoCollection getAvailableDevices(); private: void startProcessing() override; void stopProcessing() override; void run() override; int setHWParams( const ch_cnt_t _channels, snd_pcm_access_t _access ); int setSWParams(); int handleError( int _err ); snd_pcm_t * m_handle; snd_pcm_uframes_t m_bufferSize; snd_pcm_uframes_t m_periodSize; snd_pcm_hw_params_t * m_hwParams; snd_pcm_sw_params_t * m_swParams; bool m_convertEndian; } ; } // namespace lmms #endif // LMMS_HAVE_ALSA #endif // LMMS_AUDIO_ALSA_H
2,661
C++
.h
83
29.795181
78
0.762446
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,468
Microtuner.h
LMMS_lmms/include/Microtuner.h
/* * Microtuner.h - manage tuning and scale information of an instrument * * Copyright (c) 2020 Martin Pavelek <he29.HS/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_MICROTUNER_H #define LMMS_MICROTUNER_H #include "AutomatableModel.h" #include "ComboBoxModel.h" #include "JournallingObject.h" namespace lmms { class LMMS_EXPORT Microtuner : public Model, public JournallingObject { Q_OBJECT public: explicit Microtuner(); bool enabled() const {return m_enabledModel.value();} bool keyRangeImport() const {return enabled() && m_keyRangeImportModel.value();} int currentScale() const {return m_scaleModel.value();} int currentKeymap() const {return m_keymapModel.value();} BoolModel *enabledModel() {return &m_enabledModel;} ComboBoxModel *scaleModel() {return &m_scaleModel;} ComboBoxModel *keymapModel() {return &m_keymapModel;} BoolModel *keyRangeImportModel() {return &m_keyRangeImportModel;} int firstKey() const; int lastKey() const; int baseKey() const; float baseFreq() const; float keyToFreq(int key, int userBaseNote) const; int octaveSize() const; QString nodeName() const override {return "microtuner";} void saveSettings(QDomDocument & document, QDomElement &element) override; void loadSettings(const QDomElement &element) override; protected slots: void updateScaleList(int index); void updateKeymapList(int index); private: BoolModel m_enabledModel; //!< Enable microtuner (otherwise using 12-TET @440 Hz) ComboBoxModel m_scaleModel; ComboBoxModel m_keymapModel; BoolModel m_keyRangeImportModel; }; } // namespace lmms #endif // LMMS_MICROTUNER_H
2,392
C++
.h
63
36
96
0.771058
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,469
Oscilloscope.h
LMMS_lmms/include/Oscilloscope.h
/* * Oscilloscope.h * * Copyright (c) 2005-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of"the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_OSCILLOSCOPE_H #define LMMS_GUI_OSCILLOSCOPE_H #include <QWidget> #include <QPixmap> #include "lmms_basics.h" namespace lmms { class SampleFrame; } namespace lmms::gui { class Oscilloscope : public QWidget { Q_OBJECT public: Q_PROPERTY( QColor leftChannelColor READ leftChannelColor WRITE setLeftChannelColor ) Q_PROPERTY( QColor rightChannelColor READ rightChannelColor WRITE setRightChannelColor ) Q_PROPERTY( QColor otherChannelsColor READ otherChannelsColor WRITE setOtherChannelsColor ) Q_PROPERTY( QColor clippingColor READ clippingColor WRITE setClippingColor ) Oscilloscope( QWidget * _parent ); ~Oscilloscope() override; void setActive( bool _active ); QColor const & leftChannelColor() const; void setLeftChannelColor(QColor const & leftChannelColor); QColor const & rightChannelColor() const; void setRightChannelColor(QColor const & rightChannelColor); QColor const & otherChannelsColor() const; void setOtherChannelsColor(QColor const & otherChannelsColor); QColor const & clippingColor() const; void setClippingColor(QColor const & clippingColor); protected: void paintEvent( QPaintEvent * _pe ) override; void mousePressEvent( QMouseEvent * _me ) override; protected slots: void updateAudioBuffer(const lmms::SampleFrame* buffer); private: bool clips(float level) const; private: QPixmap m_background; QPointF * m_points; SampleFrame* m_buffer; bool m_active; QColor m_leftChannelColor; QColor m_rightChannelColor; QColor m_otherChannelsColor; QColor m_clippingColor; } ; } // namespace lmms::gui #endif // LMMS_GUI_OSCILLOSCOPE_H
2,514
C++
.h
72
32.847222
92
0.793046
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,470
AudioEngineProfiler.h
LMMS_lmms/include/AudioEngineProfiler.h
/* * AudioEngineProfiler.h - class for profiling performance of AudioEngine * * Copyright (c) 2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_AUDIO_ENGINE_PROFILER_H #define LMMS_AUDIO_ENGINE_PROFILER_H #include <array> #include <atomic> #include <QFile> #include "lmms_basics.h" #include "MicroTimer.h" namespace lmms { class AudioEngineProfiler { public: AudioEngineProfiler(); ~AudioEngineProfiler() = default; void startPeriod() { m_periodTimer.reset(); } void finishPeriod( sample_rate_t sampleRate, fpp_t framesPerPeriod ); int cpuLoad() const { return m_cpuLoad; } void setOutputFile( const QString& outputFile ); enum class DetailType { NoteSetup, Instruments, Effects, Mixing, Count }; constexpr static auto DetailCount = static_cast<std::size_t>(DetailType::Count); int detailLoad(const DetailType type) const { return m_detailLoad[static_cast<std::size_t>(type)].load(std::memory_order_relaxed); } class Probe { public: Probe(AudioEngineProfiler& profiler, AudioEngineProfiler::DetailType type) : m_profiler(profiler) , m_type(type) { profiler.startDetail(type); } ~Probe() { m_profiler.finishDetail(m_type); } Probe& operator=(const Probe&) = delete; Probe(const Probe&) = delete; Probe(Probe&&) = delete; private: AudioEngineProfiler &m_profiler; const AudioEngineProfiler::DetailType m_type; }; private: void startDetail(const DetailType type) { m_detailTimer[static_cast<std::size_t>(type)].reset(); } void finishDetail(const DetailType type) { m_detailTime[static_cast<std::size_t>(type)] = m_detailTimer[static_cast<std::size_t>(type)].elapsed(); } MicroTimer m_periodTimer; std::atomic<float> m_cpuLoad; QFile m_outputFile; // Use arrays to avoid dynamic allocations in realtime code std::array<MicroTimer, DetailCount> m_detailTimer; std::array<int, DetailCount> m_detailTime{0}; std::array<std::atomic<float>, DetailCount> m_detailLoad{0}; }; } // namespace lmms #endif // LMMS_AUDIO_ENGINE_PROFILER_H
2,836
C++
.h
92
28.543478
105
0.755596
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,471
PatternTrackView.h
LMMS_lmms/include/PatternTrackView.h
/* * PatternTrackView.h * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_PATTERN_TRACK_VIEW_H #define LMMS_GUI_PATTERN_TRACK_VIEW_H #include "TrackView.h" namespace lmms { class PatternTrack; namespace gui { class TrackLabelButton; class PatternTrackView : public TrackView { Q_OBJECT public: PatternTrackView(PatternTrack* pt, TrackContainerView* tcv); ~PatternTrackView() override; bool close() override; const PatternTrack* getPatternTrack() const { return (m_patternTrack); } public slots: void clickedTrackLabel(); private: PatternTrack* m_patternTrack; TrackLabelButton * m_trackLabel; } ; } // namespace gui } // namespace lmms #endif // LMMS_GUI_PATTERN_TRACK_VIEW_H
1,550
C++
.h
52
27.788462
77
0.772819
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,472
TimeLineWidget.h
LMMS_lmms/include/TimeLineWidget.h
/* * TimeLineWidget.h - class timeLine, representing a time-line with position marker * * Copyright (c) 2004-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_TIMELINE_WIDGET_H #define LMMS_GUI_TIMELINE_WIDGET_H #include <array> #include <QBrush> #include <QSize> #include <QWidget> #include "Song.h" #include "embed.h" class QPixmap; class QToolBar; namespace lmms { class Timeline; } // namespace lmms namespace lmms::gui { class NStateButton; class TextFloat; class SongEditor; class TimeLineWidget : public QWidget { Q_OBJECT public: Q_PROPERTY( QColor barLineColor READ getBarLineColor WRITE setBarLineColor ) Q_PROPERTY( QColor barNumberColor READ getBarNumberColor WRITE setBarNumberColor ) Q_PROPERTY( QColor inactiveLoopColor READ getInactiveLoopColor WRITE setInactiveLoopColor ) Q_PROPERTY( QBrush inactiveLoopBrush READ getInactiveLoopBrush WRITE setInactiveLoopBrush ) Q_PROPERTY( QColor inactiveLoopInnerColor READ getInactiveLoopInnerColor WRITE setInactiveLoopInnerColor ) Q_PROPERTY(QColor inactiveLoopHandleColor MEMBER m_inactiveLoopHandleColor) Q_PROPERTY( QColor activeLoopColor READ getActiveLoopColor WRITE setActiveLoopColor ) Q_PROPERTY( QBrush activeLoopBrush READ getActiveLoopBrush WRITE setActiveLoopBrush ) Q_PROPERTY( QColor activeLoopInnerColor READ getActiveLoopInnerColor WRITE setActiveLoopInnerColor ) Q_PROPERTY(QColor activeLoopHandleColor MEMBER m_activeLoopHandleColor) Q_PROPERTY( int loopRectangleVerticalPadding READ getLoopRectangleVerticalPadding WRITE setLoopRectangleVerticalPadding ) Q_PROPERTY(int loopHandleWidth MEMBER m_loopHandleWidth) Q_PROPERTY(QSize mouseHotspotSelLeft READ mouseHotspotSelLeft WRITE setMouseHotspotSelLeft) Q_PROPERTY(QSize mouseHotspotSelRight READ mouseHotspotSelRight WRITE setMouseHotspotSelRight) enum class AutoScrollState { Stepped, Continuous, Disabled }; TimeLineWidget(int xoff, int yoff, float ppb, Song::PlayPos& pos, Timeline& timeline, const TimePos& begin, Song::PlayMode mode, QWidget* parent); ~TimeLineWidget() override; inline QColor const & getBarLineColor() const { return m_barLineColor; } inline void setBarLineColor(QColor const & barLineColor) { m_barLineColor = barLineColor; } inline QColor const & getBarNumberColor() const { return m_barNumberColor; } inline void setBarNumberColor(QColor const & barNumberColor) { m_barNumberColor = barNumberColor; } inline QColor const & getInactiveLoopColor() const { return m_inactiveLoopColor; } inline void setInactiveLoopColor(QColor const & inactiveLoopColor) { m_inactiveLoopColor = inactiveLoopColor; } inline QBrush const & getInactiveLoopBrush() const { return m_inactiveLoopBrush; } inline void setInactiveLoopBrush(QBrush const & inactiveLoopBrush) { m_inactiveLoopBrush = inactiveLoopBrush; } inline QColor const & getInactiveLoopInnerColor() const { return m_inactiveLoopInnerColor; } inline void setInactiveLoopInnerColor(QColor const & inactiveLoopInnerColor) { m_inactiveLoopInnerColor = inactiveLoopInnerColor; } inline QColor const & getActiveLoopColor() const { return m_activeLoopColor; } inline void setActiveLoopColor(QColor const & activeLoopColor) { m_activeLoopColor = activeLoopColor; } inline QBrush const & getActiveLoopBrush() const { return m_activeLoopBrush; } inline void setActiveLoopBrush(QBrush const & activeLoopBrush) { m_activeLoopBrush = activeLoopBrush; } inline QColor const & getActiveLoopInnerColor() const { return m_activeLoopInnerColor; } inline void setActiveLoopInnerColor(QColor const & activeLoopInnerColor) { m_activeLoopInnerColor = activeLoopInnerColor; } inline int const & getLoopRectangleVerticalPadding() const { return m_loopRectangleVerticalPadding; } inline void setLoopRectangleVerticalPadding(int const & loopRectangleVerticalPadding) { m_loopRectangleVerticalPadding = loopRectangleVerticalPadding; } auto mouseHotspotSelLeft() const -> QSize { const auto point = m_cursorSelectLeft.hotSpot(); return QSize{point.x(), point.y()}; } void setMouseHotspotSelLeft(const QSize& s) { m_cursorSelectLeft = QCursor{m_cursorSelectLeft.pixmap(), s.width(), s.height()}; } auto mouseHotspotSelRight() const -> QSize { const auto point = m_cursorSelectRight.hotSpot(); return QSize{point.x(), point.y()}; } void setMouseHotspotSelRight(const QSize& s) { m_cursorSelectRight = QCursor{m_cursorSelectRight.pixmap(), s.width(), s.height()}; } inline Song::PlayPos & pos() { return( m_pos ); } AutoScrollState autoScroll() const { return m_autoScroll; } inline void setPixelsPerBar( float ppb ) { m_ppb = ppb; update(); } void setXOffset(const int x); void addToolButtons(QToolBar* _tool_bar ); inline int markerX( const TimePos & _t ) const { return m_xOffset + static_cast<int>( ( _t - m_begin ) * m_ppb / TimePos::ticksPerBar() ); } signals: void positionChanged(const lmms::TimePos& postion); void regionSelectedFromPixels( int, int ); void selectionFinished(); public slots: void updatePosition(); void setSnapSize( const float snapSize ) { m_snapSize = snapSize; } void toggleAutoScroll( int _n ); protected: void paintEvent( QPaintEvent * _pe ) override; void mousePressEvent( QMouseEvent * _me ) override; void mouseMoveEvent( QMouseEvent * _me ) override; void mouseReleaseEvent( QMouseEvent * _me ) override; void contextMenuEvent(QContextMenuEvent* event) override; private: enum class Action { NoAction, MovePositionMarker, MoveLoopBegin, MoveLoopEnd, MoveLoop, SelectSongClip, }; auto getClickedTime(int xPosition) const -> TimePos; auto getLoopAction(QMouseEvent* event) const -> Action; auto actionCursor(Action action) const -> QCursor; QPixmap m_posMarkerPixmap = embed::getIconPixmap("playpos_marker"); QColor m_inactiveLoopColor = QColor{52, 63, 53, 64}; QBrush m_inactiveLoopBrush = QColor{255, 255, 255, 32}; QColor m_inactiveLoopInnerColor = QColor{255, 255, 255, 32}; QColor m_inactiveLoopHandleColor = QColor{255, 255, 255, 32}; QColor m_activeLoopColor = QColor{52, 63, 53, 255}; QBrush m_activeLoopBrush = QColor{55, 141, 89}; QColor m_activeLoopInnerColor = QColor{74, 155, 100, 255}; QColor m_activeLoopHandleColor = QColor{74, 155, 100, 255}; int m_loopRectangleVerticalPadding = 1; int m_loopHandleWidth = 5; QColor m_barLineColor = QColor{192, 192, 192}; QColor m_barNumberColor = m_barLineColor.darker(120); QCursor m_cursorSelectLeft = QCursor{embed::getIconPixmap("cursor_select_left"), 0, 16}; QCursor m_cursorSelectRight = QCursor{embed::getIconPixmap("cursor_select_right"), 32, 16}; AutoScrollState m_autoScroll = AutoScrollState::Stepped; // Width of the unused region on the widget's left (above track labels or piano) int m_xOffset; float m_ppb; float m_snapSize = 1.f; Song::PlayPos & m_pos; Timeline* m_timeline; // Leftmost position visible in parent editor const TimePos & m_begin; const Song::PlayMode m_mode; // When in MoveLoop mode we need the initial positions. Storing only the latest // position allows for unquantized drag but fails when toggling quantization. std::array<TimePos, 2> m_oldLoopPos; TimePos m_dragStartPos; TextFloat* m_hint = nullptr; int m_initalXSelect; Action m_action = Action::NoAction; }; } // namespace lmms::gui #endif // LMMS_GUI_TIMELINE_WIDGET_H
8,150
C++
.h
189
40.857143
153
0.790265
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,473
AudioFileWave.h
LMMS_lmms/include/AudioFileWave.h
/* * AudioFileWave.h - AudioDevice which encodes wave-stream and writes it * into a WAVE-file. This is used for song-export. * * Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_AUDIO_FILE_WAVE_H #define LMMS_AUDIO_FILE_WAVE_H #include "lmmsconfig.h" #include "AudioFileDevice.h" #include <sndfile.h> namespace lmms { class AudioFileWave : public AudioFileDevice { public: AudioFileWave( OutputSettings const & outputSettings, const ch_cnt_t channels, bool & successful, const QString & file, AudioEngine* audioEngine ); ~AudioFileWave() override; static AudioFileDevice * getInst( const QString & outputFilename, OutputSettings const & outputSettings, const ch_cnt_t channels, AudioEngine* audioEngine, bool & successful ) { return new AudioFileWave( outputSettings, channels, successful, outputFilename, audioEngine ); } private: void writeBuffer(const SampleFrame* _ab, const fpp_t _frames) override; bool startEncoding(); void finishEncoding(); private: SF_INFO m_si; SNDFILE * m_sf; } ; } // namespace lmms #endif // LMMS_AUDIO_FILE_WAVE_H
1,972
C++
.h
59
30.813559
77
0.746842
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,474
OscillatorConstants.h
LMMS_lmms/include/OscillatorConstants.h
/* * OscillatorConstants.h - declaration of constants used in Oscillator and SampleBuffer * for band limited wave tables * * Copyright (c) 2018 Dave French <dave/dot/french3/at/googlemail/dot/com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_OSCILLATORCONSTANTS_H #define LMMS_OSCILLATORCONSTANTS_H #include <array> #include "lmms_basics.h" namespace lmms::OscillatorConstants { // Limit wavetables to the audible audio spectrum const int MAX_FREQ = 20000; // Minimum size of table to have all audible bands for midi note 1 (i.e. 20 000 Hz / 8.176 Hz) constexpr int WAVETABLE_LENGTH = static_cast<int>(MAX_FREQ / 8.176); //SEMITONES_PER_TABLE, the smaller the value the smoother the harmonics change on frequency sweeps // with the trade off of increased memory requirements to store the wave tables // require memory = NumberOfWaveShapes*WAVETABLE_LENGTH*(MidiNoteCount/SEMITONES_PER_TABLE)*BytePerSample_t // 7*2446*(128/1)*4 = 8766464 bytes const int SEMITONES_PER_TABLE = 1; const int WAVE_TABLES_PER_WAVEFORM_COUNT = 128 / SEMITONES_PER_TABLE; // There is some ambiguity around the use of "wavetable", "wavetable synthesis" or related terms. // The following meanings and definitions were selected for use in the Oscillator class: // - wave shape: abstract and precise definition of the graph associated with a given type of wave; // - waveform: digital representations the wave shape, a set of waves optimized for use at varying pitches; // - wavetable: a table containing one period of a wave, with frequency content optimized for a specific pitch. using wavetable_t = std::array<sample_t, WAVETABLE_LENGTH>; using waveform_t = std::array<wavetable_t, WAVE_TABLES_PER_WAVEFORM_COUNT>; } // namespace lmms::OscillatorConstants #endif // LMMS_OSCILLATORCONSTANTS_H
2,570
C++
.h
49
50.44898
113
0.769108
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,475
ControllerDialog.h
LMMS_lmms/include/ControllerDialog.h
/* * ControllerDialog.h - per-controller-specific view for changing a * controller's settings * * Copyright (c) 2008-2009 Paul Giblock <drfaygo/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_CONTROLLER_DIALOG_H #define LMMS_GUI_CONTROLLER_DIALOG_H #include <QWidget> #include "ModelView.h" namespace lmms { class Controller; namespace gui { class ControllerDialog : public QWidget, public ModelView { Q_OBJECT public: ControllerDialog( Controller * _controller, QWidget * _parent ); ~ControllerDialog() override = default; signals: void closed(); protected: void closeEvent( QCloseEvent * _ce ) override; } ; } // namespace gui } // namespace lmms #endif // LMMS_GUI_CONTROLLER_DIALOG_H
1,515
C++
.h
47
30.212766
70
0.751895
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,476
GuiApplication.h
LMMS_lmms/include/GuiApplication.h
/* * GuiApplication.h * * Copyright (c) 2014 Lukas W <lukaswhl/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_GUI_APPLICATION_H #define LMMS_GUI_GUI_APPLICATION_H #include <QObject> #include "lmms_export.h" #include "lmmsconfig.h" class QLabel; namespace lmms::gui { class AutomationEditorWindow; class ControllerRackView; class MixerView; class MainWindow; class MicrotunerConfig; class PatternEditorWindow; class PianoRollWindow; class ProjectNotes; class SongEditorWindow; class LMMS_EXPORT GuiApplication : public QObject { Q_OBJECT; public: explicit GuiApplication(); ~GuiApplication() override; static GuiApplication* instance(); #ifdef LMMS_BUILD_WIN32 static QFont getWin32SystemFont(); #endif MainWindow* mainWindow() { return m_mainWindow; } MixerView* mixerView() { return m_mixerView; } SongEditorWindow* songEditor() { return m_songEditor; } PatternEditorWindow* patternEditor() { return m_patternEditor; } PianoRollWindow* pianoRoll() { return m_pianoRoll; } ProjectNotes* getProjectNotes() { return m_projectNotes; } MicrotunerConfig* getMicrotunerConfig() { return m_microtunerConfig; } AutomationEditorWindow* automationEditor() { return m_automationEditor; } ControllerRackView* getControllerRackView() { return m_controllerRackView; } public slots: void displayInitProgress(const QString &msg); private slots: void childDestroyed(QObject *obj); private: static GuiApplication* s_instance; MainWindow* m_mainWindow; MixerView* m_mixerView; SongEditorWindow* m_songEditor; AutomationEditorWindow* m_automationEditor; PatternEditorWindow* m_patternEditor; PianoRollWindow* m_pianoRoll; ProjectNotes* m_projectNotes; MicrotunerConfig* m_microtunerConfig; ControllerRackView* m_controllerRackView; QLabel* m_loadingProgressLabel; }; // Short-hand function LMMS_EXPORT GuiApplication* getGUI(); } // namespace lmms::gui #endif // LMMS_GUI_GUI_APPLICATION_H
2,694
C++
.h
80
31.8625
77
0.795997
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
20,477
Oscillator.h
LMMS_lmms/include/Oscillator.h
/* * Oscillator.h - declaration of class Oscillator * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * 2018 Dave French <dave/dot/french3/at/googlemail/dot/com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_OSCILLATOR_H #define LMMS_OSCILLATOR_H #include <cassert> #include <fftw3.h> #include <memory> #include <cstdlib> #include "interpolation.h" #include "Engine.h" #include "lmms_constants.h" #include "lmmsconfig.h" #include "AudioEngine.h" #include "OscillatorConstants.h" #include "SampleBuffer.h" namespace lmms { class IntModel; class LMMS_EXPORT Oscillator { public: enum class WaveShape { Sine, Triangle, Saw, Square, MoogSaw, Exponential, WhiteNoise, UserDefined, Count //!< Number of all available wave shapes }; constexpr static auto NumWaveShapes = static_cast<std::size_t>(WaveShape::Count); //! First wave shape that has a pre-generated table constexpr static auto FirstWaveShapeTable = static_cast<std::size_t>(WaveShape::Triangle); //! Number of band-limited wave shapes to be generated constexpr static auto NumWaveShapeTables = static_cast<std::size_t>(WaveShape::WhiteNoise) - FirstWaveShapeTable; enum class ModulationAlgo { PhaseModulation, AmplitudeModulation, SignalMix, SynchronizedBySubOsc, FrequencyModulation, Count } ; constexpr static auto NumModulationAlgos = static_cast<std::size_t>(ModulationAlgo::Count); Oscillator( const IntModel *wave_shape_model, const IntModel *mod_algo_model, const float &freq, const float &detuning_div_samplerate, const float &phase_offset, const float &volume, Oscillator *m_subOsc = nullptr); virtual ~Oscillator() { delete m_subOsc; } static void waveTableInit(); static void destroyFFTPlans(); static std::unique_ptr<OscillatorConstants::waveform_t> generateAntiAliasUserWaveTable(const SampleBuffer* sampleBuffer); inline void setUseWaveTable(bool n) { m_useWaveTable = n; } void setUserWave(std::shared_ptr<const SampleBuffer> _wave) { m_userWave = _wave; } void setUserAntiAliasWaveTable(std::shared_ptr<const OscillatorConstants::waveform_t> waveform) { m_userAntiAliasWaveTable = waveform; } void update(SampleFrame* ab, const fpp_t frames, const ch_cnt_t chnl, bool modulator = false); // now follow the wave-shape-routines... static inline sample_t sinSample( const float _sample ) { return sinf( _sample * F_2PI ); } static inline sample_t triangleSample( const float _sample ) { const float ph = absFraction( _sample ); if( ph <= 0.25f ) { return ph * 4.0f; } else if( ph <= 0.75f ) { return 2.0f - ph * 4.0f; } return ph * 4.0f - 4.0f; } static inline sample_t sawSample( const float _sample ) { return -1.0f + absFraction( _sample ) * 2.0f; } static inline sample_t squareSample( const float _sample ) { return ( absFraction( _sample ) > 0.5f ) ? -1.0f : 1.0f; } static inline sample_t moogSawSample( const float _sample ) { const float ph = absFraction( _sample ); if( ph < 0.5f ) { return -1.0f + ph * 4.0f; } return 1.0f - 2.0f * ph; } static inline sample_t expSample( const float _sample ) { float ph = absFraction( _sample ); if( ph > 0.5f ) { ph = 1.0f - ph; } return -1.0f + 8.0f * ph * ph; } static inline sample_t noiseSample( const float ) { return 1.0f - rand() * 2.0f / RAND_MAX; } static sample_t userWaveSample(const SampleBuffer* buffer, const float sample) { if (buffer == nullptr || buffer->size() == 0) { return 0; } const auto frames = buffer->size(); const auto frame = absFraction(sample) * frames; const auto f1 = static_cast<f_cnt_t>(frame); return linearInterpolate(buffer->data()[f1][0], buffer->data()[(f1 + 1) % frames][0], fraction(frame)); } struct wtSampleControl { float frame; f_cnt_t f1; f_cnt_t f2; int band; }; inline wtSampleControl getWtSampleControl(const float sample) const { wtSampleControl control; control.frame = absFraction(sample) * OscillatorConstants::WAVETABLE_LENGTH; control.f1 = static_cast<f_cnt_t>(control.frame); control.f2 = control.f1 < OscillatorConstants::WAVETABLE_LENGTH - 1 ? control.f1 + 1 : 0; control.band = waveTableBandFromFreq( m_freq * m_detuning_div_samplerate * Engine::audioEngine()->outputSampleRate()); return control; } inline sample_t wtSample( const sample_t table[OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT][OscillatorConstants::WAVETABLE_LENGTH], const float sample) const { assert(table != nullptr); wtSampleControl control = getWtSampleControl(sample); return linearInterpolate(table[control.band][control.f1], table[control.band][control.f2], fraction(control.frame)); } sample_t wtSample(const OscillatorConstants::waveform_t* table, const float sample) const { assert(table != nullptr); wtSampleControl control = getWtSampleControl(sample); return linearInterpolate((*table)[control.band][control.f1], (*table)[control.band][control.f2], fraction(control.frame)); } inline sample_t wtSample(sample_t **table, const float sample) const { assert(table != nullptr); wtSampleControl control = getWtSampleControl(sample); return linearInterpolate(table[control.band][control.f1], table[control.band][control.f2], fraction(control.frame)); } static inline int waveTableBandFromFreq(float freq) { // Frequency bands are indexed relative to default MIDI key frequencies. // I.e., 440 Hz (A4, key 69): 69 + 12 * log2(1) = 69 // To always avoid aliasing, ceil() is used instead of round(). It ensures that the nearest wavetable with // lower than optimal number of harmonics is used when exactly matching wavetable is not available. int band = (69 + static_cast<int>(std::ceil(12.0f * std::log2(freq / 440.0f)))) / OscillatorConstants::SEMITONES_PER_TABLE; // Limit the returned value to a valid wavetable index range. // (qBound would bring Qt into the audio code, which not a preferable option due to realtime safety. // C++17 std::clamp() could be used in the future.) return band <= 1 ? 1 : band >= OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT-1 ? OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT-1 : band; } static inline float freqFromWaveTableBand(int band) { return 440.0f * std::pow(2.0f, (band * OscillatorConstants::SEMITONES_PER_TABLE - 69.0f) / 12.0f); } private: const IntModel * m_waveShapeModel; const IntModel * m_modulationAlgoModel; const float & m_freq; const float & m_detuning_div_samplerate; const float & m_volume; const float & m_ext_phaseOffset; Oscillator * m_subOsc; float m_phaseOffset; float m_phase; std::shared_ptr<const SampleBuffer> m_userWave = SampleBuffer::emptyBuffer(); std::shared_ptr<const OscillatorConstants::waveform_t> m_userAntiAliasWaveTable; bool m_useWaveTable; // There are many update*() variants; the modulator flag is stored as a member variable to avoid // adding more explicit parameters to all of them. Can be converted to a parameter if needed. bool m_isModulator; /* Multiband WaveTable */ static sample_t s_waveTables[NumWaveShapeTables][OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT][OscillatorConstants::WAVETABLE_LENGTH]; static fftwf_plan s_fftPlan; static fftwf_plan s_ifftPlan; static fftwf_complex * s_specBuf; static std::array<float, OscillatorConstants::WAVETABLE_LENGTH> s_sampleBuffer; static void generateSawWaveTable(int bands, sample_t* table, int firstBand = 1); static void generateTriangleWaveTable(int bands, sample_t* table, int firstBand = 1); static void generateSquareWaveTable(int bands, sample_t* table, int firstBand = 1); static void generateFromFFT(int bands, sample_t* table); static void generateWaveTables(); static void createFFTPlans(); /* End Multiband wavetable */ void updateNoSub( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); void updatePM( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); void updateAM( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); void updateMix( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); void updateSync( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); void updateFM( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); float syncInit( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); inline bool syncOk( float _osc_coeff ); template<WaveShape W> void updateNoSub( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); template<WaveShape W> void updatePM( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); template<WaveShape W> void updateAM( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); template<WaveShape W> void updateMix( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); template<WaveShape W> void updateSync( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); template<WaveShape W> void updateFM( SampleFrame* _ab, const fpp_t _frames, const ch_cnt_t _chnl ); template<WaveShape W> inline sample_t getSample( const float _sample ); inline void recalcPhase(); } ; } // namespace lmms #endif // LMMS_OSCILLATOR_H
10,070
C++
.h
278
33.44964
150
0.734995
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,478
Flags.h
LMMS_lmms/include/Flags.h
/* * Flags.h - class to make flags from enums * * Copyright (c) 2023 Dominic Clark * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_FLAGS_H #define LMMS_FLAGS_H #include <type_traits> namespace lmms { template<typename T> class Flags { static_assert(std::is_enum_v<T>, "lmms::Flags can only be used with enum types"); public: using EnumType = T; using UnderlyingType = std::underlying_type_t<T>; constexpr Flags() = default; constexpr Flags(T value) : // Intentionally not explicit m_value{static_cast<UnderlyingType>(value)} {} constexpr explicit Flags(UnderlyingType value) : m_value{value} {} constexpr auto testAll(Flags flags) const -> bool { return (*this & flags) == flags; } constexpr auto testAny(Flags flags) const -> bool { return (*this & flags) != Flags{}; } constexpr auto testFlag(EnumType flag) const -> bool { return static_cast<bool>(*this & flag); } constexpr auto operator~() const -> Flags { return Flags{~m_value}; } friend constexpr auto operator&(Flags l, Flags r) -> Flags { return Flags{l.m_value & r.m_value}; } friend constexpr auto operator|(Flags l, Flags r) -> Flags { return Flags{l.m_value | r.m_value}; } friend constexpr auto operator^(Flags l, Flags r) -> Flags { return Flags{l.m_value ^ r.m_value}; } friend constexpr auto operator+(Flags l, Flags r) -> Flags { return Flags{l.m_value | r.m_value}; } friend constexpr auto operator-(Flags l, Flags r) -> Flags { return Flags{l.m_value & ~r.m_value}; } constexpr auto operator&=(Flags f) -> Flags& { m_value &= f.m_value; return *this; } constexpr auto operator|=(Flags f) -> Flags& { m_value |= f.m_value; return *this; } constexpr auto operator^=(Flags f) -> Flags& { m_value ^= f.m_value; return *this; } constexpr auto operator+=(Flags f) -> Flags& { m_value |= f.m_value; return *this; } constexpr auto operator-=(Flags f) -> Flags& { m_value &= ~f.m_value; return *this; } constexpr explicit operator UnderlyingType() const { return m_value; } // TODO C++23: explicit(std::is_scoped_enum<T>) constexpr explicit operator bool() const { return m_value != 0; } friend constexpr auto operator==(Flags l, Flags r) -> bool { return l.m_value == r.m_value; } // TODO C++20: = default friend constexpr auto operator!=(Flags l, Flags r) -> bool { return l.m_value != r.m_value; } // TODO C++20: Remove private: UnderlyingType m_value = 0; }; #define LMMS_DECLARE_OPERATORS_FOR_FLAGS(type) \ constexpr inline auto operator|(type l, type r) -> ::lmms::Flags<type> { return ::lmms::Flags{l} | ::lmms::Flags{r}; } } // namespace lmms #endif // LMMS_FLAGS_H
3,346
C++
.h
66
48.636364
119
0.708244
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,479
StepRecorder.h
LMMS_lmms/include/StepRecorder.h
/* * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_STEP_RECORDER_H #define LMMS_STEP_RECORDER_H #include <QColor> #include <QElapsedTimer> #include <QTimer> #include <QObject> #include "Note.h" class QKeyEvent; class QMouseEvent; namespace lmms { class MidiClip; namespace gui { class PianoRoll; class StepRecorderWidget; } // namespace gui class StepRecorder : public QObject { Q_OBJECT public: StepRecorder(gui::PianoRoll& pianoRoll, gui::StepRecorderWidget& stepRecorderWidget); void initialize(); void start(const TimePos& currentPosition,const TimePos& stepLength); void stop(); void notePressed(const Note & n); void noteReleased(const Note & n); bool keyPressEvent(QKeyEvent* ke); bool mousePressEvent(QMouseEvent* ke); void setCurrentMidiClip(MidiClip* newMidiClip); void setStepsLength(const TimePos& newLength); std::vector<Note*> getCurStepNotes(); bool isRecording() const { return m_isRecording; } QColor curStepNoteColor() const { return QColor(245,3,139); // radiant pink } private slots: void removeNotesReleasedForTooLong(); private: void stepForwards(); void stepBackwards(); void applyStep(); void dismissStep(); void prepareNewStep(); TimePos getCurStepEndPos(); void updateCurStepNotes(); void updateWidget(); bool allCurStepNotesReleased(); gui::PianoRoll& m_pianoRoll; gui::StepRecorderWidget& m_stepRecorderWidget; bool m_isRecording = false; TimePos m_curStepStartPos = 0; TimePos m_curStepEndPos = 0; TimePos m_stepsLength; TimePos m_curStepLength; // current step length refers to the step currently recorded. it may defer from m_stepsLength // since the user can make current step larger QTimer m_updateReleasedTimer; MidiClip* m_midiClip; class StepNote { public: StepNote(const Note & note) : m_note(note), m_pressed(true) {}; void setPressed() { m_pressed = true; } void setReleased() { m_pressed = false; releasedTimer.start(); } int timeSinceReleased() { return releasedTimer.elapsed(); } bool isPressed() const { return m_pressed; } bool isReleased() const { return !m_pressed; } Note m_note; private: bool m_pressed; QElapsedTimer releasedTimer; } ; std::vector<StepNote*> m_curStepNotes; // contains the current recorded step notes (i.e. while user still press the notes; before they are applied to the clip) StepNote* findCurStepNote(const int key); bool m_isStepInProgress = false; }; } // namespace lmms #endif // LMMS_STEP_RECORDER_H
3,287
C++
.h
117
25.598291
160
0.761814
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,480
PianoView.h
LMMS_lmms/include/PianoView.h
/* * PianoView.h - declaration of PianoView, an interactive piano/keyboard-widget * * Copyright (c) 2004-2010 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_PIANO_VIEW_H #define LMMS_GUI_PIANO_VIEW_H #include <QPixmap> #include <QScrollBar> #include "AutomatableModel.h" #include "ModelView.h" #include "embed.h" namespace lmms { class Piano; namespace gui { class PianoView : public QWidget, public ModelView { Q_OBJECT public: PianoView( QWidget * _parent ); ~PianoView() override = default; static int getKeyFromKeyEvent( QKeyEvent * _ke ); public: void keyPressEvent( QKeyEvent * ke ) override; void keyReleaseEvent( QKeyEvent * ke ) override; protected: void modelChanged() override; void contextMenuEvent( QContextMenuEvent * _me ) override; void paintEvent( QPaintEvent * ) override; void mousePressEvent( QMouseEvent * me ) override; void mouseReleaseEvent( QMouseEvent * me ) override; void mouseMoveEvent( QMouseEvent * me ) override; void focusOutEvent( QFocusEvent * _fe ) override; void focusInEvent( QFocusEvent * fe ) override; void resizeEvent( QResizeEvent * _event ) override; private: int getKeyFromMouse( const QPoint & _p ) const; int getKeyX( int _key_num ) const; int getKeyWidth(int key_num) const; int getKeyHeight(int key_num) const; IntModel *getNearestMarker(int key, QString* title = nullptr); QPixmap m_whiteKeyPm = embed::getIconPixmap("white_key"); QPixmap m_blackKeyPm = embed::getIconPixmap("black_key"); QPixmap m_whiteKeyPressedPm = embed::getIconPixmap("white_key_pressed"); QPixmap m_blackKeyPressedPm = embed::getIconPixmap("black_key_pressed"); QPixmap m_whiteKeyDisabledPm = embed::getIconPixmap("white_key_disabled"); QPixmap m_blackKeyDisabledPm = embed::getIconPixmap("black_key_disabled"); Piano * m_piano; QScrollBar * m_pianoScroll; int m_startKey; //!< first key when drawing int m_lastKey; //!< previously pressed key IntModel *m_movedNoteModel; //!< note marker which is being moved private slots: void pianoScrolled( int _new_pos ); signals: void keyPressed( int ); void baseNoteChanged(); } ; } // namespace gui } // namespace lmms #endif // LMMS_GUI_PIANO_VIEW_H
3,003
C++
.h
81
35.061728
79
0.763467
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,481
LocklessAllocator.h
LMMS_lmms/include/LocklessAllocator.h
/* * LocklessAllocator.h - allocator with lockless alloc and free * * Copyright (c) 2016 Javier Serrano Polo <javier@jasp.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_LOCKLESS_ALLOCATOR_H #define LMMS_LOCKLESS_ALLOCATOR_H #include <atomic> #include <cstddef> namespace lmms { class LocklessAllocator { public: LocklessAllocator( size_t nmemb, size_t size ); virtual ~LocklessAllocator(); void * alloc(); void free( void * ptr ); private: char * m_pool; size_t m_capacity; size_t m_elementSize; std::atomic_int * m_freeState; size_t m_freeStateSets; std::atomic_size_t m_available; std::atomic_size_t m_startIndex; } ; template<typename T> class LocklessAllocatorT : private LocklessAllocator { public: LocklessAllocatorT( size_t nmemb ) : LocklessAllocator( nmemb, sizeof( T ) ) { } ~LocklessAllocatorT() override = default; T * alloc() { return (T *)LocklessAllocator::alloc(); } void free( T * ptr ) { LocklessAllocator::free( ptr ); } } ; } // namespace lmms #endif // LMMS_LOCKLESS_ALLOCATOR_H
1,817
C++
.h
65
25.861538
70
0.748555
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,482
TempoSyncKnob.h
LMMS_lmms/include/TempoSyncKnob.h
/* * TempoSyncKnob.h - adds bpm to ms conversion for knob class * * Copyright (c) 2005-2008 Danny McRae <khjklujn/at/yahoo.com> * Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_TEMPO_SYNC_KNOB_H #define LMMS_GUI_TEMPO_SYNC_KNOB_H #include <QPixmap> #include <QPointer> #include "Knob.h" #include "TempoSyncKnobModel.h" namespace lmms::gui { class MeterDialog; class LMMS_EXPORT TempoSyncKnob : public Knob { Q_OBJECT public: TempoSyncKnob( KnobType knobNum, QWidget* parent = nullptr, const QString& name = QString() ); ~TempoSyncKnob() override; const QString & syncDescription(); void setSyncDescription( const QString & _new_description ); const QPixmap & syncIcon(); void setSyncIcon( const QPixmap & _new_pix ); TempoSyncKnobModel * model() { return castModel<TempoSyncKnobModel>(); } void modelChanged() override; signals: void syncDescriptionChanged( const QString & _new_description ); void syncIconChanged(); protected: void contextMenuEvent( QContextMenuEvent * _me ) override; protected slots: void updateDescAndIcon(); void showCustom(); private: QPixmap m_tempoSyncIcon; QString m_tempoSyncDescription; QPointer<MeterDialog> m_custom; } ; } // namespace lmms::gui #endif // LMMS_GUI_TEMPO_SYNC_KNOB_H
2,102
C++
.h
63
31.285714
95
0.768238
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,483
MainApplication.h
LMMS_lmms/include/MainApplication.h
/* * MainApplication.h - Main QApplication handler * * Copyright (c) 2017-2017 Tres Finocchiaro <tres.finocchiaro/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_MAIN_APPLICATION_H #define LMMS_GUI_MAIN_APPLICATION_H #include "lmmsconfig.h" #include <QApplication> #ifdef LMMS_BUILD_WIN32 #include <windows.h> #include <QAbstractNativeEventFilter> #endif namespace lmms::gui { #if defined(LMMS_BUILD_WIN32) class MainApplication : public QApplication, public QAbstractNativeEventFilter #else class MainApplication : public QApplication #endif { public: MainApplication(int& argc, char** argv); bool event(QEvent* event) override; #ifdef LMMS_BUILD_WIN32 bool winEventFilter(MSG* msg, long* result); bool nativeEventFilter(const QByteArray& eventType, void* message, long* result); #endif inline QString& queuedFile() { return m_queuedFile; } private: QString m_queuedFile; }; } // namespace lmms::gui #endif // LMMS_GUI_MAIN_APPLICATION_H
1,747
C++
.h
56
29.303571
78
0.774405
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,484
AudioDeviceSetupWidget.h
LMMS_lmms/include/AudioDeviceSetupWidget.h
/* * AudioDeviceSetupWidget.h - Base class for audio device setup widgets * * Copyright (c) 2004-2015 Tobias Doerffel <tobydox/at/users.sourceforge.net> * Copyright (c) 2023- Michael Gregorius * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_AUDIO_DEVICE_SETUP_WIDGET_H #define LMMS_GUI_AUDIO_DEVICE_SETUP_WIDGET_H #include <QGroupBox> namespace lmms::gui { class AudioDeviceSetupWidget : public QGroupBox { Q_OBJECT public: AudioDeviceSetupWidget( const QString & _caption, QWidget * _parent ); ~AudioDeviceSetupWidget() override = default; virtual void saveSettings() = 0; virtual void show(); }; } // namespace lmms::gui #endif // LMMS_GUI_AUDIO_DEVICE_SETUP_WIDGET_H
1,454
C++
.h
40
34.35
77
0.762989
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,485
QuadratureLfo.h
LMMS_lmms/include/QuadratureLfo.h
/* * quadraturelfo.h - defination of QuadratureLfo class. * * Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_QUADRATURE_LFO_H #define LMMS_QUADRATURE_LFO_H #include "lmms_math.h" namespace lmms { class QuadratureLfo { public: QuadratureLfo( int sampleRate ) : m_frequency(0), m_phase(0), m_offset(D_PI / 2) { setSampleRate(sampleRate); } ~QuadratureLfo() = default; inline void setFrequency( double frequency ) { if( frequency < 0 || frequency > m_samplerate / 2.0 || frequency == m_frequency ) { return; } m_frequency = frequency; m_increment = m_frequency * m_twoPiOverSr; } inline void restart() { m_phase = 0; } inline void setSampleRate ( int samplerate ) { m_samplerate = samplerate; m_twoPiOverSr = F_2PI / samplerate; m_increment = m_frequency * m_twoPiOverSr; } inline void setOffset( double offsetVal ) { m_offset = offsetVal; } void tick( float *l, float *r ) { *l = sinf( m_phase ); *r = sinf( m_phase + m_offset ); m_phase += m_increment; while (m_phase >= D_2PI) { m_phase -= D_2PI; } } private: double m_frequency; double m_phase; double m_increment; double m_twoPiOverSr; double m_offset; int m_samplerate; }; } // namespace lmms #endif // LMMS_QUADRATURE_LFO_H
2,106
C++
.h
82
23.292683
83
0.71992
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,486
AudioDummy.h
LMMS_lmms/include/AudioDummy.h
/* * AudioDummy.h - dummy audio-device * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_AUDIO_DUMMY_H #define LMMS_AUDIO_DUMMY_H #include "AudioDevice.h" #include "AudioDeviceSetupWidget.h" #include "AudioEngine.h" #include "MicroTimer.h" namespace lmms { class AudioDummy : public QThread, public AudioDevice { Q_OBJECT public: AudioDummy( bool & _success_ful, AudioEngine* audioEngine ) : AudioDevice( DEFAULT_CHANNELS, audioEngine ) { _success_ful = true; } ~AudioDummy() override { stopProcessing(); } inline static QString name() { return QT_TRANSLATE_NOOP( "AudioDeviceSetupWidget", "Dummy (no sound output)" ); } class setupWidget : public gui::AudioDeviceSetupWidget { public: setupWidget( QWidget * _parent ) : gui::AudioDeviceSetupWidget( AudioDummy::name(), _parent ) { } ~setupWidget() override = default; void saveSettings() override { } void show() override { parentWidget()->hide(); QWidget::show(); } } ; private: void startProcessing() override { start(); } void stopProcessing() override { stopProcessingThread( this ); } void run() override { MicroTimer timer; while( true ) { timer.reset(); const SampleFrame* b = audioEngine()->nextBuffer(); if( !b ) { break; } if( audioEngine()->hasFifoWriter() ) { delete[] b; } const int microseconds = static_cast<int>( audioEngine()->framesPerPeriod() * 1000000.0f / audioEngine()->outputSampleRate() - timer.elapsed() ); if( microseconds > 0 ) { usleep( microseconds ); } } } } ; } // namespace lmms #endif // LMMS_AUDIO_DUMMY_H
2,470
C++
.h
99
22.313131
148
0.717992
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,487
Piano.h
LMMS_lmms/include/Piano.h
/* * Piano.h - declaration of class Piano * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_PIANO_H #define LMMS_PIANO_H #include <array> #include "Model.h" #include "Note.h" namespace lmms { class InstrumentTrack; class MidiEventProcessor; class Piano final : public Model { public: enum class KeyType { White, Black } ; Piano(InstrumentTrack* track); void setKeyState(int key, bool state); bool isKeyPressed(int key) const { return m_pressedKeys[key]; } void handleKeyPress(int key, int midiVelocity = -1); void handleKeyRelease(int key); InstrumentTrack* instrumentTrack() const { return m_instrumentTrack; } MidiEventProcessor* midiEventProcessor() const { return m_midiEvProc; } static bool isWhiteKey(int key); static bool isBlackKey(int key); static const unsigned int WhiteKeysPerOctave = 7; static const unsigned int BlackKeysPerOctave = 5; static const unsigned int NumWhiteKeys = 75; static const unsigned int NumBlackKeys = 53; private: static bool isValidKey(int key) { return key >= 0 && key < NumKeys; } InstrumentTrack* m_instrumentTrack; MidiEventProcessor* m_midiEvProc; std::array<bool, NumKeys> m_pressedKeys = {}; } ; } // namespace lmms #endif // LMMS_PIANO_H
2,082
C++
.h
73
26.383562
77
0.763581
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,488
Lv2ControlBase.h
LMMS_lmms/include/Lv2ControlBase.h
/* * Lv2ControlBase.h - Lv2 control base class * * Copyright (c) 2018-2023 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_LV2_CONTROL_BASE_H #define LMMS_LV2_CONTROL_BASE_H #include "lmmsconfig.h" #ifdef LMMS_HAVE_LV2 #include <lilv/lilv.h> #include <memory> #include "DataFile.h" #include "LinkedModelGroups.h" #include "lmms_export.h" #include "Plugin.h" namespace lmms { class Lv2Proc; class PluginIssue; class SampleFrame; /** Common base class for Lv2 plugins This class contains a vector of Lv2Proc, usually 1 (for stereo plugins) or 2 (for mono plugins). Most of the logic is done there, this class primarily forwards work to the Lv2Proc and collects the results. This class provides everything Lv2 plugins have in common. It's not named Lv2Plugin, because * it does not inherit Instrument * the Plugin subclass Effect does not inherit this class This class would usually be a Model subclass. However, Qt doesn't allow this: * inheriting only from Model will cause diamond inheritance for QObject, which will cause errors with Q_OBJECT * making this a direct subclass of Instrument resp. EffectControls would require CRTP, which would make this class a template class, which would conflict with Q_OBJECT The consequence is that this class can neither inherit QObject or Model, nor Instrument or EffectControls, which means in fact: * this class contains no signals or slots, but it offers stubs for slots that shall be called by child classes * this class can not override virtuals of Instrument or EffectControls, so it will offer functions that must be called by virtuals in its child class */ class LMMS_EXPORT Lv2ControlBase : public LinkedModelGroups { public: static Plugin::Type check(const LilvPlugin* m_plugin, std::vector<PluginIssue> &issues); void shutdown(); void init(Model* meAsModel); const LilvPlugin* getPlugin() const { return m_plugin; } Lv2Proc *control(std::size_t idx) { return m_procs[idx].get(); } const Lv2Proc *control(std::size_t idx) const { return m_procs[idx].get(); } bool hasGui() const { return m_hasGUI; } void setHasGui(bool val) { m_hasGUI = val; } protected: /* ctor/dtor */ //! @param that the class inheriting this class and inheriting Model; //! this is the same pointer as this, but a different type //! @param uri the Lv2 URI telling this class what plugin to construct Lv2ControlBase(class Model *that, const QString& uri); Lv2ControlBase(const Lv2ControlBase&) = delete; ~Lv2ControlBase() override; void reload(); Lv2ControlBase& operator=(const Lv2ControlBase&) = delete; /* overrides */ LinkedModelGroup* getGroup(std::size_t idx) override; const LinkedModelGroup* getGroup(std::size_t idx) const override; /* utils for the run thread */ //! Copy values from the LMMS core (connected models, MIDI events, ...) into //! the respective ports void copyModelsFromLmms(); //! Bring values from all ports to the LMMS core void copyModelsToLmms() const; //! Copy buffer passed by LMMS into our ports void copyBuffersFromLmms(const SampleFrame* buf, fpp_t frames); //! Copy our ports into buffers passed by LMMS void copyBuffersToLmms(SampleFrame* buf, fpp_t frames) const; //! Run the Lv2 plugin instance for @param frames frames void run(fpp_t frames); /* load/save, must be called from virtuals */ void saveSettings(QDomDocument &doc, QDomElement &that); void loadSettings(const QDomElement &that); void loadFile(const QString &file); /* more functions that must be called from virtuals */ std::size_t controlCount() const; QString nodeName() const { return "lv2controls"; } bool hasNoteInput() const; void handleMidiInputEvent(const class MidiEvent &event, const class TimePos &time, f_cnt_t offset); private: //! Independent processors //! If this is a mono effect, the vector will have size 2 in order to //! fulfill LMMS' requirement of having stereo input and output std::vector<std::unique_ptr<Lv2Proc>> m_procs; bool m_hasGUI = false; unsigned m_channelsPerProc; const LilvPlugin* m_plugin; }; } // namespace lmms #endif // LMMS_HAVE_LV2 #endif // LMMS_LV2_CONTROL_BASE_H
4,977
C++
.h
130
36.115385
80
0.764535
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,489
RemotePluginBase.h
LMMS_lmms/include/RemotePluginBase.h
/* * RemotePluginBase.h - base class providing RPC like mechanisms * * Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_REMOTE_PLUGIN_BASE_H #define LMMS_REMOTE_PLUGIN_BASE_H #include "MidiEvent.h" #include <atomic> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <cassert> #if !(defined(LMMS_HAVE_SYS_IPC_H) && defined(LMMS_HAVE_SEMAPHORE_H)) #define SYNC_WITH_SHM_FIFO #ifdef LMMS_HAVE_PROCESS_H #include <process.h> #endif #else // !(LMMS_HAVE_SYS_IPC_H && LMMS_HAVE_SEMAPHORE_H) #ifdef LMMS_HAVE_UNISTD_H #include <unistd.h> #endif #endif // !(LMMS_HAVE_SYS_IPC_H && LMMS_HAVE_SEMAPHORE_H) #ifdef LMMS_HAVE_LOCALE_H #include <clocale> #endif #ifdef LMMS_HAVE_PTHREAD_H #include <pthread.h> #endif #ifdef BUILD_REMOTE_PLUGIN_CLIENT #undef LMMS_EXPORT #define LMMS_EXPORT #ifndef SYNC_WITH_SHM_FIFO #include <sys/socket.h> #include <sys/un.h> #endif // SYNC_WITH_SHM_FIFO #else // BUILD_REMOTE_PLUGIN_CLIENT #include "lmms_export.h" #include <QMutex> #include <QProcess> #include <QThread> #include <QString> #include <QUuid> #ifndef SYNC_WITH_SHM_FIFO #include <poll.h> #include <unistd.h> #endif // SYNC_WITH_SHM_FIFO #endif // BUILD_REMOTE_PLUGIN_CLIENT #ifdef SYNC_WITH_SHM_FIFO #include "SharedMemory.h" #include "SystemSemaphore.h" #endif namespace lmms { #ifdef SYNC_WITH_SHM_FIFO // sometimes we need to exchange bigger messages (e.g. for VST parameter dumps) // so set a usable value here const int SHM_FIFO_SIZE = 512*1024; // implements a FIFO inside a shared memory segment class shmFifo { // need this union to handle different sizes of sem_t on 32 bit // and 64 bit platforms union sem32_t { int semKey; char fill[32]; } ; struct shmData { sem32_t dataSem; // semaphore for locking this // FIFO management data sem32_t messageSem; // semaphore for incoming messages int32_t startPtr; // current start of FIFO in memory int32_t endPtr; // current end of FIFO in memory char data[SHM_FIFO_SIZE]; // actual data } ; public: #ifndef BUILD_REMOTE_PLUGIN_CLIENT // constructor for master-side shmFifo() : m_invalid( false ), m_master( true ), m_lockDepth( 0 ) { m_data.create(QUuid::createUuid().toString().toStdString()); m_data->startPtr = m_data->endPtr = 0; static int k = 0; m_data->dataSem.semKey = ( getpid()<<10 ) + ++k; m_data->messageSem.semKey = ( getpid()<<10 ) + ++k; m_dataSem = SystemSemaphore{std::to_string(m_data->dataSem.semKey), 1u}; m_messageSem = SystemSemaphore{std::to_string(m_data->messageSem.semKey), 0u}; } #endif // constructor for remote-/client-side - use _shm_key for making up // the connection to master shmFifo(const std::string& shmKey) : m_invalid( false ), m_master( false ), m_lockDepth( 0 ) { m_data.attach(shmKey); m_dataSem = SystemSemaphore{std::to_string(m_data->dataSem.semKey)}; m_messageSem = SystemSemaphore{std::to_string(m_data->messageSem.semKey)}; } inline bool isInvalid() const { return m_invalid; } void invalidate() { m_invalid = true; } // do we act as master (i.e. not as remote-process?) inline bool isMaster() const { return m_master; } // recursive lock inline void lock() { if( !isInvalid() && m_lockDepth.fetch_add( 1 ) == 0 ) { m_dataSem.acquire(); } } // recursive unlock inline void unlock() { if( m_lockDepth.fetch_sub( 1 ) <= 1 ) { m_dataSem.release(); } } // wait until message-semaphore is available inline void waitForMessage() { if( !isInvalid() ) { m_messageSem.acquire(); } } // increase message-semaphore inline void messageSent() { m_messageSem.release(); } inline int32_t readInt() { int32_t i; read( &i, sizeof( i ) ); return i; } inline void writeInt( const int32_t & _i ) { write( &_i, sizeof( _i ) ); } inline std::string readString() { const int len = readInt(); if( len ) { char * sc = new char[len + 1]; read( sc, len ); sc[len] = 0; std::string s( sc ); delete[] sc; return s; } return std::string(); } inline void writeString( const std::string & _s ) { const int len = _s.size(); writeInt( len ); write( _s.c_str(), len ); } inline bool messagesLeft() { if( isInvalid() ) { return false; } lock(); const bool empty = ( m_data->startPtr == m_data->endPtr ); unlock(); return !empty; } const std::string& shmKey() const { return m_data.key(); } private: static inline void fastMemCpy( void * _dest, const void * _src, const int _len ) { // calling memcpy() for just an integer is obsolete overhead if( _len == 4 ) { *( (int32_t *) _dest ) = *( (int32_t *) _src ); } else { memcpy( _dest, _src, _len ); } } void read( void * _buf, int _len ) { if( isInvalid() ) { memset( _buf, 0, _len ); return; } lock(); while( isInvalid() == false && _len > m_data->endPtr - m_data->startPtr ) { unlock(); #ifndef LMMS_BUILD_WIN32 usleep( 5 ); #endif lock(); } fastMemCpy( _buf, m_data->data + m_data->startPtr, _len ); m_data->startPtr += _len; // nothing left? if( m_data->startPtr == m_data->endPtr ) { // then reset to 0 m_data->startPtr = m_data->endPtr = 0; } unlock(); } void write( const void * _buf, int _len ) { if( isInvalid() || _len > SHM_FIFO_SIZE ) { return; } lock(); while( _len > SHM_FIFO_SIZE - m_data->endPtr ) { // if no space is left, try to move data to front if( m_data->startPtr > 0 ) { memmove( m_data->data, m_data->data + m_data->startPtr, m_data->endPtr - m_data->startPtr ); m_data->endPtr = m_data->endPtr - m_data->startPtr; m_data->startPtr = 0; } unlock(); #ifndef LMMS_BUILD_WIN32 usleep( 5 ); #endif lock(); } fastMemCpy( m_data->data + m_data->endPtr, _buf, _len ); m_data->endPtr += _len; unlock(); } volatile bool m_invalid; bool m_master; SharedMemory<shmData> m_data; SystemSemaphore m_dataSem; SystemSemaphore m_messageSem; std::atomic_int m_lockDepth; }; #endif // SYNC_WITH_SHM_FIFO enum RemoteMessageIDs { IdUndefined, IdHostInfoGotten, IdInitDone, IdQuit, IdSyncKey, IdSampleRateInformation, IdBufferSizeInformation, IdInformationUpdated, IdMidiEvent, IdStartProcessing, IdProcessingDone, IdChangeSharedMemoryKey, IdChangeInputCount, IdChangeOutputCount, IdChangeInputOutputCount, IdShowUI, IdHideUI, IdToggleUI, IdIsUIVisible, IdSaveSettingsToString, IdSaveSettingsToFile, IdLoadSettingsFromString, IdLoadSettingsFromFile, IdSavePresetFile, IdLoadPresetFile, IdDebugMessage, IdIdle, IdUserBase = 64 } ; class LMMS_EXPORT RemotePluginBase { public: struct message { message() : id( IdUndefined ), data() { } message( const message & _m ) = default; message( int _id ) : id( _id ), data() { } inline message & addString( const std::string & _s ) { data.push_back( _s ); return *this; } message & addInt( int _i ) { char buf[32]; std::snprintf(buf, 32, "%d", _i); data.emplace_back( buf ); return *this; } message & addFloat( float _f ) { char buf[32]; std::snprintf(buf, 32, "%f", _f); data.emplace_back( buf ); return *this; } inline std::string getString( int _p = 0 ) const { return data[_p]; } #ifndef BUILD_REMOTE_PLUGIN_CLIENT inline QString getQString( int _p = 0 ) const { return QString::fromStdString( getString( _p ) ); } #endif inline int getInt( int _p = 0 ) const { return atoi( data[_p].c_str() ); } inline float getFloat( int _p ) const { return (float) atof( data[_p].c_str() ); } inline bool operator==( const message & _m ) const { return( id == _m.id ); } int id; private: std::vector<std::string> data; friend class RemotePluginBase; } ; #ifdef SYNC_WITH_SHM_FIFO RemotePluginBase( shmFifo * _in, shmFifo * _out ); #else RemotePluginBase(); #endif virtual ~RemotePluginBase(); #ifdef SYNC_WITH_SHM_FIFO void reset( shmFifo *in, shmFifo *out ) { delete m_in; delete m_out; m_in = in; m_out = out; } #endif int sendMessage( const message & _m ); message receiveMessage(); inline bool isInvalid() const { #ifdef SYNC_WITH_SHM_FIFO return m_in->isInvalid() || m_out->isInvalid(); #else return m_invalid; #endif } message waitForMessage( const message & _m, bool _busy_waiting = false ); inline message fetchAndProcessNextMessage() { message m = receiveMessage(); processMessage( m ); return m; } #ifndef SYNC_WITH_SHM_FIFO inline int32_t readInt() { int32_t i; read( &i, sizeof( i ) ); return i; } inline void writeInt( const int32_t & _i ) { write( &_i, sizeof( _i ) ); } inline std::string readString() { const int len = readInt(); if( len ) { char * sc = new char[len + 1]; read( sc, len ); sc[len] = 0; std::string s( sc ); delete[] sc; return s; } return std::string(); } inline void writeString( const std::string & _s ) { const int len = _s.size(); writeInt( len ); write( _s.c_str(), len ); } #endif // SYNC_WITH_SHM_FIFO #ifndef BUILD_REMOTE_PLUGIN_CLIENT inline bool messagesLeft() { #ifdef SYNC_WITH_SHM_FIFO return m_in->messagesLeft(); #else struct pollfd pollin; pollin.fd = m_socket; pollin.events = POLLIN; if ( poll( &pollin, 1, 0 ) == -1 ) { qWarning( "Unexpected poll error." ); } return pollin.revents & POLLIN; #endif } inline void fetchAndProcessAllMessages() { while( messagesLeft() ) { fetchAndProcessNextMessage(); } } static bool isMainThreadWaiting() { return waitDepthCounter() > 0; } #endif // BUILD_REMOTE_PLUGIN_CLIENT virtual bool processMessage( const message & _m ) = 0; protected: #ifdef SYNC_WITH_SHM_FIFO inline const shmFifo * in() const { return m_in; } inline const shmFifo * out() const { return m_out; } #endif inline void invalidate() { #ifdef SYNC_WITH_SHM_FIFO m_in->invalidate(); m_out->invalidate(); m_in->messageSent(); #else m_invalid = true; #endif } #ifndef SYNC_WITH_SHM_FIFO int m_socket; #endif private: #ifndef BUILD_REMOTE_PLUGIN_CLIENT static int & waitDepthCounter() { static int waitDepth = 0; return waitDepth; } #endif #ifdef SYNC_WITH_SHM_FIFO shmFifo * m_in; shmFifo * m_out; #else void read( void * _buf, int _len ) { if( isInvalid() ) { memset( _buf, 0, _len ); return; } char * buf = (char *) _buf; int remaining = _len; while ( remaining ) { ssize_t nread = ::read( m_socket, buf, remaining ); switch ( nread ) { case -1: fprintf( stderr, "Error while reading.\n" ); case 0: invalidate(); memset( _buf, 0, _len ); return; } buf += nread; remaining -= nread; } } void write( const void * _buf, int _len ) { if( isInvalid() ) { return; } const char * buf = (const char *) _buf; int remaining = _len; while ( remaining ) { ssize_t nwritten = ::write( m_socket, buf, remaining ); switch ( nwritten ) { case -1: fprintf( stderr, "Error while writing.\n" ); case 0: invalidate(); return; } buf += nwritten; remaining -= nwritten; } } bool m_invalid; pthread_mutex_t m_receiveMutex; pthread_mutex_t m_sendMutex; #endif // SYNC_WITH_SHM_FIFO } ; } // namespace lmms #endif // LMMS_REMOTE_PLUGIN_BASE_H
12,239
C++
.h
570
18.778947
80
0.674646
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,490
TrackLabelButton.h
LMMS_lmms/include/TrackLabelButton.h
/* * TrackLabelButton.h - class trackLabelButton * * Copyright (c) 2004-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_TRACK_LABEL_BUTTON_H #define LMMS_GUI_TRACK_LABEL_BUTTON_H #include <string> #include <QToolButton> namespace lmms::gui { class TrackView; class TrackRenameLineEdit; class TrackLabelButton : public QToolButton { Q_OBJECT public: TrackLabelButton( TrackView * _tv, QWidget * _parent ); ~TrackLabelButton() override = default; public slots: void rename(); void renameFinished(); void nameChanged(); protected: void dragEnterEvent( QDragEnterEvent * _dee ) override; void dropEvent( QDropEvent * _de ) override; void mousePressEvent( QMouseEvent * _me ) override; void mouseDoubleClickEvent( QMouseEvent * _me ) override; void mouseReleaseEvent( QMouseEvent * _me ) override; void paintEvent(QPaintEvent* pe) override; void resizeEvent( QResizeEvent * _re ) override; private: bool isInCompactMode() const; private: TrackView * m_trackView; std::string m_iconName; TrackRenameLineEdit * m_renameLineEdit; QRect m_buttonRect; QString elideName( const QString &name ); } ; } // namespace lmms::gui #endif // LMMS_GUI_TRACK_LABEL_BUTTON_H
2,012
C++
.h
60
31.55
77
0.770941
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,491
MicroTimer.h
LMMS_lmms/include/MicroTimer.h
/* * MicroTimer.h - simple high-precision timer * * Copyright (c) 2005-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_MICRO_TIMER_H #define LMMS_MICRO_TIMER_H #include <chrono> namespace lmms { class MicroTimer { using time_point = std::chrono::steady_clock::time_point; public: MicroTimer(); ~MicroTimer() = default; void reset(); int elapsed() const; private: time_point begin; } ; } // namespace lmms #endif // LMMS_MICRO_TIMER_H
1,268
C++
.h
41
29
77
0.752671
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,492
MidiPort.h
LMMS_lmms/include/MidiPort.h
/* * MidiPort.h - abstraction of MIDI ports which are part of LMMS' MIDI * sequencing system * * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_MIDI_PORT_H #define LMMS_MIDI_PORT_H #include <QString> #include <QList> #include <QMap> #include "Midi.h" #include "TimePos.h" #include "AutomatableModel.h" namespace lmms { class MidiClient; class MidiEvent; class MidiEventProcessor; namespace gui { class MidiPortMenu; class ControllerConnectionDialog; class InstrumentMidiIOView; } // class for abstraction of MIDI-port class MidiPort : public Model, public SerializingObject { Q_OBJECT mapPropertyFromModel(int,inputChannel,setInputChannel,m_inputChannelModel); mapPropertyFromModel(int,outputChannel,setOutputChannel,m_outputChannelModel); mapPropertyFromModel(int,inputController,setInputController,m_inputControllerModel); mapPropertyFromModel(int,outputController,setOutputController,m_outputControllerModel); mapPropertyFromModel(int,fixedInputVelocity,setFixedInputVelocity,m_fixedInputVelocityModel); mapPropertyFromModel(int,fixedOutputVelocity,setFixedOutputVelocity,m_fixedOutputVelocityModel); mapPropertyFromModel(int,fixedOutputNote,setFixedOutputNote,m_fixedOutputNoteModel); mapPropertyFromModel(int,outputProgram,setOutputProgram,m_outputProgramModel); mapPropertyFromModel(int,baseVelocity,setBaseVelocity,m_baseVelocityModel); mapPropertyFromModel(bool,isReadable,setReadable,m_readableModel); mapPropertyFromModel(bool,isWritable,setWritable,m_writableModel); public: using Map = QMap<QString, bool>; enum class Mode { Disabled, // don't route any MIDI-events (default) Input, // from MIDI-client to MIDI-event-processor Output, // from MIDI-event-processor to MIDI-client Duplex // both directions } ; MidiPort( const QString& name, MidiClient* client, MidiEventProcessor* eventProcessor, Model* parent = nullptr, Mode mode = Mode::Disabled ); ~MidiPort() override; void setName( const QString& name ); Mode mode() const { return m_mode; } void setMode( Mode mode ); bool isInputEnabled() const { return mode() == Mode::Input || mode() == Mode::Duplex; } bool isOutputEnabled() const { return mode() == Mode::Output || mode() == Mode::Duplex; } int realOutputChannel() const { // There's a possibility of outputChannel being 0 ("--"), which is used to keep all // midi channels when forwarding. In that case, realOutputChannel will return the // default channel 1 (whose value is 0). return outputChannel() ? outputChannel() - 1 : 0; } void processInEvent( const MidiEvent& event, const TimePos& time = TimePos() ); void processOutEvent( const MidiEvent& event, const TimePos& time = TimePos() ); void saveSettings( QDomDocument& doc, QDomElement& thisElement ) override; void loadSettings( const QDomElement& thisElement ) override; QString nodeName() const override { return "midiport"; } void subscribeReadablePort( const QString& port, bool subscribe = true ); void subscribeWritablePort( const QString& port, bool subscribe = true ); const Map& readablePorts() const { return m_readablePorts; } const Map& writablePorts() const { return m_writablePorts; } void invalidateCilent(); gui::MidiPortMenu* m_readablePortsMenu; gui::MidiPortMenu* m_writablePortsMenu; public slots: void updateMidiPortMode(); private slots: void updateReadablePorts(); void updateWritablePorts(); void updateOutputProgram(); private: MidiClient* m_midiClient; MidiEventProcessor* m_midiEventProcessor; Mode m_mode; IntModel m_inputChannelModel; IntModel m_outputChannelModel; IntModel m_inputControllerModel; IntModel m_outputControllerModel; IntModel m_fixedInputVelocityModel; IntModel m_fixedOutputVelocityModel; IntModel m_fixedOutputNoteModel; IntModel m_outputProgramModel; IntModel m_baseVelocityModel; BoolModel m_readableModel; BoolModel m_writableModel; Map m_readablePorts; Map m_writablePorts; friend class gui::ControllerConnectionDialog; friend class gui::InstrumentMidiIOView; signals: void readablePortsChanged(); void writablePortsChanged(); void modeChanged(); } ; using MidiPortList = QList<MidiPort*>; } // namespace lmms #endif // LMMS_MIDI_PORT_H
5,083
C++
.h
148
32.114865
97
0.792885
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,493
ColorChooser.h
LMMS_lmms/include/ColorChooser.h
/* ColorChooser.h - declaration and definition of ColorChooser class. * * Copyright (c) 2019 CYBERDEViLNL <cyberdevilnl/at/protonmail/dot/ch> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_COLOR_CHOOSER_H #define LMMS_GUI_COLOR_CHOOSER_H #include <QApplication> #include <QColor> #include <QColorDialog> #include <QKeyEvent> #include <QVector> namespace lmms::gui { class ColorChooser : public QColorDialog { public: ColorChooser(const QColor &initial, QWidget *parent): QColorDialog(initial, parent) {}; ColorChooser(QWidget *parent): QColorDialog(parent) {}; //! For getting a color without having to initialise a color dialog ColorChooser() = default; enum class Palette {Default, Track, Mixer}; //! Set global palette via array, checking bounds void setPalette (QVector<QColor>); //! Set global paletter via enum void setPalette (Palette); //! Set palette via enum, return self pointer for chaining ColorChooser* withPalette (Palette); //! Return a certain palette static QVector<QColor> getPalette (Palette); protected: //! Forward key events to the parent to prevent stuck notes when the dialog gets focus void keyReleaseEvent(QKeyEvent *event) override { QKeyEvent ke(*event); QApplication::sendEvent(parentWidget(), &ke); } private: //! Copy the current QColorDialog palette into an array static QVector<QColor> defaultPalette(); //! Generate a nice palette, with adjustable value static QVector<QColor> nicePalette (int); }; } // namespace lmms::gui #endif // LMMS_GUI_COLOR_CHOOSER_H
2,294
C++
.h
62
35.112903
88
0.768781
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,494
AudioSdl.h
LMMS_lmms/include/AudioSdl.h
/* * AudioSdl.h - device-class that performs PCM-output via SDL * * Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_AUDIO_SDL_H #define LMMS_AUDIO_SDL_H #include "lmmsconfig.h" #ifdef LMMS_HAVE_SDL #include <SDL2/SDL_audio.h> #include "AudioDevice.h" #include "AudioDeviceSetupWidget.h" class QComboBox; namespace lmms { class AudioSdl : public AudioDevice { public: AudioSdl( bool & _success_ful, AudioEngine* audioEngine ); ~AudioSdl() override; inline static QString name() { return QT_TRANSLATE_NOOP( "AudioDeviceSetupWidget", "SDL (Simple DirectMedia Layer)" ); } class setupWidget : public gui::AudioDeviceSetupWidget { public: setupWidget( QWidget * _parent ); ~setupWidget() override = default; void saveSettings() override; private: void populatePlaybackDeviceComboBox(); void populateInputDeviceComboBox(); private: QComboBox* m_playbackDeviceComboBox = nullptr; QComboBox* m_inputDeviceComboBox = nullptr; static QString s_systemDefaultDevice; } ; private: void startProcessing() override; void stopProcessing() override; static void sdlAudioCallback( void * _udata, Uint8 * _buf, int _len ); void sdlAudioCallback( Uint8 * _buf, int _len ); static void sdlInputAudioCallback( void * _udata, Uint8 * _buf, int _len ); void sdlInputAudioCallback( Uint8 * _buf, int _len ); SDL_AudioSpec m_audioHandle; SampleFrame* m_outBuf; size_t m_currentBufferFramePos; size_t m_currentBufferFramesCount; bool m_stopped; SDL_AudioDeviceID m_outputDevice; SDL_AudioSpec m_inputAudioHandle; SDL_AudioDeviceID m_inputDevice; } ; } // namespace lmms #endif // LMMS_HAVE_SDL #endif // LMMS_AUDIO_SDL_H
2,509
C++
.h
76
30.697368
77
0.76571
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,495
MixerChannelLcdSpinBox.h
LMMS_lmms/include/MixerChannelLcdSpinBox.h
/* * MixerChannelLcdSpinBox.h - a specialization of LcdSpnBox for setting mixer channels * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_MIXER_CHANNEL_LCD_SPIN_BOX_H #define LMMS_GUI_MIXER_CHANNEL_LCD_SPIN_BOX_H #include "LcdSpinBox.h" namespace lmms::gui { class TrackView; class MixerChannelLcdSpinBox : public LcdSpinBox { Q_OBJECT public: MixerChannelLcdSpinBox(int numDigits, QWidget * parent, const QString& name, TrackView * tv = nullptr) : LcdSpinBox(numDigits, parent, name), m_tv(tv) {} ~MixerChannelLcdSpinBox() override = default; void setTrackView(TrackView * tv); protected: void mouseDoubleClickEvent(QMouseEvent* event) override; void contextMenuEvent(QContextMenuEvent* event) override; private: void enterValue(); TrackView * m_tv; }; } // namespace lmms::gui #endif // LMMS_GUI_MIXER_CHANNEL_LCD_SPIN_BOX_H
1,696
C++
.h
47
34.085106
105
0.772477
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,496
MidiPortMenu.h
LMMS_lmms/include/MidiPortMenu.h
/* * MidiPortMenu.h - a menu for subscribing a MidiPort to several external * MIDI ports * * Copyright (c) 2008-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_MIDI_PORT_MENU_H #define LMMS_GUI_MIDI_PORT_MENU_H #include <QMenu> #include "ModelView.h" #include "MidiPort.h" class QAction; namespace lmms::gui { class MidiPortMenu : public QMenu, public ModelView { Q_OBJECT public: MidiPortMenu( MidiPort::Mode _mode ); ~MidiPortMenu() override = default; public slots: void updateMenu(); protected slots: void activatedPort( QAction * _item ); private: void modelChanged() override; MidiPort::Mode m_mode; } ; } // namespace lmms::gui #endif // LMMS_GUI_MIDI_PORT_MENU_H
1,534
C++
.h
48
30
77
0.75034
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,497
EnvelopeAndLfoParameters.h
LMMS_lmms/include/EnvelopeAndLfoParameters.h
/* * EnvelopeAndLfoParameters.h - class EnvelopeAndLfoParameters * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_ENVELOPE_AND_LFO_PARAMETERS_H #define LMMS_ENVELOPE_AND_LFO_PARAMETERS_H #include <memory> #include <vector> #include "JournallingObject.h" #include "AutomatableModel.h" #include "SampleBuffer.h" #include "TempoSyncKnobModel.h" #include "lmms_basics.h" namespace lmms { namespace gui { class EnvelopeAndLfoView; } class LMMS_EXPORT EnvelopeAndLfoParameters : public Model, public JournallingObject { Q_OBJECT public: class LfoInstances { public: LfoInstances() = default; ~LfoInstances() = default; inline bool isEmpty() const { return m_lfos.isEmpty(); } void trigger(); void reset(); void add( EnvelopeAndLfoParameters * lfo ); void remove( EnvelopeAndLfoParameters * lfo ); private: QMutex m_lfoListMutex; using LfoList = QList<EnvelopeAndLfoParameters*>; LfoList m_lfos; }; enum class LfoShape { SineWave, TriangleWave, SawWave, SquareWave, UserDefinedWave, RandomWave, Count }; EnvelopeAndLfoParameters( float _value_for_zero_amount, Model * _parent ); ~EnvelopeAndLfoParameters() override; static inline float expKnobVal( float _val ) { return ( ( _val < 0 ) ? -_val : _val ) * _val; } static LfoInstances * instances() { return s_lfoInstances; } void fillLevel( float * _buf, f_cnt_t _frame, const f_cnt_t _release_begin, const fpp_t _frames ); inline bool isUsed() const { return m_used; } void saveSettings( QDomDocument & _doc, QDomElement & _parent ) override; void loadSettings( const QDomElement & _this ) override; QString nodeName() const override { return "el"; } inline f_cnt_t PAHD_Frames() const { return m_pahdFrames; } inline f_cnt_t releaseFrames() const { return m_rFrames; } // Envelope const FloatModel& getPredelayModel() const { return m_predelayModel; } const FloatModel& getAttackModel() const { return m_attackModel; } const FloatModel& getHoldModel() const { return m_holdModel; } const FloatModel& getDecayModel() const { return m_decayModel; } const FloatModel& getSustainModel() const { return m_sustainModel; } const FloatModel& getReleaseModel() const { return m_releaseModel; } const FloatModel& getAmountModel() const { return m_amountModel; } FloatModel& getAmountModel() { return m_amountModel; } // LFO inline f_cnt_t getLfoPredelayFrames() const { return m_lfoPredelayFrames; } inline f_cnt_t getLfoAttackFrames() const { return m_lfoAttackFrames; } inline f_cnt_t getLfoOscillationFrames() const { return m_lfoOscillationFrames; } const FloatModel& getLfoAmountModel() const { return m_lfoAmountModel; } FloatModel& getLfoAmountModel() { return m_lfoAmountModel; } const TempoSyncKnobModel& getLfoSpeedModel() const { return m_lfoSpeedModel; } const BoolModel& getX100Model() const { return m_x100Model; } const IntModel& getLfoWaveModel() const { return m_lfoWaveModel; } std::shared_ptr<const SampleBuffer> getLfoUserWave() const { return m_userWave; } public slots: void updateSampleVars(); protected: void fillLfoLevel( float * _buf, f_cnt_t _frame, const fpp_t _frames ); private: static LfoInstances * s_lfoInstances; bool m_used; QMutex m_paramMutex; FloatModel m_predelayModel; FloatModel m_attackModel; FloatModel m_holdModel; FloatModel m_decayModel; FloatModel m_sustainModel; FloatModel m_releaseModel; FloatModel m_amountModel; float m_sustainLevel; float m_amount; float m_valueForZeroAmount; float m_amountAdd; f_cnt_t m_pahdFrames; f_cnt_t m_rFrames; sample_t * m_pahdEnv; sample_t * m_rEnv; f_cnt_t m_pahdBufSize; f_cnt_t m_rBufSize; FloatModel m_lfoPredelayModel; FloatModel m_lfoAttackModel; TempoSyncKnobModel m_lfoSpeedModel; FloatModel m_lfoAmountModel; IntModel m_lfoWaveModel; BoolModel m_x100Model; BoolModel m_controlEnvAmountModel; f_cnt_t m_lfoPredelayFrames; f_cnt_t m_lfoAttackFrames; f_cnt_t m_lfoOscillationFrames; f_cnt_t m_lfoFrame; float m_lfoAmount; bool m_lfoAmountIsZero; sample_t * m_lfoShapeData; sample_t m_random; bool m_bad_lfoShapeData; std::shared_ptr<const SampleBuffer> m_userWave = SampleBuffer::emptyBuffer(); constexpr static auto NumLfoShapes = static_cast<std::size_t>(LfoShape::Count); sample_t lfoShapeSample( fpp_t _frame_offset ); void updateLfoShapeData(); friend class gui::EnvelopeAndLfoView; } ; } // namespace lmms #endif // LMMS_ENVELOPE_AND_LFO_PARAMETERS_H
5,332
C++
.h
170
29
83
0.766132
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,498
LocklessList.h
LMMS_lmms/include/LocklessList.h
/* * LocklessList.h - list with lockless push and pop * * Copyright (c) 2016 Javier Serrano Polo <javier@jasp.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_LOCKLESS_LIST_H #define LMMS_LOCKLESS_LIST_H #include "LocklessAllocator.h" #include <atomic> namespace lmms { template<typename T> class LocklessList { public: struct Element { T value; Element * next; } ; LocklessList( size_t size ) : m_first(nullptr), m_allocator(new LocklessAllocatorT<Element>(size)) { } ~LocklessList() { delete m_allocator; } void push( T value ) { Element * e = m_allocator->alloc(); e->value = value; e->next = m_first.load(std::memory_order_relaxed); while (!m_first.compare_exchange_weak(e->next, e, std::memory_order_release, std::memory_order_relaxed)) { // Empty loop (compare_exchange_weak updates e->next) } } Element * popList() { return m_first.exchange(nullptr); } Element * first() { return m_first.load(std::memory_order_acquire); } void setFirst( Element * e ) { m_first.store(e, std::memory_order_release); } void free( Element * e ) { m_allocator->free( e ); } private: std::atomic<Element*> m_first; LocklessAllocatorT<Element> * m_allocator; } ; } // namespace lmms #endif // LMMS_LOCKLESS_LIST_H
2,051
C++
.h
81
22.987654
70
0.724244
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,499
RecentProjectsMenu.h
LMMS_lmms/include/RecentProjectsMenu.h
/* * RecentProjectsMenu.h * * Copyright (c) 2004-2022 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_RECENT_PROJECTS_MENU_H #define LMMS_GUI_RECENT_PROJECTS_MENU_H #include <QMenu> namespace lmms::gui { class RecentProjectsMenu : public QMenu { Q_OBJECT public: RecentProjectsMenu(QWidget *parent = nullptr); private slots: void fillMenu(); void openProject(QAction * _action ); }; } // namespace lmms::gui #endif // LMMS_GUI_RECENT_PROJECTS_MENU_H
1,280
C++
.h
39
30.923077
77
0.762175
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,500
NoCopyNoMove.h
LMMS_lmms/include/NoCopyNoMove.h
/* * NoCopyNoMove.h - NoCopyNoMove class * * Copyright (c) 2023-2023 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_NOCOPYNOMOVE_H #define LMMS_NOCOPYNOMOVE_H namespace lmms { /** * Inherit this class to make your class non-copyable and non-movable */ class NoCopyNoMove { protected: NoCopyNoMove() = default; NoCopyNoMove(const NoCopyNoMove& other) = delete; NoCopyNoMove& operator=(const NoCopyNoMove& other) = delete; NoCopyNoMove(NoCopyNoMove&& other) = delete; NoCopyNoMove& operator=(NoCopyNoMove&& other) = delete; }; } // namespace lmms #endif // LMMS_NOCOPYNOMOVE_H
1,405
C++
.h
41
32.414634
80
0.760677
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,501
MidiAlsaRaw.h
LMMS_lmms/include/MidiAlsaRaw.h
/* * MidiAlsaRaw.h - MIDI client for RawMIDI via ALSA * * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_MIDI_ALSA_RAW_H #define LMMS_MIDI_ALSA_RAW_H #include "lmmsconfig.h" #ifdef LMMS_HAVE_ALSA #include <alsa/asoundlib.h> #include <QMap> #include <QThread> #include "MidiClient.h" struct pollfd; namespace lmms { class MidiAlsaRaw : public QThread, public MidiClientRaw { Q_OBJECT public: MidiAlsaRaw(); ~MidiAlsaRaw() override; static QString probeDevice(); inline static QString name() { return QT_TRANSLATE_NOOP( "MidiSetupWidget", "ALSA Raw-MIDI (Advanced Linux Sound Architecture)" ); } inline static QString configSection() { return "MidiAlsaRaw"; } protected: void sendByte( const unsigned char c ) override; void run() override; private: snd_rawmidi_t * m_input, * * m_inputp; snd_rawmidi_t * m_output, * * m_outputp; int m_npfds; pollfd * m_pfds; volatile bool m_quit; } ; } // namespace lmms #endif // LMMS_HAVE_ALSA #endif // LMMS_MIDI_ALSA_RAW_H
1,847
C++
.h
63
27.190476
77
0.751563
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,502
Clipboard.h
LMMS_lmms/include/Clipboard.h
/* * Clipboard.h - the clipboard for clips, notes etc. * * Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_CLIPBOARD_H #define LMMS_CLIPBOARD_H #include <QDomElement> #include <QMap> #include "lmms_export.h" class QMimeData; namespace lmms::Clipboard { enum class MimeType { StringPair, Default }; // Convenience Methods const QMimeData * getMimeData(); bool hasFormat( MimeType mT ); // Helper methods for String data void LMMS_EXPORT copyString(const QString& str, MimeType mT); QString getString( MimeType mT ); // Helper methods for String Pair data void copyStringPair( const QString & key, const QString & value ); QString decodeKey( const QMimeData * mimeData ); QString decodeValue( const QMimeData * mimeData ); inline const char * mimeType( MimeType type ) { switch( type ) { case MimeType::StringPair: return "application/x-lmms-stringpair"; break; case MimeType::Default: default: return "application/x-lmms-clipboard"; break; } } } // namespace lmms::Clipboard #endif // LMMS_CLIPBOARD_H
1,900
C++
.h
61
28.770492
77
0.750411
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,503
CPULoadWidget.h
LMMS_lmms/include/CPULoadWidget.h
/* * CPULoadWidget.h - widget for displaying CPU-load (partly based on * Hydrogen's CPU-load-widget) * * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_CPU_LOAD_WIDGET_H #define LMMS_GUI_CPU_LOAD_WIDGET_H #include <algorithm> #include <QTimer> #include <QPixmap> #include <QWidget> #include "lmms_basics.h" namespace lmms::gui { class CPULoadWidget : public QWidget { Q_OBJECT Q_PROPERTY(int stepSize MEMBER m_stepSize) public: CPULoadWidget( QWidget * _parent ); ~CPULoadWidget() override = default; protected: void paintEvent( QPaintEvent * _ev ) override; protected slots: void updateCpuLoad(); private: int stepSize() const { return std::max(1, m_stepSize); } int m_currentLoad; QPixmap m_temp; QPixmap m_background; QPixmap m_leds; bool m_changed; QTimer m_updateTimer; int m_stepSize = 1; } ; } // namespace lmms::gui #endif // LMMS_GUI_CPU_LOAD_WIDGET_H
1,759
C++
.h
56
29.357143
77
0.748959
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,504
StepRecorderWidget.h
LMMS_lmms/include/StepRecorderWidget.h
/* * StepRecorderWidget.h - widget that provide gui markers for step recording * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of"the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_STEP_RECOREDER_WIDGET_H #define LMMS_GUI_STEP_RECOREDER_WIDGET_H #include <QWidget> #include <QColor> #include "TimePos.h" namespace lmms::gui { class StepRecorderWidget : public QWidget { Q_OBJECT public: StepRecorderWidget( QWidget * parent, const int ppb, const int marginTop, const int marginBottom, const int marginLeft, const int marginRight); //API used by PianoRoll void setPixelsPerBar(int ppb); void setCurrentPosition(TimePos currentPosition); void setMargins(const QMargins &qm); void setBottomMargin(const int marginBottom); QMargins margins(); //API used by StepRecorder void setStepsLength(TimePos stepsLength); void setStartPosition(TimePos pos); void setEndPosition(TimePos pos); void showHint(); private: void paintEvent(QPaintEvent * pe) override; int xCoordOfTick(int tick); void drawVerLine(QPainter* painter, int x, const QColor& color, int top, int bottom); void drawVerLine(QPainter* painter, const TimePos& pos, const QColor& color, int top, int bottom); void updateBoundaries(); TimePos m_stepsLength; TimePos m_curStepStartPos; TimePos m_curStepEndPos; int m_ppb; // pixels per bar TimePos m_currentPosition; // current position showed by on PianoRoll QColor m_colorLineStart; QColor m_colorLineEnd; // boundaries within piano roll window int m_top; int m_bottom; int m_left; int m_right; const int m_marginTop; int m_marginBottom; // not const since can change on resize of edit-note area const int m_marginLeft; const int m_marginRight; signals: void positionChanged(const lmms::TimePos & t); } ; } // namespace lmms::gui #endif // LMMS_GUI_STEP_RECOREDER_WIDGET_H
2,553
C++
.h
77
31.012987
99
0.777597
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,505
AutomationTrackView.h
LMMS_lmms/include/AutomationTrackView.h
/* * AutomationTrackView.h - declaration of class AutomationTrackView * * Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * Copyright (c) 2006-2008 Javier Serrano Polo <jasp00/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_AUTOMATION_TRACK_VIEW_H #define LMMS_GUI_AUTOMATION_TRACK_VIEW_H #include "TrackView.h" namespace lmms { class AutomationTrack; namespace gui { class AutomationTrackView : public TrackView { public: AutomationTrackView( AutomationTrack* at, TrackContainerView* tcv ); ~AutomationTrackView() override = default; void dragEnterEvent( QDragEnterEvent * _dee ) override; void dropEvent( QDropEvent * _de ) override; } ; } // namespace gui } // namespace lmms #endif // LMMS_GUI_AUTOMATION_TRACK_VIEW_H
1,558
C++
.h
43
34.325581
80
0.772455
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,506
DummyPlugin.h
LMMS_lmms/include/DummyPlugin.h
/* * DummyPlugin.h - empty plugin which is used as fallback if a plugin couldn't * be found * * Copyright (c) 2005-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_DUMMY_PLUGIN_H #define LMMS_DUMMY_PLUGIN_H #include "Plugin.h" #include "PluginView.h" namespace lmms { class DummyPlugin : public Plugin { public: DummyPlugin() : Plugin( nullptr, nullptr ) { } ~DummyPlugin() override = default; void saveSettings( QDomDocument &, QDomElement & ) override { } void loadSettings( const QDomElement & ) override { } QString nodeName() const override { return "DummyPlugin"; } protected: gui::PluginView * instantiateView( QWidget * _parent ) override { return new gui::PluginView( this, _parent ); } } ; } // namespace lmms #endif // LMMS_DUMMY_PLUGIN_H
1,621
C++
.h
56
26.875
78
0.74
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,509
PluginView.h
LMMS_lmms/include/PluginView.h
/* * PluginView.h - declaration of class PluginView * * Copyright (c) 2008-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_PLUGIN_VIEW_H #define LMMS_GUI_PLUGIN_VIEW_H #include <QWidget> #include "ModelView.h" #include "Plugin.h" namespace lmms::gui { class LMMS_EXPORT PluginView : public QWidget, public ModelView { public: PluginView(Plugin* _plugin, QWidget* _parent) : QWidget(_parent) , ModelView(_plugin, this) { } virtual bool isResizable() const { return false; } }; } // namespace lmms::gui #endif // LMMS_GUI_PLUGIN_VIEW_H
1,372
C++
.h
41
31.536585
77
0.752079
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,510
MidiEventToByteSeq.h
LMMS_lmms/include/MidiEventToByteSeq.h
/* * MidiEventToByteSeq.h - writeToByteSeq declaration * * Copyright (c) 2020-2020 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_MIDIEVENTTOBYTESEQ_H #define LMMS_MIDIEVENTTOBYTESEQ_H #include <cstddef> #include <cstdint> #include "lmms_export.h" namespace lmms { /** Write MIDI event into byte sequence. Conforming to http://lv2plug.in/ns/ext/midi#MidiEvent @param data Pointer to the target buffer for the byte sequence. Must point to existing memory with at least 3 bytes size. @param bufsize Available size of the target buffer. @return Used size of the target buffer, or 0 if the MidiEvent could not be converted. */ std::size_t LMMS_EXPORT writeToByteSeq( const class MidiEvent& ev, uint8_t* data, std::size_t bufsize ); } // namespace lmms #endif // LMMS_MIDIEVENTTOBYTESEQ_H
1,631
C++
.h
43
35.72093
80
0.762207
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,511
Note.h
LMMS_lmms/include/Note.h
/* * Note.h - declaration of class note which contains all informations about a * note + definitions of several constants and enums * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_NOTE_H #define LMMS_NOTE_H #include <optional> #include <vector> #include "volume.h" #include "panning.h" #include "SerializingObject.h" #include "TimePos.h" namespace lmms { class DetuningHelper; enum class Key : int { C = 0, Cis = 1, Des = 1, D = 2, Dis = 3, Es = 3, E = 4, Fes = 4, F = 5, Fis = 6, Ges = 6, G = 7, Gis = 8, As = 8, A = 9, Ais = 10, B = 10, H = 11 } ; enum class Octave : int { Octave_m1, // MIDI standard starts at C-1 Octave_0, Octave_1, Octave_2, Octave_3, Octave_4, Octave_5, Octave_6, Octave_7, Octave_8, Octave_9, // incomplete octave, MIDI only goes up to G9 }; const int FirstOctave = -1; const int KeysPerOctave = 12; constexpr inline auto operator+(Octave octave, Key key) -> int { return static_cast<int>(octave) * KeysPerOctave + static_cast<int>(key); } constexpr auto DefaultOctave = Octave::Octave_4; const int DefaultKey = DefaultOctave + Key::A; //! Number of physical keys, limited to MIDI range (valid for both MIDI 1.0 and 2.0) const int NumKeys = 128; const int DefaultMiddleKey = Octave::Octave_4 + Key::C; const int DefaultBaseKey = Octave::Octave_4 + Key::A; const float DefaultBaseFreq = 440.f; const float MaxDetuning = 5 * 12.0f; class LMMS_EXPORT Note : public SerializingObject { public: Note( const TimePos & length = TimePos( 0 ), const TimePos & pos = TimePos( 0 ), int key = DefaultKey, volume_t volume = DefaultVolume, panning_t panning = DefaultPanning, DetuningHelper * detuning = nullptr ); Note( const Note & note ); ~Note() override; // Note types enum class Type { Regular = 0, Step }; Type type() const { return m_type; } inline void setType(Type t) { m_type = t; } // used by GUI inline void setSelected( const bool selected ) { m_selected = selected; } inline void setOldKey( const int oldKey ) { m_oldKey = oldKey; } inline void setOldPos( const TimePos & oldPos ) { m_oldPos = oldPos; } inline void setOldLength( const TimePos & oldLength ) { m_oldLength = oldLength; } inline void setIsPlaying( const bool isPlaying ) { m_isPlaying = isPlaying; } void setLength( const TimePos & length ); void setPos( const TimePos & pos ); void setKey( const int key ); virtual void setVolume( volume_t volume ); virtual void setPanning( panning_t panning ); void quantizeLength( const int qGrid ); void quantizePos( const int qGrid ); static inline bool lessThan( const Note * lhs, const Note * rhs ) { // function to compare two notes - must be called explictly when // using qSort if( (int)( *lhs ).pos() < (int)( *rhs ).pos() ) { return true; } else if( (int)( *lhs ).pos() > (int)( *rhs ).pos() ) { return false; } return ( (int)( *lhs ).key() > (int)( *rhs ).key() ); } inline bool selected() const { return m_selected; } inline int oldKey() const { return m_oldKey; } inline TimePos oldPos() const { return m_oldPos; } inline TimePos oldLength() const { return m_oldLength; } inline bool isPlaying() const { return m_isPlaying; } inline TimePos endPos() const { const int l = length(); return pos() + l; } inline const TimePos & length() const { return m_length; } inline const TimePos & pos() const { return m_pos; } inline TimePos pos( TimePos basePos ) const { const int bp = basePos; return m_pos - bp; } inline int key() const { return m_key; } inline volume_t getVolume() const { return m_volume; } int midiVelocity( int midiBaseVelocity ) const { return std::min(MidiMaxVelocity, getVolume() * midiBaseVelocity / DefaultVolume); } inline panning_t getPanning() const { return m_panning; } static QString classNodeName() { return "note"; } inline QString nodeName() const override { return classNodeName(); } static TimePos quantized( const TimePos & m, const int qGrid ); DetuningHelper * detuning() const { return m_detuning; } bool hasDetuningInfo() const; bool withinRange(int tickStart, int tickEnd) const; void createDetuning(); protected: void saveSettings( QDomDocument & doc, QDomElement & parent ) override; void loadSettings( const QDomElement & _this ) override; private: // for piano roll editing bool m_selected; int m_oldKey; TimePos m_oldPos; TimePos m_oldLength; bool m_isPlaying; int m_key; volume_t m_volume; panning_t m_panning; TimePos m_length; TimePos m_pos; DetuningHelper * m_detuning; Type m_type = Type::Regular; }; using NoteVector = std::vector<Note*>; struct NoteBounds { TimePos start; TimePos end; int lowest; int highest; }; std::optional<NoteBounds> boundsForNotes(const NoteVector& notes); } // namespace lmms #endif // LMMS_NOTE_H
5,719
C++
.h
229
22.742358
84
0.716915
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,512
MidiClip.h
LMMS_lmms/include/MidiClip.h
/* * MidiClip.h - declaration of class MidiClip, which contains all information * about a clip * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_MIDI_CLIP_H #define LMMS_MIDI_CLIP_H #include "Clip.h" #include "Note.h" namespace lmms { class InstrumentTrack; namespace gui { class MidiClipView; } class LMMS_EXPORT MidiClip : public Clip { Q_OBJECT public: enum class Type { BeatClip, MelodyClip } ; MidiClip( InstrumentTrack* instrumentTrack ); MidiClip( const MidiClip& other ); ~MidiClip() override; void init(); void updateLength(); // note management Note * addNote( const Note & _new_note, const bool _quant_pos = true ); NoteVector::const_iterator removeNote(NoteVector::const_iterator it); NoteVector::const_iterator removeNote(Note* note); Note * noteAtStep( int _step ); void rearrangeAllNotes(); void clearNotes(); inline const NoteVector & notes() const { return m_notes; } Note * addStepNote( int step ); void setStep( int step, bool enabled ); // Split the list of notes on the given position void splitNotes(const NoteVector& notes, TimePos pos); // clip-type stuff inline Type type() const { return m_clipType; } // next/previous track based on position in the containing track MidiClip * previousMidiClip() const; MidiClip * nextMidiClip() const; // settings-management void saveSettings( QDomDocument & _doc, QDomElement & _parent ) override; void loadSettings( const QDomElement & _this ) override; inline QString nodeName() const override { return "midiclip"; } inline InstrumentTrack * instrumentTrack() const { return m_instrumentTrack; } bool empty(); gui::ClipView * createView( gui::TrackView * _tv ) override; using Model::dataChanged; public slots: void addSteps(); void cloneSteps(); void removeSteps(); void clear(); protected: void updatePatternTrack(); protected slots: void changeTimeSignature(); private: TimePos beatClipLength() const; void setType( Type _new_clip_type ); void checkType(); void resizeToFirstTrack(); InstrumentTrack * m_instrumentTrack; Type m_clipType; // data-stuff NoteVector m_notes; int m_steps; MidiClip * adjacentMidiClipByOffset(int offset) const; friend class gui::MidiClipView; signals: void destroyedMidiClip( lmms::MidiClip* ); } ; } // namespace lmms #endif // LMMS_MIDI_CLIP_H
3,213
C++
.h
112
26.428571
77
0.756792
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,513
Lv2UridMap.h
LMMS_lmms/include/Lv2UridMap.h
/* * Lv2UridMap.cpp - Lv2UridMap class * * Copyright (c) 2019 Johannes Lorenz <j.git$$$lorenz-ho.me, $$$=@> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_LV2_URID_MAP_H #define LMMS_LV2_URID_MAP_H #include "lmmsconfig.h" #ifdef LMMS_HAVE_LV2 #include <lv2/urid/urid.h> #include <mutex> // TODO: use semaphore, even though this is not realtime critical #include <string> #include <unordered_map> #include <vector> namespace lmms { /** * Complete implementation of the Lv2 Urid Map extension */ class UridMap { std::unordered_map<std::string, LV2_URID> m_map; std::vector<const char*> m_unMap; //! mutex for both m_map and m_unMap //! the URID map is global, which is why a mutex is required here std::mutex m_MapMutex; LV2_URID_Map m_mapFeature; LV2_URID_Unmap m_unmapFeature; public: //! constructor; will set up the features UridMap(); //! map feature function LV2_URID map(const char* uri); //! unmap feature function const char* unmap(LV2_URID urid); // access the features LV2_URID_Map* mapFeature() { return &m_mapFeature; } LV2_URID_Unmap* unmapFeature() { return &m_unmapFeature; } }; } // namespace lmms #endif // LMMS_HAVE_LV2 #endif // LMMS_LV2_URID_MAP_H
1,965
C++
.h
60
30.8
82
0.740466
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,514
AudioOss.h
LMMS_lmms/include/AudioOss.h
/* * AudioOss.h - device-class that implements OSS-PCM-output * * Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_AUDIO_OSS_H #define LMMS_AUDIO_OSS_H #include "lmmsconfig.h" #ifdef LMMS_HAVE_OSS #include <QThread> #include "AudioDevice.h" #include "AudioDeviceSetupWidget.h" class QLineEdit; namespace lmms { namespace gui { class LcdSpinBox; } class AudioOss : public QThread, public AudioDevice { Q_OBJECT public: AudioOss( bool & _success_ful, AudioEngine* audioEngine ); ~AudioOss() override; inline static QString name() { return QT_TRANSLATE_NOOP( "AudioDeviceSetupWidget", "OSS (Open Sound System)" ); } static QString probeDevice(); class setupWidget : public gui::AudioDeviceSetupWidget { public: setupWidget( QWidget * _parent ); ~setupWidget() override; void saveSettings() override; private: QLineEdit * m_device; gui::LcdSpinBox * m_channels; } ; private: void startProcessing() override; void stopProcessing() override; void run() override; int m_audioFD; bool m_convertEndian; } ; } // namespace lmms #endif // LMMS_HAVE_OSS #endif // LMMS_AUDIO_OSS_H
1,959
C++
.h
68
26.691176
82
0.760858
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,515
IoHelper.h
LMMS_lmms/include/IoHelper.h
/* * IoHelper.h - helper functions for file I/O * * Copyright (c) 2018 Hyunjin Song <tteu.ingog/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_IO_HELPER_H #define LMMS_IO_HELPER_H #include "lmmsconfig.h" #include <cstdio> #ifdef _WIN32 #include <windows.h> #endif #ifdef LMMS_BUILD_WIN32 #include <io.h> #else #ifdef LMMS_HAVE_UNISTD_H #include <unistd.h> #endif #endif // LMMS_BUILD_WIN32 namespace lmms { #ifdef _WIN32 inline std::wstring toWString(const std::string& s) { std::wstring ret; int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s.length(), nullptr, 0); if (len == 0) { return ret; } ret.resize(len); MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s.length(), &ret[0], len); return ret; } #endif inline FILE* F_OPEN_UTF8(std::string const& fname, const char* mode){ #ifdef LMMS_BUILD_WIN32 return _wfopen(toWString(fname).data(), toWString(mode).data()); #else return fopen(fname.data(), mode); #endif } inline int fileToDescriptor(FILE* f, bool closeFile = true) { if (f == nullptr) {return -1;} #ifdef LMMS_BUILD_WIN32 int fh = _dup(_fileno(f)); #else int fh = dup(fileno(f)); #endif if (closeFile) {fclose(f);} return fh; } } // namespace lmms #endif // LMMS_IO_HELPER_H
2,039
C++
.h
74
25.72973
88
0.732785
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,516
ColorHelper.h
LMMS_lmms/include/ColorHelper.h
/* ColorHelper.h - Helper methods for color related algorithms, etc. * * Copyright (c) 2024- Michael Gregorius * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_COLOR_HELPER_H #define LMMS_GUI_COLOR_HELPER_H #include <QColor> namespace lmms::gui { class ColorHelper { public: static QColor interpolateInRgb(const QColor& a, const QColor& b, float t) { qreal ar, ag, ab, aa; a.getRgbF(&ar, &ag, &ab, &aa); qreal br, bg, bb, ba; b.getRgbF(&br, &bg, &bb, &ba); const float interH = lerp(ar, br, t); const float interS = lerp(ag, bg, t); const float interV = lerp(ab, bb, t); const float interA = lerp(aa, ba, t); return QColor::fromRgbF(interH, interS, interV, interA); } }; } // namespace lmms::gui #endif // LMMS_GUI_COLOR_HELPER_H
1,524
C++
.h
45
31.733333
74
0.726531
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,517
Scale.h
LMMS_lmms/include/Scale.h
/* * Scale.h - holds information about a scale and its intervals * * Copyright (c) 2020 Martin Pavelek <he29.HS/at/gmail.com> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_SCALE_H #define LMMS_SCALE_H #include <cstdint> #include <vector> #include <QObject> #include <QString> #include "SerializingObject.h" namespace lmms { class Interval : public SerializingObject { public: Interval() : m_numerator(1), m_denominator(1), m_cents(0), m_ratio(1) {}; explicit Interval(float cents); Interval(uint32_t numerator, uint32_t denominator); float getRatio() const {return m_ratio;} QString getString() const { if (m_denominator) {return QString::number(m_numerator) + "/" + QString::number(m_denominator);} else {return QString("%1").arg(m_cents, 0, 'f', 4);} } void saveSettings(QDomDocument &doc, QDomElement &element) override; void loadSettings(const QDomElement &element) override; inline QString nodeName() const override {return "interval";} private: // Scala specifies that numerators and denominators should go at least up to 2147483647 → use uint32_t. uint32_t m_numerator; //!< numerator of the interval fraction uint32_t m_denominator; //!< denominator of the interval fraction float m_cents; //!< interval defined in cents (used when denominator is set to zero) float m_ratio; //!< precomputed output value for better performance }; class Scale : public QObject, public SerializingObject { Q_OBJECT public: Scale(); Scale(QString description, std::vector<Interval> intervals); QString getDescription() const; void setDescription(QString description); const std::vector<Interval> &getIntervals() const {return m_intervals;} void setIntervals(std::vector<Interval> input) {m_intervals = std::move(input);} void saveSettings(QDomDocument &doc, QDomElement &element) override; void loadSettings(const QDomElement &element) override; inline QString nodeName() const override {return "scale";} private: QString m_description; //!< name or description of the scale std::vector<Interval> m_intervals; //!< a series of ratios that define the scale }; } // namespace lmms #endif // LMMS_SCALE_H
2,949
C++
.h
73
38.410959
106
0.749387
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,518
SideBar.h
LMMS_lmms/include/SideBar.h
/* * SideBar.h - side-bar in LMMS' MainWindow * * Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_SIDE_BAR_H #define LMMS_GUI_SIDE_BAR_H #include <QMap> #include <QButtonGroup> #include <QToolBar> class QToolButton; namespace lmms::gui { class SideBarWidget; class SideBar : public QToolBar { Q_OBJECT public: SideBar( Qt::Orientation _orientation, QWidget * _parent ); ~SideBar() override = default; void appendTab( SideBarWidget * _sbw ); private slots: void toggleButton( QAbstractButton * _btn ); private: QButtonGroup m_btnGroup; using ButtonMap = QMap<QToolButton*, QWidget*>; ButtonMap m_widgets; } ; } // namespace lmms::gui #endif // LMMS_GUI_SIDE_BAR_H
1,527
C++
.h
48
29.875
77
0.757514
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,519
SampleTrackView.h
LMMS_lmms/include/SampleTrackView.h
/* * SampleTrackView.h * * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef LMMS_GUI_SAMPLE_TRACK_VIEW_H #define LMMS_GUI_SAMPLE_TRACK_VIEW_H #include "MixerChannelLcdSpinBox.h" #include "TrackView.h" namespace lmms { class SampleTrack; namespace gui { class Knob; class SampleTrackWindow; class TrackLabelButton; class SampleTrackView : public TrackView { Q_OBJECT public: SampleTrackView( SampleTrack* Track, TrackContainerView* tcv ); ~SampleTrackView() override; SampleTrackWindow * getSampleTrackWindow() { return m_window; } SampleTrack * model() { return castModel<SampleTrack>(); } const SampleTrack * model() const { return castModel<SampleTrack>(); } QMenu * createMixerMenu( QString title, QString newMixerLabel ) override; public slots: void showEffects(); void updateIndicator(); protected: void modelChanged() override; QString nodeName() const override { return "SampleTrackView"; } void dragEnterEvent(QDragEnterEvent *dee) override; void dropEvent(QDropEvent *de) override; private slots: void assignMixerLine( int channelIndex ); void createMixerLine(); private: SampleTrackWindow * m_window; MixerChannelLcdSpinBox* m_mixerChannelNumber; Knob * m_volumeKnob; Knob * m_panningKnob; FadeButton * m_activityIndicator; TrackLabelButton * m_tlb; FadeButton * getActivityIndicator() override { return m_activityIndicator; } friend class SampleTrackWindow; } ; } // namespace gui } // namespace lmms #endif // LMMS_GUI_SAMPLE_TRACK_VIEW_H
2,355
C++
.h
84
25.904762
77
0.780009
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,520
UpgradeExtendedNoteRange.h
LMMS_lmms/src/core/UpgradeExtendedNoteRange.h
/* * UpgradeExtendedNoteRange.h - Upgrades the extended note range * * This file is part of LMMS - https://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #pragma once #ifndef LMMS_UPGRADEEXTENDEDNOTERANGE_H #define LMMS_UPGRADEEXTENDEDNOTERANGE_H class QDomElement; namespace lmms { class UpgradeExtendedNoteRange { public: UpgradeExtendedNoteRange(QDomElement & domElement); void upgrade(); private: QDomElement & m_domElement; }; } // namespace lmms #endif // LMMS_UPGRADEEXTENDEDNOTERANGE_H
1,215
C++
.h
37
30.945946
70
0.781678
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,521
connectionitem.cpp
shadowsocks_shadowsocks-qt5/src/connectionitem.cpp
#include "connectionitem.h" #include <QFont> #include <cmath> ConnectionItem::ConnectionItem(Connection *_con, QObject *parent) : QObject(parent), con(_con) { if (con) { con->setParent(this); connect(con, &Connection::stateChanged, this, &ConnectionItem::onConnectionStateChanged); connect(con, &Connection::stateChanged, this, &ConnectionItem::stateChanged); connect(con, &Connection::dataUsageChanged, this, &ConnectionItem::dataUsageChanged); connect(con, &Connection::latencyAvailable, this, &ConnectionItem::onConnectionPingFinished); connect(con, &Connection::latencyAvailable, this, &ConnectionItem::latencyChanged); connect(con, &Connection::startFailed, this, &ConnectionItem::onStartFailed); } } const QStringList ConnectionItem::bytesUnits = QStringList() << " B" << " KiB" << " MiB" << " GiB" << " TiB" << " PiB" << " EiB" << " ZiB" << " YiB"; int ConnectionItem::columnCount() { return 9; } QVariant ConnectionItem::data(int column, int role) const { if (!con) { return QVariant(); } if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (column) { case 0://name return QVariant(con->profile.name); case 1://server return QVariant(con->profile.serverAddress); case 2://status return con->isRunning() ? QVariant(tr("Connected")) : QVariant(tr("Disconnected")); case 3://latency if (role == Qt::DisplayRole) { return QVariant(convertLatencyToString(con->profile.latency)); } else { return QVariant(con->profile.latency); } case 4://local port return QVariant(con->profile.localPort); case 5://data usage (term) if (role == Qt::DisplayRole) { return QVariant(convertBytesToHumanReadable(con->profile.currentUsage)); } else { return QVariant(con->profile.currentUsage); } case 6://data usage (total) if (role == Qt::DisplayRole) { return QVariant(convertBytesToHumanReadable(con->profile.totalUsage)); } else { return QVariant(con->profile.totalUsage); } case 7://reset date if (role == Qt::DisplayRole) { return QVariant(con->profile.nextResetDate.toString(Qt::SystemLocaleShortDate)); } else { return QVariant(con->profile.nextResetDate); } case 8://last used if (role == Qt::DisplayRole) { return QVariant(con->profile.lastTime.toString(Qt::SystemLocaleShortDate)); } else { return QVariant(con->profile.lastTime); } default: return QVariant(); } } else if (role == Qt::FontRole) { QFont font; font.setBold(con->isRunning()); return QVariant(font); } return QVariant(); } QString ConnectionItem::convertLatencyToString(const int latency) { QString latencyStr; switch (latency) { case SQProfile::LATENCY_TIMEOUT: latencyStr = tr("Timeout"); break; case SQProfile::LATENCY_ERROR: latencyStr = tr("Error"); break; case SQProfile::LATENCY_UNKNOWN: latencyStr = tr("Unknown"); break; default: if (latency >= 1000) { latencyStr = QString::number(static_cast<double>(latency) / 1000.0) + QStringLiteral(" ") + tr("s"); } else { latencyStr = QString::number(latency) + QStringLiteral(" ") + tr("ms"); } } return latencyStr; } QString ConnectionItem::convertBytesToHumanReadable(quint64 quot) { int unitId = 0; quint64 rem = 0; for (; quot > 1024; ++unitId) { rem = quot % 1024;//the previous rem would be negligible quot /= 1024; } double output = static_cast<double>(quot) + static_cast<double>(rem) / 1024.0; return QString("%1 %2").arg(output, 0, 'f', 2).arg(bytesUnits.at(unitId)); } void ConnectionItem::testLatency() { con->latencyTest(); } Connection* ConnectionItem::getConnection() { return con; } void ConnectionItem::onConnectionStateChanged(bool running) { if (running) { emit message(con->getName() + " " + tr("connected")); } else { emit message(con->getName() + " " + tr("disconnected")); } } void ConnectionItem::onConnectionPingFinished(const int latency) { if (latency == SQProfile::LATENCY_TIMEOUT) { emit message(con->getName() + " " + tr("timed out")); } else if (latency == SQProfile::LATENCY_ERROR) { emit message(con->getName() + " " + tr("latency test failed")); } } void ConnectionItem::onStartFailed() { emit message(tr("Failed to start") + " " + con->getName()); }
4,975
C++
.cpp
143
27.006993
101
0.597427
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,523
sqprofile.cpp
shadowsocks_shadowsocks-qt5/src/sqprofile.cpp
#include "sqprofile.h" SQProfile::SQProfile() { autoStart = false; debug = false; serverPort = 8388; localPort = 1080; name = QObject::tr("Unnamed Profile"); localAddress = QString("127.0.0.1"); method = QString("RC4-MD5"); timeout = 600; latency = LATENCY_UNKNOWN; currentUsage = 0; totalUsage = 0; QDate currentDate = QDate::currentDate(); nextResetDate = QDate(currentDate.year(), currentDate.month() + 1, 1); httpMode = false; } SQProfile::SQProfile(const QSS::Profile &profile) : SQProfile() { name = QString::fromStdString(profile.name()); localAddress = QString::fromStdString(profile.localAddress()); localPort = profile.localPort(); serverPort = profile.serverPort(); serverAddress = QString::fromStdString(profile.serverAddress()); method = QString::fromStdString(profile.method()).toUpper(); password = QString::fromStdString(profile.password()); timeout = profile.timeout(); httpMode = profile.httpProxy(); debug = profile.debug(); } SQProfile::SQProfile(const QString &uri) { *this = SQProfile(QSS::Profile::fromUri(uri.toStdString())); } QSS::Profile SQProfile::toProfile() const { QSS::Profile qssprofile; qssprofile.setName(name.toStdString()); qssprofile.setServerAddress(serverAddress.toStdString()); qssprofile.setServerPort(serverPort); qssprofile.setLocalAddress(localAddress.toStdString()); qssprofile.setLocalPort(localPort); qssprofile.setMethod(method.toLower().toStdString()); qssprofile.setPassword(password.toStdString()); qssprofile.setTimeout(timeout); qssprofile.setHttpProxy(httpMode); if (debug) { qssprofile.enableDebug(); } else { qssprofile.disableDebug(); } return qssprofile; } QDataStream& operator << (QDataStream &out, const SQProfile &p) { out << p.autoStart << p.debug << p.serverPort << p.localPort << p.name << p.serverAddress << p.localAddress << p.method << p.password << p.timeout << p.latency << p.currentUsage << p.totalUsage << p.lastTime << p.nextResetDate << p.httpMode; return out; } QDataStream& operator >> (QDataStream &in, SQProfile &p) { in >> p.autoStart >> p.debug >> p.serverPort >> p.localPort >> p.name >> p.serverAddress >> p.localAddress >> p.method >> p.password >> p.timeout >> p.latency >> p.currentUsage >> p.totalUsage >> p.lastTime >> p.nextResetDate >> p.httpMode; return in; }
2,445
C++
.cpp
64
34.171875
245
0.698526
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,524
qrcodecapturer.cpp
shadowsocks_shadowsocks-qt5/src/qrcodecapturer.cpp
#include "qrcodecapturer.h" #include "urihelper.h" #include <QApplication> #include <QMoveEvent> #include <QResizeEvent> #include <QDesktopWidget> #include <QScreen> QRCodeCapturer::QRCodeCapturer(QWidget *parent) : QMainWindow(parent) { #ifdef Q_OS_WIN /* * On Windows, it requires Qt::FramelessWindowHint to be set to make * translucent background work, but we need a window with borders. * Therefore, we set the entire window semi-transparent so that * users are still able to see the region below while moving the * capturer above the QR code image. */ this->setWindowOpacity(0.75); #else this->setAttribute(Qt::WA_TranslucentBackground, true); #endif this->setWindowTitle(tr("QR Capturer")); this->setMinimumSize(400, 400); } QRCodeCapturer::~QRCodeCapturer() {} QString QRCodeCapturer::scanEntireScreen() { QString uri; QList<QScreen *> screens = qApp->screens(); for (QList<QScreen *>::iterator sc = screens.begin(); sc != screens.end(); ++sc) { QImage raw_sc = (*sc)->grabWindow(qApp->desktop()->winId()).toImage(); QString result = URIHelper::decodeImage(raw_sc); if (!result.isNull()) { uri = result; } } return uri; } void QRCodeCapturer::moveEvent(QMoveEvent *e) { QMainWindow::moveEvent(e); decodeCurrentRegion(); } void QRCodeCapturer::resizeEvent(QResizeEvent *e) { QMainWindow::resizeEvent(e); decodeCurrentRegion(); } void QRCodeCapturer::closeEvent(QCloseEvent *e) { QMainWindow::closeEvent(e); emit closed(); } void QRCodeCapturer::decodeCurrentRegion() { QScreen *sc = qApp->screens().at(qApp->desktop()->screenNumber(this)); QRect geometry = this->geometry(); QImage raw_sc = sc->grabWindow(qApp->desktop()->winId(), geometry.x(), geometry.y(), geometry.width(), geometry.height()).toImage(); QString result = URIHelper::decodeImage(raw_sc); if (!result.isNull()) { this->close(); // moveEvent and resizeEvent both happen quite frequent // it's very likely this signal would be emitted multiple times // the solution is to use Qt::DirectConnection signal-slot connection // and disconnect such a connection in the slot function emit qrCodeFound(result); } }
2,458
C++
.cpp
76
26.355263
78
0.651789
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,525
sharedialog.cpp
shadowsocks_shadowsocks-qt5/src/sharedialog.cpp
#include <QFileDialog> #include "qrwidget.h" #include "sharedialog.h" #include "ui_sharedialog.h" ShareDialog::ShareDialog(const QByteArray &ssUrl, QWidget *parent) : QDialog(parent), ui(new Ui::ShareDialog) { ui->setupUi(this); ui->qrWidget->setQRData(ssUrl); ui->ssUrlEdit->setText(QString(ssUrl)); ui->ssUrlEdit->setCursorPosition(0); connect(ui->saveButton, &QPushButton::clicked, this, &ShareDialog::onSaveButtonClicked); this->adjustSize(); } ShareDialog::~ShareDialog() { delete ui; } void ShareDialog::onSaveButtonClicked() { QString filename = QFileDialog::getSaveFileName(this, tr("Save QR Code"), QString(), "PNG (*.png)"); if (!filename.isEmpty()) { ui->qrWidget->getQRImage().save(filename); } }
770
C++
.cpp
26
26.269231
104
0.709066
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,527
connectiontablemodel.cpp
shadowsocks_shadowsocks-qt5/src/connectiontablemodel.cpp
#include "connectiontablemodel.h" ConnectionTableModel::ConnectionTableModel(QObject *parent) : QAbstractTableModel(parent) {} ConnectionTableModel::~ConnectionTableModel() {} ConnectionItem *ConnectionTableModel::getItem(const int &row) const { return items.at(row); } int ConnectionTableModel::rowCount(const QModelIndex &) const { return items.count(); } int ConnectionTableModel::columnCount(const QModelIndex &) const { return ConnectionItem::columnCount(); } QVariant ConnectionTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } ConnectionItem *item = getItem(index.row()); return item->data(index.column(), role); } QVariant ConnectionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical || role != Qt::DisplayRole) { return QVariant(); } switch (section) { case 0: return QVariant(tr("Name")); case 1: return QVariant(tr("Server")); case 2: return QVariant(tr("Status")); case 3: return QVariant(tr("Latency")); case 4: return QVariant(tr("Local Port")); case 5: return QVariant(tr("Term Usage")); case 6: return QVariant(tr("Total Usage")); case 7: return QVariant(tr("Reset Date")); case 8: return QVariant(tr("Last Used")); default: return QVariant(); } } QModelIndex ConnectionTableModel::index(int row, int column, const QModelIndex &) const { if (row < 0 || row >= items.size()) { return QModelIndex(); } else { ConnectionItem* item = items.at(row); return createIndex(row, column, item);//column is ignored (all columns have the same effect) } } bool ConnectionTableModel::removeRows(int row, int count, const QModelIndex &parent) { if (row < 0 || count <= 0 || count + row > items.count()) { return false; } beginRemoveRows(parent, row, row + count - 1); items.erase(items.begin() + row, items.begin() + row + count); endRemoveRows(); return true; } bool ConnectionTableModel::move(int row, int target, const QModelIndex &parent) { if (row < 0 || row >= rowCount() || target < 0 || target >= rowCount() || row == target) { return false; } //http://doc.qt.io/qt-5/qabstractitemmodel.html#beginMoveRows int movTarget = target; if (target - row > 0) { movTarget++; } beginMoveRows(parent, row, row, parent, movTarget); items.move(row, target); endMoveRows(); return true; } bool ConnectionTableModel::appendConnection(Connection *con, const QModelIndex &parent) { ConnectionItem* newItem = new ConnectionItem(con, this); connect(newItem, &ConnectionItem::message, this, &ConnectionTableModel::message); connect(newItem, &ConnectionItem::stateChanged, this, &ConnectionTableModel::onConnectionStateChanged); connect(newItem, &ConnectionItem::latencyChanged, this, &ConnectionTableModel::onConnectionLatencyChanged); connect(newItem, &ConnectionItem::dataUsageChanged, this, &ConnectionTableModel::onConnectionDataUsageChanged); beginInsertRows(parent, items.count(), items.count()); items.append(newItem); endInsertRows(); return true; } void ConnectionTableModel::disconnectConnectionsAt(const QString &addr, quint16 port) { bool anyAddr = (addr.compare("0.0.0.0") == 0); for (auto &i : items) { Connection *con = i->getConnection(); if (con->isRunning() && con->getProfile().localPort == port) { if ((con->getProfile().localAddress == addr) || (con->getProfile().localAddress.compare("0.0.0.0") == 0) || anyAddr) { con->stop(); } } } } void ConnectionTableModel::testAllLatency() { for (auto &i : items) { i->testLatency(); } } void ConnectionTableModel::onConnectionStateChanged(bool running) { ConnectionItem *item = qobject_cast<ConnectionItem*>(sender()); int row = items.indexOf(item); emit dataChanged(this->index(row, 0), this->index(row, ConnectionItem::columnCount() - 1)); emit rowStatusChanged(row, running); } void ConnectionTableModel::onConnectionLatencyChanged() { ConnectionItem *item = qobject_cast<ConnectionItem*>(sender()); int row = items.indexOf(item); emit dataChanged(this->index(row, 3), this->index(row, 3)); } void ConnectionTableModel::onConnectionDataUsageChanged() { ConnectionItem *item = qobject_cast<ConnectionItem*>(sender()); int row = items.indexOf(item); emit dataChanged(this->index(row, 5), this->index(row, 6)); }
4,732
C++
.cpp
140
28.892857
115
0.67512
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,528
connection.cpp
shadowsocks_shadowsocks-qt5/src/connection.cpp
#include "connection.h" #include "ssvalidator.h" #include <QHostInfo> #include <QHostAddress> Connection::Connection(QObject *parent) : QObject(parent), running(false) {} Connection::Connection(const SQProfile &_profile, QObject *parent) : Connection(parent) { profile = _profile; } Connection::Connection(QString uri, QObject *parent) : Connection(parent) { profile = SQProfile(uri); } Connection::~Connection() { stop(); } const SQProfile& Connection::getProfile() const { return profile; } const QString& Connection::getName() const { return profile.name; } QByteArray Connection::getURI() const { std::string uri = profile.toProfile().toUriSip002(); return QByteArray(uri.data(), uri.length()); } bool Connection::isValid() const { if (profile.serverAddress.isEmpty() || profile.localAddress.isEmpty() || profile.timeout < 1 || !SSValidator::validateMethod(profile.method)) { return false; } else { return true; } } const bool &Connection::isRunning() const { return running; } void Connection::latencyTest() { QHostAddress serverAddr(profile.serverAddress); if (serverAddr.isNull()) { QHostInfo::lookupHost(profile.serverAddress, this, SLOT(onServerAddressLookedUp(QHostInfo))); } else { testAddressLatency(serverAddr); } } void Connection::start() { profile.lastTime = QDateTime::currentDateTime(); //perform a latency test if the latency is unknown if (profile.latency == SQProfile::LATENCY_UNKNOWN) { latencyTest(); } controller = std::make_unique<QSS::Controller>(profile.toProfile(), true, false); connect(controller.get(), &QSS::Controller::runningStateChanged, [&](bool run){ running = run; emit stateChanged(run); }); connect(controller.get(), &QSS::Controller::tcpLatencyAvailable, this, &Connection::onLatencyAvailable); connect(controller.get(), &QSS::Controller::newBytesReceived, this, &Connection::onNewBytesTransmitted); connect(controller.get(), &QSS::Controller::newBytesSent, this, &Connection::onNewBytesTransmitted); if (!controller->start()) { emit startFailed(); } } void Connection::stop() { if (running) { controller.reset(); } } void Connection::testAddressLatency(const QHostAddress &addr) { QSS::AddressTester *addrTester = new QSS::AddressTester(addr, profile.serverPort, this); connect(addrTester, &QSS::AddressTester::connectivityTestFinished, this, &Connection::onConnectivityTestFinished, Qt::QueuedConnection); connect(addrTester, &QSS::AddressTester::lagTestFinished, this, &Connection::onLatencyAvailable, Qt::QueuedConnection); QSS::Profile qProfile = profile.toProfile(); addrTester->startConnectivityTest(qProfile.method(), qProfile.password()); } void Connection::onNewBytesTransmitted(const quint64 &b) { profile.currentUsage += b; profile.totalUsage += b; emit dataUsageChanged(profile.currentUsage, profile.totalUsage); } void Connection::onServerAddressLookedUp(const QHostInfo &host) { if (host.error() == QHostInfo::NoError) { testAddressLatency(host.addresses().first()); } else { onLatencyAvailable(SQProfile::LATENCY_ERROR); } } void Connection::onLatencyAvailable(const int latency) { profile.latency = latency; emit latencyAvailable(latency); } void Connection::onConnectivityTestFinished(bool con) { QSS::AddressTester* tester = qobject_cast<QSS::AddressTester*>(sender()); if (!con) { disconnect(tester, &QSS::AddressTester::lagTestFinished, this, &Connection::onLatencyAvailable); this->onLatencyAvailable(SQProfile::LATENCY_ERROR); qWarning("Internet connectivity test failed. Please check the connection's profile and your firewall settings."); } tester->deleteLater(); }
3,867
C++
.cpp
119
28.680672
147
0.726468
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,529
statusnotifier.cpp
shadowsocks_shadowsocks-qt5/src/statusnotifier.cpp
#include "statusnotifier.h" #include "mainwindow.h" #include <QApplication> #ifdef Q_OS_LINUX #include <QDBusMessage> #include <QDBusConnection> #include <QDBusPendingCall> #endif StatusNotifier::StatusNotifier(MainWindow *w, bool startHiden, QObject *parent) : QObject(parent), window(w) { systray.setIcon(QIcon(":/icons/icons/shadowsocks-qt5.png")); systray.setToolTip(QString("Shadowsocks-Qt5")); connect(&systray, &QSystemTrayIcon::activated, [this](QSystemTrayIcon::ActivationReason r) { if (r != QSystemTrayIcon::Context) { this->activate(); } }); minimiseRestoreAction = new QAction(startHiden ? tr("Restore") : tr("Minimise"), this); connect(minimiseRestoreAction, &QAction::triggered, this, &StatusNotifier::activate); systrayMenu.addAction(minimiseRestoreAction); systrayMenu.addAction(QIcon::fromTheme("application-exit", QIcon::fromTheme("exit")), tr("Quit"), qApp, SLOT(quit())); systray.setContextMenu(&systrayMenu); systray.show(); } void StatusNotifier::activate() { if (!window->isVisible() || window->isMinimized()) { window->showNormal(); window->activateWindow(); window->raise(); } else { window->hide(); } } void StatusNotifier::showNotification(const QString &msg) { #ifdef Q_OS_LINUX //Using DBus to send message. QDBusMessage method = QDBusMessage::createMethodCall("org.freedesktop.Notifications","/org/freedesktop/Notifications", "org.freedesktop.Notifications", "Notify"); QVariantList args; args << QCoreApplication::applicationName() << quint32(0) << "shadowsocks-qt5" << "Shadowsocks-Qt5" << msg << QStringList () << QVariantMap() << qint32(-1); method.setArguments(args); QDBusConnection::sessionBus().asyncCall(method); #else systray.showMessage("Shadowsocks-Qt5", msg); #endif } void StatusNotifier::onWindowVisibleChanged(bool visible) { minimiseRestoreAction->setText(visible ? tr("Minimise") : tr("Restore")); }
2,005
C++
.cpp
53
33.886792
166
0.715092
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,530
editdialog.cpp
shadowsocks_shadowsocks-qt5/src/editdialog.cpp
#include "editdialog.h" #include "ui_editdialog.h" #include "ssvalidator.h" #include "ip4validator.h" #include "portvalidator.h" EditDialog::EditDialog(Connection *_connection, QWidget *parent) : QDialog(parent), ui(new Ui::EditDialog), connection(_connection) { ui->setupUi(this); /* initialisation and validator setup */ static const QStringList supportedMethodList = SSValidator::supportedMethodList(); ui->encryptComboBox->addItems(supportedMethodList); IP4Validator *addrValidator = new IP4Validator(this); PortValidator *portValidator = new PortValidator(this); ui->serverPortEdit->setValidator(portValidator); ui->localPortEdit->setValidator(portValidator); //Maybe we shouldn't validate local address using IPv4 format? ui->localAddrEdit->setValidator(addrValidator); ui->nameEdit->setText(connection->profile.name); ui->serverAddrEdit->setText(connection->profile.serverAddress); ui->serverPortEdit->setText(QString::number(connection->profile.serverPort)); ui->localAddrEdit->setText(connection->profile.localAddress); ui->localPortEdit->setText(QString::number(connection->profile.localPort)); ui->httpRadioButton->setChecked(connection->profile.httpMode); ui->pwdEdit->setText(connection->profile.password); ui->encryptComboBox->setCurrentText(connection->profile.method.toUpper()); ui->timeoutSpinBox->setValue(connection->profile.timeout); ui->resetDateEdit->setDate(connection->profile.nextResetDate); ui->resetDateEdit->setMinimumDate(QDate::currentDate()); ui->autoStartCheckBox->setChecked(connection->profile.autoStart); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &EditDialog::save); this->adjustSize(); } EditDialog::~EditDialog() { delete ui; } void EditDialog::save() { connection->profile.name = ui->nameEdit->text(); connection->profile.serverAddress = ui->serverAddrEdit->text().trimmed(); connection->profile.serverPort = ui->serverPortEdit->text().toUShort(); connection->profile.localAddress = ui->localAddrEdit->text(); connection->profile.localPort = ui->localPortEdit->text().toUShort(); connection->profile.httpMode = ui->httpRadioButton->isChecked(); connection->profile.password = ui->pwdEdit->text(); connection->profile.method = ui->encryptComboBox->currentText(); connection->profile.timeout = ui->timeoutSpinBox->value(); connection->profile.nextResetDate = ui->resetDateEdit->date(); connection->profile.autoStart = ui->autoStartCheckBox->isChecked(); this->accept(); }
2,604
C++
.cpp
55
43.072727
81
0.750492
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,531
settingsdialog.cpp
shadowsocks_shadowsocks-qt5/src/settingsdialog.cpp
#include "settingsdialog.h" #include "ui_settingsdialog.h" #include <QPushButton> SettingsDialog::SettingsDialog(ConfigHelper *ch, QWidget *parent) : QDialog(parent), ui(new Ui::SettingsDialog), helper(ch) { ui->setupUi(this); ui->toolbarStyleComboBox->setCurrentIndex(helper->getToolbarStyle()); ui->hideCheckBox->setChecked(helper->isHideWindowOnStartup()); ui->startAtLoginCheckbox->setChecked(helper->isStartAtLogin()); ui->oneInstanceCheckBox->setChecked(helper->isOnlyOneInstance()); ui->nativeMenuBarCheckBox->setChecked(helper->isNativeMenuBar()); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &SettingsDialog::onAccepted); connect(ui->toolbarStyleComboBox, &QComboBox::currentTextChanged, this, &SettingsDialog::onChanged); connect(ui->hideCheckBox, &QCheckBox::stateChanged, this, &SettingsDialog::onChanged); connect(ui->startAtLoginCheckbox, &QCheckBox::stateChanged, this, &SettingsDialog::onChanged); connect(ui->oneInstanceCheckBox, &QCheckBox::stateChanged, this, &SettingsDialog::onChanged); connect(ui->nativeMenuBarCheckBox, &QCheckBox::stateChanged, this, &SettingsDialog::onChanged); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); this->adjustSize(); } SettingsDialog::~SettingsDialog() { delete ui; } void SettingsDialog::onAccepted() { helper->setGeneralSettings(ui->toolbarStyleComboBox->currentIndex(), ui->hideCheckBox->isChecked(), ui->startAtLoginCheckbox->isChecked(), ui->oneInstanceCheckBox->isChecked(), ui->nativeMenuBarCheckBox->isChecked()); this->accept(); } void SettingsDialog::onChanged() { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); }
1,840
C++
.cpp
40
39.6
104
0.716518
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,532
mainwindow.cpp
shadowsocks_shadowsocks-qt5/src/mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "connection.h" #include "editdialog.h" #include "urihelper.h" #include "uriinputdialog.h" #include "sharedialog.h" #include "settingsdialog.h" #include "qrcodecapturer.h" #include <QDesktopServices> #include <QDesktopWidget> #include <QFileDialog> #include <QMessageBox> #include <QCloseEvent> #include <QLocalSocket> MainWindow::MainWindow(ConfigHelper *confHelper, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), configHelper(confHelper), instanceRunning(false) { Q_ASSERT(configHelper); initSingleInstance(); ui->setupUi(this); //setup Settings menu #ifndef Q_OS_DARWIN ui->menuSettings->addAction(ui->toolBar->toggleViewAction()); #endif //initialisation model = new ConnectionTableModel(this); configHelper->read(model); proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setSortRole(Qt::EditRole); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterKeyColumn(-1);//read from all columns ui->connectionView->setModel(proxyModel); ui->toolBar->setToolButtonStyle(static_cast<Qt::ToolButtonStyle> (configHelper->getToolbarStyle())); setupActionIcon(); notifier = new StatusNotifier(this, configHelper->isHideWindowOnStartup(), this); connect(configHelper, &ConfigHelper::toolbarStyleChanged, ui->toolBar, &QToolBar::setToolButtonStyle); connect(model, &ConnectionTableModel::message, notifier, &StatusNotifier::showNotification); connect(model, &ConnectionTableModel::rowStatusChanged, this, &MainWindow::onConnectionStatusChanged); connect(ui->actionSaveManually, &QAction::triggered, this, &MainWindow::onSaveManually); connect(ui->actionTestAllLatency, &QAction::triggered, model, &ConnectionTableModel::testAllLatency); //some UI changes accoding to config ui->toolBar->setVisible(configHelper->isShowToolbar()); ui->actionShowFilterBar->setChecked(configHelper->isShowFilterBar()); ui->menuBar->setNativeMenuBar(configHelper->isNativeMenuBar()); //Move to the center of the screen this->move(QApplication::desktop()->screen()->rect().center() - this->rect().center()); //UI signals connect(ui->actionImportGUIJson, &QAction::triggered, this, &MainWindow::onImportGuiJson); connect(ui->actionExportGUIJson, &QAction::triggered, this, &MainWindow::onExportGuiJson); connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit); connect(ui->actionManually, &QAction::triggered, this, &MainWindow::onAddManually); connect(ui->actionQRCode, &QAction::triggered, this, &MainWindow::onAddScreenQRCode); connect(ui->actionScanQRCodeCapturer, &QAction::triggered, this, &MainWindow::onAddScreenQRCodeCapturer); connect(ui->actionQRCodeFromFile, &QAction::triggered, this, &MainWindow::onAddQRCodeFile); connect(ui->actionURI, &QAction::triggered, this, &MainWindow::onAddFromURI); connect(ui->actionFromConfigJson, &QAction::triggered, this, &MainWindow::onAddFromConfigJSON); connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete); connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit); connect(ui->actionShare, &QAction::triggered, this, &MainWindow::onShare); connect(ui->actionConnect, &QAction::triggered, this, &MainWindow::onConnect); connect(ui->actionForceConnect, &QAction::triggered, this, &MainWindow::onForceConnect); connect(ui->actionDisconnect, &QAction::triggered, this, &MainWindow::onDisconnect); connect(ui->actionTestLatency, &QAction::triggered, this, &MainWindow::onLatencyTest); connect(ui->actionMoveUp, &QAction::triggered, this, &MainWindow::onMoveUp); connect(ui->actionMoveDown, &QAction::triggered, this, &MainWindow::onMoveDown); connect(ui->actionGeneralSettings, &QAction::triggered, this, &MainWindow::onGeneralSettings); connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::onAbout); connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(ui->actionReportBug, &QAction::triggered, this, &MainWindow::onReportBug); connect(ui->actionShowFilterBar, &QAction::toggled, configHelper, &ConfigHelper::setShowFilterBar); connect(ui->actionShowFilterBar, &QAction::toggled, this, &MainWindow::onFilterToggled); connect(ui->toolBar, &QToolBar::visibilityChanged, configHelper, &ConfigHelper::setShowToolbar); connect(ui->filterLineEdit, &QLineEdit::textChanged, this, &MainWindow::onFilterTextChanged); connect(ui->connectionView, &QTableView::clicked, this, static_cast<void (MainWindow::*)(const QModelIndex&)> (&MainWindow::checkCurrentIndex)); connect(ui->connectionView, &QTableView::activated, this, static_cast<void (MainWindow::*)(const QModelIndex&)> (&MainWindow::checkCurrentIndex)); connect(ui->connectionView, &QTableView::doubleClicked, this, &MainWindow::onEdit); /* set custom context menu */ ui->connectionView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->connectionView, &QTableView::customContextMenuRequested, this, &MainWindow::onCustomContextMenuRequested); checkCurrentIndex(); // Restore mainWindow's geometry and state restoreGeometry(configHelper->getMainWindowGeometry()); restoreState(configHelper->getMainWindowState()); ui->connectionView->horizontalHeader()->restoreGeometry(configHelper->getTableGeometry()); ui->connectionView->horizontalHeader()->restoreState(configHelper->getTableState()); } MainWindow::~MainWindow() { configHelper->save(*model); configHelper->setTableGeometry(ui->connectionView->horizontalHeader()->saveGeometry()); configHelper->setTableState(ui->connectionView->horizontalHeader()->saveState()); configHelper->setMainWindowGeometry(saveGeometry()); configHelper->setMainWindowState(saveState()); // delete ui after everything in case it's deleted while still needed for // the functions written above delete ui; } const QUrl MainWindow::issueUrl = QUrl("https://github.com/shadowsocks/shadowsocks-qt5/issues"); void MainWindow::startAutoStartConnections() { configHelper->startAllAutoStart(*model); } void MainWindow::onImportGuiJson() { QString file = QFileDialog::getOpenFileName( this, tr("Import Connections from gui-config.json"), QString(), "GUI Configuration (gui-config.json)"); if (!file.isNull()) { configHelper->importGuiConfigJson(model, file); } } void MainWindow::onExportGuiJson() { QString file = QFileDialog::getSaveFileName( this, tr("Export Connections as gui-config.json"), QString("gui-config.json"), "GUI Configuration (gui-config.json)"); if (!file.isNull()) { configHelper->exportGuiConfigJson(*model, file); } } void MainWindow::onSaveManually() { configHelper->save(*model); } void MainWindow::onAddManually() { Connection *newCon = new Connection; newProfile(newCon); } void MainWindow::onAddScreenQRCode() { QString uri = QRCodeCapturer::scanEntireScreen(); if (uri.isNull()) { QMessageBox::critical( this, tr("QR Code Not Found"), tr("Can't find any QR code image that contains " "valid URI on your screen(s).")); } else { Connection *newCon = new Connection(uri, this); newProfile(newCon); } } void MainWindow::onAddScreenQRCodeCapturer() { QRCodeCapturer *capturer = new QRCodeCapturer(this); connect(capturer, &QRCodeCapturer::closed, capturer, &QRCodeCapturer::deleteLater); connect(capturer, &QRCodeCapturer::qrCodeFound, this, &MainWindow::onQRCodeCapturerResultFound, Qt::DirectConnection); capturer->show(); } void MainWindow::onAddQRCodeFile() { QString qrFile = QFileDialog::getOpenFileName(this, tr("Open QR Code Image File"), QString(), "Images (*.png *jpg *jpeg *xpm)"); if (!qrFile.isNull()) { QImage img(qrFile); QString uri = URIHelper::decodeImage(img); if (uri.isNull()) { QMessageBox::critical(this, tr("QR Code Not Found"), tr("Can't find any QR code image that " "contains valid URI on your screen(s).")); } else { Connection *newCon = new Connection(uri, this); newProfile(newCon); } } } void MainWindow::onAddFromURI() { URIInputDialog *inputDlg = new URIInputDialog(this); connect(inputDlg, &URIInputDialog::finished, inputDlg, &URIInputDialog::deleteLater); connect(inputDlg, &URIInputDialog::acceptedURI, [&](const QString &uri){ Connection *newCon = new Connection(uri, this); newProfile(newCon); }); inputDlg->exec(); } void MainWindow::onAddFromConfigJSON() { QString file = QFileDialog::getOpenFileName(this, tr("Open config.json"), QString(), "JSON (*.json)"); if (!file.isNull()) { Connection *con = configHelper->configJsonToConnection(file); if (con) { newProfile(con); } } } void MainWindow::onDelete() { if (model->removeRow(proxyModel->mapToSource( ui->connectionView->currentIndex()).row())) { configHelper->save(*model); } checkCurrentIndex(); } void MainWindow::onEdit() { editRow(proxyModel->mapToSource(ui->connectionView->currentIndex()).row()); } void MainWindow::onShare() { QByteArray uri = model->getItem( proxyModel->mapToSource(ui->connectionView->currentIndex()). row())->getConnection()->getURI(); ShareDialog *shareDlg = new ShareDialog(uri, this); connect(shareDlg, &ShareDialog::finished, shareDlg, &ShareDialog::deleteLater); shareDlg->exec(); } void MainWindow::onConnect() { int row = proxyModel->mapToSource(ui->connectionView->currentIndex()).row(); Connection *con = model->getItem(row)->getConnection(); if (con->isValid()) { con->start(); } else { QMessageBox::critical(this, tr("Invalid"), tr("The connection's profile is invalid!")); } } void MainWindow::onForceConnect() { int row = proxyModel->mapToSource(ui->connectionView->currentIndex()).row(); Connection *con = model->getItem(row)->getConnection(); if (con->isValid()) { model->disconnectConnectionsAt(con->getProfile().localAddress, con->getProfile().localPort); con->start(); } else { QMessageBox::critical(this, tr("Invalid"), tr("The connection's profile is invalid!")); } } void MainWindow::onDisconnect() { int row = proxyModel->mapToSource(ui->connectionView->currentIndex()).row(); model->getItem(row)->getConnection()->stop(); } void MainWindow::onConnectionStatusChanged(const int row, const bool running) { if (proxyModel->mapToSource( ui->connectionView->currentIndex()).row() == row) { ui->actionConnect->setEnabled(!running); ui->actionDisconnect->setEnabled(running); } } void MainWindow::onLatencyTest() { model->getItem(proxyModel->mapToSource(ui->connectionView->currentIndex()). row())->testLatency(); } void MainWindow::onMoveUp() { QModelIndex proxyIndex = ui->connectionView->currentIndex(); int currentRow = proxyModel->mapToSource(proxyIndex).row(); int targetRow = proxyModel->mapToSource( proxyModel->index(proxyIndex.row() - 1, proxyIndex.column(), proxyIndex.parent()) ).row(); model->move(currentRow, targetRow); checkCurrentIndex(); } void MainWindow::onMoveDown() { QModelIndex proxyIndex = ui->connectionView->currentIndex(); int currentRow = proxyModel->mapToSource(proxyIndex).row(); int targetRow = proxyModel->mapToSource( proxyModel->index(proxyIndex.row() + 1, proxyIndex.column(), proxyIndex.parent()) ).row(); model->move(currentRow, targetRow); checkCurrentIndex(); } void MainWindow::onGeneralSettings() { SettingsDialog *sDlg = new SettingsDialog(configHelper, this); connect(sDlg, &SettingsDialog::finished, sDlg, &SettingsDialog::deleteLater); if (sDlg->exec()) { configHelper->save(*model); configHelper->setStartAtLogin(); } } void MainWindow::newProfile(Connection *newCon) { EditDialog *editDlg = new EditDialog(newCon, this); connect(editDlg, &EditDialog::finished, editDlg, &EditDialog::deleteLater); if (editDlg->exec()) {//accepted model->appendConnection(newCon); configHelper->save(*model); } else { newCon->deleteLater(); } } void MainWindow::editRow(int row) { Connection *con = model->getItem(row)->getConnection(); EditDialog *editDlg = new EditDialog(con, this); connect(editDlg, &EditDialog::finished, editDlg, &EditDialog::deleteLater); if (editDlg->exec()) { configHelper->save(*model); } } void MainWindow::checkCurrentIndex() { checkCurrentIndex(ui->connectionView->currentIndex()); } void MainWindow::checkCurrentIndex(const QModelIndex &_index) { QModelIndex index = proxyModel->mapToSource(_index); const bool valid = index.isValid(); ui->actionTestLatency->setEnabled(valid); ui->actionEdit->setEnabled(valid); ui->actionDelete->setEnabled(valid); ui->actionShare->setEnabled(valid); ui->actionMoveUp->setEnabled(valid ? _index.row() > 0 : false); ui->actionMoveDown->setEnabled(valid ? _index.row() < model->rowCount() - 1 : false); if (valid) { const bool &running = model->getItem(index.row())->getConnection()->isRunning(); ui->actionConnect->setEnabled(!running); ui->actionForceConnect->setEnabled(!running); ui->actionDisconnect->setEnabled(running); } else { ui->actionConnect->setEnabled(false); ui->actionForceConnect->setEnabled(false); ui->actionDisconnect->setEnabled(false); } } void MainWindow::onAbout() { QString text = QString("<h1>Shadowsocks-Qt5</h1><p><b>Version %1</b><br />" "Using libQtShadowsocks %2</p>" "<p>Copyright © 2014-2018 Symeon Huang " "(<a href='https://twitter.com/librehat'>" "@librehat</a>)</p>" "<p>License: <a href='http://www.gnu.org/licenses/lgpl.html'>" "GNU Lesser General Public License Version 3</a><br />" "Project Hosted at " "<a href='https://github.com/shadowsocks/shadowsocks-qt5'>" "GitHub</a></p>") .arg(QStringLiteral(APP_VERSION)) .arg(QSS::Common::version()); QMessageBox::about(this, tr("About"), text); } void MainWindow::onReportBug() { QDesktopServices::openUrl(issueUrl); } void MainWindow::onCustomContextMenuRequested(const QPoint &pos) { this->checkCurrentIndex(ui->connectionView->indexAt(pos)); ui->menuConnection->popup(ui->connectionView->viewport()->mapToGlobal(pos)); } void MainWindow::onFilterToggled(bool show) { if (show) { ui->filterLineEdit->setFocus(); } } void MainWindow::onFilterTextChanged(const QString &text) { proxyModel->setFilterWildcard(text); } void MainWindow::onQRCodeCapturerResultFound(const QString &uri) { QRCodeCapturer* capturer = qobject_cast<QRCodeCapturer*>(sender()); // Disconnect immediately to avoid duplicate signals disconnect(capturer, &QRCodeCapturer::qrCodeFound, this, &MainWindow::onQRCodeCapturerResultFound); Connection *newCon = new Connection(uri, this); newProfile(newCon); } void MainWindow::hideEvent(QHideEvent *e) { QMainWindow::hideEvent(e); notifier->onWindowVisibleChanged(false); } void MainWindow::showEvent(QShowEvent *e) { QMainWindow::showEvent(e); notifier->onWindowVisibleChanged(true); this->setFocus(); } void MainWindow::closeEvent(QCloseEvent *e) { if (e->spontaneous()) { e->ignore(); hide(); } else { QMainWindow::closeEvent(e); } } void MainWindow::setupActionIcon() { ui->actionConnect->setIcon(QIcon::fromTheme("network-connect", QIcon::fromTheme("network-vpn"))); ui->actionDisconnect->setIcon(QIcon::fromTheme("network-disconnect", QIcon::fromTheme("network-offline"))); ui->actionEdit->setIcon(QIcon::fromTheme("document-edit", QIcon::fromTheme("accessories-text-editor"))); ui->actionShare->setIcon(QIcon::fromTheme("document-share", QIcon::fromTheme("preferences-system-sharing"))); ui->actionTestLatency->setIcon(QIcon::fromTheme("flag", QIcon::fromTheme("starred"))); ui->actionImportGUIJson->setIcon(QIcon::fromTheme("document-import", QIcon::fromTheme("insert-text"))); ui->actionExportGUIJson->setIcon(QIcon::fromTheme("document-export", QIcon::fromTheme("document-save-as"))); ui->actionManually->setIcon(QIcon::fromTheme("edit-guides", QIcon::fromTheme("accessories-text-editor"))); ui->actionURI->setIcon(QIcon::fromTheme("text-field", QIcon::fromTheme("insert-link"))); ui->actionQRCode->setIcon(QIcon::fromTheme("edit-image-face-recognize", QIcon::fromTheme("insert-image"))); ui->actionScanQRCodeCapturer->setIcon(ui->actionQRCode->icon()); ui->actionGeneralSettings->setIcon(QIcon::fromTheme("configure", QIcon::fromTheme("preferences-desktop"))); ui->actionReportBug->setIcon(QIcon::fromTheme("tools-report-bug", QIcon::fromTheme("help-faq"))); } bool MainWindow::isInstanceRunning() const { return instanceRunning; } void MainWindow::initSingleInstance() { const QString serverName = QCoreApplication::applicationName(); QLocalSocket socket; socket.connectToServer(serverName); if (socket.waitForConnected(500)) { instanceRunning = true; if (configHelper->isOnlyOneInstance()) { qWarning() << "An instance of ss-qt5 is already running"; } QByteArray username = qgetenv("USER"); if (username.isEmpty()) { username = qgetenv("USERNAME"); } socket.write(username); socket.waitForBytesWritten(); return; } /* Can't connect to server, indicating it's the first instance of the user */ instanceServer = new QLocalServer(this); instanceServer->setSocketOptions(QLocalServer::WorldAccessOption); connect(instanceServer, &QLocalServer::newConnection, this, &MainWindow::onSingleInstanceConnect); if (instanceServer->listen(serverName)) { /* Remove server in case of crashes */ if (instanceServer->serverError() == QAbstractSocket::AddressInUseError && QFile::exists(instanceServer->serverName())) { QFile::remove(instanceServer->serverName()); instanceServer->listen(serverName); } } } void MainWindow::onSingleInstanceConnect() { QLocalSocket *socket = instanceServer->nextPendingConnection(); if (!socket) { return; } if (socket->waitForReadyRead(1000)) { QByteArray username = qgetenv("USER"); if (username.isEmpty()) { username = qgetenv("USERNAME"); } QByteArray recvUsername = socket->readAll(); if (recvUsername == username) { // Only show the window if it's the same user show(); } else { qWarning("Another user is trying to run another instance of ss-qt5"); } } socket->deleteLater(); }
21,088
C++
.cpp
534
31.589888
94
0.648514
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
20,533
portvalidator.cpp
shadowsocks_shadowsocks-qt5/src/portvalidator.cpp
#include "portvalidator.h" #include "ssvalidator.h" PortValidator::PortValidator(QObject *parent) : QValidator(parent) {} QValidator::State PortValidator::validate(QString &input, int &) const { if (SSValidator::validatePort(input)) { return Acceptable; } else return Invalid; }
313
C++
.cpp
13
20.461538
70
0.718121
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,534
uriinputdialog.cpp
shadowsocks_shadowsocks-qt5/src/uriinputdialog.cpp
#include "uriinputdialog.h" #include "ui_uriinputdialog.h" #include "ssvalidator.h" #include <QPushButton> URIInputDialog::URIInputDialog(QWidget *parent) : QDialog(parent), ui(new Ui::URIInputDialog) { ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); connect(ui->uriEdit, &QLineEdit::textChanged, this, &URIInputDialog::onURIChanged); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &URIInputDialog::onAccepted); this->adjustSize(); } URIInputDialog::~URIInputDialog() { delete ui; } void URIInputDialog::onURIChanged(const QString &str) { if (!SSValidator::validate(str)) { ui->uriEdit->setStyleSheet("background: pink"); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); } else { ui->uriEdit->setStyleSheet("background: #81F279"); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } } void URIInputDialog::onAccepted() { emit acceptedURI(ui->uriEdit->text()); this->accept(); }
1,045
C++
.cpp
34
27
91
0.714712
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,535
confighelper.cpp
shadowsocks_shadowsocks-qt5/src/confighelper.cpp
#include "confighelper.h" #include <QCoreApplication> #include <QDir> #include <QFile> #include <QJsonParseError> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> ConfigHelper::ConfigHelper(const QString &configuration, QObject *parent) : QObject(parent), configFile(configuration) { settings = new QSettings(configFile, QSettings::IniFormat, this); readGeneralSettings(); } const QString ConfigHelper::profilePrefix = "Profile"; void ConfigHelper::save(const ConnectionTableModel &model) { int size = model.rowCount(); settings->beginWriteArray(profilePrefix); for (int i = 0; i < size; ++i) { settings->setArrayIndex(i); Connection *con = model.getItem(i)->getConnection(); QVariant value = QVariant::fromValue<SQProfile>(con->getProfile()); settings->setValue("SQProfile", value); } settings->endArray(); settings->setValue("ToolbarStyle", QVariant(toolbarStyle)); settings->setValue("HideWindowOnStartup", QVariant(hideWindowOnStartup)); settings->setValue("StartAtLogin", QVariant(startAtLogin)); settings->setValue("OnlyOneInstance", QVariant(onlyOneInstace)); settings->setValue("ShowToolbar", QVariant(showToolbar)); settings->setValue("ShowFilterBar", QVariant(showFilterBar)); settings->setValue("NativeMenuBar", QVariant(nativeMenuBar)); settings->setValue("ConfigVersion", QVariant(2.6)); } void ConfigHelper::importGuiConfigJson(ConnectionTableModel *model, const QString &file) { QFile JSONFile(file); JSONFile.open(QIODevice::ReadOnly | QIODevice::Text); if (!JSONFile.isOpen()) { qCritical() << "Error: cannot open " << file; return; } if(!JSONFile.isReadable()) { qCritical() << "Error: cannot read " << file; return; } QJsonParseError pe; QJsonDocument JSONDoc = QJsonDocument::fromJson(JSONFile.readAll(), &pe); JSONFile.close(); if (pe.error != QJsonParseError::NoError) { qCritical() << pe.errorString(); } if (JSONDoc.isEmpty()) { qCritical() << "JSON Document" << file << "is empty!"; return; } QJsonObject JSONObj = JSONDoc.object(); QJsonArray CONFArray = JSONObj["configs"].toArray(); if (CONFArray.isEmpty()) { qWarning() << "configs in " << file << " is empty."; return; } for (QJsonArray::iterator it = CONFArray.begin(); it != CONFArray.end(); ++it) { QJsonObject json = (*it).toObject(); SQProfile p; if (!json["server_port"].isString()) { /* * shadowsocks-csharp uses integers to store ports directly. */ p.name = json["remarks"].toString(); p.serverPort = json["server_port"].toInt(); //shadowsocks-csharp has only global local port (all profiles use the same port) p.localPort = JSONObj["localPort"].toInt(); if (JSONObj["shareOverLan"].toBool()) { /* * it can only configure share over LAN or not (also a global value) * which is basically 0.0.0.0 or 127.0.0.1 (which is the default) */ p.localAddress = QString("0.0.0.0"); } } else { /* * Otherwise, the gui-config is from legacy shadowsocks-qt5 (v0.x) */ p.name = json["profile"].toString(); p.serverPort = json["server_port"].toString().toUShort(); p.localAddress = json["local_address"].toString(); p.localPort = json["local_port"].toString().toUShort(); p.timeout = json["timeout"].toString().toInt(); } p.serverAddress = json["server"].toString(); p.method = json["method"].toString(); p.password = json["password"].toString(); Connection *con = new Connection(p, this); model->appendConnection(con); } } void ConfigHelper::exportGuiConfigJson(const ConnectionTableModel &model, const QString &file) { QJsonArray confArray; int size = model.rowCount(); for (int i = 0; i < size; ++i) { Connection *con = model.getItem(i)->getConnection(); QJsonObject json; json["remarks"] = QJsonValue(con->profile.name); json["method"] = QJsonValue(con->profile.method.toLower()); json["password"] = QJsonValue(con->profile.password); json["server_port"] = QJsonValue(con->profile.serverPort); json["server"] = QJsonValue(con->profile.serverAddress); confArray.append(QJsonValue(json)); } QJsonObject JSONObj; JSONObj["configs"] = QJsonValue(confArray); JSONObj["localPort"] = QJsonValue(1080); JSONObj["shareOverLan"] = QJsonValue(false); QJsonDocument JSONDoc(JSONObj); QFile JSONFile(file); JSONFile.open(QIODevice::WriteOnly | QIODevice::Text); if (!JSONFile.isOpen()) { qCritical() << "Error: cannot open " << file; return; } if(!JSONFile.isWritable()) { qCritical() << "Error: cannot write into " << file; return; } JSONFile.write(JSONDoc.toJson()); JSONFile.close(); } Connection* ConfigHelper::configJsonToConnection(const QString &file) { QFile JSONFile(file); JSONFile.open(QIODevice::ReadOnly | QIODevice::Text); if (!JSONFile.isOpen()) { qCritical() << "Error: cannot open " << file; } if(!JSONFile.isReadable()) { qCritical() << "Error: cannot read " << file; } QJsonParseError pe; QJsonDocument JSONDoc = QJsonDocument::fromJson(JSONFile.readAll(), &pe); JSONFile.close(); if (pe.error != QJsonParseError::NoError) { qCritical() << pe.errorString(); } if (JSONDoc.isEmpty()) { qCritical() << "JSON Document" << file << "is empty!"; return nullptr; } QJsonObject configObj = JSONDoc.object(); SQProfile p; p.serverAddress = configObj["server"].toString(); p.serverPort = configObj["server_port"].toInt(); p.localAddress = configObj["local_address"].toString(); p.localPort = configObj["local_port"].toInt(); p.method = configObj["method"].toString(); p.password = configObj["password"].toString(); p.timeout = configObj["timeout"].toInt(); Connection *con = new Connection(p, this); return con; } int ConfigHelper::getToolbarStyle() const { return toolbarStyle; } bool ConfigHelper::isHideWindowOnStartup() const { return hideWindowOnStartup; } bool ConfigHelper::isStartAtLogin() const { return startAtLogin; } bool ConfigHelper::isOnlyOneInstance() const { return onlyOneInstace; } bool ConfigHelper::isShowToolbar() const { return showToolbar; } bool ConfigHelper::isShowFilterBar() const { return showFilterBar; } bool ConfigHelper::isNativeMenuBar() const { return nativeMenuBar; } void ConfigHelper::setGeneralSettings(int ts, bool hide, bool sal, bool oneInstance, bool nativeMB) { if (toolbarStyle != ts) { emit toolbarStyleChanged(static_cast<Qt::ToolButtonStyle>(ts)); } toolbarStyle = ts; hideWindowOnStartup = hide; startAtLogin = sal; onlyOneInstace = oneInstance; nativeMenuBar = nativeMB; } void ConfigHelper::setShowToolbar(bool show) { showToolbar = show; } void ConfigHelper::setShowFilterBar(bool show) { showFilterBar = show; } void ConfigHelper::read(ConnectionTableModel *model) { qreal configVer = settings->value("ConfigVersion", QVariant(2.4)).toReal(); int size = settings->beginReadArray(profilePrefix); for (int i = 0; i < size; ++i) { settings->setArrayIndex(i); QVariant value = settings->value("SQProfile"); SQProfile profile = value.value<SQProfile>(); checkProfileDataUsageReset(profile); Connection *con = new Connection(profile, this); model->appendConnection(con); } settings->endArray(); readGeneralSettings(); } void ConfigHelper::readGeneralSettings() { toolbarStyle = settings->value("ToolbarStyle", QVariant(4)).toInt(); startAtLogin = settings->value("StartAtLogin").toBool(); hideWindowOnStartup = settings->value("HideWindowOnStartup").toBool(); onlyOneInstace = settings->value("OnlyOneInstance", QVariant(true)).toBool(); showToolbar = settings->value("ShowToolbar", QVariant(true)).toBool(); showFilterBar = settings->value("ShowFilterBar", QVariant(true)).toBool(); nativeMenuBar = settings->value("NativeMenuBar", QVariant(false)).toBool(); } void ConfigHelper::checkProfileDataUsageReset(SQProfile &profile) { QDate currentDate = QDate::currentDate(); if (profile.nextResetDate.isNull()){//invalid if the config.ini is old //the default reset day is 1 of every month profile.nextResetDate = QDate(currentDate.year(), currentDate.month(), 1); qDebug() << "config.ini upgraded from old version"; profile.totalUsage += profile.currentUsage;//we used to use sent and received } if (profile.nextResetDate < currentDate) {//not <= because that'd casue multiple reset on this day profile.currentUsage = 0; while (profile.nextResetDate <= currentDate) { profile.nextResetDate = profile.nextResetDate.addMonths(1); } } } void ConfigHelper::startAllAutoStart(const ConnectionTableModel& model) { int size = model.rowCount(); for (int i = 0; i < size; ++i) { Connection *con = model.getItem(i)->getConnection(); if (con->profile.autoStart) { con->start(); } } } void ConfigHelper::setStartAtLogin() { QString applicationName = "Shadowsocks-Qt5"; QString applicationFilePath = QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); #if defined(Q_OS_WIN) QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat); #elif defined(Q_OS_LINUX) QFile file(QDir::homePath() + "/.config/autostart/shadowsocks-qt5.desktop"); QString fileContent( "[Desktop Entry]\n" "Name=%1\n" "Exec=%2\n" "Type=Application\n" "Terminal=false\n" "X-GNOME-Autostart-enabled=true\n"); #elif defined(Q_OS_MAC) QFile file(QDir::homePath() + "/Library/LaunchAgents/org.shadowsocks.shadowsocks-qt5.launcher.plist"); QString fileContent( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" "<plist version=\"1.0\">\n" "<dict>\n" " <key>Label</key>\n" " <string>org.shadowsocks.shadowsocks-qt5.launcher</string>\n" " <key>LimitLoadToSessionType</key>\n" " <string>Aqua</string>\n" " <key>ProgramArguments</key>\n" " <array>\n" " <string>%2</string>\n" " </array>\n" " <key>RunAtLoad</key>\n" " <true/>\n" " <key>StandardErrorPath</key>\n" " <string>/dev/null</string>\n" " <key>StandardOutPath</key>\n" " <string>/dev/null</string>\n" "</dict>\n" "</plist>\n"); #else QFile file; QString fileContent; #endif if (this->isStartAtLogin()) { // Create start up item #if defined(Q_OS_WIN) settings.setValue(applicationName, applicationFilePath); #else fileContent.replace("%1", applicationName); fileContent.replace("%2", applicationFilePath); if ( file.open(QIODevice::WriteOnly) ) { file.write(fileContent.toUtf8()); file.close(); } #endif } else { // Delete start up item #if defined(Q_OS_WIN) settings.remove(applicationName); #else if ( file.exists() ) { file.remove(); } #endif } } QByteArray ConfigHelper::getMainWindowGeometry() const { return settings->value("MainWindowGeometry").toByteArray(); } QByteArray ConfigHelper::getMainWindowState() const { return settings->value("MainWindowState").toByteArray(); } QByteArray ConfigHelper::getTableGeometry() const { return settings->value("MainTableGeometry").toByteArray(); } QByteArray ConfigHelper::getTableState() const { return settings->value("MainTableState").toByteArray(); } void ConfigHelper::setMainWindowGeometry(const QByteArray &geometry) { settings->setValue("MainWindowGeometry", QVariant(geometry)); } void ConfigHelper::setMainWindowState(const QByteArray &state) { settings->setValue("MainWindowState", QVariant(state)); } void ConfigHelper::setTableGeometry(const QByteArray &geometry) { settings->setValue("MainTableGeometry", QVariant(geometry)); } void ConfigHelper::setTableState(const QByteArray &state) { settings->setValue("MainTableState", QVariant(state)); }
12,970
C++
.cpp
358
30.128492
120
0.65418
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,536
ssvalidator.cpp
shadowsocks_shadowsocks-qt5/src/ssvalidator.cpp
#include "ssvalidator.h" #include <QtShadowsocks> QStringList SSValidator::supportedMethodList() { std::vector<std::string> methodBA = QSS::Cipher::supportedMethods(); std::sort(methodBA.begin(), methodBA.end()); QStringList methodList; for (const std::string& method : methodBA) { methodList.push_back(QString::fromStdString(method).toUpper()); } return methodList; } bool SSValidator::validate(const QString &input) { bool valid = true; try { QSS::Profile::fromUri(input.toStdString()); } catch(const std::exception&) { valid = false; } return valid; } bool SSValidator::validatePort(const QString &port) { bool ok; port.toUShort(&ok); return ok; } bool SSValidator::validateMethod(const QString &method) { static const QStringList validMethodList = supportedMethodList(); return validMethodList.contains(method, Qt::CaseInsensitive); }
931
C++
.cpp
33
24.424242
72
0.714765
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,537
ip4validator.cpp
shadowsocks_shadowsocks-qt5/src/ip4validator.cpp
#include "ip4validator.h" IP4Validator::IP4Validator(QObject *parent) : QValidator(parent) {} QValidator::State IP4Validator::validate(QString &input, int &) const { if (input.isEmpty()) { return Acceptable; } QStringList slist = input.split("."); int number = slist.size(); if (number > 4) { return Invalid; } bool emptyGroup = false; for (int i = 0; i < number; i++) { bool ok; if(slist[i].isEmpty()){ emptyGroup = true; continue; } ushort value = slist[i].toUShort(&ok); if(!ok || value > 255) { return Invalid; } } if(number < 4 || emptyGroup) { return Intermediate; } return Acceptable; }
756
C++
.cpp
31
18.16129
69
0.566064
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
20,539
editdialog.h
shadowsocks_shadowsocks-qt5/src/editdialog.h
/* * Copyright (C) 2015-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef EDITDIALOG_H #define EDITDIALOG_H #include <QDialog> #include "connection.h" namespace Ui { class EditDialog; } class EditDialog : public QDialog { Q_OBJECT public: explicit EditDialog(Connection *_connection, QWidget *parent = 0); ~EditDialog(); private: Ui::EditDialog *ui; Connection *connection; private slots: void save(); }; #endif // EDITDIALOG_H
1,165
C++
.h
37
29.189189
75
0.758036
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,541
ssvalidator.h
shadowsocks_shadowsocks-qt5/src/ssvalidator.h
/* * Copyright (C) 2014-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef SSVALIDATOR_H #define SSVALIDATOR_H #include <QString> #include <QStringList> class SSValidator { public: static bool validate(const QString &input); static bool validatePort(const QString &port); static bool validateMethod(const QString &method); /* * Return supported encryption method list at run-time * To avoid repetitive query, please store return result as static. */ static QStringList supportedMethodList(); }; #endif // SSVALIDATOR_H
1,262
C++
.h
34
34.5
75
0.761438
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,542
connection.h
shadowsocks_shadowsocks-qt5/src/connection.h
/* * Copyright (C) 2015-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef CONNECTION_H #define CONNECTION_H #include <QObject> #include <QtShadowsocks> #include <memory> #include "sqprofile.h" class Connection : public QObject { Q_OBJECT public: Connection(QObject *parent = 0); Connection(const SQProfile &_profile, QObject *parent = 0); Connection(QString uri, QObject *parent = 0); ~Connection(); Connection(const Connection&) = delete; Connection(Connection&&) = default; const SQProfile &getProfile() const; const QString &getName() const; QByteArray getURI() const; bool isValid() const; const bool &isRunning() const; void latencyTest(); signals: void stateChanged(bool started); void latencyAvailable(const int); void newLogAvailable(const QString &); void dataUsageChanged(const quint64 &current, const quint64 &total); void startFailed(); public slots: void start(); void stop(); private: std::unique_ptr<QSS::Controller> controller; SQProfile profile; bool running; void testAddressLatency(const QHostAddress &addr); friend class EditDialog; friend class ConfigHelper; friend class StatusDialog; friend class ConnectionItem; private slots: void onNewBytesTransmitted(const quint64 &); void onServerAddressLookedUp(const QHostInfo &host); void onLatencyAvailable(const int); void onConnectivityTestFinished(bool); }; Q_DECLARE_METATYPE(Connection*) #endif // CONNECTION_H
2,227
C++
.h
65
30.861538
75
0.749302
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,543
statusnotifier.h
shadowsocks_shadowsocks-qt5/src/statusnotifier.h
/* * Copyright (C) 2015-2017 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef STATUSNOTIFIER_H #define STATUSNOTIFIER_H #include <QObject> #include <QSystemTrayIcon> #include <QMenu> class MainWindow; class StatusNotifier : public QObject { Q_OBJECT public: StatusNotifier(MainWindow *w, bool startHiden, QObject *parent = 0); public slots: void activate(); void showNotification(const QString &); void onWindowVisibleChanged(bool visible); private: QMenu systrayMenu; QAction *minimiseRestoreAction; QSystemTrayIcon systray; MainWindow *window; }; #endif // STATUSNOTIFIER_H
1,320
C++
.h
39
31.333333
75
0.770016
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,545
connectionitem.h
shadowsocks_shadowsocks-qt5/src/connectionitem.h
/* * Copyright (C) 2015-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef CONNECTIONITEM_H #define CONNECTIONITEM_H #include <QObject> #include <QStringList> #include "connection.h" class ConnectionItem : public QObject { Q_OBJECT public: explicit ConnectionItem(Connection *_con, QObject *parent = nullptr); static int columnCount(); QVariant data(int column, int role = Qt::DisplayRole) const; Connection* getConnection(); void testLatency(); signals: void message(const QString&); void stateChanged(bool); void dataUsageChanged(const quint64 &current, const quint64 &total); void latencyChanged(); private: Connection *con; static QString convertLatencyToString(const int latency); static QString convertBytesToHumanReadable(quint64 bytes); static const QStringList bytesUnits; private slots: void onConnectionStateChanged(bool running); void onConnectionPingFinished(const int latency); void onStartFailed(); }; #endif // CONNECTIONITEM_H
1,727
C++
.h
47
33.723404
75
0.768125
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,546
confighelper.h
shadowsocks_shadowsocks-qt5/src/confighelper.h
/* * Copyright (C) 2015-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef CONFIGHELPER_H #define CONFIGHELPER_H #include <QSettings> #include "connectiontablemodel.h" #include "connection.h" class ConfigHelper : public QObject { Q_OBJECT public: /* * Construct a ConfigHelper object using specified configuration file * This constructor will call readGeneralSettings(). */ explicit ConfigHelper(const QString &configuration, QObject *parent = nullptr); /* * Call read() function to read all connection profiles into * specified ConnectionTableModel. * This function also calls readGeneralSettings(). */ void read(ConnectionTableModel *model); /* * readGeneralSettings() only reads General settings and store them into * member variables. */ void readGeneralSettings(); void save(const ConnectionTableModel &model); void importGuiConfigJson(ConnectionTableModel *model, const QString &file); //the format is only compatible with shadowsocks-csharp (shadowsocks-windows) void exportGuiConfigJson(const ConnectionTableModel& model, const QString &file); Connection* configJsonToConnection(const QString &file); //start those connections marked as auto-start void startAllAutoStart(const ConnectionTableModel& model); //create or delete start up item for shadowsocks-qt5 void setStartAtLogin(); /* some functions used to communicate with SettingsDialog */ int getToolbarStyle() const; bool isHideWindowOnStartup() const; bool isStartAtLogin() const; bool isOnlyOneInstance() const; bool isShowToolbar() const; bool isShowFilterBar() const; bool isNativeMenuBar() const; void setGeneralSettings(int ts, bool hide, bool automaticStartUp, bool oneInstance, bool nativeMB); void setMainWindowGeometry(const QByteArray &geometry); void setMainWindowState(const QByteArray &state); void setTableGeometry(const QByteArray &geometry); void setTableState(const QByteArray &state); QByteArray getMainWindowGeometry() const; QByteArray getMainWindowState() const; QByteArray getTableGeometry() const; QByteArray getTableState() const; public slots: void setShowToolbar(bool show); void setShowFilterBar(bool show); signals: void toolbarStyleChanged(const Qt::ToolButtonStyle); private: int toolbarStyle; bool hideWindowOnStartup; bool startAtLogin; bool onlyOneInstace; bool showToolbar; bool showFilterBar; bool nativeMenuBar; QSettings *settings; QString configFile; void checkProfileDataUsageReset(SQProfile &profile); static const QString profilePrefix; }; #endif // CONFIGHELPER_H
3,435
C++
.h
87
35.333333
103
0.762921
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,548
ip4validator.h
shadowsocks_shadowsocks-qt5/src/ip4validator.h
/* * Copyright (C) 2014-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. * * This class is based on a piece of code posted on Qt Centre. * http://www.qtcentre.org/threads/6228-Ip-Address-Validation?p=32368#post32368 */ #ifndef IP4VALIDATOR_H #define IP4VALIDATOR_H #include <QValidator> class IP4Validator : public QValidator { public: IP4Validator(QObject *parent = 0); State validate(QString &input, int &) const; }; #endif // IP4VALIDATOR_H
1,154
C++
.h
30
36.433333
79
0.765179
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,549
sqprofile.h
shadowsocks_shadowsocks-qt5/src/sqprofile.h
/* * Copyright (C) 2014-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef SQPROFILE_H #define SQPROFILE_H #include <QDataStream> #include <QDate> #include <QDateTime> #include <QtShadowsocks> struct SQProfile { SQProfile(); SQProfile(const QSS::Profile& profile); // Copy values from QSS Profile SQProfile(const QString& uri); // Construct it using ss protocol QSS::Profile toProfile() const; // Convert it into a QSS Profile bool autoStart; bool debug; quint16 serverPort; quint16 localPort; QString name; QString serverAddress; QString localAddress; QString method; QString password; int timeout; int latency; quint64 currentUsage; quint64 totalUsage; QDateTime lastTime;//last time this connection is used QDate nextResetDate;//next scheduled date to reset data usage bool httpMode; static const int LATENCY_TIMEOUT = -1; static const int LATENCY_ERROR = -2; static const int LATENCY_UNKNOWN = -3; }; Q_DECLARE_METATYPE(SQProfile) QDataStream& operator << (QDataStream &out, const SQProfile &p); QDataStream& operator >> (QDataStream &in, SQProfile &p); #endif // SQPROFILE_H
1,884
C++
.h
53
32.358491
75
0.748217
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,551
qrcodecapturer.h
shadowsocks_shadowsocks-qt5/src/qrcodecapturer.h
/* * Copyright (C) 2015-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef QRCODECAPTURER_H #define QRCODECAPTURER_H #include <QMainWindow> class QRCodeCapturer : public QMainWindow { Q_OBJECT public: explicit QRCodeCapturer(QWidget *parent = 0); ~QRCodeCapturer(); static QString scanEntireScreen(); signals: void qrCodeFound(const QString &result); void closed(); protected slots: void moveEvent(QMoveEvent *e); void resizeEvent(QResizeEvent *e); void closeEvent(QCloseEvent *e); private: void decodeCurrentRegion(); }; #endif // QRCODECAPTURER_H
1,302
C++
.h
38
31.552632
75
0.76255
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,553
urihelper.h
shadowsocks_shadowsocks-qt5/src/urihelper.h
/* * Copyright (C) 2015-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef URIHELPER_H #define URIHELPER_H #include <QString> #include <QImage> class URIHelper { public: virtual ~URIHelper() = 0; static QImage convertToGrey(const QImage &input); static QString decodeImage(const QImage &img); }; #endif // URIHELPER_H
1,039
C++
.h
29
33.689655
75
0.763184
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,554
portvalidator.h
shadowsocks_shadowsocks-qt5/src/portvalidator.h
/* * Copyright (C) 2014-2016 Symeon Huang <hzwhuang@gmail.com> * * shadowsocks-qt5 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * shadowsocks-qt5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libQtShadowsocks; see the file LICENSE. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef PORTVALIDATOR_H #define PORTVALIDATOR_H #include <QValidator> class PortValidator : public QValidator { public: PortValidator(QObject *parent = 0); State validate(QString &input, int &) const; }; #endif // PORTVALIDATOR_H
1,013
C++
.h
27
35.481481
75
0.766802
shadowsocks/shadowsocks-qt5
7,972
2,331
75
LGPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,556
test_vm_mount.cpp
canonical_multipass/tests/test_vm_mount.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include <multipass/vm_mount.h> namespace mp = multipass; namespace mpt = multipass::test; using namespace testing; namespace { struct TestVMMount : public Test { static const mp::VMMount a_mount; }; struct TestUnequalVMMountsTestSuite : public Test, public WithParamInterface<std::pair<mp::VMMount, mp::VMMount>> { }; const mp::VMMount TestVMMount::a_mount{"asdf", {{1, 2}, {2, 4}}, {{8, 4}, {6, 3}}, mp::VMMount::MountType::Classic}; TEST_P(TestUnequalVMMountsTestSuite, CompareMountsUnequal) { auto [mount_a, mount_b] = GetParam(); // Force use of overloaded operator== and operator!= EXPECT_TRUE(mount_a != mount_b); EXPECT_FALSE(mount_a == mount_b); } INSTANTIATE_TEST_SUITE_P( VMMounts, TestUnequalVMMountsTestSuite, Values(std::make_pair(TestVMMount::a_mount, mp::VMMount(TestVMMount::a_mount.get_source_path(), TestVMMount::a_mount.get_gid_mappings(), TestVMMount::a_mount.get_uid_mappings(), mp::VMMount::MountType::Native)), std::make_pair(TestVMMount::a_mount, mp::VMMount("fdsa", TestVMMount::a_mount.get_gid_mappings(), TestVMMount::a_mount.get_uid_mappings(), TestVMMount::a_mount.get_mount_type())), std::make_pair(TestVMMount::a_mount, mp::VMMount(TestVMMount::a_mount.get_source_path(), mp::id_mappings{{1, 2}, {2, 4}, {10, 5}}, TestVMMount::a_mount.get_uid_mappings(), TestVMMount::a_mount.get_mount_type())), std::make_pair(TestVMMount::a_mount, mp::VMMount(TestVMMount::a_mount.get_source_path(), TestVMMount::a_mount.get_gid_mappings(), mp::id_mappings({TestVMMount::a_mount.get_uid_mappings()[0]}), TestVMMount::a_mount.get_mount_type())))); TEST_F(TestVMMount, comparesEqual) { auto b = a_mount; EXPECT_EQ(a_mount, b); EXPECT_EQ(b, a_mount); EXPECT_NE(&b, &a_mount); } TEST_F(TestVMMount, serializeAndDeserializeToAndFromJson) { auto jsonObj = TestVMMount::a_mount.serialize(); EXPECT_EQ(jsonObj["source_path"].toString().toStdString(), TestVMMount::a_mount.get_source_path()); EXPECT_EQ(jsonObj["mount_type"], static_cast<int>(TestVMMount::a_mount.get_mount_type())); auto b_mount = mp::VMMount{jsonObj}; EXPECT_EQ(TestVMMount::a_mount, b_mount); } TEST_F(TestVMMount, duplicateUidsThrowsWithDuplicateHostID) { MP_EXPECT_THROW_THAT(mp::VMMount("src", mp::id_mappings{{1000, 1000}}, mp::id_mappings{{1000, 1000}, {1000, 1001}}, mp::VMMount::MountType::Classic), std::runtime_error, mpt::match_what(AllOf(HasSubstr("Mount cannot apply mapping with duplicate ids:"), HasSubstr("uids: 1000: "), HasSubstr("1000:1001"), HasSubstr("1000:1000")))); } TEST_F(TestVMMount, duplicateUidsThrowsWithDuplicateTargetID) { MP_EXPECT_THROW_THAT(mp::VMMount("src", mp::id_mappings{{1000, 1000}}, mp::id_mappings{{1002, 1001}, {1000, 1001}}, mp::VMMount::MountType::Classic), std::runtime_error, mpt::match_what(AllOf(HasSubstr("Mount cannot apply mapping with duplicate ids:"), HasSubstr("uids: 1001: "), HasSubstr("1002:1001"), HasSubstr("1000:1001")))); } TEST_F(TestVMMount, duplicateGidsThrowsWithDuplicateHostID) { MP_EXPECT_THROW_THAT(mp::VMMount("src", mp::id_mappings{{1000, 1000}, {1000, 1001}}, mp::id_mappings{{1000, 1000}}, mp::VMMount::MountType::Classic), std::runtime_error, mpt::match_what(AllOf(HasSubstr("Mount cannot apply mapping with duplicate ids:"), HasSubstr("gids: 1000: "), HasSubstr("1000:1001"), HasSubstr("1000:1000")))); } TEST_F(TestVMMount, duplicateGidsThrowsWithDuplicateTargetID) { MP_EXPECT_THROW_THAT(mp::VMMount("src", mp::id_mappings{{1002, 1001}, {1000, 1001}}, mp::id_mappings{{1000, 1000}}, mp::VMMount::MountType::Classic), std::runtime_error, mpt::match_what(AllOf(HasSubstr("Mount cannot apply mapping with duplicate ids:"), HasSubstr("gids: 1001: "), HasSubstr("1002:1001"), HasSubstr("1000:1001")))); } } // namespace
6,222
C++
.cpp
125
33.44
116
0.517434
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,557
test_sftp_client.cpp
canonical_multipass/tests/test_sftp_client.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "mock_file_ops.h" #include "mock_logger.h" #include "mock_recursive_dir_iterator.h" #include "mock_sftp.h" #include "mock_sftp_dir_iterator.h" #include "mock_sftp_utils.h" #include "mock_ssh_test_fixture.h" #include "stub_ssh_key_provider.h" #include <Poco/TeeStream.h> #include <multipass/ssh/sftp_client.h> #include <multipass/ssh/ssh_session.h> #include <fmt/std.h> namespace mp = multipass; namespace mpt = multipass::test; namespace mpl = multipass::logging; namespace fs = mp::fs; using namespace testing; namespace { sftp_file get_dummy_sftp_file(sftp_session sftp = nullptr) { auto file = static_cast<sftp_file_struct*>(calloc(1, sizeof(struct sftp_file_struct))); file->sftp = sftp; return file; } sftp_attributes get_dummy_sftp_attr(uint8_t type = SSH_FILEXFER_TYPE_REGULAR, const fs::path& name = "", mode_t perms = 0777) { auto attr = static_cast<sftp_attributes_struct*>(calloc(1, sizeof(struct sftp_attributes_struct))); attr->type = type; attr->name = strdup(name.u8string().c_str()); attr->permissions = perms; return attr; } struct SFTPClient : public testing::Test { SFTPClient() : sftp_new{mock_sftp_new, [](ssh_session session) -> sftp_session { auto sftp = static_cast<sftp_session_struct*>(std::calloc(1, sizeof(struct sftp_session_struct))); return sftp; }}, free_sftp{mock_sftp_free, [](sftp_session sftp) { std::free(sftp); }} { close.returnValue(SSH_OK); } mp::SFTPClient make_sftp_client() { return {std::make_unique<mp::SSHSession>("b", 43, "ubuntu", key_provider)}; } decltype(MOCK(sftp_close)) close{MOCK(sftp_close)}; MockScope<decltype(mock_sftp_new)> sftp_new; MockScope<decltype(mock_sftp_free)> free_sftp; const mpt::StubSSHKeyProvider key_provider; mpt::MockSSHTestFixture mock_ssh_test_fixture; mpt::MockFileOps::GuardedMock mock_file_ops_guard{mpt::MockFileOps::inject()}; mpt::MockFileOps* mock_file_ops{mock_file_ops_guard.first}; mpt::MockSFTPUtils::GuardedMock mock_sftp_utils_guard{mpt::MockSFTPUtils::inject()}; mpt::MockSFTPUtils* mock_sftp_utils{mock_sftp_utils_guard.first}; mpt::MockLogger::Scope mock_logger_scope{mpt::MockLogger::inject()}; std::shared_ptr<testing::NiceMock<mpt::MockLogger>> mock_logger{mock_logger_scope.mock_logger}; fs::path source_path{"source/path"}; fs::path target_path{"target/path"}; }; } // namespace // testing sftp_session TEST_F(SFTPClient, throws_when_unable_to_allocate_sftp_session) { REPLACE(sftp_new, [](auto...) { return nullptr; }); EXPECT_THROW(make_sftp_client(), std::runtime_error); } TEST_F(SFTPClient, throws_when_failed_to_init) { REPLACE(sftp_init, [](auto...) { return SSH_ERROR; }); EXPECT_THROW(make_sftp_client(), std::runtime_error); } TEST_F(SFTPClient, is_dir) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); auto mocked_sftp_stat = MOCK(sftp_stat); auto sftp_client = make_sftp_client(); mocked_sftp_stat.returnValue(nullptr); EXPECT_FALSE(sftp_client.is_remote_dir("non/existent/path")); mocked_sftp_stat.returnValue(get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY)); EXPECT_TRUE(sftp_client.is_remote_dir("a/true/directory")); mocked_sftp_stat.returnValue(get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR)); EXPECT_FALSE(sftp_client.is_remote_dir("not/a/directory")); } TEST_F(SFTPClient, push_file_success) { std::string test_data = "test_data"; REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(false)); EXPECT_CALL(*mock_sftp_utils, get_remote_file_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); EXPECT_CALL(*mock_file_ops, open_read(source_path, _)) .WillOnce(Return(std::make_unique<std::stringstream>(test_data))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); std::string written_data; REPLACE(sftp_write, [&](auto, auto data, auto size) { return written_data.append((char*)data, size).size(); }); auto status = fs::file_status{fs::file_type::regular, fs::perms::all}; EXPECT_CALL(*mock_file_ops, status(source_path, _)).WillOnce(Return(status)); mode_t written_perms; REPLACE(sftp_chmod, [&](auto, auto, auto perms) { written_perms = perms; return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.push(source_path, target_path)); EXPECT_EQ(test_data, written_data); EXPECT_EQ(static_cast<mode_t>(status.permissions()), written_perms); } TEST_F(SFTPClient, push_file_cannot_open_source) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(false)); EXPECT_CALL(*mock_sftp_utils, get_remote_file_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto err = EACCES; EXPECT_CALL(*mock_file_ops, open_read(source_path, _)).WillOnce([&](auto...) { auto file = std::make_unique<std::stringstream>(); file->setstate(std::ios_base::failbit); errno = err; return file; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot open local file {}: {}", source_path, strerror(err))); EXPECT_FALSE(sftp_client.push(source_path, target_path)); } TEST_F(SFTPClient, push_file_cannot_open_target) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(false)); EXPECT_CALL(*mock_sftp_utils, get_remote_file_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); EXPECT_CALL(*mock_file_ops, open_read(source_path, _)).WillOnce(Return(std::make_unique<std::stringstream>())); REPLACE(sftp_open, [](auto...) { return nullptr; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot open remote file {}: {}", target_path, err)); EXPECT_FALSE(sftp_client.push(source_path, target_path)); } TEST_F(SFTPClient, push_file_cannot_write_target) { std::string test_data = "test_data"; REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(false)); EXPECT_CALL(*mock_sftp_utils, get_remote_file_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); EXPECT_CALL(*mock_file_ops, open_read(source_path, _)) .WillOnce(Return(std::make_unique<std::stringstream>(test_data))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); REPLACE(sftp_write, [](auto...) { return -1; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot write to remote file {}: {}", target_path, err)); EXPECT_FALSE(sftp_client.push(source_path, target_path)); } TEST_F(SFTPClient, push_file_cannot_read_source) { std::string test_data = "test_data"; REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(false)); EXPECT_CALL(*mock_sftp_utils, get_remote_file_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto test_file = std::make_unique<std::stringstream>(test_data); auto test_file_p = test_file.get(); EXPECT_CALL(*mock_file_ops, open_read(source_path, _)).WillOnce(Return(std::move(test_file))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); REPLACE(sftp_write, [](auto, auto, auto size) { return size; }); auto err = EACCES; EXPECT_CALL(*mock_file_ops, status(source_path, _)).WillOnce([&](auto...) { test_file_p->clear(); test_file_p->setstate(std::ios_base::failbit); errno = err; return fs::file_status{fs::file_type::regular, fs::perms::all}; }); REPLACE(sftp_chmod, [](auto...) { return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot read from local file {}: {}", source_path, strerror(err))); EXPECT_FALSE(sftp_client.push(source_path, target_path)); } TEST_F(SFTPClient, push_file_cannot_set_perms) { std::string test_data = "test_data"; REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(false)); EXPECT_CALL(*mock_sftp_utils, get_remote_file_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); EXPECT_CALL(*mock_file_ops, open_read(source_path, _)) .WillOnce(Return(std::make_unique<std::stringstream>(test_data))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); REPLACE(sftp_write, [](auto, auto, auto size) { return size; }); EXPECT_CALL(*mock_file_ops, status(source_path, _)) .WillOnce(Return(fs::file_status{fs::file_type::regular, fs::perms::all})); REPLACE(sftp_chmod, [](auto...) { return -1; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot set permissions for remote file {}: {}", target_path, err)); EXPECT_FALSE(sftp_client.push(source_path, target_path)); } TEST_F(SFTPClient, pull_file_success) { std::string test_data = "test_data"; REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_sftp_utils, get_local_file_target(source_path, target_path, _)).WillOnce(Return(target_path)); std::stringstream test_file; auto tee_stream = std::make_unique<Poco::TeeOutputStream>(); tee_stream->addStream(test_file); EXPECT_CALL(*mock_file_ops, open_write(target_path, _)).WillOnce(Return(std::move(tee_stream))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); auto mocked_sftp_read = [&, read = false](auto, void* data, auto) mutable { strcpy((char*)data, test_data.c_str()); return (read = !read) ? test_data.size() : 0; }; REPLACE(sftp_read, mocked_sftp_read); mode_t perms = 0777; REPLACE(sftp_stat, [&](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "", perms); }); fs::perms written_perms; EXPECT_CALL(*mock_file_ops, permissions(target_path, static_cast<fs::perms>(perms), _)) .WillOnce([&](auto, auto perms, auto) { written_perms = perms; }); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.pull(source_path, target_path)); EXPECT_EQ(test_data, test_file.str()); EXPECT_EQ(static_cast<fs::perms>(perms), written_perms); } TEST_F(SFTPClient, pull_file_cannot_open_source) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(); }); EXPECT_CALL(*mock_sftp_utils, get_local_file_target(source_path, target_path, _)).WillOnce(Return(target_path)); EXPECT_CALL(*mock_file_ops, open_write(target_path, _)).WillOnce(Return(std::make_unique<std::stringstream>())); REPLACE(sftp_open, [](auto...) { return nullptr; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot open remote file {}: {}", source_path, err)); EXPECT_FALSE(sftp_client.pull(source_path, target_path)); } TEST_F(SFTPClient, pull_file_cannot_open_target) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(); }); EXPECT_CALL(*mock_sftp_utils, get_local_file_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto err = EACCES; EXPECT_CALL(*mock_file_ops, open_write(target_path, _)).WillOnce([&](auto...) { auto file = std::make_unique<std::stringstream>(); file->setstate(std::ios_base::failbit); errno = err; return file; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot open local file {}: {}", target_path, strerror(err))); EXPECT_FALSE(sftp_client.pull(source_path, target_path)); } TEST_F(SFTPClient, pull_file_cannot_write_target) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_sftp_utils, get_local_file_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto test_file = std::make_unique<std::stringstream>(); auto test_file_p = test_file.get(); EXPECT_CALL(*mock_file_ops, open_write(target_path, _)).WillOnce(Return(std::move(test_file))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); auto err = EACCES; auto mocked_sftp_read = [&, read = false](auto...) mutable { test_file_p->clear(); test_file_p->setstate(std::ios_base::failbit); errno = err; return (read = !read) ? 10 : 0; }; REPLACE(sftp_read, mocked_sftp_read); REPLACE(sftp_stat, [&](auto...) { return get_dummy_sftp_attr(); }); EXPECT_CALL(*mock_file_ops, permissions(target_path, _, _)); REPLACE(sftp_setstat, [](auto...) { return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot write to local file {}: {}", target_path, strerror(err))); EXPECT_FALSE(sftp_client.pull(source_path, target_path)); } TEST_F(SFTPClient, pull_file_cannot_read_source) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(); }); EXPECT_CALL(*mock_sftp_utils, get_local_file_target(source_path, target_path, _)).WillOnce(Return(target_path)); EXPECT_CALL(*mock_file_ops, open_write(target_path, _)).WillOnce(Return(std::make_unique<std::stringstream>())); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); REPLACE(sftp_read, [](auto...) { return -1; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot read from remote file {}: {}", source_path, err)); EXPECT_FALSE(sftp_client.pull(source_path, target_path)); } TEST_F(SFTPClient, pull_file_cannot_set_perms) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_sftp_utils, get_local_file_target(source_path, target_path, _)).WillOnce(Return(target_path)); EXPECT_CALL(*mock_file_ops, open_write(target_path, _)).WillOnce(Return(std::make_unique<std::stringstream>())); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); REPLACE(sftp_read, [read = false](auto...) mutable { return (read = !read) ? 10 : 0; }); mode_t perms = 0777; REPLACE(sftp_stat, [&](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "", perms); }); auto err = std::make_error_code(std::errc::permission_denied); EXPECT_CALL(*mock_file_ops, permissions(target_path, static_cast<fs::perms>(perms), _)) .WillOnce([&](auto, auto, std::error_code& e) { e = err; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot set permissions for local file {}: {}", target_path, err.message())); EXPECT_FALSE(sftp_client.pull(source_path, target_path)); } TEST_F(SFTPClient, push_dir_success_regular) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::regular, fs::perms::all}; fs::path path{"file"}; EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); std::string test_data = "test_data"; EXPECT_CALL(*mock_file_ops, open_read).WillOnce(Return(std::make_unique<std::stringstream>(test_data))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); std::string written_data; REPLACE(sftp_write, [&](auto, const void* data, auto size) { return written_data.append((char*)data, size).size(); }); EXPECT_CALL(*mock_file_ops, status).Times(2).WillRepeatedly(Return(status)); mode_t written_perms; REPLACE(sftp_chmod, [&](auto, auto, auto perms) { written_perms = perms; return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); EXPECT_EQ(status.permissions(), static_cast<fs::perms>(written_perms)); EXPECT_EQ(test_data, written_data); } TEST_F(SFTPClient, push_dir_success_dir) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::directory, fs::perms::all}; fs::path path{"dir"}; EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); REPLACE(sftp_mkdir, [](auto...) { return SSH_FX_OK; }); EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(status)); mode_t set_perms; REPLACE(sftp_chmod, [&](auto, auto, auto perms) { set_perms = perms; return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); EXPECT_EQ(set_perms, static_cast<mode_t>(status.permissions())); } TEST_F(SFTPClient, push_dir_fail_dir) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::directory, fs::perms::all}; fs::path path{source_path / "dir"}; EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(status)); EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); REPLACE(sftp_mkdir, [](auto...) { return -1; }); REPLACE(sftp_get_error, [](auto...) { return SSH_FX_PERMISSION_DENIED; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); REPLACE(sftp_chmod, [](auto...) { return -1; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot create remote directory \"{}\": {}", target_path.u8string() + "/dir", err)); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot set permissions for remote directory {}: {}", target_path, err)); EXPECT_FALSE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_success_symlink) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::symlink, fs::perms::all}; fs::path path{"symlink"}; EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(status)); EXPECT_CALL(*mock_file_ops, read_symlink); REPLACE(sftp_lstat, [](auto...) { return get_dummy_sftp_attr(); }); REPLACE(sftp_unlink, [](auto...) { return SSH_FX_OK; }); REPLACE(sftp_symlink, [](auto...) { return SSH_FX_OK; }); REPLACE(sftp_chmod, [](auto...) { return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_cannot_read_symlink) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::symlink, fs::perms::all}; fs::path path{source_path / "symlink"}; EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(status)); auto err = std::make_error_code(std::errc::permission_denied); EXPECT_CALL(*mock_file_ops, read_symlink).WillOnce([&](auto, std::error_code& e) { e = err; return ""; }); REPLACE(sftp_chmod, [](auto...) { return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot read local link {}: {}", source_path / "symlink", err.message())); EXPECT_FALSE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_cannot_create_symlink) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::symlink, fs::perms::all}; fs::path path{source_path / "symlink"}; EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(status)); EXPECT_CALL(*mock_file_ops, read_symlink); REPLACE(sftp_lstat, [](auto...) { return get_dummy_sftp_attr(); }); REPLACE(sftp_unlink, [](auto...) { return SSH_FX_OK; }); REPLACE(sftp_symlink, [](auto...) { return -1; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); REPLACE(sftp_chmod, [](auto...) { return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot create remote symlink \"{}\": {}", target_path.u8string() + "/symlink", err)); EXPECT_FALSE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_symlink_over_dir) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::symlink, fs::perms::all}; fs::path path{source_path / "symlink"}; EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(status)); EXPECT_CALL(*mock_file_ops, read_symlink); REPLACE(sftp_lstat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); REPLACE(sftp_chmod, [](auto...) { return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot overwrite remote directory \"{}\" with non-directory", target_path.u8string() + "/symlink")); EXPECT_FALSE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_unknown_file_type) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockRecursiveDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); mpt::MockDirectoryEntry entry; auto status = fs::file_status{fs::file_type::unknown, fs::perms::all}; fs::path path{source_path / "unknown"}; EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(status)); EXPECT_CALL(entry, path).WillRepeatedly(ReturnRef(path)); EXPECT_CALL(entry, symlink_status()).WillRepeatedly(Return(status)); EXPECT_CALL(*iter_p, next).WillOnce(ReturnRef(entry)); REPLACE(sftp_chmod, [](auto...) { return SSH_FX_OK; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot copy {}: not a regular file", source_path / "unknown")); EXPECT_FALSE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_open_iter_fail) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_sftp_utils, get_remote_dir_target(_, source_path, target_path, _)).WillOnce(Return(target_path)); auto err = std::make_error_code(std::errc::permission_denied); EXPECT_CALL(*mock_file_ops, recursive_dir_iterator(source_path, _)).WillOnce([&](auto, std::error_code& e) { e = err; return std::make_unique<mpt::MockRecursiveDirIterator>(); }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot open local directory {}: {}", source_path, err.message())); EXPECT_FALSE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_cannot_access_target) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); auto err = std::make_error_code(std::errc::permission_denied); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce([&](auto, std::error_code& e) { e = err; return false; }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot access {}: {}", source_path, err.message())); EXPECT_FALSE(sftp_client.push(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, push_dir_r_not_specified) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_file_ops, is_directory(source_path, _)).WillOnce(Return(true)); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("omitting local directory {}: recursive mode not specified", source_path)); EXPECT_FALSE(sftp_client.push(source_path, target_path)); } TEST_F(SFTPClient, pull_dir_success_regular) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, source_path / "file")))); std::string test_data = "test_data"; std::stringstream test_file; auto tee_stream = std::make_unique<Poco::TeeOutputStream>(); tee_stream->addStream(test_file); EXPECT_CALL(*mock_file_ops, open_write).WillOnce(Return(std::move(tee_stream))); REPLACE(sftp_open, [](auto sftp, auto...) { return get_dummy_sftp_file(sftp); }); auto mocked_sftp_read = [&, read = false](auto, const void* data, auto size) mutable { strcpy((char*)data, test_data.c_str()); return (read = !read) ? test_data.size() : 0; }; REPLACE(sftp_read, mocked_sftp_read); mode_t perms = 0777; REPLACE(sftp_stat, [&](auto, auto path) { return source_path == path ? get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "", perms) : get_dummy_sftp_attr(SSH_FILEXFER_TYPE_REGULAR, "", perms); }); fs::perms file_written_perms; fs::perms dir_written_perms; EXPECT_CALL(*mock_file_ops, permissions(target_path / "file", static_cast<fs::perms>(perms), _)) .WillOnce([&](auto, auto perms, auto) { file_written_perms = perms; }); EXPECT_CALL(*mock_file_ops, permissions(target_path, static_cast<fs::perms>(perms), _)) .WillOnce([&](auto, auto perms, auto) { dir_written_perms = perms; }); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); EXPECT_EQ(test_data, test_file.str()); EXPECT_EQ(static_cast<fs::perms>(perms), file_written_perms); EXPECT_EQ(static_cast<fs::perms>(perms), dir_written_perms); } TEST_F(SFTPClient, pull_dir_success_dir) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, "source/path/dir")))); EXPECT_CALL(*mock_file_ops, create_directory(target_path / "dir", _)); EXPECT_CALL(*mock_file_ops, permissions(_, _, _)).Times(2); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, pull_dir_fail_dir) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY, source_path / "dir")))); auto err = std::make_error_code(std::errc::permission_denied); EXPECT_CALL(*mock_file_ops, create_directory(target_path / "dir", _)).WillOnce([&](auto, std::error_code& e) { e = err; return false; }); EXPECT_CALL(*mock_file_ops, permissions(_, _, _)); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot create local directory {}: {}", target_path / "dir", err.message())); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot set permissions for local directory {}: {}", target_path, err.message())); EXPECT_FALSE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, pull_dir_success_symlink) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_SYMLINK, source_path / "symlink")))); REPLACE(sftp_readlink, [](auto...) { return (char*)malloc(10); }); EXPECT_CALL(*mock_file_ops, is_directory).WillOnce(Return(false)); EXPECT_CALL(*mock_file_ops, remove(_, _)).WillOnce(Return(true)); EXPECT_CALL(*mock_file_ops, create_symlink(_, target_path / "symlink", _)); EXPECT_CALL(*mock_file_ops, permissions(_, _, _)); auto sftp_client = make_sftp_client(); EXPECT_TRUE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, pull_dir_cannot_read_symlink) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_SYMLINK, source_path.u8string() + "/symlink")))); REPLACE(sftp_readlink, [](auto...) { return nullptr; }); auto err = "SFTP server: Permission denied"; REPLACE(ssh_get_error, [&](auto...) { return err; }); EXPECT_CALL(*mock_file_ops, permissions(_, _, _)); auto sftp_client = make_sftp_client(); mock_logger->expect_log( mpl::Level::error, fmt::format("cannot read remote link \"{}\": {}", source_path.u8string() + "/symlink", err)); EXPECT_FALSE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, pull_dir_cannot_create_symlink) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_SYMLINK, source_path / "symlink")))); REPLACE(sftp_readlink, [](auto...) { return (char*)malloc(10); }); EXPECT_CALL(*mock_file_ops, is_directory).WillOnce(Return(false)); EXPECT_CALL(*mock_file_ops, remove(_, _)).WillOnce(Return(true)); auto err = std::make_error_code(std::errc::permission_denied); EXPECT_CALL(*mock_file_ops, create_symlink(_, target_path / "symlink", _)) .WillOnce([&](auto, auto, std::error_code& e) { e = err; }); EXPECT_CALL(*mock_file_ops, permissions(_, _, _)).WillOnce([](auto, auto, auto& err) { err.clear(); }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot create local symlink {}: {}", target_path / "symlink", err.message())); EXPECT_FALSE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, pull_dir_symlink_over_dir) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_SYMLINK, source_path / "symlink")))); REPLACE(sftp_readlink, [](auto...) { return (char*)malloc(10); }); EXPECT_CALL(*mock_file_ops, is_directory).WillOnce(Return(true)); EXPECT_CALL(*mock_file_ops, permissions(_, _, _)); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot overwrite local directory {} with non-directory", target_path / "symlink")); EXPECT_FALSE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, pull_dir_unknown_file_type) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); EXPECT_CALL(*mock_sftp_utils, get_local_dir_target(source_path, target_path, _)).WillOnce(Return(target_path)); auto iter = std::make_unique<mpt::MockSFTPDirIterator>(); auto iter_p = iter.get(); EXPECT_CALL(*mock_sftp_utils, make_SFTPDirIterator(_, source_path)).WillOnce(Return(std::move(iter))); EXPECT_CALL(*iter_p, hasNext).WillOnce(Return(true)).WillRepeatedly(Return(false)); EXPECT_CALL(*iter_p, next) .WillOnce(Return(std::unique_ptr<sftp_attributes_struct>( get_dummy_sftp_attr(SSH_FILEXFER_TYPE_UNKNOWN, source_path.u8string() + "/unknown")))); EXPECT_CALL(*mock_file_ops, permissions(_, _, _)); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("cannot copy \"{}\": not a regular file", source_path.u8string() + "/unknown")); EXPECT_FALSE(sftp_client.pull(source_path, target_path, mp::SFTPClient::Flag::Recursive)); } TEST_F(SFTPClient, pull_dir_r_not_specified) { REPLACE(sftp_init, [](auto...) { return SSH_OK; }); REPLACE(sftp_stat, [](auto...) { return get_dummy_sftp_attr(SSH_FILEXFER_TYPE_DIRECTORY); }); auto sftp_client = make_sftp_client(); mock_logger->expect_log(mpl::Level::error, fmt::format("omitting remote directory {}: recursive mode not specified", source_path)); EXPECT_FALSE(sftp_client.pull(source_path, target_path)); }
43,761
C++
.cpp
770
50.951948
120
0.66286
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,558
test_ssh_client.cpp
canonical_multipass/tests/test_ssh_client.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "disabling_macros.h" #include "fake_key_data.h" #include "mock_ssh_client.h" #include "mock_ssh_test_fixture.h" #include "stub_console.h" #include "stub_ssh_key_provider.h" #include <multipass/ssh/ssh_client.h> #include <multipass/ssh/ssh_session.h> namespace mp = multipass; namespace mpt = multipass::test; namespace { struct SSHClient : public testing::Test { mp::SSHClient make_ssh_client() { return {std::make_unique<mp::SSHSession>("a", 42, "ubuntu", key_provider), console_creator}; } const mpt::StubSSHKeyProvider key_provider; mpt::MockSSHTestFixture mock_ssh_test_fixture; mp::SSHClient::ConsoleCreator console_creator = [](auto /*channel*/) { return std::make_unique<mpt::StubConsole>(); }; }; } TEST_F(SSHClient, standardCtorDoesNotThrow) { EXPECT_NO_THROW(mp::SSHClient("a", 42, "foo", mpt::fake_key_data, console_creator)); } TEST_F(SSHClient, execSingleCommandReturnsOKNoFailure) { auto client = make_ssh_client(); EXPECT_EQ(client.exec({"foo"}), SSH_OK); } TEST_F(SSHClient, execMultipleCommandsReturnsOKNoFailure) { auto client = make_ssh_client(); std::vector<std::vector<std::string>> commands{{"ls", "-la"}, {"pwd"}}; EXPECT_EQ(client.exec(commands), SSH_OK); } TEST_F(SSHClient, execReturnsErrorCodeOnFailure) { const int failure_code{127}; auto client = make_ssh_client(); REPLACE(ssh_channel_get_exit_status, [&failure_code](auto) { return failure_code; }); EXPECT_EQ(client.exec({"foo"}), failure_code); } TEST_F(SSHClient, DISABLE_ON_WINDOWS(execPollingWorksAsExpected)) { int poll_count{0}; auto client = make_ssh_client(); mock_ssh_test_fixture.is_eof.returnValue(0); auto event_dopoll = [this, &poll_count](auto...) { ++poll_count; mock_ssh_test_fixture.is_eof.returnValue(true); return SSH_OK; }; REPLACE(ssh_event_dopoll, event_dopoll); EXPECT_EQ(client.exec({"foo"}), SSH_OK); EXPECT_EQ(poll_count, 1); } TEST_F(SSHClient, throws_when_unable_to_open_session) { REPLACE(ssh_channel_open_session, [](auto...) { return SSH_ERROR; }); EXPECT_THROW(make_ssh_client(), std::runtime_error); } TEST_F(SSHClient, throw_when_request_shell_fails) { auto client = make_ssh_client(); REPLACE(ssh_channel_request_pty, [](auto...) { return SSH_OK; }); REPLACE(ssh_channel_change_pty_size, [](auto...) { return SSH_OK; }); REPLACE(ssh_channel_request_shell, [](auto...) { return SSH_ERROR; }); EXPECT_THROW(client.connect(), std::runtime_error); } TEST_F(SSHClient, throw_when_request_exec_fails) { auto client = make_ssh_client(); REPLACE(ssh_channel_request_pty, [](auto...) { return SSH_OK; }); REPLACE(ssh_channel_change_pty_size, [](auto...) { return SSH_OK; }); REPLACE(ssh_channel_request_exec, [](auto...) { return SSH_ERROR; }); EXPECT_THROW(client.exec({"foo"}), std::runtime_error); }
3,580
C++
.cpp
99
32.868687
100
0.699161
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,559
test_daemon_authenticate.cpp
canonical_multipass/tests/test_daemon_authenticate.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "daemon_test_fixture.h" #include "mock_platform.h" #include "mock_server_reader_writer.h" #include "mock_settings.h" #include "mock_utils.h" #include <multipass/constants.h> namespace mp = multipass; namespace mpt = multipass::test; using namespace testing; namespace { constexpr auto saved_hash{"f28cb995d91eed8064674766f28e468aae8065"}; constexpr auto good_hash{"f28cb995d91eed8064674766f28e468aae8065"}; constexpr auto bad_hash{"b2cf02af556c857dd77de2d2476f3830fd0214"}; struct TestDaemonAuthenticate : public mpt::DaemonTestFixture { TestDaemonAuthenticate() { EXPECT_CALL(mock_settings, register_handler(_)).WillRepeatedly(Return(nullptr)); EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber()); } mpt::MockUtils::GuardedMock utils_attr{mpt::MockUtils::inject<NiceMock>()}; mpt::MockUtils* mock_utils = utils_attr.first; mpt::MockPlatform::GuardedMock platform_attr{mpt::MockPlatform::inject<NiceMock>()}; mpt::MockPlatform* mock_platform = platform_attr.first; mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject(); mpt::MockSettings& mock_settings = *mock_settings_injection.first; }; } // namespace TEST_F(TestDaemonAuthenticate, authenticateNoErrorReturnsOk) { mp::Daemon daemon{config_builder.build()}; EXPECT_CALL(mock_settings, get(Eq(mp::passphrase_key))).WillOnce(Return(saved_hash)); EXPECT_CALL(*mock_utils, generate_scrypt_hash_for(Eq(QString("foo")))).WillOnce(Return(good_hash)); mp::AuthenticateRequest request; request.set_passphrase("foo"); auto status = call_daemon_slot(daemon, &mp::Daemon::authenticate, request, StrictMock<mpt::MockServerReaderWriter<mp::AuthenticateReply, mp::AuthenticateRequest>>{}); EXPECT_TRUE(status.ok()); } TEST_F(TestDaemonAuthenticate, authenticateNoPassphraseSetReturnsError) { mp::Daemon daemon{config_builder.build()}; EXPECT_CALL(mock_settings, get(Eq(mp::passphrase_key))); mp::AuthenticateRequest request; request.set_passphrase("foo"); auto status = call_daemon_slot(daemon, &mp::Daemon::authenticate, request, StrictMock<mpt::MockServerReaderWriter<mp::AuthenticateReply, mp::AuthenticateRequest>>{}); EXPECT_EQ(status.error_code(), grpc::StatusCode::FAILED_PRECONDITION); EXPECT_EQ(status.error_message(), "Passphrase is not set. Please `multipass set local.passphrase` with a trusted client."); } TEST_F(TestDaemonAuthenticate, authenticatePassphraseMismatchReturnsError) { mp::Daemon daemon{config_builder.build()}; EXPECT_CALL(mock_settings, get(Eq(mp::passphrase_key))).WillOnce(Return(saved_hash)); EXPECT_CALL(*mock_utils, generate_scrypt_hash_for(Eq(QString("foo")))).WillOnce(Return(bad_hash)); mp::AuthenticateRequest request; request.set_passphrase("foo"); auto status = call_daemon_slot(daemon, &mp::Daemon::authenticate, request, StrictMock<mpt::MockServerReaderWriter<mp::AuthenticateReply, mp::AuthenticateRequest>>{}); EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT); EXPECT_EQ(status.error_message(), "Passphrase is not correct. Please try again."); } TEST_F(TestDaemonAuthenticate, authenticateCatchesExceptionReturnsError) { const std::string error_msg{"Getting settings failed"}; mp::Daemon daemon{config_builder.build()}; EXPECT_CALL(mock_settings, get(Eq(mp::passphrase_key))).WillOnce(Throw(std::runtime_error(error_msg))); mp::AuthenticateRequest request; request.set_passphrase("foo"); auto status = call_daemon_slot(daemon, &mp::Daemon::authenticate, request, StrictMock<mpt::MockServerReaderWriter<mp::AuthenticateReply, mp::AuthenticateRequest>>{}); EXPECT_EQ(status.error_code(), grpc::StatusCode::INTERNAL); EXPECT_EQ(status.error_message(), error_msg); }
4,614
C++
.cpp
97
42.824742
116
0.737687
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,560
test_ip_address.cpp
canonical_multipass/tests/test_ip_address.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include <multipass/ip_address.h> namespace mp = multipass; using namespace testing; TEST(IPAddress, can_initialize_from_string) { mp::IPAddress ip{"192.168.1.3"}; EXPECT_THAT(ip.octets[0], Eq(192)); EXPECT_THAT(ip.octets[1], Eq(168)); EXPECT_THAT(ip.octets[2], Eq(1)); EXPECT_THAT(ip.octets[3], Eq(3)); } TEST(IPAddress, can_convert_to_string) { mp::IPAddress ip{std::array<uint8_t, 4>{{192, 168, 1, 3}}}; EXPECT_THAT(ip.as_string(), StrEq("192.168.1.3")); } TEST(IPAddress, throws_on_invalid_ip_string) { EXPECT_THROW(mp::IPAddress ip{"100111.3434.3"}, std::invalid_argument); EXPECT_THROW(mp::IPAddress ip{"256.256.256.256"}, std::invalid_argument); EXPECT_THROW(mp::IPAddress ip{"-2.-3.-5.-6"}, std::invalid_argument); EXPECT_THROW(mp::IPAddress ip{"a.b.c.d"}, std::invalid_argument); } TEST(IPAddress, can_be_converted_to_integer) { mp::IPAddress ip{std::array<uint8_t, 4>{{0xC0, 0xA8, 0x1, 0x3}}}; EXPECT_THAT(ip.as_uint32(), Eq(0xC0A80103)); } TEST(IPAddress, can_use_comparison_operators) { mp::IPAddress low{"10.120.0.0"}; mp::IPAddress high{"10.120.2.255"}; EXPECT_TRUE(low != high); EXPECT_TRUE(low == low); EXPECT_TRUE(low < high); EXPECT_TRUE(low <= low); EXPECT_TRUE(high > low); EXPECT_TRUE(high >= high); } TEST(IPAddress, supports_addition_operator) { mp::IPAddress an_ip{"10.120.0.255"}; mp::IPAddress expected_ip{"10.120.1.3"}; auto result_ip = an_ip + 4; EXPECT_THAT(result_ip, Eq(expected_ip)); }
2,180
C++
.cpp
63
31.555556
77
0.692344
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,561
temp_dir.cpp
canonical_multipass/tests/temp_dir.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "temp_dir.h" #include <stdexcept> namespace mpt = multipass::test; mpt::TempDir::TempDir() : the_path{dir.path()} { if (the_path.isEmpty()) throw std::runtime_error("test failed to create temporary directory"); }
866
C++
.cpp
24
33.791667
78
0.739857
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,562
test_ssh_exec_failure.cpp
canonical_multipass/tests/test_ssh_exec_failure.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include <multipass/exceptions/ssh_exception.h> namespace mp = multipass; using namespace testing; namespace { TEST(TestSSHExecFailure, recordsExitCode) { int expected_exit_code = 5; mp::SSHExecFailure sshExecFailure("OnPurpose", expected_exit_code); EXPECT_EQ(sshExecFailure.exit_code(), expected_exit_code); } } // namespace
993
C++
.cpp
29
32.103448
72
0.763048
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,563
test_ssh_key_provider.cpp
canonical_multipass/tests/test_ssh_key_provider.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "file_operations.h" #include "mock_utils.h" #include "temp_dir.h" #include <multipass/ssh/openssh_key_provider.h> #include <multipass/utils.h> #include <thread> namespace mp = multipass; namespace mpt = multipass::test; using namespace testing; struct SSHKeyProvider : public testing::Test { mpt::TempDir key_dir; }; TEST_F(SSHKeyProvider, creates_key) { mp::OpenSSHKeyProvider key_provider{key_dir.path()}; EXPECT_THAT(key_provider.public_key_as_base64(), StrNe("")); } TEST_F(SSHKeyProvider, imports_existing_key) { constexpr auto key_data = "-----BEGIN RSA PRIVATE KEY-----\n" "MIIEpAIBAAKCAQEAv3lEFtxT3kd2OrWQ8k3v1SHILNDwwm9U7awNbLDqVEresZNd\n" "mRGmH381fO8tHpNdeQ+XEMff16FZiMKRQWx5OlHTQ33cS7X/huZ5Ge5YVKsBMmqy\n" "vJADK7Ud38mNaKi3hqepD87labVmY1ARTNHSLDG68c5bIyquvzbawwwkM7qPTbw5\n" "ZHOEpKehwPZ/034oPnmPV3BAbX1HySi/zrOZE/D1JW3uHvhF1yprDWhJumOVBSYB\n" "zDloJSsFfFEEYOzkdmAwZ0q3yfMVxLiwTlP2Hhf+i8kOzjQfz29PPfNwroYJZqKT\n" "Eg8YAqBr28ryHzHa8W+htUoZbntID2w9aDeJ2wIDAQABAoIBABpk0vf7wyve2fNZ\n" "1/MuvyK4F2nmG2oSArkIgIk9EfAwqeX8lGhnQGkTFgJ0zdlrIvVvKrnLc5W7ziXF\n" "/FPyafuaD+87yEQ/gEvONV9XtaFmOTID90N67pT10HpqxC1rJHFRZ0KgmIsr0ENc\n" "ZCYcvkYNTOHMOk/ssE33d8xvPgZLMf/EvVqcgPyhJXXg0Y1po9cLPQjCBCfmigiM\n" "U+3Hlrz8w6rtp3RUuM2jzrA+uHQGSa4fC/Wn2WT5fR2RZz7BPdJ+kHlTfFRq27oy\n" "lsTITYDJf26ej1wmsWIV4AqznV33xSRZBK6KZjq98D6MKc28fyfZQKxnc1jWG1Xi\n" "erLM+YECgYEA73wVxCdX/9eBXlquQ5wrj94UFOV9zlbr/oE0CYZC8SkG6fCf9/a/\n" "lUUz25CK+kugJcOFHOmOXIjydXzDDFXEUgsf6MeX0WiLy6rvFdlq3xnQ9oUKBzCv\n" "6gLL9s2Ozo4NMeY3rlqxAswdyGx3f5HHkB722MeUlafjXPkJ82m61GECgYEAzK2V\n" "iX1v+b76HG9XnDd1eK0L/JINSJrFJUMD1KhY84FmXqPoBWcuoEtUPA+cvOhAzr3l\n" "TFqKbXbY5JVx1c66uEkCMYYVPYyOVZNnEz+bGOmrK2NaYDwIySG6WhD2Zh69VIXa\n" "kfvMzba0M26FXjWBDN3oluT6RLBHb2xdZgMHx7sCgYB1B3QziO5t7cggbbve+kAn\n" "a+TwWT1jSgLFOipNxTiNVPk19QqXSBNTRKAU2cuwiKhYC/XOrSuOeLXTSAagzoDD\n" "fwA25uJ/yNEX1A5F5RteruT4swa1gMtWVcuKbeUtdylnixMGtvbtYQXk3WyAAKM/\n" "AIKsaMtpXsOyuVhthOtxwQKBgQCBvIGtzcHdd01IGtdYoNqoLGANr3IWFGxkSw8x\n" "i6geaWY/FPvr+NRYLIdvLqI2J610nm+qrzVRX2Tpt0SZttkqGLT4OTpbci2CVtWe\n" "INIpv2uNLAPMPiF/hA6AKoJUhqWR3uqFYCsYNfgRJbwJ1DZBtqNIikmMooQVP4YQ\n" "NFmJIwKBgQCjxMF4SFzzRbNfiHKLL39D8RHlCPalbmX2CXaiUT4H1rq2oK3EiI+O\n" "+SzzmxbHAjFRRuKeqhmC9+yhhHssBt6lJe71Fl3e01McjOcW9P1AZQdgYsDyCqR0\n" "Yy460TKDO1em0N9GlXfsYgiSFJv1WmD7M/kvGpGxSERcnR4+bBd2BQ==\n" "-----END RSA PRIVATE KEY-----\n"; auto ssh_keys_path = MP_UTILS.make_dir(key_dir.path(), "ssh-keys"); mpt::make_file_with_content(QDir{ssh_keys_path}.filePath("id_rsa"), key_data); mp::OpenSSHKeyProvider key_provider{key_dir.path()}; EXPECT_THAT(key_provider.private_key_as_base64(), StrEq(key_data)); constexpr auto expected_pub_key_data = "AAAAB3NzaC1yc2EAAAADAQABAAABAQC/eUQW3FPeR3Y6tZDyTe/VIcgs0PDCb1TtrA1ssOpUSt6xk12ZEaYffzV87y0ek115D5cQx9/" "XoVmIwpFBbHk6UdNDfdxLtf+G5nkZ7lhUqwEyarK8kAMrtR3fyY1oqLeGp6kPzuVptWZjUBFM0dIsMbrxzlsjKq6/" "NtrDDCQzuo9NvDlkc4Skp6HA9n/Tfig+eY9XcEBtfUfJKL/" "Os5kT8PUlbe4e+EXXKmsNaEm6Y5UFJgHMOWglKwV8UQRg7OR2YDBnSrfJ8xXEuLBOU/YeF/6LyQ7ONB/" "Pb08983CuhglmopMSDxgCoGvbyvIfMdrxb6G1Shlue0gPbD1oN4nb"; EXPECT_THAT(key_provider.public_key_as_base64(), StrEq(expected_pub_key_data)); } TEST_F(SSHKeyProvider, public_key_is_stable) { mp::OpenSSHKeyProvider key_provider{key_dir.path()}; const auto key_one = key_provider.public_key_as_base64(); const auto key_two = key_provider.public_key_as_base64(); EXPECT_THAT(key_one, StrEq(key_two)); }
4,914
C++
.cpp
83
47.277108
113
0.69325
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,564
file_operations.cpp
canonical_multipass/tests/file_operations.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Alberto Aguirre <alberto.aguirre@canonical.com> * */ #include "file_operations.h" #include "path.h" #include <multipass/format.h> #include <multipass/utils.h> #include <QDir> #include <QFile> #include <QFileInfo> namespace mpt = multipass::test; QByteArray mpt::load(QString path) { QFile file(path); if (file.exists()) { file.open(QIODevice::ReadOnly); return file.readAll(); } throw std::invalid_argument(path.toStdString() + " does not exist"); } QByteArray mpt::load_test_file(const char* file_name) { auto file_path = multipass::test::test_data_path_for(file_name); return multipass::test::load(file_path); } void mpt::make_file_with_content(const QString& file_name, const std::string& content) { MP_UTILS.Utils::make_file_with_content(file_name.toStdString(), content); // call the base impl even if it is a mock }
1,519
C++
.cpp
45
31.155556
120
0.732106
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,565
test_daemon_suspend.cpp
canonical_multipass/tests/test_daemon_suspend.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "daemon_test_fixture.h" #include "mock_mount_handler.h" #include "mock_platform.h" #include "mock_server_reader_writer.h" #include "mock_settings.h" #include "mock_virtual_machine.h" #include "mock_vm_image_vault.h" #include <multipass/exceptions/not_implemented_on_this_backend_exception.h> namespace mp = multipass; namespace mpt = multipass::test; using namespace testing; namespace { struct TestDaemonSuspend : public mpt::DaemonTestFixture { void SetUp() override { EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr)); EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber()); config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>(); } const std::string mock_instance_name{"real-zebraphant"}; const std::string mac_addr{"52:54:00:73:76:28"}; const std::string fake_target_path{"/home/ubuntu/foo"}; std::vector<mp::NetworkInterface> extra_interfaces; mpt::MockPlatform::GuardedMock platform_attr{mpt::MockPlatform::inject<NiceMock>()}; mpt::MockPlatform* mock_platform = platform_attr.first; mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject(); mpt::MockSettings& mock_settings = *mock_settings_injection.first; }; } // namespace TEST_F(TestDaemonSuspend, suspendNotSupportedDoesNotStopMounts) { auto mock_factory = use_a_mock_vm_factory(); std::unordered_map<std::string, mp::VMMount> mounts{ {fake_target_path, {"foo", {}, {}, mp::VMMount::MountType::Native}}}; const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts)); config_builder.data_directory = temp_dir->path(); auto mock_mount_handler = std::make_unique<mpt::MockMountHandler>(); EXPECT_CALL(*mock_mount_handler, deactivate_impl).Times(0); auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name); EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path, _)) .WillOnce(Return(std::move(mock_mount_handler))); EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm))); EXPECT_CALL(*mock_factory, require_suspend_support) .WillOnce(Throw(mp::NotImplementedOnThisBackendException{"suspend"})); mp::Daemon daemon{config_builder.build()}; mp::SuspendRequest request; request.mutable_instance_names()->add_instance_name(mock_instance_name); auto status = call_daemon_slot(daemon, &mp::Daemon::suspend, request, StrictMock<mpt::MockServerReaderWriter<mp::SuspendReply, mp::SuspendRequest>>{}); EXPECT_EQ(status.error_code(), grpc::StatusCode::FAILED_PRECONDITION); EXPECT_THAT(status.error_message(), HasSubstr(("The suspend feature is not implemented on this backend."))); } TEST_F(TestDaemonSuspend, suspendStopsMounts) { auto mock_factory = use_a_mock_vm_factory(); std::unordered_map<std::string, mp::VMMount> mounts{ {fake_target_path, {"foo", {}, {}, mp::VMMount::MountType::Native}}}; const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts)); config_builder.data_directory = temp_dir->path(); auto mock_mount_handler = std::make_unique<mpt::MockMountHandler>(); EXPECT_CALL(*mock_mount_handler, is_active).WillOnce(Return(true)); EXPECT_CALL(*mock_mount_handler, deactivate_impl); auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name); EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path, _)) .WillOnce(Return(std::move(mock_mount_handler))); EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm))); mp::Daemon daemon{config_builder.build()}; mp::SuspendRequest request; request.mutable_instance_names()->add_instance_name(mock_instance_name); auto status = call_daemon_slot(daemon, &mp::Daemon::suspend, request, StrictMock<mpt::MockServerReaderWriter<mp::SuspendReply, mp::SuspendRequest>>{}); EXPECT_TRUE(status.ok()); } TEST_F(TestDaemonSuspend, suspendNotSupportedReturnsErrorStatus) { const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces)); config_builder.data_directory = temp_dir->path(); mp::Daemon daemon{config_builder.build()}; mp::SuspendRequest request; request.mutable_instance_names()->add_instance_name(mock_instance_name); auto status = call_daemon_slot(daemon, &mp::Daemon::suspend, request, StrictMock<mpt::MockServerReaderWriter<mp::SuspendReply, mp::SuspendRequest>>{}); EXPECT_EQ(status.error_code(), grpc::StatusCode::FAILED_PRECONDITION); EXPECT_THAT(status.error_message(), HasSubstr(("The suspend feature is not implemented on this backend."))); }
5,795
C++
.cpp
110
45.981818
116
0.697275
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,566
test_sftp_dir_iterator.cpp
canonical_multipass/tests/test_sftp_dir_iterator.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "mock_sftp.h" #include "mock_ssh.h" #include <multipass/ssh/sftp_dir_iterator.h> #include <multipass/ssh/sftp_utils.h> namespace mp = multipass; namespace mpt = multipass::test; using namespace testing; namespace { auto get_dummy_attr(const char* name, uint8_t type) { auto attr = static_cast<sftp_attributes_struct*>(calloc(1, sizeof(struct sftp_attributes_struct))); attr->name = strdup(name); attr->type = type; return attr; } auto get_dummy_dir(const char* name) { auto dir = static_cast<sftp_dir_struct*>(calloc(1, sizeof(struct sftp_dir_struct))); dir->name = strdup(name); return dir; } } // namespace TEST(SFTPDirIterator, success) { std::vector<sftp_dir> dirs{ get_dummy_dir("dir"), get_dummy_dir("dir/dir1"), get_dummy_dir("dir/dir1/dir2"), get_dummy_dir("dir/dir3"), }; std::vector<sftp_attributes> entries{ get_dummy_attr("file1", SSH_FILEXFER_TYPE_REGULAR), get_dummy_attr("dir1", SSH_FILEXFER_TYPE_DIRECTORY), get_dummy_attr("file2", SSH_FILEXFER_TYPE_REGULAR), get_dummy_attr("dir2", SSH_FILEXFER_TYPE_DIRECTORY), get_dummy_attr("file3", SSH_FILEXFER_TYPE_REGULAR), nullptr, get_dummy_attr(".", SSH_FILEXFER_TYPE_DIRECTORY), get_dummy_attr("..", SSH_FILEXFER_TYPE_DIRECTORY), get_dummy_attr("file4", SSH_FILEXFER_TYPE_REGULAR), get_dummy_attr("file5", SSH_FILEXFER_TYPE_REGULAR), nullptr, get_dummy_attr("dir3", SSH_FILEXFER_TYPE_DIRECTORY), get_dummy_attr("file6", SSH_FILEXFER_TYPE_REGULAR), nullptr, }; auto open_dir = [&, i = 0](auto...) mutable { return i == (int)dirs.size() ? nullptr : dirs[i++]; }; auto read_dir = [&, i = 0](auto...) mutable { return i == (int)entries.size() ? nullptr : entries[i++]; }; REPLACE(sftp_opendir, open_dir); REPLACE(sftp_readdir, read_dir); REPLACE(sftp_dir_eof, [](auto...) { return true; }); mp::SFTPDirIterator iter{nullptr, "dir"}; std::vector<std::string> result; while (iter.hasNext()) result.emplace_back(iter.next()->name); EXPECT_THAT(result, UnorderedElementsAre("dir/file1", "dir/dir1", "dir/dir1/file2", "dir/dir1/dir2", "dir/dir1/dir2/file3", "dir/dir1/file4", "dir/dir1/file5", "dir/dir3", "dir/dir3/file6")); } TEST(SFTPDirIterator, fail_opendir) { REPLACE(sftp_opendir, [](auto...) { return nullptr; }); REPLACE(ssh_get_error, [](auto...) { return "SFTP server: No such file"; }); sftp_session_struct sftp{}; MP_EXPECT_THROW_THAT((mp::SFTPDirIterator{&sftp, "dir"}), mp::SFTPError, mpt::match_what(StrEq("cannot open remote directory 'dir': SFTP server: No such file"))); } TEST(SFTPDirIterator, fail_readdir) { REPLACE(sftp_opendir, [](auto, auto path) { return get_dummy_dir(path); }); REPLACE(sftp_readdir, [](auto...) { return nullptr; }); REPLACE(sftp_dir_eof, [](auto...) { return false; }); REPLACE(ssh_get_error, [](auto...) { return "SFTP server: Permission denied"; }); sftp_session_struct sftp{}; MP_EXPECT_THROW_THAT((mp::SFTPDirIterator{&sftp, "dir"}), mp::SFTPError, mpt::match_what(StrEq("cannot read remote directory 'dir': SFTP server: Permission denied"))); }
3,997
C++
.cpp
95
36.789474
119
0.655341
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,567
test_ssh_process.cpp
canonical_multipass/tests/test_ssh_process.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "mock_ssh_test_fixture.h" #include "stub_ssh_key_provider.h" #include <multipass/ssh/ssh_session.h> #include <algorithm> #include <thread> namespace mp = multipass; namespace mpt = multipass::test; using namespace testing; namespace { struct SSHProcess : public Test { const mpt::StubSSHKeyProvider key_provider; mpt::MockSSHTestFixture mock_ssh_test_fixture; mp::SSHSession session{"theanswertoeverything", 42, "ubuntu", key_provider}; }; } // namespace TEST_F(SSHProcess, can_retrieve_exit_status) { ssh_channel_callbacks callbacks{nullptr}; auto add_channel_cbs = [&callbacks](ssh_channel, ssh_channel_callbacks cb) { callbacks = cb; return SSH_OK; }; REPLACE(ssh_add_channel_callbacks, add_channel_cbs); int expected_status{42}; auto event_dopoll = [&callbacks, &expected_status](auto...) { if (!callbacks) return SSH_ERROR; callbacks->channel_exit_status_function(nullptr, nullptr, expected_status, callbacks->userdata); return SSH_OK; }; REPLACE(ssh_event_dopoll, event_dopoll); auto proc = session.exec("something"); EXPECT_THAT(proc.exit_code(), Eq(expected_status)); } TEST_F(SSHProcess, exit_code_times_out) { REPLACE(ssh_event_dopoll, [](ssh_event, int timeout) { std::this_thread::sleep_for(std::chrono::milliseconds(timeout + 1)); return SSH_OK; }); auto proc = session.exec("something"); EXPECT_THROW(proc.exit_code(std::chrono::milliseconds(1)), std::runtime_error); } TEST_F(SSHProcess, specifies_stderr_correctly) { int expected_is_stderr = 0; auto channel_read = [&expected_is_stderr](ssh_channel, void*, uint32_t, int is_stderr, int) { EXPECT_THAT(expected_is_stderr, Eq(is_stderr)); return 0; }; REPLACE(ssh_channel_read_timeout, channel_read); auto proc = session.exec("something"); proc.read_std_output(); expected_is_stderr = 1; proc.read_std_error(); } TEST_F(SSHProcess, reading_output_returns_empty_if_channel_closed) { REPLACE(ssh_channel_is_closed, [](auto...) { return 1; }); auto proc = session.exec("something"); auto output = proc.read_std_output(); EXPECT_TRUE(output.empty()); } TEST_F(SSHProcess, reading_failure_returns_empty_if_channel_closed) { int channel_closed{0}; REPLACE(ssh_channel_read_timeout, [&channel_closed](auto...) { channel_closed = 1; return -1; }); REPLACE(ssh_channel_is_closed, [&channel_closed](auto...) { return channel_closed; }); auto proc = session.exec("something"); auto output = proc.read_std_output(); EXPECT_TRUE(output.empty()); } TEST_F(SSHProcess, throws_on_read_errors) { REPLACE(ssh_channel_read_timeout, [](auto...) { return -1; }); auto proc = session.exec("something"); EXPECT_THROW(proc.read_std_output(), std::runtime_error); } TEST_F(SSHProcess, read_std_output_returns_empty_string_on_eof) { REPLACE(ssh_channel_read_timeout, [](auto...) { return 0; }); auto proc = session.exec("something"); auto output = proc.read_std_output(); EXPECT_TRUE(output.empty()); } TEST_F(SSHProcess, can_read_output) { std::string expected_output{"some content here"}; auto remaining = expected_output.size(); auto channel_read = [&expected_output, &remaining](ssh_channel, void* dest, uint32_t count, int is_stderr, int) { const auto num_to_copy = std::min(count, static_cast<uint32_t>(remaining)); const auto begin = expected_output.begin() + expected_output.size() - remaining; std::copy_n(begin, num_to_copy, reinterpret_cast<char*>(dest)); remaining -= num_to_copy; return num_to_copy; }; REPLACE(ssh_channel_read_timeout, channel_read); auto proc = session.exec("something"); auto output = proc.read_std_output(); EXPECT_THAT(output, StrEq(expected_output)); }
4,552
C++
.cpp
123
32.894309
117
0.693303
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,568
test_persistent_settings_handler.cpp
canonical_multipass/tests/test_persistent_settings_handler.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "mock_file_ops.h" #include "mock_qsettings.h" #include <multipass/constants.h> #include <multipass/exceptions/settings_exceptions.h> #include <multipass/settings/basic_setting_spec.h> #include <multipass/settings/custom_setting_spec.h> #include <multipass/settings/persistent_settings_handler.h> #include <QString> #include <functional> namespace mp = multipass; namespace mpt = mp::test; using namespace testing; namespace { class TestPersistentSettingsHandler : public Test { public: mp::PersistentSettingsHandler make_handler(const std::optional<QString>& specific_key = std::nullopt, const std::optional<QString>& specific_val = std::nullopt, const std::optional<std::function<QString(QString)>>& specific_interpreter = std::nullopt) { auto setting_set = make_basic_persistent_settings(); if (specific_key) { auto val = specific_val.value_or("banana"); if (specific_interpreter) setting_set.insert(std::make_unique<mp::CustomSettingSpec>(*specific_key, val, *specific_interpreter)); else setting_set.insert(std::make_unique<mp::BasicSettingSpec>(*specific_key, val)); } return mp::PersistentSettingsHandler{fake_filename, std::move(setting_set)}; } void inject_mock_qsettings() // moves the mock, so call once only, after setting expectations { EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings(Eq(fake_filename), Eq(QSettings::IniFormat))) .WillOnce(Return(ByMove(std::move(mock_qsettings)))); } void mock_unreadable_settings_file() { std::fstream fstream{}; fstream.setstate(std::ios_base::failbit); EXPECT_CALL(*mock_file_ops, open(_, StrEq(qPrintable(fake_filename)), Eq(std::ios_base::in))) .WillOnce(DoAll(WithArg<0>([](auto& stream) { stream.setstate(std::ios_base::failbit); }), Assign(&errno, EACCES))); EXPECT_CALL(*mock_qsettings, fileName).WillOnce(Return(fake_filename)); } public: QString fake_filename = "/tmp/fake.filename"; std::map<QString, QString> defaults{ {"a.key", "a value"}, {"another.key", "with a value"}, {"one.further.key", "and its default value"}}; mpt::MockFileOps::GuardedMock mock_file_ops_injection = mpt::MockFileOps::inject<NiceMock>(); mpt::MockFileOps* mock_file_ops = mock_file_ops_injection.first; mpt::MockQSettingsProvider::GuardedMock mock_qsettings_injection = mpt::MockQSettingsProvider::inject<StrictMock>(); /* strict to ensure that, other than explicitly injected, no QSettings are used */ mpt::MockQSettingsProvider* mock_qsettings_provider = mock_qsettings_injection.first; std::unique_ptr<NiceMock<mpt::MockQSettings>> mock_qsettings = std::make_unique<NiceMock<mpt::MockQSettings>>(); private: mp::SettingSpec::Set make_basic_persistent_settings() const { mp::SettingSpec::Set ret; for (const auto& [k, v] : defaults) ret.insert(std::make_unique<mp::BasicSettingSpec>(k, v)); return ret; } }; TEST_F(TestPersistentSettingsHandler, keysReturnsEmptyWhenNoSettingsSpec) { mp::PersistentSettingsHandler handler{fake_filename, {}}; EXPECT_THAT(handler.keys(), IsEmpty()); } TEST_F(TestPersistentSettingsHandler, keysReturnsSpecsKey) { auto handler = make_handler(); std::vector<QString> expected; expected.reserve(defaults.size()); for (const auto& item : defaults) expected.push_back(item.first); EXPECT_THAT(handler.keys(), UnorderedPointwise(Eq(), expected)); } TEST_F(TestPersistentSettingsHandler, getThrowsOnUnreadableFile) { const auto key = "foo"; const auto handler = make_handler(key); mock_unreadable_settings_file(); inject_mock_qsettings(); MP_EXPECT_THROW_THAT(handler.get(key), mp::PersistentSettingsException, mpt::match_what(AllOf(HasSubstr("read"), HasSubstr("access")))); } TEST_F(TestPersistentSettingsHandler, setThrowsOnUnreadableFile) { const auto key = mp::mounts_key, val = "yes"; auto handler = make_handler(key, val); mock_unreadable_settings_file(); inject_mock_qsettings(); MP_EXPECT_THROW_THAT(handler.set(key, val), mp::PersistentSettingsException, mpt::match_what(AllOf(HasSubstr("read"), HasSubstr("access")))); } using DescribedQSettingsStatus = std::tuple<QSettings::Status, std::string>; struct TestPersistentSettingsReadWriteError : public TestPersistentSettingsHandler, public WithParamInterface<DescribedQSettingsStatus> { }; TEST_P(TestPersistentSettingsReadWriteError, getThrowsOnFileReadError) { const auto& [status, desc] = GetParam(); const auto key = "token"; const auto handler = make_handler(key); EXPECT_CALL(*mock_qsettings, status).WillOnce(Return(status)); inject_mock_qsettings(); MP_EXPECT_THROW_THAT(handler.get(key), mp::PersistentSettingsException, mpt::match_what(AllOf(HasSubstr("read"), HasSubstr(desc)))); } TEST_P(TestPersistentSettingsReadWriteError, setThrowsOnFileWriteError) { const auto& [status, desc] = GetParam(); const auto key = "blah"; auto handler = make_handler(key); { InSequence seq; EXPECT_CALL(*mock_qsettings, sync); // needs to flush to ensure failure to write EXPECT_CALL(*mock_qsettings, status).WillOnce(Return(status)); } inject_mock_qsettings(); MP_EXPECT_THROW_THAT(handler.set(key, "bleh"), mp::PersistentSettingsException, mpt::match_what(AllOf(HasSubstr("write"), HasSubstr(desc)))); } INSTANTIATE_TEST_SUITE_P(TestSettingsAllReadErrors, TestPersistentSettingsReadWriteError, Values(DescribedQSettingsStatus{QSettings::FormatError, "format"}, DescribedQSettingsStatus{QSettings::AccessError, "access"})); TEST_F(TestPersistentSettingsHandler, getReturnsRecordedSetting) { const auto key = "choose.a.key", val = "asdf", default_ = "some default"; const auto handler = make_handler(key, default_); EXPECT_CALL(*mock_qsettings, value_impl(Eq(key), _)).WillOnce(Return(val)); inject_mock_qsettings(); ASSERT_NE(val, default_); EXPECT_EQ(handler.get(key), QString{val}); } TEST_F(TestPersistentSettingsHandler, getResetsInvalidValueAndReturnsDefault) { const auto key = "tampered.setting", val = "xyz", default_ = "abc", error = "nonsense"; const auto handler = make_handler(key, default_, [&key, &val, &error](QString v) -> QString { if (v == val) throw mp::InvalidSettingException{key, val, error}; return v; }); { InSequence seq; EXPECT_CALL(*mock_qsettings, value_impl(Eq(key), _)).WillOnce(Return(val)); EXPECT_CALL(*mock_qsettings, remove(Eq(key))); } inject_mock_qsettings(); ASSERT_NE(val, default_); EXPECT_EQ(handler.get(key), QString{default_}); } TEST_F(TestPersistentSettingsHandler, getReturnsDefaultByDefault) { const auto key = "chave", default_ = "Cylinder"; const auto handler = make_handler(key, default_); EXPECT_CALL(*mock_qsettings, value_impl(Eq(key), Eq(default_))).WillOnce(Return(default_)); inject_mock_qsettings(); ASSERT_EQ(handler.get(key), QString(default_)); } TEST_F(TestPersistentSettingsHandler, getThrowsOnUnknownKey) { const auto key = "clef"; const auto handler = make_handler(); EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings).Times(0); MP_EXPECT_THROW_THAT(handler.get(key), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key))); } TEST_F(TestPersistentSettingsHandler, setThrowsOnUnknownKey) { const auto key = "ki"; auto handler = make_handler(); EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings).Times(0); MP_EXPECT_THROW_THAT(handler.set(key, "asdf"), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key))); } TEST_F(TestPersistentSettingsHandler, setRecordsProvidedBasicSetting) { const auto key = "name.a.key", val = "and a value"; auto handler = make_handler(key); EXPECT_CALL(*mock_qsettings, setValue(Eq(key), Eq(val))); inject_mock_qsettings(); ASSERT_NO_THROW(handler.set(key, val)); } TEST_F(TestPersistentSettingsHandler, setRecordsInterpretedSetting) { const auto key = "k.e.y", given_val = "given", interpreted_val = "interpreted"; auto handler = make_handler(key, "default", [&interpreted_val](QString) { return interpreted_val; }); EXPECT_CALL(*mock_qsettings, setValue(Eq(key), Eq(interpreted_val))); inject_mock_qsettings(); ASSERT_NO_THROW(handler.set(key, given_val)); } TEST_F(TestPersistentSettingsHandler, setThrowsInterpreterExceptions) { const auto key = "clave", default_ = "valid", val = "invalid", error = "nope"; auto handler = make_handler(key, default_, [&key, &default_, &val, &error](QString v) { if (v == default_) return v; throw mp::InvalidSettingException{key, val, error}; }); EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings).Times(0); MP_EXPECT_THROW_THAT(handler.set(key, val), mp::InvalidSettingException, mpt::match_what(HasSubstr(error))); } } // namespace
10,107
C++
.cpp
224
39.151786
119
0.694447
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,569
test_blueprint_provider.cpp
canonical_multipass/tests/test_blueprint_provider.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "common.h" #include "mock_logger.h" #include "mock_platform.h" #include "mock_poco_zip_utils.h" #include "mock_url_downloader.h" #include "path.h" #include "temp_dir.h" #include <multipass/default_vm_blueprint_provider.h> #include <multipass/exceptions/blueprint_exceptions.h> #include <multipass/exceptions/download_exception.h> #include <multipass/memory_size.h> #include <multipass/url_downloader.h> #include <multipass/yaml_node_utils.h> #include <Poco/Exception.h> #include <QFileInfo> #include <chrono> namespace mp = multipass; namespace mpl = multipass::logging; namespace mpt = multipass::test; using namespace std::chrono_literals; using namespace testing; namespace { const QString test_blueprints_zip{"/test-blueprints.zip"}; const QString multipass_blueprints_zip{"/multipass-blueprints.zip"}; const char* sha256_checksum = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; struct VMBlueprintProvider : public Test { QString blueprints_zip_url{QUrl::fromLocalFile(mpt::test_data_path()).toString() + test_blueprints_zip}; mp::URLDownloader url_downloader{std::chrono::seconds(10)}; mpt::TempDir cache_dir; std::chrono::seconds default_ttl{1s}; mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(); }; } // namespace TEST_F(VMBlueprintProvider, downloadsZipToExpectedLocation) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const QFileInfo original_zip{mpt::test_data_path() + test_blueprints_zip}; const QFileInfo downloaded_zip{cache_dir.path() + multipass_blueprints_zip}; EXPECT_TRUE(downloaded_zip.exists()); EXPECT_EQ(downloaded_zip.size(), original_zip.size()); } TEST_F(VMBlueprintProvider, fetchBlueprintForUnknownBlueprintThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; EXPECT_THROW(blueprint_provider.fetch_blueprint_for("phony", vm_desc, dummy_data), std::out_of_range); } TEST_F(VMBlueprintProvider, infoForUnknownBlueprintReturnsEmpty) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.info_for("phony"), std::nullopt); } TEST_F(VMBlueprintProvider, invalidImageSchemeThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("invalid-image-blueprint", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("Unsupported image scheme in Blueprint"))); } TEST_F(VMBlueprintProvider, invalidMinCoresThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("invalid-cpu-blueprint", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("Minimum CPU value in Blueprint is invalid"))); } TEST_F(VMBlueprintProvider, invalidMinMemorySizeThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("invalid-memory-size-blueprint", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("Minimum memory size value in Blueprint is invalid"))); } TEST_F(VMBlueprintProvider, invalidMinDiskSpaceThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("invalid-disk-space-blueprint", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("Minimum disk space value in Blueprint is invalid"))); } TEST_F(VMBlueprintProvider, invalidAliasDefinitionThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("invalid-alias-blueprint", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("Alias definition must be in the form instance:command"))); } TEST_F(VMBlueprintProvider, fetchTestBlueprint1ReturnsExpectedInfo) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; auto query = blueprint_provider.fetch_blueprint_for("test-blueprint1", vm_desc, dummy_data); auto yaml_as_str = mp::utils::emit_yaml(vm_desc.vendor_data_config); EXPECT_EQ(query.release, "default"); EXPECT_EQ(vm_desc.num_cores, 2); EXPECT_EQ(vm_desc.mem_size, mp::MemorySize("2G")); EXPECT_EQ(vm_desc.disk_space, mp::MemorySize("25G")); EXPECT_THAT(yaml_as_str, AllOf(HasSubstr("runcmd"), HasSubstr("echo \"Have fun!\""))); } TEST_F(VMBlueprintProvider, fetchTestBlueprint1ReturnsExpectedAliasesAndWorkspace) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData launch_data; auto query = blueprint_provider.fetch_blueprint_for("test-blueprint1", vm_desc, launch_data); EXPECT_EQ(launch_data.aliases_to_be_created.size(), 2); auto lst_alias = launch_data.aliases_to_be_created["lst"]; EXPECT_EQ(lst_alias.instance, "test-blueprint1"); EXPECT_EQ(lst_alias.command, "ls"); EXPECT_EQ(lst_alias.working_directory, "map"); auto lsp_alias = launch_data.aliases_to_be_created["lsp"]; EXPECT_EQ(lsp_alias.instance, "test-blueprint1"); EXPECT_EQ(lsp_alias.command, "pwd"); EXPECT_EQ(lsp_alias.working_directory, "map"); EXPECT_TRUE(launch_data.workspaces_to_be_created.size() == 1 && launch_data.workspaces_to_be_created[0] == "test-blueprint1"); } TEST_F(VMBlueprintProvider, fetchTestBlueprint2ReturnsExpectedInfo) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData launch_data; auto query = blueprint_provider.fetch_blueprint_for("test-blueprint2", vm_desc, launch_data); EXPECT_EQ(query.release, "bionic"); EXPECT_EQ(query.remote_name, "daily"); EXPECT_EQ(vm_desc.num_cores, 4); EXPECT_EQ(vm_desc.mem_size, mp::MemorySize("4G")); EXPECT_EQ(vm_desc.disk_space, mp::MemorySize("50G")); EXPECT_TRUE(vm_desc.vendor_data_config.IsNull()); EXPECT_EQ(launch_data.workspaces_to_be_created.size(), 0); } TEST_F(VMBlueprintProvider, missingDescriptionThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const std::string blueprint{"missing-description-blueprint"}; MP_EXPECT_THROW_THAT( blueprint_provider.info_for(blueprint), mp::InvalidBlueprintException, mpt::match_what(StrEq(fmt::format("The \'description\' key is required for the {} Blueprint", blueprint)))); } TEST_F(VMBlueprintProvider, missingVersionThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const std::string blueprint{"missing-version-blueprint"}; MP_EXPECT_THROW_THAT( blueprint_provider.info_for(blueprint), mp::InvalidBlueprintException, mpt::match_what(StrEq(fmt::format("The \'version\' key is required for the {} Blueprint", blueprint)))); } TEST_F(VMBlueprintProvider, invalidDescriptionThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const std::string blueprint{"invalid-description-blueprint"}; MP_EXPECT_THROW_THAT( blueprint_provider.info_for(blueprint), mp::InvalidBlueprintException, mpt::match_what(StrEq(fmt::format("Cannot convert \'description\' key for the {} Blueprint", blueprint)))); } TEST_F(VMBlueprintProvider, invalidVersionThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const std::string blueprint{"invalid-version-blueprint"}; MP_EXPECT_THROW_THAT( blueprint_provider.info_for(blueprint), mp::InvalidBlueprintException, mpt::match_what(StrEq(fmt::format("Cannot convert \'version\' key for the {} Blueprint", blueprint)))); } TEST_F(VMBlueprintProvider, invalidCloudInitThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; const std::string blueprint{"invalid-cloud-init-blueprint"}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT( blueprint_provider.fetch_blueprint_for(blueprint, vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq(fmt::format("Cannot convert cloud-init data for the {} Blueprint", blueprint)))); } TEST_F(VMBlueprintProvider, givenCoresLessThanMinimumThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{1, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("test-blueprint1", vm_desc, dummy_data), mp::BlueprintMinimumException, mpt::match_what(AllOf(HasSubstr("Number of CPUs"), HasSubstr("2")))); } TEST_F(VMBlueprintProvider, givenMemLessThanMinimumThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, mp::MemorySize{"1G"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("test-blueprint1", vm_desc, dummy_data), mp::BlueprintMinimumException, mpt::match_what(AllOf(HasSubstr("Memory size"), HasSubstr("2G")))); } TEST_F(VMBlueprintProvider, givenDiskSpaceLessThanMinimumThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, mp::MemorySize{"20G"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.fetch_blueprint_for("test-blueprint1", vm_desc, dummy_data), mp::BlueprintMinimumException, mpt::match_what(AllOf(HasSubstr("Disk space"), HasSubstr("25G")))); } TEST_F(VMBlueprintProvider, higherOptionsIsNotOverridden) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{ 4, mp::MemorySize{"4G"}, mp::MemorySize{"50G"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; blueprint_provider.fetch_blueprint_for("test-blueprint1", vm_desc, dummy_data); EXPECT_EQ(vm_desc.num_cores, 4); EXPECT_EQ(vm_desc.mem_size, mp::MemorySize("4G")); EXPECT_EQ(vm_desc.disk_space, mp::MemorySize("50G")); } TEST_F(VMBlueprintProvider, infoForReturnsExpectedInfo) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; auto blueprint = blueprint_provider.info_for("test-blueprint2"); ASSERT_TRUE(blueprint); ASSERT_EQ(blueprint->aliases.size(), 1); EXPECT_EQ(blueprint->aliases[0], "test-blueprint2"); EXPECT_EQ(blueprint->release_title, "Another test blueprint"); EXPECT_EQ(blueprint->version, "0.1"); } TEST_F(VMBlueprintProvider, allBlueprintsReturnsExpectedInfo) { logger_scope.mock_logger->screen_logs(mpl::Level::error); logger_scope.mock_logger->expect_log( mpl::Level::error, "Invalid Blueprint: Cannot convert 'description' key for the invalid-description-blueprint Blueprint"); logger_scope.mock_logger->expect_log( mpl::Level::error, "Invalid Blueprint: Cannot convert 'version' key for the invalid-version-blueprint Blueprint"); logger_scope.mock_logger->expect_log( mpl::Level::error, "Invalid Blueprint: The 'description' key is required for the missing-description-blueprint Blueprint"); logger_scope.mock_logger->expect_log( mpl::Level::error, "Invalid Blueprint: The 'version' key is required for the missing-version-blueprint Blueprint"); logger_scope.mock_logger->expect_log( mpl::Level::error, "Invalid Blueprint name \'42-invalid-hostname-blueprint\': must be a valid host name"); logger_scope.mock_logger->expect_log(mpl::Level::debug, "Not loading malformed \"invalid-arch\" v1"); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; auto blueprints = blueprint_provider.all_blueprints(); EXPECT_EQ(blueprints.size(), 12ul); EXPECT_TRUE(std::find_if(blueprints.cbegin(), blueprints.cend(), [](const mp::VMImageInfo& blueprint_info) { return ((blueprint_info.aliases.size() == 1) && (blueprint_info.aliases[0] == "test-blueprint1") && (blueprint_info.release_title == "The first test blueprint")); }) != blueprints.cend()); EXPECT_TRUE(std::find_if(blueprints.cbegin(), blueprints.cend(), [](const mp::VMImageInfo& blueprint_info) { return ((blueprint_info.aliases.size() == 1) && (blueprint_info.aliases[0] == "test-blueprint2") && (blueprint_info.release_title == "Another test blueprint")); }) != blueprints.cend()); } TEST_F(VMBlueprintProvider, doesNotUpdateBlueprintsWhenNotNeeded) { mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)) .Times(1) .WillRepeatedly([](auto, const QString& file_name, auto...) { QFile file(file_name); file.open(QFile::WriteOnly); }); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &mock_url_downloader, cache_dir.path(), default_ttl}; blueprint_provider.all_blueprints(); } TEST_F(VMBlueprintProvider, updatesBlueprintsWhenNeeded) { mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)) .Times(2) .WillRepeatedly([](auto, const QString& file_name, auto...) { QFile file(file_name); if (!file.exists()) file.open(QFile::WriteOnly); }); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &mock_url_downloader, cache_dir.path(), std::chrono::milliseconds(0)}; blueprint_provider.all_blueprints(); } TEST_F(VMBlueprintProvider, downloadFailureOnStartupLogsErrorAndDoesNotThrow) { const std::string error_msg{"There is a problem, Houston."}; const std::string url{"https://fake.url"}; mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)).WillOnce(Throw(mp::DownloadException(url, error_msg))); auto logger_scope = mpt::MockLogger::inject(); logger_scope.mock_logger->screen_logs(mpl::Level::error); logger_scope.mock_logger->expect_log( mpl::Level::error, fmt::format("Error fetching Blueprints: failed to download from '{}': {}", url, error_msg)); EXPECT_NO_THROW( mp::DefaultVMBlueprintProvider(blueprints_zip_url, &mock_url_downloader, cache_dir.path(), default_ttl)); } TEST_F(VMBlueprintProvider, downloadFailureDuringUpdateLogsErrorAndDoesNotThrow) { const std::string error_msg{"There is a problem, Houston."}; const std::string url{"https://fake.url"}; mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)) .Times(2) .WillOnce([](auto, const QString& file_name, auto...) { QFile file(file_name); file.open(QFile::WriteOnly); }) .WillRepeatedly(Throw(mp::DownloadException(url, error_msg))); auto logger_scope = mpt::MockLogger::inject(); logger_scope.mock_logger->screen_logs(mpl::Level::error); logger_scope.mock_logger->expect_log( mpl::Level::error, fmt::format("Error fetching Blueprints: failed to download from '{}': {}", url, error_msg)); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &mock_url_downloader, cache_dir.path(), std::chrono::milliseconds(0)}; EXPECT_NO_THROW(blueprint_provider.all_blueprints()); } TEST_F(VMBlueprintProvider, zipArchivePocoExceptionLogsErrorAndDoesNotThrow) { auto [mock_poco_zip_utils, guard] = mpt::MockPocoZipUtils::inject(); const std::string error_msg{"Rubbish zip file"}; EXPECT_CALL(*mock_poco_zip_utils, zip_archive_for(_)).WillOnce(Throw(Poco::IllegalStateException(error_msg))); auto logger_scope = mpt::MockLogger::inject(); logger_scope.mock_logger->screen_logs(mpl::Level::error); logger_scope.mock_logger->expect_log( mpl::Level::error, fmt::format("Error extracting Blueprints zip file: Illegal state: {}", error_msg)); EXPECT_NO_THROW(mp::DefaultVMBlueprintProvider(blueprints_zip_url, &url_downloader, cache_dir.path(), std::chrono::milliseconds(0))); } TEST_F(VMBlueprintProvider, generalExceptionDuringStartupThrows) { const std::string error_msg{"Bad stuff just happened"}; mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)).WillRepeatedly(Throw(std::runtime_error(error_msg))); MP_EXPECT_THROW_THAT(mp::DefaultVMBlueprintProvider blueprint_provider( blueprints_zip_url, &mock_url_downloader, cache_dir.path(), std::chrono::milliseconds(0)), std::runtime_error, mpt::match_what(StrEq(error_msg))); } TEST_F(VMBlueprintProvider, generalExceptionDuringCallThrows) { const std::string error_msg{"This can't be possible"}; mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)) .Times(2) .WillOnce([](auto, const QString& file_name, auto...) { QFile file(file_name); file.open(QFile::WriteOnly); }) .WillRepeatedly(Throw(std::runtime_error(error_msg))); mp::DefaultVMBlueprintProvider blueprint_provider(blueprints_zip_url, &mock_url_downloader, cache_dir.path(), std::chrono::milliseconds(0)); MP_EXPECT_THROW_THAT(blueprint_provider.info_for("foo"), std::runtime_error, mpt::match_what(StrEq(error_msg))); } TEST_F(VMBlueprintProvider, validBlueprintReturnsExpectedName) { const std::string blueprint_name{"test-blueprint1"}; mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; auto name = blueprint_provider.name_from_blueprint(blueprint_name); EXPECT_EQ(name, blueprint_name); } TEST_F(VMBlueprintProvider, nonexistentBlueprintReturnsEmptyName) { const std::string blueprint_name{"not-a-blueprint"}; mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; auto name = blueprint_provider.name_from_blueprint(blueprint_name); EXPECT_TRUE(name.empty()); } TEST_F(VMBlueprintProvider, returnsExpectedTimeout) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.blueprint_timeout("test-blueprint1"), 600); } TEST_F(VMBlueprintProvider, noTimeoutReturnsZero) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.blueprint_timeout("test-blueprint2"), 0); } TEST_F(VMBlueprintProvider, nonexistentBlueprintTimeoutReturnsZero) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.blueprint_timeout("not-a-blueprint"), 0); } TEST_F(VMBlueprintProvider, invalidTimeoutThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; MP_EXPECT_THROW_THAT(blueprint_provider.blueprint_timeout("invalid-timeout-blueprint"), mp::InvalidBlueprintException, mpt::match_what(StrEq(fmt::format("Invalid timeout given in Blueprint")))); } TEST_F(VMBlueprintProvider, noImageDefinedReturnsDefault) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; auto query = blueprint_provider.fetch_blueprint_for("no-image-blueprint", vm_desc, dummy_data); EXPECT_EQ(query.release, "default"); } TEST_F(VMBlueprintProvider, nameMismatchThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT( blueprint_provider.fetch_blueprint_for("name-mismatch", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("There are no instance definitions matching Blueprint name \"name-mismatch\""))); } TEST_F(VMBlueprintProvider, invalidRunsOnThrows) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const std::string blueprint{"invalid-description-blueprint"}; MP_EXPECT_THROW_THAT( blueprint_provider.info_for(blueprint), mp::InvalidBlueprintException, mpt::match_what(StrEq(fmt::format("Cannot convert \'description\' key for the {} Blueprint", blueprint)))); } TEST_F(VMBlueprintProvider, fetchForInvalidReturnsEmpty) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const std::string blueprint{"invalid-arch"}; // This call fails with an std::nullopt exception because the Blueprint is invalid and was filtered out by // blueprints_map_for() at provider construction. EXPECT_EQ(blueprint_provider.info_for(blueprint), std::nullopt); } TEST_F(VMBlueprintProvider, infoForIncompatibleReturnsEmpty) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; const std::string blueprint{"arch-only"}; // This call fails with an std::nullopt exception because the Blueprint is invalid and was filtered out by // blueprints_map_for() at provider construction. EXPECT_EQ(blueprint_provider.info_for(blueprint), std::nullopt); } TEST_F(VMBlueprintProvider, infoForCompatibleReturnsExpectedInfo) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "arch"}; auto blueprint = blueprint_provider.info_for("arch-only"); ASSERT_TRUE(blueprint); ASSERT_EQ(blueprint->aliases.size(), 1); EXPECT_EQ(blueprint->aliases[0], "arch-only"); EXPECT_EQ(blueprint->release_title, "An arch-only blueprint"); } TEST_F(VMBlueprintProvider, allBlueprintsReturnsExpectedInfoForArch) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "arch"}; auto blueprints = blueprint_provider.all_blueprints(); EXPECT_EQ(blueprints.size(), 13ul); EXPECT_TRUE(std::find_if(blueprints.cbegin(), blueprints.cend(), [](const mp::VMImageInfo& blueprint_info) { return ((blueprint_info.aliases.size() == 1) && (blueprint_info.aliases[0] == "arch-only") && (blueprint_info.release_title == "An arch-only blueprint")); }) != blueprints.cend()); ASSERT_EQ(blueprints[0].aliases.size(), 1); } // // Blueprints v2 tests. // TEST_F(VMBlueprintProvider, v2WithNoInstancesKeyNotAdded) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.info_for("no-instances"), std::nullopt); } TEST_F(VMBlueprintProvider, v2WithNoBlueprintKeyNotAdded) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.info_for("no-blueprint"), std::nullopt); } TEST_F(VMBlueprintProvider, v2WithNoImagesKeyNotAdded) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.info_for("no-images"), std::nullopt); } TEST_F(VMBlueprintProvider, v2WithNoUrlKeyNotAdded) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "multivacs"}; EXPECT_EQ(blueprint_provider.info_for("no-url"), std::nullopt); } TEST_F(VMBlueprintProvider, v2MinimalDefinitionAdded) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "multivacs"}; EXPECT_NO_THROW(blueprint_provider.info_for("minimal")); } TEST_F(VMBlueprintProvider, v2MinimalDefinitionWithShaOnUrlAdded) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "multivacs"}; EXPECT_NO_THROW(blueprint_provider.info_for("minimal-with-sha256-url")); } TEST_F(VMBlueprintProvider, v2MinimalDefinitionWithHardcodedShaAdded) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "multivacs"}; EXPECT_NO_THROW(blueprint_provider.info_for("minimal-with-sha256-string")); } TEST_F(VMBlueprintProvider, v2ShaOnUrlIsCorrectlyPropagated) { mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)) .WillOnce([this](const QUrl& url, const QString& file_name, int64_t size, const int download_type, const mp::ProgressMonitor& monitor) { url_downloader.download_to(url, file_name, size, download_type, monitor); }); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &mock_url_downloader, cache_dir.path(), default_ttl, "multivacs"}; mp::VirtualMachineDescription vm_desc; mp::ClientLaunchData launch_data; EXPECT_CALL(mock_url_downloader, download(_)).Times(1).WillRepeatedly([](auto) { char full_sha256_string[73]; strcpy(full_sha256_string, sha256_checksum); strcat(full_sha256_string, " sha256\n"); return QByteArray{full_sha256_string}; }); auto query = blueprint_provider.fetch_blueprint_for("minimal-with-sha256-url", vm_desc, launch_data); ASSERT_EQ(vm_desc.image.id, sha256_checksum); } TEST_F(VMBlueprintProvider, v2HardcodedShaIsCorrectlyPropagated) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "multivacs"}; mp::VirtualMachineDescription vm_desc; mp::ClientLaunchData launch_data; auto query = blueprint_provider.fetch_blueprint_for("minimal-with-sha256-string", vm_desc, launch_data); ASSERT_EQ(vm_desc.image.id, sha256_checksum); } TEST_F(VMBlueprintProvider, v2WithoutShaIsCorrectlyPropagated) { mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "multivacs"}; mp::VirtualMachineDescription vm_desc; mp::ClientLaunchData launch_data; auto query = blueprint_provider.fetch_blueprint_for("minimal", vm_desc, launch_data); ASSERT_EQ(vm_desc.image.id, ""); } // // Test loading Blueprints from file. // struct VMBlueprintFileLaunch : public VMBlueprintProvider { mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject<NiceMock>()}; mpt::MockPlatform* mock_platform = attr.first; }; struct VMBlueprintFileLaunchFromFile : public VMBlueprintFileLaunch, public WithParamInterface<std::pair<std::string, std::string>> { }; TEST_P(VMBlueprintFileLaunchFromFile, loadsFile) { const auto& [file, blueprint_name] = GetParam(); mpt::MockURLDownloader mock_url_downloader; EXPECT_CALL(mock_url_downloader, download_to(_, _, _, _, _)) .WillRepeatedly([](auto, const QString& file_name, auto...) { QFile file(file_name); file.open(QFile::WriteOnly); }); ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); auto blueprint_path = QString(mpt::test_data_path() + "/blueprints/" + QString::fromStdString(file)).toStdString(); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &mock_url_downloader, cache_dir.path(), default_ttl, "multivacs"}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; auto query = blueprint_provider.blueprint_from_file(blueprint_path, blueprint_name, vm_desc, dummy_data); EXPECT_EQ(vm_desc.num_cores, 2); EXPECT_EQ(vm_desc.mem_size, mp::MemorySize("2G")); EXPECT_EQ(vm_desc.disk_space, mp::MemorySize("25G")); auto yaml_as_str = mp::utils::emit_yaml(vm_desc.vendor_data_config); EXPECT_THAT(yaml_as_str, AllOf(HasSubstr("runcmd"), HasSubstr("echo \"Have fun!\""))); } INSTANTIATE_TEST_SUITE_P(VMBlueprintFileLaunch, VMBlueprintFileLaunchFromFile, Values(std::pair{"v1/test-blueprint1.yaml", "test-blueprint1"}, std::pair{"v2/test-blueprint1.yaml", "test-blueprint1"})); TEST_F(VMBlueprintFileLaunch, mergesBlueprintVendorData) { ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; YAML::Node vendor_data; vendor_data["runcmd"].push_back("echo 123"); vendor_data["system_info"]["default_user"]["name"] = "ubuntu"; vendor_data["growpart"]["devices"].push_back("/dev/vdb1"); mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, vendor_data, {}}; mp::ClientLaunchData dummy_data; const auto blueprint_path = mpt::test_data_path() + "blueprints/v1/complex-cloud-init.yaml"; blueprint_provider.blueprint_from_file(blueprint_path.toStdString(), "complex-cloud-init", vm_desc, dummy_data); const auto runcmd = vm_desc.vendor_data_config["runcmd"]; EXPECT_EQ(runcmd[0].Scalar(), "echo 123"); EXPECT_EQ(runcmd[1].Scalar(), "echo abc"); EXPECT_EQ(runcmd[2].Scalar(), "echo def"); const auto default_user = vm_desc.vendor_data_config["system_info"]["default_user"]; EXPECT_EQ(default_user["name"].Scalar(), "ubuntu"); EXPECT_EQ(default_user["shell"].Scalar(), "/bin/zsh"); const auto devices = vm_desc.vendor_data_config["growpart"]["devices"]; EXPECT_EQ(devices[0].Scalar(), "/dev/vdb1"); EXPECT_EQ(devices[1].Scalar(), "/"); } TEST_F(VMBlueprintFileLaunch, failsMergeVmBlueprintVendorDataDifferentTypes) { ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; YAML::Node vendor_data; vendor_data["runcmd"] = "echo 123"; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, vendor_data, {}}; mp::ClientLaunchData dummy_data; const auto blueprint_path = mpt::test_data_path() + "blueprints/v1/complex-cloud-init.yaml"; MP_EXPECT_THROW_THAT( blueprint_provider.blueprint_from_file(blueprint_path.toStdString(), "complex-cloud-init", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(HasSubstr("Cannot merge values of runcmd"))); } TEST_F(VMBlueprintFileLaunch, failsMergeVmBlueprintVendorDataScalarValues) { ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; YAML::Node vendor_data; vendor_data["system_info"]["default_user"]["shell"] = "/bin/fish"; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, vendor_data, {}}; mp::ClientLaunchData dummy_data; const auto blueprint_path = mpt::test_data_path() + "blueprints/v1/complex-cloud-init.yaml"; MP_EXPECT_THROW_THAT( blueprint_provider.blueprint_from_file(blueprint_path.toStdString(), "complex-cloud-init", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(HasSubstr("Cannot merge values of shell"))); } TEST_F(VMBlueprintFileLaunch, failsWithNonexistentFile) { ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.blueprint_from_file("/blah.yaml", "blah", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("Wrong file '/blah.yaml'"))); } TEST_F(VMBlueprintFileLaunch, fileLoadfailsWithInvalidHostName) { ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); auto blueprint_path = QString(mpt::test_data_path() + "/blueprints/v1/42-invalid-hostname-blueprint.yaml").toStdString(); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT( blueprint_provider.blueprint_from_file(blueprint_path, "42-invalid-hostname-blueprint", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("Invalid Blueprint name \'42-invalid-hostname-blueprint\': must be a valid host name"))); } TEST_F(VMBlueprintFileLaunch, failsIfFileLaunchIsUnsupported) { ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(false)); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.blueprint_from_file("/blah.yaml", "blah", vm_desc, dummy_data), std::runtime_error, mpt::match_what(StrEq("Launching a Blueprint from a file is not supported"))); } struct NameFromBlueprintTestSuite : public VMBlueprintProvider, public WithParamInterface<std::pair<std::string, std::string>> { }; TEST_P(NameFromBlueprintTestSuite, nameFromBlueprintWorks) { const auto& [input, output] = GetParam(); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl}; EXPECT_EQ(blueprint_provider.name_from_blueprint(input), output); } INSTANTIATE_TEST_SUITE_P(VMBlueprintProvider, NameFromBlueprintTestSuite, Values(std::pair{"file:///blah/blueprint1.yaml", "blueprint1"}, std::pair{"file:///blah/blueprint2.yml", "blueprint2"}, std::pair{"nonexistent-blueprint", ""})); TEST_F(VMBlueprintFileLaunch, fileLoadfailsWithNoUrl) { auto blueprint_path = QString(mpt::test_data_path() + "/blueprints/v2/test-blueprint1.yaml").toStdString(); ON_CALL(*mock_platform, is_image_url_supported()).WillByDefault(Return(true)); mp::DefaultVMBlueprintProvider blueprint_provider{blueprints_zip_url, &url_downloader, cache_dir.path(), default_ttl, "microvac"}; mp::VirtualMachineDescription vm_desc{0, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}; mp::ClientLaunchData dummy_data; MP_EXPECT_THROW_THAT(blueprint_provider.blueprint_from_file(blueprint_path, "test-blueprint1", vm_desc, dummy_data), mp::InvalidBlueprintException, mpt::match_what(StrEq("No image URL for architecture microvac in Blueprint"))); }
42,783
C++
.cpp
752
46.861702
120
0.647557
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
20,570
blueprint_test_lambdas.cpp
canonical_multipass/tests/blueprint_test_lambdas.cpp
/* * Copyright (C) Canonical, Ltd. * * 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 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef MULTIPASS_BLUEPRINTS_TEST_LAMBDAS_H #define MULTIPASS_BLUEPRINTS_TEST_LAMBDAS_H #include <multipass/client_launch_data.h> #include <multipass/memory_size.h> #include <multipass/query.h> #include <multipass/virtual_machine.h> #include <multipass/virtual_machine_description.h> #include <multipass/vm_image.h> #include "blueprint_test_lambdas.h" #include "common.h" #include "stub_virtual_machine.h" #include "stub_vm_image_vault.h" #include "temp_dir.h" namespace mp = multipass; namespace mpt = multipass::test; std::function<mp::VMImage(const mp::FetchType&, const mp::Query&, const mp::VMImageVault::PrepareAction&, const mp::ProgressMonitor&, const bool, const std::optional<std::string>, const mp::Path&)> mpt::fetch_image_lambda(const std::string& release, const std::string& remote, const bool must_have_checksum) { return [&release, &remote, must_have_checksum](const mp::FetchType& fetch_type, const mp::Query& query, const mp::VMImageVault::PrepareAction& prepare, const mp::ProgressMonitor& monitor, const bool unlock, const std::optional<std::string>& checksum, const mp::Path& save_dir) { EXPECT_EQ(query.release, release); if (remote.empty()) { EXPECT_TRUE(query.remote_name.empty()); } else { EXPECT_EQ(query.remote_name, remote); } if (must_have_checksum) { EXPECT_NE(checksum, std::nullopt); } return mpt::StubVMImageVault().fetch_image(fetch_type, query, prepare, monitor, unlock, checksum, save_dir); }; } std::function< mp::VirtualMachine::UPtr(const mp::VirtualMachineDescription&, const mp::SSHKeyProvider&, mp::VMStatusMonitor&)> mpt::create_virtual_machine_lambda(const int& num_cores, const mp::MemorySize& mem_size, const mp::MemorySize& disk_space, const std::string& name) { return [&num_cores, &mem_size, &disk_space, &name](const mp::VirtualMachineDescription& vm_desc, const mp::SSHKeyProvider&, mp::VMStatusMonitor&) { EXPECT_EQ(vm_desc.num_cores, num_cores); EXPECT_EQ(vm_desc.mem_size, mem_size); EXPECT_EQ(vm_desc.disk_space, disk_space); if (!name.empty()) { EXPECT_EQ(vm_desc.vm_name, name); } return std::make_unique<mpt::StubVirtualMachine>(); }; } std::function<mp::Query(const std::string&, mp::VirtualMachineDescription&, mp::ClientLaunchData&)> mpt::fetch_blueprint_for_lambda(const int& num_cores, const mp::MemorySize& mem_size, const mp::MemorySize& disk_space, const std::string& release, const std::string& remote, std::optional<std::pair<std::string, mp::AliasDefinition>> alias, std::optional<std::string> workspace, std::optional<std::string> sha256) { return [&num_cores, &mem_size, &disk_space, &release, &remote, alias, workspace, sha256](const auto&, mp::VirtualMachineDescription& vm_desc, mp::ClientLaunchData& l_data) -> mp::Query { vm_desc.num_cores = num_cores; vm_desc.mem_size = mem_size; vm_desc.disk_space = disk_space; if (sha256) vm_desc.image.id = *sha256; if (alias) l_data.aliases_to_be_created.emplace(alias->first, alias->second); if (workspace) l_data.workspaces_to_be_created.push_back(*workspace); return {"", release, false, remote, mp::Query::Type::Alias}; }; } #endif // MULTIPASS_BLUEPRINTS_TEST_LAMBDAS_H
4,830
C++
.cpp
104
34.615385
119
0.585526
canonical/multipass
7,732
642
476
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false