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
19,848
Lv2Evbuf.cpp
LMMS_lmms/src/core/lv2/Lv2Evbuf.cpp
/* * lv2_evbuf.cpp - Lv2 event buffer implementation * * Copyright (c) 2019-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. * */ /* * The original code was written by David Robillard <http://drobilla.net> */ #include "Lv2Evbuf.h" #ifdef LMMS_HAVE_LV2 #include <cassert> #include <cstdlib> #include <cstring> #include <lv2/atom/atom.h> namespace lmms { struct LV2_Evbuf_Impl { uint32_t capacity; uint32_t atom_Chunk; uint32_t atom_Sequence; LV2_Atom_Sequence buf; }; static inline uint32_t lv2_evbuf_pad_size(uint32_t size) { return (size + 7) & (~7); } LV2_Evbuf* lv2_evbuf_new(uint32_t capacity, uint32_t atom_Chunk, uint32_t atom_Sequence) { // FIXME: memory must be 64-bit aligned auto evbuf = (LV2_Evbuf*)malloc(sizeof(LV2_Evbuf) + sizeof(LV2_Atom_Sequence) + capacity); evbuf->capacity = capacity; evbuf->atom_Chunk = atom_Chunk; evbuf->atom_Sequence = atom_Sequence; lv2_evbuf_reset(evbuf, true); return evbuf; } void lv2_evbuf_free(LV2_Evbuf* evbuf) { free(evbuf); } void lv2_evbuf_reset(LV2_Evbuf* evbuf, bool input) { if (input) { evbuf->buf.atom.size = sizeof(LV2_Atom_Sequence_Body); evbuf->buf.atom.type = evbuf->atom_Sequence; } else { evbuf->buf.atom.size = evbuf->capacity; evbuf->buf.atom.type = evbuf->atom_Chunk; } } uint32_t lv2_evbuf_get_size(LV2_Evbuf* evbuf) { assert(evbuf->buf.atom.type != evbuf->atom_Sequence || evbuf->buf.atom.size >= sizeof(LV2_Atom_Sequence_Body)); return evbuf->buf.atom.type == evbuf->atom_Sequence ? evbuf->buf.atom.size - sizeof(LV2_Atom_Sequence_Body) : 0; } void* lv2_evbuf_get_buffer(LV2_Evbuf* evbuf) { return &evbuf->buf; } LV2_Evbuf_Iterator lv2_evbuf_begin(LV2_Evbuf* evbuf) { LV2_Evbuf_Iterator iter = { evbuf, 0 }; return iter; } LV2_Evbuf_Iterator lv2_evbuf_end(LV2_Evbuf* evbuf) { const uint32_t size = lv2_evbuf_get_size(evbuf); const LV2_Evbuf_Iterator iter = { evbuf, lv2_evbuf_pad_size(size) }; return iter; } bool lv2_evbuf_is_valid(LV2_Evbuf_Iterator iter) { return iter.offset < lv2_evbuf_get_size(iter.evbuf); } LV2_Evbuf_Iterator lv2_evbuf_next(LV2_Evbuf_Iterator iter) { if (!lv2_evbuf_is_valid(iter)) { return iter; } LV2_Evbuf* evbuf = iter.evbuf; uint32_t offset = iter.offset; const auto contents = static_cast<char*>(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, &evbuf->buf.atom)) + offset; const uint32_t size = reinterpret_cast<LV2_Atom_Event*>(contents)->body.size; offset += lv2_evbuf_pad_size(sizeof(LV2_Atom_Event) + size); LV2_Evbuf_Iterator next = { evbuf, offset }; return next; } bool lv2_evbuf_get(LV2_Evbuf_Iterator iter, uint32_t* frames, uint32_t* type, uint32_t* size, uint8_t** data) { *frames = *type = *size = 0; *data = nullptr; if (!lv2_evbuf_is_valid(iter)) { return false; } LV2_Atom_Sequence* aseq = &iter.evbuf->buf; auto aev = (LV2_Atom_Event*)((char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, aseq) + iter.offset); *frames = aev->time.frames; *type = aev->body.type; *size = aev->body.size; *data = (uint8_t*)LV2_ATOM_BODY(&aev->body); return true; } bool lv2_evbuf_write(LV2_Evbuf_Iterator* iter, uint32_t frames, uint32_t type, uint32_t size, const uint8_t* data) { LV2_Atom_Sequence* aseq = &iter->evbuf->buf; if (iter->evbuf->capacity - sizeof(LV2_Atom) - aseq->atom.size < sizeof(LV2_Atom_Event) + size) { return false; } auto aev = (LV2_Atom_Event*)((char*)LV2_ATOM_CONTENTS(LV2_Atom_Sequence, aseq) + iter->offset); aev->time.frames = frames; aev->body.type = type; aev->body.size = size; memcpy(LV2_ATOM_BODY(&aev->body), data, size); size = lv2_evbuf_pad_size(sizeof(LV2_Atom_Event) + size); aseq->atom.size += size; iter->offset += size; return true; } } // namespace lmms #endif // LMMS_HAVE_LV2
4,524
C++
.cpp
162
26.037037
107
0.724584
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,849
AudioFileOgg.cpp
LMMS_lmms/src/core/audio/AudioFileOgg.cpp
/* * AudioFileOgg.cpp - audio-device which encodes wave-stream and writes it * into an OGG-file. This is used for song-export. * * This file is based on encode.c from vorbis-tools-source, for more information * see below. * * 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. * */ #include "AudioFileOgg.h" #ifdef LMMS_HAVE_OGGVORBIS #if (QT_VERSION >= QT_VERSION_CHECK(5,10,0)) #include <QRandomGenerator> #endif #include <string> #include <vorbis/vorbisenc.h> #include "AudioEngine.h" namespace lmms { AudioFileOgg::AudioFileOgg( OutputSettings const & outputSettings, const ch_cnt_t channels, bool & successful, const QString & file, AudioEngine* audioEngine ) : AudioFileDevice( outputSettings, channels, file, audioEngine ) { m_ok = successful = outputFileOpened() && startEncoding(); } AudioFileOgg::~AudioFileOgg() { finishEncoding(); } inline int AudioFileOgg::writePage() { int written = writeData( m_og.header, m_og.header_len ); written += writeData( m_og.body, m_og.body_len ); return written; } bool AudioFileOgg::startEncoding() { vorbis_comment vc; const char * comments = "Cool=This song has been made using LMMS"; std::string user_comments_str(comments); int comment_length = user_comments_str.size(); char * user_comments = &user_comments_str[0]; vc.user_comments = &user_comments; vc.comment_lengths = &comment_length; vc.comments = 1; vc.vendor = nullptr; m_channels = channels(); bool useVariableBitRate = getOutputSettings().getBitRateSettings().isVariableBitRate(); bitrate_t minimalBitrate = nominalBitrate(); bitrate_t maximumBitrate = nominalBitrate(); if( useVariableBitRate ) { minimalBitrate = minBitrate(); // min for vbr maximumBitrate = maxBitrate(); // max for vbr } m_rate = sampleRate(); // default-samplerate if( m_rate > 48000 ) { m_rate = 48000; setSampleRate( 48000 ); } m_comments = &vc; // comments for ogg-file // Have vorbisenc choose a mode for us vorbis_info_init( &m_vi ); if( vorbis_encode_setup_managed( &m_vi, m_channels, m_rate, ( maximumBitrate > 0 )? maximumBitrate * 1000 : -1, nominalBitrate() * 1000, ( minimalBitrate > 0 )? minimalBitrate * 1000 : -1 ) ) { printf( "Mode initialization failed: invalid parameters for " "bitrate\n" ); vorbis_info_clear( &m_vi ); return false; } if( useVariableBitRate ) { // Turn off management entirely (if it was turned on). vorbis_encode_ctl( &m_vi, OV_ECTL_RATEMANAGE_SET, nullptr ); } else { vorbis_encode_ctl( &m_vi, OV_ECTL_RATEMANAGE_AVG, nullptr ); } vorbis_encode_setup_init( &m_vi ); // Now, set up the analysis engine, stream encoder, and other // preparation before the encoding begins. vorbis_analysis_init( &m_vd, &m_vi ); vorbis_block_init( &m_vd, &m_vb ); // We give our ogg file a random serial number and avoid // 0 and UINT32_MAX which can get you into trouble. #if (QT_VERSION >= QT_VERSION_CHECK(5,10,0)) // QRandomGenerator::global() is already initialized, and we can't seed() it. m_serialNo = 0xD0000000 + QRandomGenerator::global()->generate() % 0x0FFFFFFF; #else qsrand(time(0)); m_serialNo = 0xD0000000 + qrand() % 0x0FFFFFFF; #endif ogg_stream_init( &m_os, m_serialNo ); // Now, build the three header packets and send through to the stream // output stage (but defer actual file output until the main encode // loop) ogg_packet header_main; ogg_packet header_comments; ogg_packet header_codebooks; // Build the packets vorbis_analysis_headerout( &m_vd, m_comments, &header_main, &header_comments, &header_codebooks ); // And stream them out ogg_stream_packetin( &m_os, &header_main ); ogg_stream_packetin( &m_os, &header_comments ); ogg_stream_packetin( &m_os, &header_codebooks ); while (ogg_stream_flush(&m_os, &m_og)) { if (int ret = writePage(); ret != m_og.header_len + m_og.body_len) { // clean up finishEncoding(); return false; } } return true; } void AudioFileOgg::writeBuffer(const SampleFrame* _ab, const fpp_t _frames) { int eos = 0; float * * buffer = vorbis_analysis_buffer( &m_vd, _frames * BYTES_PER_SAMPLE * channels() ); for( fpp_t frame = 0; frame < _frames; ++frame ) { for( ch_cnt_t chnl = 0; chnl < channels(); ++chnl ) { buffer[chnl][frame] = _ab[frame][chnl]; } } vorbis_analysis_wrote( &m_vd, _frames ); // While we can get enough data from the library to analyse, // one block at a time... while( vorbis_analysis_blockout( &m_vd, &m_vb ) == 1 ) { // Do the main analysis, creating a packet vorbis_analysis( &m_vb, nullptr ); vorbis_bitrate_addblock( &m_vb ); while( vorbis_bitrate_flushpacket( &m_vd, &m_op ) ) { // Add packet to bitstream ogg_stream_packetin( &m_os, &m_op ); // If we've gone over a page boundary, we can do // actual output, so do so (for however many pages // are available) while( !eos ) { int result = ogg_stream_pageout( &m_os, &m_og ); if( !result ) { break; } int ret = writePage(); if( ret != m_og.header_len + m_og.body_len ) { printf( "failed writing to " "outstream\n" ); return; } if( ogg_page_eos( &m_og ) ) { eos = 1; } } } } } void AudioFileOgg::finishEncoding() { if( m_ok ) { // just for flushing buffers... writeBuffer(nullptr, 0); // clean up ogg_stream_clear( &m_os ); vorbis_block_clear( &m_vb ); vorbis_dsp_clear( &m_vd ); vorbis_info_clear( &m_vi ); } } } // namespace lmms #endif // LMMS_HAVE_OGGVORBIS
6,413
C++
.cpp
210
27.628571
88
0.691669
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,850
AudioOss.cpp
LMMS_lmms/src/core/audio/AudioOss.cpp
/* * AudioOss.cpp - 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. * */ #include "AudioOss.h" #ifdef LMMS_HAVE_OSS #include <QFileInfo> #include <QFormLayout> #include <QLineEdit> #include "endian_handling.h" #include "LcdSpinBox.h" #include "AudioEngine.h" #include "Engine.h" #ifdef LMMS_HAVE_UNISTD_H #include <unistd.h> #endif #ifdef LMMS_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef LMMS_HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef LMMS_HAVE_SYS_SOUNDCARD_H // This is recommended by OSS #include <sys/soundcard.h> #elif defined(LMMS_HAVE_SOUNDCARD_H) // This is installed on some systems #include <soundcard.h> #endif #include "ConfigManager.h" namespace lmms { static const QString PATH_DEV_DSP = #if defined(__NetBSD__) || defined(__OpenBSD__) "/dev/audio"; #else "/dev/dsp"; #endif AudioOss::AudioOss( bool & _success_ful, AudioEngine* _audioEngine ) : AudioDevice(std::clamp<ch_cnt_t>( ConfigManager::inst()->value("audiooss", "channels").toInt(), DEFAULT_CHANNELS, DEFAULT_CHANNELS), _audioEngine), m_convertEndian( false ) { _success_ful = false; m_audioFD = open( probeDevice().toLatin1().constData(), O_WRONLY, 0 ); if( m_audioFD == -1 ) { printf( "AudioOss: failed opening audio-device\n" ); return; } // Make the file descriptor use blocking writes with fcntl() if ( fcntl( m_audioFD, F_SETFL, fcntl( m_audioFD, F_GETFL ) & ~O_NONBLOCK ) < 0 ) { printf( "could not set audio blocking mode\n" ); return; } // set FD_CLOEXEC flag for file descriptor so forked processes // do not inherit it fcntl( m_audioFD, F_SETFD, fcntl( m_audioFD, F_GETFD ) | FD_CLOEXEC ); int frag_spec; for (frag_spec = 0; 1u << frag_spec < audioEngine()->framesPerPeriod() * channels() * BYTES_PER_INT_SAMPLE; ++frag_spec) { } frag_spec |= 0x00020000; // two fragments, for low latency if ( ioctl( m_audioFD, SNDCTL_DSP_SETFRAGMENT, &frag_spec ) < 0 ) { perror( "SNDCTL_DSP_SETFRAGMENT" ); printf( "Warning: Couldn't set audio fragment size\n" ); } unsigned int value; // Get a list of supported hardware formats if ( ioctl( m_audioFD, SNDCTL_DSP_GETFMTS, &value ) < 0 ) { perror( "SNDCTL_DSP_GETFMTS" ); printf( "Couldn't get audio format list\n" ); return; } // Set the audio format if( value & AFMT_S16_LE ) { value = AFMT_S16_LE; } else if( value & AFMT_S16_BE ) { value = AFMT_S16_BE; } else { printf(" Soundcard doesn't support signed 16-bit-data\n"); } if ( ioctl( m_audioFD, SNDCTL_DSP_SETFMT, &value ) < 0 ) { perror( "SNDCTL_DSP_SETFMT" ); printf( "Couldn't set audio format\n" ); return; } if( ( isLittleEndian() && ( value == AFMT_S16_BE ) ) || ( !isLittleEndian() && ( value == AFMT_S16_LE ) ) ) { m_convertEndian = true; } // Set the number of channels of output value = channels(); if ( ioctl( m_audioFD, SNDCTL_DSP_CHANNELS, &value ) < 0 ) { perror( "SNDCTL_DSP_CHANNELS" ); printf( "Cannot set the number of channels\n" ); return; } if( value != channels() ) { printf( "Couldn't set number of channels\n" ); return; } // Set the DSP frequency value = sampleRate(); if ( ioctl( m_audioFD, SNDCTL_DSP_SPEED, &value ) < 0 ) { perror( "SNDCTL_DSP_SPEED" ); printf( "Couldn't set audio frequency\n" ); return; } if( value != sampleRate() ) { value = audioEngine()->baseSampleRate(); if ( ioctl( m_audioFD, SNDCTL_DSP_SPEED, &value ) < 0 ) { perror( "SNDCTL_DSP_SPEED" ); printf( "Couldn't set audio frequency\n" ); return; } setSampleRate( value ); } _success_ful = true; } AudioOss::~AudioOss() { stopProcessing(); close( m_audioFD ); } QString AudioOss::probeDevice() { QString dev = ConfigManager::inst()->value( "AudioOss", "Device" ); if( dev.isEmpty() ) { char * adev = getenv( "AUDIODEV" ); // Is there a standard // variable name? if( adev != nullptr ) { dev = adev; } else { dev = PATH_DEV_DSP; // default device } } // if the first open fails, look for other devices if( QFileInfo( dev ).isWritable() == false ) { int instance = -1; while( true ) { dev = PATH_DEV_DSP + QString::number( ++instance ); if( !QFileInfo( dev ).exists() ) { dev = PATH_DEV_DSP; break; } if( QFileInfo( dev ).isWritable() ) { break; } } } return dev; } void AudioOss::startProcessing() { if( !isRunning() ) { start( QThread::HighPriority ); } } void AudioOss::stopProcessing() { stopProcessingThread( this ); } void AudioOss::run() { auto temp = new SampleFrame[audioEngine()->framesPerPeriod()]; auto outbuf = new int_sample_t[audioEngine()->framesPerPeriod() * channels()]; while( true ) { const fpp_t frames = getNextBuffer( temp ); if( !frames ) { break; } int bytes = convertToS16(temp, frames, outbuf, m_convertEndian); if( write( m_audioFD, outbuf, bytes ) != bytes ) { break; } } delete[] temp; delete[] outbuf; } AudioOss::setupWidget::setupWidget( QWidget * _parent ) : AudioDeviceSetupWidget( AudioOss::name(), _parent ) { QFormLayout * form = new QFormLayout(this); m_device = new QLineEdit( probeDevice(), this ); form->addRow(tr("Device"), m_device); auto m = new gui::LcdSpinBoxModel(/* this */); m->setRange(DEFAULT_CHANNELS, DEFAULT_CHANNELS); m->setStep( 2 ); m->setValue( ConfigManager::inst()->value( "audiooss", "channels" ).toInt() ); m_channels = new gui::LcdSpinBox( 1, this ); m_channels->setModel( m ); form->addRow(tr("Channels"), m_channels); } AudioOss::setupWidget::~setupWidget() { delete m_channels->model(); } void AudioOss::setupWidget::saveSettings() { ConfigManager::inst()->setValue( "audiooss", "device", m_device->text() ); ConfigManager::inst()->setValue( "audiooss", "channels", QString::number( m_channels->value<int>() ) ); } } // namespace lmms #endif // LMMS_HAVE_OSS
6,743
C++
.cpp
259
23.555985
89
0.685006
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,851
AudioFileWave.cpp
LMMS_lmms/src/core/audio/AudioFileWave.cpp
/* * AudioFileWave.cpp - audio-device which encodes wave-stream and writes it * into a WAVE-file. This is used for song-export. * * Copyright (c) 2004-2013 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. * */ #include "AudioFileWave.h" #include "endian_handling.h" #include "AudioEngine.h" namespace lmms { AudioFileWave::AudioFileWave( OutputSettings const & outputSettings, const ch_cnt_t channels, bool & successful, const QString & file, AudioEngine* audioEngine ) : AudioFileDevice( outputSettings, channels, file, audioEngine ), m_sf( nullptr ) { successful = outputFileOpened() && startEncoding(); } AudioFileWave::~AudioFileWave() { finishEncoding(); } bool AudioFileWave::startEncoding() { m_si.samplerate = sampleRate(); m_si.channels = channels(); m_si.frames = audioEngine()->framesPerPeriod(); m_si.sections = 1; m_si.seekable = 0; m_si.format = SF_FORMAT_WAV; switch( getOutputSettings().getBitDepth() ) { case OutputSettings::BitDepth::Depth32Bit: m_si.format |= SF_FORMAT_FLOAT; break; case OutputSettings::BitDepth::Depth24Bit: m_si.format |= SF_FORMAT_PCM_24; break; case OutputSettings::BitDepth::Depth16Bit: default: m_si.format |= SF_FORMAT_PCM_16; break; } // Use file handle to handle unicode file name on Windows m_sf = sf_open_fd( outputFileHandle(), SFM_WRITE, &m_si, false ); if (!m_sf) { qWarning("Error: AudioFileWave::startEncoding: %s", sf_strerror(nullptr)); return false; } // Prevent fold overs when encountering clipped data sf_command(m_sf, SFC_SET_CLIPPING, nullptr, SF_TRUE); sf_set_string ( m_sf, SF_STR_SOFTWARE, "LMMS" ); return true; } void AudioFileWave::writeBuffer(const SampleFrame* _ab, const fpp_t _frames) { OutputSettings::BitDepth bitDepth = getOutputSettings().getBitDepth(); if( bitDepth == OutputSettings::BitDepth::Depth32Bit || bitDepth == OutputSettings::BitDepth::Depth24Bit ) { auto buf = new float[_frames * channels()]; for( fpp_t frame = 0; frame < _frames; ++frame ) { for( ch_cnt_t chnl = 0; chnl < channels(); ++chnl ) { buf[frame * channels() + chnl] = _ab[frame][chnl]; } } sf_writef_float( m_sf, buf, _frames ); delete[] buf; } else { auto buf = new int_sample_t[_frames * channels()]; convertToS16(_ab, _frames, buf, !isLittleEndian()); sf_writef_short( m_sf, buf, _frames ); delete[] buf; } } void AudioFileWave::finishEncoding() { if( m_sf ) { sf_close( m_sf ); } } } // namespace lmms
3,298
C++
.cpp
107
28.439252
107
0.718167
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,852
AudioFileMP3.cpp
LMMS_lmms/src/core/audio/AudioFileMP3.cpp
/* * AudioFileMP3.cpp - Audio-device which encodes a wave stream into * an MP3 file. This is used for song export. * * Copyright (c) 2017 to present Michael Gregorius <michael.gregorius.git/at/arcor[dot]de> * * 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. * */ #include "AudioFileMP3.h" #include "SampleFrame.h" #ifdef LMMS_HAVE_MP3LAME #include <cassert> namespace lmms { AudioFileMP3::AudioFileMP3( OutputSettings const & outputSettings, const ch_cnt_t channels, bool & successful, const QString & file, AudioEngine* audioEngine ) : AudioFileDevice( outputSettings, channels, file, audioEngine ) { successful = true; // For now only accept stereo sources successful &= channels == 2; successful &= initEncoder(); successful &= outputFileOpened(); } AudioFileMP3::~AudioFileMP3() { flushRemainingBuffers(); tearDownEncoder(); } void AudioFileMP3::writeBuffer(const SampleFrame* _buf, const fpp_t _frames) { if (_frames < 1) { return; } std::vector<float> interleavedDataBuffer(_frames * 2); for (fpp_t i = 0; i < _frames; ++i) { interleavedDataBuffer[2*i] = _buf[i][0]; interleavedDataBuffer[2*i + 1] = _buf[i][1]; } size_t minimumBufferSize = 1.25 * _frames + 7200; std::vector<unsigned char> encodingBuffer(minimumBufferSize); int bytesWritten = lame_encode_buffer_interleaved_ieee_float(m_lame, &interleavedDataBuffer[0], _frames, &encodingBuffer[0], static_cast<int>(encodingBuffer.size())); assert (bytesWritten >= 0); writeData(&encodingBuffer[0], bytesWritten); } void AudioFileMP3::flushRemainingBuffers() { // The documentation states that flush should have at least 7200 bytes. So let's be generous. std::vector<unsigned char> encodingBuffer(7200 * 4); int bytesWritten = lame_encode_flush(m_lame, &encodingBuffer[0], static_cast<int>(encodingBuffer.size())); assert (bytesWritten >= 0); writeData(&encodingBuffer[0], bytesWritten); } MPEG_mode mapToMPEG_mode(OutputSettings::StereoMode stereoMode) { switch (stereoMode) { case OutputSettings::StereoMode::Stereo: return STEREO; case OutputSettings::StereoMode::JointStereo: return JOINT_STEREO; case OutputSettings::StereoMode::Mono: return MONO; default: return NOT_SET; } } bool AudioFileMP3::initEncoder() { m_lame = lame_init(); // Handle stereo/joint/mono settings OutputSettings::StereoMode stereoMode = getOutputSettings().getStereoMode(); lame_set_mode(m_lame, mapToMPEG_mode(stereoMode)); // Handle bit rate settings OutputSettings::BitRateSettings bitRateSettings = getOutputSettings().getBitRateSettings(); int bitRate = static_cast<int>(bitRateSettings.getBitRate()); lame_set_VBR(m_lame, vbr_off); lame_set_brate(m_lame, bitRate); // Add a comment id3tag_init(m_lame); id3tag_set_comment(m_lame, "Created with LMMS"); return lame_init_params(m_lame) != -1; } void AudioFileMP3::tearDownEncoder() { lame_close(m_lame); } } // namespace lmms #endif // LMMS_HAVE_MP3LAME
3,708
C++
.cpp
110
31.572727
167
0.7528
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,853
AudioPortAudio.cpp
LMMS_lmms/src/core/audio/AudioPortAudio.cpp
/* * AudioPortAudio.cpp - device-class that performs PCM-output via PortAudio * * Copyright (c) 2008 Csaba Hruska <csaba.hruska/at/gmail.com> * Copyright (c) 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. * */ #include "AudioPortAudio.h" #ifndef LMMS_HAVE_PORTAUDIO namespace lmms { void AudioPortAudioSetupUtil::updateBackends() { } void AudioPortAudioSetupUtil::updateDevices() { } void AudioPortAudioSetupUtil::updateChannels() { } } // namespace lmms #endif #ifdef LMMS_HAVE_PORTAUDIO #include <QFormLayout> #include "Engine.h" #include "ConfigManager.h" #include "ComboBox.h" #include "AudioEngine.h" namespace lmms { AudioPortAudio::AudioPortAudio( bool & _success_ful, AudioEngine * _audioEngine ) : AudioDevice(std::clamp<ch_cnt_t>( ConfigManager::inst()->value("audioportaudio", "channels").toInt(), DEFAULT_CHANNELS, DEFAULT_CHANNELS), _audioEngine), m_paStream( nullptr ), m_wasPAInitError( false ), m_outBuf(new SampleFrame[audioEngine()->framesPerPeriod()]), m_outBufPos( 0 ) { _success_ful = false; m_outBufSize = audioEngine()->framesPerPeriod(); PaError err = Pa_Initialize(); if( err != paNoError ) { printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) ); m_wasPAInitError = true; return; } if( Pa_GetDeviceCount() <= 0 ) { return; } const QString& backend = ConfigManager::inst()->value( "audioportaudio", "backend" ); const QString& device = ConfigManager::inst()->value( "audioportaudio", "device" ); PaDeviceIndex inDevIdx = -1; PaDeviceIndex outDevIdx = -1; for( int i = 0; i < Pa_GetDeviceCount(); ++i ) { const auto di = Pa_GetDeviceInfo(i); if( di->name == device && Pa_GetHostApiInfo( di->hostApi )->name == backend ) { inDevIdx = i; outDevIdx = i; } } if( inDevIdx < 0 ) { inDevIdx = Pa_GetDefaultInputDevice(); } if( outDevIdx < 0 ) { outDevIdx = Pa_GetDefaultOutputDevice(); } if( inDevIdx < 0 || outDevIdx < 0 ) { return; } double inLatency = 0;//(double)audioEngine()->framesPerPeriod() / (double)sampleRate(); double outLatency = 0;//(double)audioEngine()->framesPerPeriod() / (double)sampleRate(); //inLatency = Pa_GetDeviceInfo( inDevIdx )->defaultLowInputLatency; //outLatency = Pa_GetDeviceInfo( outDevIdx )->defaultLowOutputLatency; const int samples = audioEngine()->framesPerPeriod(); // Configure output parameters. m_outputParameters.device = outDevIdx; m_outputParameters.channelCount = channels(); m_outputParameters.sampleFormat = paFloat32; // 32 bit floating point output m_outputParameters.suggestedLatency = outLatency; m_outputParameters.hostApiSpecificStreamInfo = nullptr; // Configure input parameters. m_inputParameters.device = inDevIdx; m_inputParameters.channelCount = DEFAULT_CHANNELS; m_inputParameters.sampleFormat = paFloat32; // 32 bit floating point input m_inputParameters.suggestedLatency = inLatency; m_inputParameters.hostApiSpecificStreamInfo = nullptr; // Open an audio I/O stream. err = Pa_OpenStream( &m_paStream, supportsCapture() ? &m_inputParameters : nullptr, // The input parameter &m_outputParameters, // The outputparameter sampleRate(), samples, paNoFlag, // Don't use any flags _process_callback, // our callback function this ); if( err == paInvalidDevice && sampleRate() < 48000 ) { printf("Pa_OpenStream() failed with 44,1 KHz, trying again with 48 KHz\n"); // some backends or drivers do not allow 32 bit floating point data // with a samplerate of 44100 Hz setSampleRate( 48000 ); err = Pa_OpenStream( &m_paStream, supportsCapture() ? &m_inputParameters : nullptr, // The input parameter &m_outputParameters, // The outputparameter sampleRate(), samples, paNoFlag, // Don't use any flags _process_callback, // our callback function this ); } if( err != paNoError ) { printf( "Couldn't open PortAudio: %s\n", Pa_GetErrorText( err ) ); return; } printf( "Input device: '%s' backend: '%s'\n", Pa_GetDeviceInfo( inDevIdx )->name, Pa_GetHostApiInfo( Pa_GetDeviceInfo( inDevIdx )->hostApi )->name ); printf( "Output device: '%s' backend: '%s'\n", Pa_GetDeviceInfo( outDevIdx )->name, Pa_GetHostApiInfo( Pa_GetDeviceInfo( outDevIdx )->hostApi )->name ); // TODO: debug AudioEngine::pushInputFrames() //m_supportsCapture = true; _success_ful = true; } AudioPortAudio::~AudioPortAudio() { stopProcessing(); if( !m_wasPAInitError ) { Pa_Terminate(); } delete[] m_outBuf; } void AudioPortAudio::startProcessing() { m_stopped = false; PaError err = Pa_StartStream( m_paStream ); if( err != paNoError ) { m_stopped = true; printf( "PortAudio error: %s\n", Pa_GetErrorText( err ) ); } } void AudioPortAudio::stopProcessing() { if( m_paStream && Pa_IsStreamActive( m_paStream ) ) { m_stopped = true; PaError err = Pa_StopStream( m_paStream ); if( err != paNoError ) { printf( "PortAudio error: %s\n", Pa_GetErrorText( err ) ); } } } int AudioPortAudio::process_callback(const float* _inputBuffer, float* _outputBuffer, f_cnt_t _framesPerBuffer) { if( supportsCapture() ) { audioEngine()->pushInputFrames( (SampleFrame*)_inputBuffer, _framesPerBuffer ); } if( m_stopped ) { memset( _outputBuffer, 0, _framesPerBuffer * channels() * sizeof(float) ); return paComplete; } while( _framesPerBuffer ) { if( m_outBufPos == 0 ) { // frames depend on the sample rate const fpp_t frames = getNextBuffer( m_outBuf ); if( !frames ) { m_stopped = true; memset( _outputBuffer, 0, _framesPerBuffer * channels() * sizeof(float) ); return paComplete; } m_outBufSize = frames; } const auto min_len = std::min(_framesPerBuffer, m_outBufSize - m_outBufPos); for( fpp_t frame = 0; frame < min_len; ++frame ) { for( ch_cnt_t chnl = 0; chnl < channels(); ++chnl ) { (_outputBuffer + frame * channels())[chnl] = AudioEngine::clip(m_outBuf[frame][chnl]); } } _outputBuffer += min_len * channels(); _framesPerBuffer -= min_len; m_outBufPos += min_len; m_outBufPos %= m_outBufSize; } return paContinue; } int AudioPortAudio::_process_callback( const void *_inputBuffer, void * _outputBuffer, unsigned long _framesPerBuffer, const PaStreamCallbackTimeInfo * _timeInfo, PaStreamCallbackFlags _statusFlags, void * _arg ) { Q_UNUSED(_timeInfo); Q_UNUSED(_statusFlags); auto _this = static_cast<AudioPortAudio*>(_arg); return _this->process_callback( (const float*)_inputBuffer, (float*)_outputBuffer, _framesPerBuffer ); } void AudioPortAudioSetupUtil::updateBackends() { PaError err = Pa_Initialize(); if( err != paNoError ) { printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) ); return; } for( int i = 0; i < Pa_GetHostApiCount(); ++i ) { const auto hi = Pa_GetHostApiInfo(i); m_backendModel.addItem( hi->name ); } Pa_Terminate(); } void AudioPortAudioSetupUtil::updateDevices() { PaError err = Pa_Initialize(); if( err != paNoError ) { printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) ); return; } // get active backend const QString& backend = m_backendModel.currentText(); int hostApi = 0; for( int i = 0; i < Pa_GetHostApiCount(); ++i ) { const auto hi = Pa_GetHostApiInfo(i); if( backend == hi->name ) { hostApi = i; break; } } // get devices for selected backend m_deviceModel.clear(); for( int i = 0; i < Pa_GetDeviceCount(); ++i ) { const auto di = Pa_GetDeviceInfo(i); if( di->hostApi == hostApi ) { m_deviceModel.addItem( di->name ); } } Pa_Terminate(); } void AudioPortAudioSetupUtil::updateChannels() { PaError err = Pa_Initialize(); if( err != paNoError ) { printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) ); return; } // get active backend Pa_Terminate(); } AudioPortAudio::setupWidget::setupWidget( QWidget * _parent ) : AudioDeviceSetupWidget( AudioPortAudio::name(), _parent ) { using gui::ComboBox; QFormLayout * form = new QFormLayout(this); m_backend = new ComboBox( this, "BACKEND" ); form->addRow(tr("Backend"), m_backend); m_device = new ComboBox( this, "DEVICE" ); form->addRow(tr("Device"), m_device); /* LcdSpinBoxModel * m = new LcdSpinBoxModel( ); m->setRange( DEFAULT_CHANNELS, DEFAULT_CHANNELS ); m->setStep( 2 ); m->setValue( ConfigManager::inst()->value( "audioportaudio", "channels" ).toInt() ); m_channels = new LcdSpinBox( 1, this ); m_channels->setModel( m ); m_channels->setLabel( tr( "Channels" ) ); m_channels->move( 308, 20 );*/ connect( &m_setupUtil.m_backendModel, SIGNAL(dataChanged()), &m_setupUtil, SLOT(updateDevices())); connect( &m_setupUtil.m_deviceModel, SIGNAL(dataChanged()), &m_setupUtil, SLOT(updateChannels())); m_backend->setModel( &m_setupUtil.m_backendModel ); m_device->setModel( &m_setupUtil.m_deviceModel ); } AudioPortAudio::setupWidget::~setupWidget() { disconnect( &m_setupUtil.m_backendModel, SIGNAL(dataChanged()), &m_setupUtil, SLOT(updateDevices())); disconnect( &m_setupUtil.m_deviceModel, SIGNAL(dataChanged()), &m_setupUtil, SLOT(updateChannels())); } void AudioPortAudio::setupWidget::saveSettings() { ConfigManager::inst()->setValue( "audioportaudio", "backend", m_setupUtil.m_backendModel.currentText() ); ConfigManager::inst()->setValue( "audioportaudio", "device", m_setupUtil.m_deviceModel.currentText() ); /* ConfigManager::inst()->setValue( "audioportaudio", "channels", QString::number( m_channels->value<int>() ) );*/ } void AudioPortAudio::setupWidget::show() { if( m_setupUtil.m_backendModel.size() == 0 ) { // populate the backend model the first time we are shown m_setupUtil.updateBackends(); const QString& backend = ConfigManager::inst()->value( "audioportaudio", "backend" ); const QString& device = ConfigManager::inst()->value( "audioportaudio", "device" ); int i = std::max(0, m_setupUtil.m_backendModel.findText(backend)); m_setupUtil.m_backendModel.setValue( i ); m_setupUtil.updateDevices(); i = std::max(0, m_setupUtil.m_deviceModel.findText(device)); m_setupUtil.m_deviceModel.setValue( i ); } AudioDeviceSetupWidget::show(); } } // namespace lmms #endif // LMMS_HAVE_PORTAUDIO
11,100
C++
.cpp
352
28.772727
153
0.71333
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,854
AudioAlsa.cpp
LMMS_lmms/src/core/audio/AudioAlsa.cpp
/* * AudioAlsa.cpp - device-class which implements ALSA-PCM-output * * 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. * */ #include "AudioAlsa.h" #ifdef LMMS_HAVE_ALSA #include "endian_handling.h" #include "AudioEngine.h" #include "ConfigManager.h" #include "Engine.h" namespace lmms { AudioAlsa::AudioAlsa( bool & _success_ful, AudioEngine* _audioEngine ) : AudioDevice(std::clamp<ch_cnt_t>( ConfigManager::inst()->value("audioalsa", "channels").toInt(), DEFAULT_CHANNELS, DEFAULT_CHANNELS), _audioEngine), m_handle( nullptr ), m_hwParams( nullptr ), m_swParams( nullptr ), m_convertEndian( false ) { _success_ful = false; if( setenv( "PULSE_ALSA_HOOK_CONF", "/dev/null", 0 ) ) { fprintf( stderr, "Could not avoid possible interception by PulseAudio\n" ); } if (int err = snd_pcm_open(&m_handle, probeDevice().toLatin1().constData(), SND_PCM_STREAM_PLAYBACK, 0); err < 0) { printf( "Playback open error: %s\n", snd_strerror( err ) ); return; } snd_pcm_hw_params_malloc( &m_hwParams ); snd_pcm_sw_params_malloc( &m_swParams ); if (int err = setHWParams(channels(), SND_PCM_ACCESS_RW_INTERLEAVED); err < 0) { printf( "Setting of hwparams failed: %s\n", snd_strerror( err ) ); return; } if (int err = setSWParams(); err < 0) { printf( "Setting of swparams failed: %s\n", snd_strerror( err ) ); return; } // set FD_CLOEXEC flag for all file descriptors so forked processes // do not inherit them int count = snd_pcm_poll_descriptors_count( m_handle ); auto ufds = new pollfd[count]; snd_pcm_poll_descriptors( m_handle, ufds, count ); for (int i = 0; i < std::max(3, count); ++i) { const int fd = ( i >= count ) ? ufds[0].fd+i : ufds[i].fd; int oldflags = fcntl( fd, F_GETFD, 0 ); if( oldflags < 0 ) continue; oldflags |= FD_CLOEXEC; fcntl( fd, F_SETFD, oldflags ); } delete[] ufds; _success_ful = true; } AudioAlsa::~AudioAlsa() { stopProcessing(); if( m_handle != nullptr ) { snd_pcm_close( m_handle ); } if( m_hwParams != nullptr ) { snd_pcm_hw_params_free( m_hwParams ); } if( m_swParams != nullptr ) { snd_pcm_sw_params_free( m_swParams ); } } QString AudioAlsa::probeDevice() { QString dev = ConfigManager::inst()->value( "audioalsa", "device" ); if( dev == "" ) { if( getenv( "AUDIODEV" ) != nullptr ) { return getenv( "AUDIODEV" ); } return "default"; } return dev; } /** * @brief Creates a list of all available devices. * * Uses the hints API of ALSA to collect all devices. This also includes plug * devices. The reason to collect these and not the raw hardware devices * (e.g. hw:0,0) is that hardware devices often have a very limited number of * supported formats, etc. Plugs on the other hand are software components that * map all types of formats and inputs to the hardware and therefore they are * much more flexible and more what we want. * * Further helpful info http://jan.newmarch.name/LinuxSound/Sampled/Alsa/. * * @return A collection of devices found on the system. */ AudioAlsa::DeviceInfoCollection AudioAlsa::getAvailableDevices() { DeviceInfoCollection deviceInfos; char** hints = nullptr; /* Enumerate sound devices */ int err = snd_device_name_hint(-1, "pcm", (void***)&hints); if (err != 0) { return deviceInfos; } char** n = hints; while (*n != nullptr) { char *name = snd_device_name_get_hint(*n, "NAME"); char *description = snd_device_name_get_hint(*n, "DESC"); if (name != 0 && description != 0) { deviceInfos.push_back(DeviceInfo(QString(name), QString(description))); } free(name); free(description); n++; } //Free the hint buffer snd_device_name_free_hint((void**)hints); return deviceInfos; } int AudioAlsa::handleError( int _err ) { if( _err == -EPIPE ) { // under-run _err = snd_pcm_prepare( m_handle ); if( _err < 0 ) printf( "Can't recover from underrun, prepare " "failed: %s\n", snd_strerror( _err ) ); return ( 0 ); } #ifdef ESTRPIPE else if( _err == -ESTRPIPE ) { while( ( _err = snd_pcm_resume( m_handle ) ) == -EAGAIN ) { sleep( 1 ); // wait until the suspend flag // is released } if( _err < 0 ) { _err = snd_pcm_prepare( m_handle ); if( _err < 0 ) printf( "Can't recover from suspend, prepare " "failed: %s\n", snd_strerror( _err ) ); } return ( 0 ); } #endif return _err; } void AudioAlsa::startProcessing() { if( !isRunning() ) { start( QThread::HighPriority ); } } void AudioAlsa::stopProcessing() { stopProcessingThread( this ); } void AudioAlsa::run() { auto temp = new SampleFrame[audioEngine()->framesPerPeriod()]; auto outbuf = new int_sample_t[audioEngine()->framesPerPeriod() * channels()]; auto pcmbuf = new int_sample_t[m_periodSize * channels()]; int outbuf_size = audioEngine()->framesPerPeriod() * channels(); int outbuf_pos = 0; int pcmbuf_size = m_periodSize * channels(); bool quit = false; while( quit == false ) { int_sample_t * ptr = pcmbuf; int len = pcmbuf_size; while( len ) { if( outbuf_pos == 0 ) { // frames depend on the sample rate const fpp_t frames = getNextBuffer( temp ); if( !frames ) { quit = true; memset( ptr, 0, len * sizeof( int_sample_t ) ); break; } outbuf_size = frames * channels(); convertToS16(temp, frames, outbuf, m_convertEndian); } int min_len = std::min(len, outbuf_size - outbuf_pos); memcpy( ptr, outbuf + outbuf_pos, min_len * sizeof( int_sample_t ) ); ptr += min_len; len -= min_len; outbuf_pos += min_len; outbuf_pos %= outbuf_size; } f_cnt_t frames = m_periodSize; ptr = pcmbuf; while( frames ) { int err = snd_pcm_writei( m_handle, ptr, frames ); if( err == -EAGAIN ) { continue; } if( err < 0 ) { if( handleError( err ) < 0 ) { printf( "Write error: %s\n", snd_strerror( err ) ); } break; // skip this buffer } ptr += err * channels(); frames -= err; } } delete[] temp; delete[] outbuf; delete[] pcmbuf; } int AudioAlsa::setHWParams( const ch_cnt_t _channels, snd_pcm_access_t _access ) { // choose all parameters if (int err = snd_pcm_hw_params_any(m_handle, m_hwParams); err < 0) { printf( "Broken configuration for playback: no configurations " "available: %s\n", snd_strerror( err ) ); return err; } // set the interleaved read/write format if (int err = snd_pcm_hw_params_set_access(m_handle, m_hwParams, _access); err < 0) { printf( "Access type not available for playback: %s\n", snd_strerror( err ) ); return err; } // set the sample format if (int err = snd_pcm_hw_params_set_format(m_handle, m_hwParams, SND_PCM_FORMAT_S16_LE); err < 0) { if (int err = snd_pcm_hw_params_set_format(m_handle, m_hwParams, SND_PCM_FORMAT_S16_BE); err < 0) { printf( "Neither little- nor big-endian available for " "playback: %s\n", snd_strerror( err ) ); return err; } m_convertEndian = isLittleEndian(); } else { m_convertEndian = !isLittleEndian(); } // set the count of channels if (int err = snd_pcm_hw_params_set_channels(m_handle, m_hwParams, _channels); err < 0) { printf( "Channel count (%i) not available for playbacks: %s\n" "(Does your soundcard not support surround?)\n", _channels, snd_strerror( err ) ); return err; } // set the sample rate if (int err = snd_pcm_hw_params_set_rate(m_handle, m_hwParams, sampleRate(), 0); err < 0) { if (int err = snd_pcm_hw_params_set_rate(m_handle, m_hwParams, audioEngine()->baseSampleRate(), 0); err < 0) { printf( "Could not set sample rate: %s\n", snd_strerror( err ) ); return err; } } m_periodSize = audioEngine()->framesPerPeriod(); m_bufferSize = m_periodSize * 8; int dir; if (int err = snd_pcm_hw_params_set_period_size_near(m_handle, m_hwParams, &m_periodSize, &dir); err < 0) { printf( "Unable to set period size %lu for playback: %s\n", m_periodSize, snd_strerror( err ) ); return err; } dir = 0; if (int err = snd_pcm_hw_params_get_period_size(m_hwParams, &m_periodSize, &dir); err < 0) { printf( "Unable to get period size for playback: %s\n", snd_strerror( err ) ); } dir = 0; if (int err = snd_pcm_hw_params_set_buffer_size_near(m_handle, m_hwParams, &m_bufferSize); err < 0) { printf( "Unable to set buffer size %lu for playback: %s\n", m_bufferSize, snd_strerror( err ) ); return ( err ); } if (int err = snd_pcm_hw_params_get_buffer_size(m_hwParams, &m_bufferSize); 2 * m_periodSize > m_bufferSize) { printf( "buffer to small, could not use\n" ); return ( err ); } // write the parameters to device if (int err = snd_pcm_hw_params(m_handle, m_hwParams); err < 0) { printf( "Unable to set hw params for playback: %s\n", snd_strerror( err ) ); return ( err ); } return ( 0 ); // all ok } int AudioAlsa::setSWParams() { // get the current swparams if (int err = snd_pcm_sw_params_current(m_handle, m_swParams); err < 0) { printf( "Unable to determine current swparams for playback: %s" "\n", snd_strerror( err ) ); return err; } // start the transfer when a period is full if (int err = snd_pcm_sw_params_set_start_threshold(m_handle, m_swParams, m_periodSize); err < 0) { printf( "Unable to set start threshold mode for playback: %s\n", snd_strerror( err ) ); return err; } // allow the transfer when at least m_periodSize samples can be // processed if (int err = snd_pcm_sw_params_set_avail_min(m_handle, m_swParams, m_periodSize); err < 0) { printf( "Unable to set avail min for playback: %s\n", snd_strerror( err ) ); return err; } // align all transfers to 1 sample #if SND_LIB_VERSION < ((1<<16)|(0)|16) if( ( err = snd_pcm_sw_params_set_xfer_align( m_handle, m_swParams, 1 ) ) < 0 ) { printf( "Unable to set transfer align for playback: %s\n", snd_strerror( err ) ); return err; } #endif // write the parameters to the playback device if (int err = snd_pcm_sw_params(m_handle, m_swParams); err < 0) { printf( "Unable to set sw params for playback: %s\n", snd_strerror( err ) ); return err; } return 0; // all ok } } // namespace lmms #endif // LMMS_HAVE_ALSA
11,074
C++
.cpp
388
25.623711
114
0.66673
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,855
AudioPort.cpp
LMMS_lmms/src/core/audio/AudioPort.cpp
/* * AudioPort.cpp - base-class for objects providing sound at a port * * 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. * */ #include "AudioPort.h" #include "AudioDevice.h" #include "AudioEngine.h" #include "EffectChain.h" #include "Mixer.h" #include "Engine.h" #include "MixHelpers.h" #include "BufferManager.h" namespace lmms { AudioPort::AudioPort( const QString & _name, bool _has_effect_chain, FloatModel * volumeModel, FloatModel * panningModel, BoolModel * mutedModel ) : m_bufferUsage( false ), m_portBuffer( BufferManager::acquire() ), m_extOutputEnabled( false ), m_nextMixerChannel( 0 ), m_name( "unnamed port" ), m_effects( _has_effect_chain ? new EffectChain( nullptr ) : nullptr ), m_volumeModel( volumeModel ), m_panningModel( panningModel ), m_mutedModel( mutedModel ) { Engine::audioEngine()->addAudioPort( this ); setExtOutputEnabled( true ); } AudioPort::~AudioPort() { setExtOutputEnabled( false ); Engine::audioEngine()->removeAudioPort( this ); BufferManager::release( m_portBuffer ); } void AudioPort::setExtOutputEnabled( bool _enabled ) { if( _enabled != m_extOutputEnabled ) { m_extOutputEnabled = _enabled; if( m_extOutputEnabled ) { Engine::audioEngine()->audioDev()->registerPort( this ); } else { Engine::audioEngine()->audioDev()->unregisterPort( this ); } } } void AudioPort::setName( const QString & _name ) { m_name = _name; Engine::audioEngine()->audioDev()->renamePort( this ); } bool AudioPort::processEffects() { if( m_effects ) { bool more = m_effects->processAudioBuffer( m_portBuffer, Engine::audioEngine()->framesPerPeriod(), m_bufferUsage ); return more; } return false; } void AudioPort::doProcessing() { if( m_mutedModel && m_mutedModel->value() ) { return; } const fpp_t fpp = Engine::audioEngine()->framesPerPeriod(); // clear the buffer zeroSampleFrames(m_portBuffer, fpp); //qDebug( "Playhandles: %d", m_playHandles.size() ); for( PlayHandle * ph : m_playHandles ) // now we mix all playhandle buffers into the audioport buffer { if( ph->buffer() ) { if( ph->usesBuffer() && ( ph->type() == PlayHandle::Type::NotePlayHandle || !MixHelpers::isSilent( ph->buffer(), fpp ) ) ) { m_bufferUsage = true; MixHelpers::add( m_portBuffer, ph->buffer(), fpp ); } ph->releaseBuffer(); // gets rid of playhandle's buffer and sets // pointer to null, so if it doesn't get re-acquired we know to skip it next time } } if( m_bufferUsage ) { // handle volume and panning // has both vol and pan models if( m_volumeModel && m_panningModel ) { ValueBuffer * volBuf = m_volumeModel->valueBuffer(); ValueBuffer * panBuf = m_panningModel->valueBuffer(); // both vol and pan have s.ex.data: if( volBuf && panBuf ) { for( f_cnt_t f = 0; f < fpp; ++f ) { float v = volBuf->values()[ f ] * 0.01f; float p = panBuf->values()[ f ] * 0.01f; m_portBuffer[f][0] *= ( p <= 0 ? 1.0f : 1.0f - p ) * v; m_portBuffer[f][1] *= ( p >= 0 ? 1.0f : 1.0f + p ) * v; } } // only vol has s.ex.data: else if( volBuf ) { float p = m_panningModel->value() * 0.01f; float l = ( p <= 0 ? 1.0f : 1.0f - p ); float r = ( p >= 0 ? 1.0f : 1.0f + p ); for( f_cnt_t f = 0; f < fpp; ++f ) { float v = volBuf->values()[ f ] * 0.01f; m_portBuffer[f][0] *= v * l; m_portBuffer[f][1] *= v * r; } } // only pan has s.ex.data: else if( panBuf ) { float v = m_volumeModel->value() * 0.01f; for( f_cnt_t f = 0; f < fpp; ++f ) { float p = panBuf->values()[ f ] * 0.01f; m_portBuffer[f][0] *= ( p <= 0 ? 1.0f : 1.0f - p ) * v; m_portBuffer[f][1] *= ( p >= 0 ? 1.0f : 1.0f + p ) * v; } } // neither has s.ex.data: else { float p = m_panningModel->value() * 0.01f; float v = m_volumeModel->value() * 0.01f; for( f_cnt_t f = 0; f < fpp; ++f ) { m_portBuffer[f][0] *= ( p <= 0 ? 1.0f : 1.0f - p ) * v; m_portBuffer[f][1] *= ( p >= 0 ? 1.0f : 1.0f + p ) * v; } } } // has vol model only else if( m_volumeModel ) { ValueBuffer * volBuf = m_volumeModel->valueBuffer(); if( volBuf ) { for( f_cnt_t f = 0; f < fpp; ++f ) { float v = volBuf->values()[ f ] * 0.01f; m_portBuffer[f][0] *= v; m_portBuffer[f][1] *= v; } } else { float v = m_volumeModel->value() * 0.01f; for( f_cnt_t f = 0; f < fpp; ++f ) { m_portBuffer[f][0] *= v; m_portBuffer[f][1] *= v; } } } } // as of now there's no situation where we only have panning model but no volume model // if we have neither, we don't have to do anything here - just pass the audio as is // handle effects const bool me = processEffects(); if( me || m_bufferUsage ) { Engine::mixer()->mixToChannel( m_portBuffer, m_nextMixerChannel ); // send output to mixer // TODO: improve the flow here - convert to pull model m_bufferUsage = false; } } void AudioPort::addPlayHandle( PlayHandle * handle ) { m_playHandleLock.lock(); m_playHandles.append( handle ); m_playHandleLock.unlock(); } void AudioPort::removePlayHandle( PlayHandle * handle ) { m_playHandleLock.lock(); PlayHandleList::Iterator it = std::find( m_playHandles.begin(), m_playHandles.end(), handle ); if( it != m_playHandles.end() ) { m_playHandles.erase( it ); } m_playHandleLock.unlock(); } } // namespace lmms
6,286
C++
.cpp
216
25.819444
117
0.6412
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,856
AudioSndio.cpp
LMMS_lmms/src/core/audio/AudioSndio.cpp
/* * AudioSndio.cpp - base-class that implements sndio audio support * * Copyright (c) 2010-2016 jackmsr@openbsd.net * Copyright (c) 2016-2017 David Carlier <devnexen@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. * */ #include "AudioSndio.h" #ifdef LMMS_HAVE_SNDIO #include <cstdlib> #include <QFormLayout> #include <QLineEdit> #include "endian_handling.h" #include "LcdSpinBox.h" #include "AudioEngine.h" #include "Engine.h" #include "ConfigManager.h" namespace lmms { AudioSndio::AudioSndio(bool & _success_ful, AudioEngine * _audioEngine) : AudioDevice(std::clamp<ch_cnt_t>( ConfigManager::inst()->value("audiosndio", "channels").toInt(), DEFAULT_CHANNELS, DEFAULT_CHANNELS), _audioEngine), m_convertEndian ( false ) { _success_ful = false; QString dev = ConfigManager::inst()->value( "audiosndio", "device" ); if (dev == "") { m_hdl = sio_open( nullptr, SIO_PLAY, 0 ); } else { m_hdl = sio_open( dev.toLatin1().constData(), SIO_PLAY, 0 ); } if( m_hdl == nullptr ) { printf( "sndio: failed opening audio-device\n" ); return; } sio_initpar(&m_par); m_par.pchan = channels(); m_par.bits = 16; m_par.le = SIO_LE_NATIVE; m_par.rate = sampleRate(); m_par.round = audioEngine()->framesPerPeriod(); m_par.appbufsz = m_par.round * 2; if ( (isLittleEndian() && (m_par.le == 0)) || (!isLittleEndian() && (m_par.le == 1))) { m_convertEndian = true; } struct sio_par reqpar = m_par; if (!sio_setpar(m_hdl, &m_par)) { printf( "sndio: sio_setpar failed\n" ); return; } if (!sio_getpar(m_hdl, &m_par)) { printf( "sndio: sio_getpar failed\n" ); return; } if (reqpar.pchan != m_par.pchan || reqpar.bits != m_par.bits || reqpar.le != m_par.le || (::abs(static_cast<int>(reqpar.rate) - static_cast<int>(m_par.rate)) * 100)/reqpar.rate > 2) { printf( "sndio: returned params not as requested\n" ); return; } if (!sio_start(m_hdl)) { printf( "sndio: sio_start failed\n" ); return; } _success_ful = true; } AudioSndio::~AudioSndio() { stopProcessing(); if (m_hdl != nullptr) { sio_close( m_hdl ); m_hdl = nullptr; } } void AudioSndio::startProcessing() { if( !isRunning() ) { start( QThread::HighPriority ); } } void AudioSndio::stopProcessing() { stopProcessingThread( this ); } void AudioSndio::run() { SampleFrame* temp = new SampleFrame[audioEngine()->framesPerPeriod()]; int_sample_t * outbuf = new int_sample_t[audioEngine()->framesPerPeriod() * channels()]; while( true ) { const fpp_t frames = getNextBuffer( temp ); if( !frames ) { break; } uint bytes = convertToS16(temp, frames, outbuf, m_convertEndian); if( sio_write( m_hdl, outbuf, bytes ) != bytes ) { break; } } delete[] temp; delete[] outbuf; } AudioSndio::setupWidget::setupWidget( QWidget * _parent ) : AudioDeviceSetupWidget( AudioSndio::name(), _parent ) { QFormLayout * form = new QFormLayout(this); m_device = new QLineEdit( "", this ); form->addRow(tr("Device"), m_device); gui::LcdSpinBoxModel * m = new gui::LcdSpinBoxModel( /* this */ ); m->setRange(DEFAULT_CHANNELS, DEFAULT_CHANNELS); m->setStep( 2 ); m->setValue( ConfigManager::inst()->value( "audiosndio", "channels" ).toInt() ); m_channels = new gui::LcdSpinBox( 1, this ); m_channels->setModel( m ); form->addRow(tr("Channels"), m_channels); } void AudioSndio::setupWidget::saveSettings() { ConfigManager::inst()->setValue( "audiosndio", "device", m_device->text() ); ConfigManager::inst()->setValue( "audiosndio", "channels", QString::number( m_channels->value<int>() ) ); } } // namespace lmms #endif // LMMS_HAVE_SNDIO
4,386
C++
.cpp
159
25.238994
94
0.691665
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,857
AudioSdl.cpp
LMMS_lmms/src/core/audio/AudioSdl.cpp
/* * AudioSdl.cpp - 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. * */ #include "AudioSdl.h" #include "lmms_basics.h" #ifdef LMMS_HAVE_SDL #include <QFormLayout> #include <QLineEdit> #include <QComboBox> #include <SDL.h> #include "AudioEngine.h" #include "ConfigManager.h" namespace lmms { constexpr auto SectionSDL = "audiosdl"; constexpr auto PlaybackDeviceSDL = "device"; constexpr auto InputDeviceSDL = "inputdevice"; AudioSdl::AudioSdl( bool & _success_ful, AudioEngine* _audioEngine ) : AudioDevice( DEFAULT_CHANNELS, _audioEngine ), m_outBuf(new SampleFrame[audioEngine()->framesPerPeriod()]) { _success_ful = false; m_currentBufferFramesCount = 0; m_currentBufferFramePos = 0; if( SDL_Init( SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE ) < 0 ) { qCritical( "Couldn't initialize SDL: %s\n", SDL_GetError() ); return; } m_audioHandle.freq = sampleRate(); m_audioHandle.format = AUDIO_F32SYS; // we want it in byte-order // of system, so we don't have // to convert the buffers m_audioHandle.channels = channels(); m_audioHandle.samples = std::max(f_cnt_t{1024}, audioEngine()->framesPerPeriod() * 2); m_audioHandle.callback = sdlAudioCallback; m_audioHandle.userdata = this; SDL_AudioSpec actual; const auto playbackDevice = ConfigManager::inst()->value(SectionSDL, PlaybackDeviceSDL).toStdString(); const bool isDefaultPlayback = playbackDevice.empty(); // Try with the configured device const auto playbackDeviceCStr = isDefaultPlayback ? nullptr : playbackDevice.c_str(); m_outputDevice = SDL_OpenAudioDevice(playbackDeviceCStr, 0, &m_audioHandle, &actual, 0); // If we did not get a device ID try again with the default device if we did not try that before if (m_outputDevice == 0 && !isDefaultPlayback) { m_outputDevice = SDL_OpenAudioDevice(nullptr, 0, &m_audioHandle, &actual, 0); } if (m_outputDevice == 0) { qCritical( "Couldn't open SDL-audio: %s\n", SDL_GetError() ); return; } _success_ful = true; // Workaround for a race condition that causes SDL to segfault SDL_Delay(50); m_inputAudioHandle = m_audioHandle; m_inputAudioHandle.callback = sdlInputAudioCallback; const auto inputDevice = ConfigManager::inst()->value(SectionSDL, InputDeviceSDL).toStdString(); const bool isDefaultInput = inputDevice.empty(); // Try with the configured device const auto inputDeviceCStr = isDefaultInput ? nullptr : inputDevice.c_str(); m_inputDevice = SDL_OpenAudioDevice (inputDeviceCStr, 1, &m_inputAudioHandle, &actual, 0); // If we did not get a device ID try again with the default device if we did not try that before if (m_inputDevice == 0 && !isDefaultInput) { m_inputDevice = SDL_OpenAudioDevice(nullptr, 1, &m_inputAudioHandle, &actual, 0); } if (m_inputDevice != 0) { m_supportsCapture = true; } else { m_supportsCapture = false; qWarning ( "Couldn't open SDL capture device: %s\n", SDL_GetError ()); } } AudioSdl::~AudioSdl() { stopProcessing(); if (m_inputDevice != 0) SDL_CloseAudioDevice(m_inputDevice); if (m_outputDevice != 0) SDL_CloseAudioDevice(m_outputDevice); SDL_Quit(); delete[] m_outBuf; } void AudioSdl::startProcessing() { m_stopped = false; SDL_PauseAudioDevice (m_outputDevice, 0); SDL_PauseAudioDevice (m_inputDevice, 0); } void AudioSdl::stopProcessing() { if( SDL_GetAudioDeviceStatus(m_outputDevice) == SDL_AUDIO_PLAYING ) { SDL_LockAudioDevice (m_inputDevice); SDL_LockAudioDevice (m_outputDevice); m_stopped = true; SDL_PauseAudioDevice (m_inputDevice, 1); SDL_PauseAudioDevice (m_outputDevice, 1); SDL_UnlockAudioDevice (m_inputDevice); SDL_UnlockAudioDevice (m_outputDevice); } } void AudioSdl::sdlAudioCallback( void * _udata, Uint8 * _buf, int _len ) { auto _this = static_cast<AudioSdl*>(_udata); _this->sdlAudioCallback( _buf, _len ); } void AudioSdl::sdlAudioCallback( Uint8 * _buf, int _len ) { if( m_stopped ) { memset( _buf, 0, _len ); return; } // SDL2: process float samples while( _len ) { if( m_currentBufferFramePos == 0 ) { // frames depend on the sample rate const fpp_t frames = getNextBuffer( m_outBuf ); if( !frames ) { memset( _buf, 0, _len ); return; } m_currentBufferFramesCount = frames; } const uint min_frames_count = std::min(_len/sizeof(SampleFrame), m_currentBufferFramesCount - m_currentBufferFramePos); memcpy( _buf, m_outBuf + m_currentBufferFramePos, min_frames_count*sizeof(SampleFrame) ); _buf += min_frames_count*sizeof(SampleFrame); _len -= min_frames_count*sizeof(SampleFrame); m_currentBufferFramePos += min_frames_count; m_currentBufferFramePos %= m_currentBufferFramesCount; } } void AudioSdl::sdlInputAudioCallback(void *_udata, Uint8 *_buf, int _len) { auto _this = static_cast<AudioSdl*>(_udata); _this->sdlInputAudioCallback( _buf, _len ); } void AudioSdl::sdlInputAudioCallback(Uint8 *_buf, int _len) { auto samples_buffer = (SampleFrame*)_buf; fpp_t frames = _len / sizeof ( SampleFrame ); audioEngine()->pushInputFrames (samples_buffer, frames); } QString AudioSdl::setupWidget::s_systemDefaultDevice = AudioDeviceSetupWidget::tr("[System Default]"); AudioSdl::setupWidget::setupWidget( QWidget * _parent ) : AudioDeviceSetupWidget( AudioSdl::name(), _parent ) { QFormLayout * form = new QFormLayout(this); form->setRowWrapPolicy(QFormLayout::WrapLongRows); m_playbackDeviceComboBox = new QComboBox(this); populatePlaybackDeviceComboBox(); form->addRow(tr("Playback device"), m_playbackDeviceComboBox); m_inputDeviceComboBox = new QComboBox(this); populateInputDeviceComboBox(); form->addRow(tr("Input device"), m_inputDeviceComboBox); } void AudioSdl::setupWidget::saveSettings() { const auto currentPlaybackDevice = m_playbackDeviceComboBox->currentText(); if (currentPlaybackDevice == s_systemDefaultDevice) { // Represent the default playback device with an empty string ConfigManager::inst()->setValue(SectionSDL, PlaybackDeviceSDL, ""); } else if (!currentPlaybackDevice.isEmpty()) { ConfigManager::inst()->setValue(SectionSDL, PlaybackDeviceSDL, currentPlaybackDevice); } const auto currentInputDevice = m_inputDeviceComboBox->currentText(); if (currentInputDevice == s_systemDefaultDevice) { // Represent the default input device with an empty string ConfigManager::inst()->setValue(SectionSDL, InputDeviceSDL, ""); } else if (!currentInputDevice.isEmpty()) { ConfigManager::inst()->setValue(SectionSDL, InputDeviceSDL, currentInputDevice); } } void AudioSdl::setupWidget::populatePlaybackDeviceComboBox() { m_playbackDeviceComboBox->addItem(s_systemDefaultDevice); QStringList playbackDevices; const int numberOfPlaybackDevices = SDL_GetNumAudioDevices(0); for (int i = 0; i < numberOfPlaybackDevices; ++i) { const QString deviceName = SDL_GetAudioDeviceName(i, 0); playbackDevices.append(deviceName); } playbackDevices.sort(); m_playbackDeviceComboBox->addItems(playbackDevices); const auto playbackDevice = ConfigManager::inst()->value(SectionSDL, PlaybackDeviceSDL); m_playbackDeviceComboBox->setCurrentText(playbackDevice.isEmpty() ? s_systemDefaultDevice : playbackDevice); } void AudioSdl::setupWidget::populateInputDeviceComboBox() { m_inputDeviceComboBox->addItem(s_systemDefaultDevice); QStringList inputDevices; const int numberOfInputDevices = SDL_GetNumAudioDevices(1); for (int i = 0; i < numberOfInputDevices; ++i) { const QString deviceName = SDL_GetAudioDeviceName(i, 1); inputDevices.append(deviceName); } inputDevices.sort(); m_inputDeviceComboBox->addItems(inputDevices); // Set the current device to the one in the configuration const auto inputDevice = ConfigManager::inst()->value(SectionSDL, InputDeviceSDL); m_inputDeviceComboBox->setCurrentText(inputDevice.isEmpty() ? s_systemDefaultDevice : inputDevice); } } // namespace lmms #endif // LMMS_HAVE_SDL
8,776
C++
.cpp
237
34.514768
109
0.756475
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
19,858
AudioSampleRecorder.cpp
LMMS_lmms/src/core/audio/AudioSampleRecorder.cpp
/* * AudioSampleRecorder.cpp - device-class that implements recording * audio-buffers into RAM * * 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. * */ #include "AudioSampleRecorder.h" #include "SampleBuffer.h" #include "debug.h" namespace lmms { AudioSampleRecorder::AudioSampleRecorder( const ch_cnt_t _channels, bool & _success_ful, AudioEngine * _audioEngine ) : AudioDevice( _channels, _audioEngine ), m_buffers() { _success_ful = true; } AudioSampleRecorder::~AudioSampleRecorder() { while( !m_buffers.empty() ) { delete[] m_buffers.front().first; m_buffers.erase( m_buffers.begin() ); } } f_cnt_t AudioSampleRecorder::framesRecorded() const { f_cnt_t frames = 0; for (const auto& buffer : m_buffers) { frames += buffer.second; } return frames; } std::shared_ptr<const SampleBuffer> AudioSampleRecorder::createSampleBuffer() { const f_cnt_t frames = framesRecorded(); // create buffer to store all recorded buffers in auto bigBuffer = std::vector<SampleFrame>(frames); // now copy all buffers into big buffer auto framesCopied = 0; for (const auto& [buf, numFrames] : m_buffers) { std::copy_n(buf, numFrames, bigBuffer.begin() + framesCopied); framesCopied += numFrames; } // create according sample-buffer out of big buffer return std::make_shared<const SampleBuffer>(std::move(bigBuffer), sampleRate()); } void AudioSampleRecorder::writeBuffer(const SampleFrame* _ab, const fpp_t _frames) { auto buf = new SampleFrame[_frames]; for( fpp_t frame = 0; frame < _frames; ++frame ) { for( ch_cnt_t chnl = 0; chnl < DEFAULT_CHANNELS; ++chnl ) { buf[frame][chnl] = _ab[frame][chnl]; } } m_buffers.push_back( qMakePair( buf, _frames ) ); } } // namespace lmms
2,585
C++
.cpp
82
29.280488
82
0.727749
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
19,859
AudioFileFlac.cpp
LMMS_lmms/src/core/audio/AudioFileFlac.cpp
/* * AudioFileFlac.cpp - Audio device which encodes a wave stream into a FLAC file (Implementation). * * Copyright (c) 2017 to present Levin Oehlmann <irrenhaus3/at/gmail[dot]com> et al. * * 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. * */ #include <QtGlobal> #include <cmath> #include <memory> #include "AudioFileFlac.h" #include "endian_handling.h" #include "AudioEngine.h" namespace lmms { AudioFileFlac::AudioFileFlac(OutputSettings const& outputSettings, ch_cnt_t const channels, bool& successful, QString const& file, AudioEngine* audioEngine): AudioFileDevice(outputSettings,channels,file,audioEngine), m_sf(nullptr) { successful = outputFileOpened() && startEncoding(); } AudioFileFlac::~AudioFileFlac() { finishEncoding(); } bool AudioFileFlac::startEncoding() { m_sfinfo.samplerate=sampleRate(); m_sfinfo.channels=channels(); m_sfinfo.frames = audioEngine()->framesPerPeriod(); m_sfinfo.sections=1; m_sfinfo.seekable=0; m_sfinfo.format = SF_FORMAT_FLAC; switch (getOutputSettings().getBitDepth()) { case OutputSettings::BitDepth::Depth24Bit: case OutputSettings::BitDepth::Depth32Bit: // FLAC does not support 32bit sampling, so take it as 24. m_sfinfo.format |= SF_FORMAT_PCM_24; break; default: m_sfinfo.format |= SF_FORMAT_PCM_16; } #ifdef LMMS_HAVE_SF_COMPLEVEL double compression = getOutputSettings().getCompressionLevel(); sf_command(m_sf, SFC_SET_COMPRESSION_LEVEL, &compression, sizeof(double)); #endif m_sf = sf_open( #ifdef LMMS_BUILD_WIN32 outputFile().toLocal8Bit().constData(), #else outputFile().toUtf8().constData(), #endif SFM_WRITE, &m_sfinfo ); sf_command(m_sf, SFC_SET_CLIPPING, nullptr, SF_TRUE); sf_set_string(m_sf, SF_STR_SOFTWARE, "LMMS"); return true; } void AudioFileFlac::writeBuffer(const SampleFrame* _ab, fpp_t const frames) { OutputSettings::BitDepth depth = getOutputSettings().getBitDepth(); float clipvalue = std::nextafterf( -1.0f, 0.0f ); if (depth == OutputSettings::BitDepth::Depth24Bit || depth == OutputSettings::BitDepth::Depth32Bit) // Float encoding { auto buf = std::vector<sample_t>(frames * channels()); for(fpp_t frame = 0; frame < frames; ++frame) { for(ch_cnt_t channel=0; channel<channels(); ++channel) { // Clip the negative side to just above -1.0 in order to prevent it from changing sign // Upstream issue: https://github.com/erikd/libsndfile/issues/309 // When this commit is reverted libsndfile-1.0.29 must be made a requirement for FLAC buf[frame*channels() + channel] = std::max(clipvalue, _ab[frame][channel]); } } sf_writef_float(m_sf, static_cast<float*>(buf.data()), frames); } else // integer PCM encoding { auto buf = std::vector<int_sample_t>(frames * channels()); convertToS16(_ab, frames, buf.data(), !isLittleEndian()); sf_writef_short(m_sf, static_cast<short*>(buf.data()), frames); } } void AudioFileFlac::finishEncoding() { if (m_sf) { sf_write_sync(m_sf); sf_close(m_sf); } } } // namespace lmms
3,743
C++
.cpp
111
31.432432
157
0.738445
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,860
AudioPulseAudio.cpp
LMMS_lmms/src/core/audio/AudioPulseAudio.cpp
/* * AudioPulseAudio.cpp - device-class which implements PulseAudio-output * * 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. * */ #include <QFormLayout> #include <QLineEdit> #include "AudioPulseAudio.h" #ifdef LMMS_HAVE_PULSEAUDIO #include "ConfigManager.h" #include "LcdSpinBox.h" #include "AudioEngine.h" #include "Engine.h" namespace lmms { static void stream_write_callback(pa_stream *s, size_t length, void *userdata) { static_cast<AudioPulseAudio *>( userdata )->streamWriteCallback( s, length ); } AudioPulseAudio::AudioPulseAudio( bool & _success_ful, AudioEngine* _audioEngine ) : AudioDevice(std::clamp<ch_cnt_t>( ConfigManager::inst()->value("audiopa", "channels").toInt(), DEFAULT_CHANNELS, DEFAULT_CHANNELS), _audioEngine), m_s( nullptr ), m_quit( false ), m_convertEndian( false ) { _success_ful = false; m_sampleSpec.format = PA_SAMPLE_S16LE; m_sampleSpec.rate = sampleRate(); m_sampleSpec.channels = channels(); _success_ful = true; } AudioPulseAudio::~AudioPulseAudio() { stopProcessing(); } QString AudioPulseAudio::probeDevice() { QString dev = ConfigManager::inst()->value( "audiopa", "device" ); if( dev.isEmpty() ) { if( getenv( "AUDIODEV" ) != nullptr ) { return getenv( "AUDIODEV" ); } return "default"; } return dev; } void AudioPulseAudio::startProcessing() { if( !isRunning() ) { start( QThread::HighPriority ); } } void AudioPulseAudio::stopProcessing() { m_quit = true; stopProcessingThread( this ); } /* This routine is called whenever the stream state changes */ static void stream_state_callback( pa_stream *s, void * userdata ) { switch( pa_stream_get_state( s ) ) { case PA_STREAM_CREATING: case PA_STREAM_TERMINATED: break; case PA_STREAM_READY: qDebug( "Stream successfully created\n" ); break; case PA_STREAM_FAILED: default: qCritical( "Stream error: %s\n", pa_strerror(pa_context_errno( pa_stream_get_context( s ) ) ) ); } } /* This is called whenever the context status changes */ static void context_state_callback(pa_context *c, void *userdata) { auto _this = static_cast<AudioPulseAudio*>(userdata); switch( pa_context_get_state( c ) ) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: { qDebug( "Connection established.\n" ); _this->m_s = pa_stream_new( c, "lmms", &_this->m_sampleSpec, nullptr); pa_stream_set_state_callback( _this->m_s, stream_state_callback, _this ); pa_stream_set_write_callback( _this->m_s, stream_write_callback, _this ); pa_buffer_attr buffer_attr; buffer_attr.maxlength = (uint32_t)(-1); // play silence in case of buffer underun instead of using default rewind buffer_attr.prebuf = 0; buffer_attr.minreq = (uint32_t)(-1); buffer_attr.fragsize = (uint32_t)(-1); double latency = (double)( Engine::audioEngine()->framesPerPeriod() ) / (double)_this->sampleRate(); // ask PulseAudio for the desired latency (which might not be approved) buffer_attr.tlength = pa_usec_to_bytes( latency * PA_USEC_PER_MSEC, &_this->m_sampleSpec ); pa_stream_connect_playback( _this->m_s, nullptr, &buffer_attr, PA_STREAM_ADJUST_LATENCY, nullptr, // volume nullptr ); _this->signalConnected( true ); break; } case PA_CONTEXT_TERMINATED: break; case PA_CONTEXT_FAILED: default: qCritical( "Connection failure: %s\n", pa_strerror( pa_context_errno( c ) ) ); _this->signalConnected( false ); } } void AudioPulseAudio::run() { pa_mainloop * mainLoop = pa_mainloop_new(); if( !mainLoop ) { qCritical( "pa_mainloop_new() failed.\n" ); return; } pa_mainloop_api * mainloop_api = pa_mainloop_get_api( mainLoop ); pa_context *context = pa_context_new( mainloop_api, "lmms" ); if ( context == nullptr ) { qCritical( "pa_context_new() failed." ); return; } m_connected = false; pa_context_set_state_callback( context, context_state_callback, this ); // connect the context pa_context_connect( context, nullptr, (pa_context_flags) 0, nullptr ); while (!m_connectedSemaphore.tryAcquire()) { pa_mainloop_iterate(mainLoop, 1, nullptr); } // run the main loop if( m_connected ) { int ret = 0; m_quit = false; while( m_quit == false && pa_mainloop_iterate( mainLoop, 1, &ret ) >= 0 ) { } pa_stream_disconnect( m_s ); pa_stream_unref( m_s ); } else { const fpp_t fpp = audioEngine()->framesPerPeriod(); auto temp = new SampleFrame[fpp]; while( getNextBuffer( temp ) ) { } delete[] temp; } pa_context_disconnect( context ); pa_context_unref( context ); pa_mainloop_free( mainLoop ); } void AudioPulseAudio::streamWriteCallback( pa_stream *s, size_t length ) { const fpp_t fpp = audioEngine()->framesPerPeriod(); auto temp = new SampleFrame[fpp]; auto pcmbuf = (int_sample_t*)pa_xmalloc(fpp * channels() * sizeof(int_sample_t)); size_t fd = 0; while( fd < length/4 && m_quit == false ) { const fpp_t frames = getNextBuffer( temp ); if( !frames ) { m_quit = true; break; } int bytes = convertToS16(temp, frames, pcmbuf, m_convertEndian); if( bytes > 0 ) { pa_stream_write( m_s, pcmbuf, bytes, nullptr, 0, PA_SEEK_RELATIVE ); } fd += frames; } pa_xfree( pcmbuf ); delete[] temp; } void AudioPulseAudio::signalConnected( bool connected ) { if( !m_connected ) { m_connected = connected; m_connectedSemaphore.release(); } } AudioPulseAudio::setupWidget::setupWidget( QWidget * _parent ) : AudioDeviceSetupWidget( AudioPulseAudio::name(), _parent ) { QFormLayout * form = new QFormLayout(this); m_device = new QLineEdit( AudioPulseAudio::probeDevice(), this ); form->addRow(tr("Device"), m_device); auto m = new gui::LcdSpinBoxModel(); m->setRange(DEFAULT_CHANNELS, DEFAULT_CHANNELS); m->setStep( 2 ); m->setValue( ConfigManager::inst()->value( "audiopa", "channels" ).toInt() ); m_channels = new gui::LcdSpinBox( 1, this ); m_channels->setModel( m ); form->addRow(tr("Channels"), m_channels); } AudioPulseAudio::setupWidget::~setupWidget() { delete m_channels->model(); } void AudioPulseAudio::setupWidget::saveSettings() { ConfigManager::inst()->setValue( "audiopa", "device", m_device->text() ); ConfigManager::inst()->setValue( "audiopa", "channels", QString::number( m_channels->value<int>() ) ); } } // namespace lmms #endif // LMMS_HAVE_PULSEAUDIO
7,307
C++
.cpp
248
26.608871
103
0.703141
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,861
AudioDevice.cpp
LMMS_lmms/src/core/audio/AudioDevice.cpp
/* * AudioDevice.cpp - base-class for audio-devices used by LMMS audio engine * * 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. * */ #include <cstring> #include "AudioDevice.h" #include "AudioEngine.h" #include "ConfigManager.h" #include "debug.h" namespace lmms { AudioDevice::AudioDevice( const ch_cnt_t _channels, AudioEngine* _audioEngine ) : m_supportsCapture( false ), m_sampleRate( _audioEngine->outputSampleRate() ), m_channels( _channels ), m_audioEngine( _audioEngine ), m_buffer(new SampleFrame[audioEngine()->framesPerPeriod()]) { } AudioDevice::~AudioDevice() { delete[] m_buffer; m_devMutex.tryLock(); unlock(); } void AudioDevice::processNextBuffer() { const fpp_t frames = getNextBuffer( m_buffer ); if (frames) { writeBuffer(m_buffer, frames); } else { m_inProcess = false; } } fpp_t AudioDevice::getNextBuffer(SampleFrame* _ab) { fpp_t frames = audioEngine()->framesPerPeriod(); const SampleFrame* b = audioEngine()->nextBuffer(); if (!b) { return 0; } memcpy(_ab, b, frames * sizeof(SampleFrame)); if (audioEngine()->hasFifoWriter()) { delete[] b; } return frames; } void AudioDevice::stopProcessing() { if( audioEngine()->hasFifoWriter() ) { while( m_inProcess ) { processNextBuffer(); } } } void AudioDevice::stopProcessingThread( QThread * thread ) { if( !thread->wait( 30000 ) ) { fprintf( stderr, "Terminating audio device thread\n" ); thread->terminate(); if( !thread->wait( 1000 ) ) { fprintf( stderr, "Thread not terminated yet\n" ); } } } void AudioDevice::registerPort( AudioPort * ) { } void AudioDevice::unregisterPort( AudioPort * _port ) { } void AudioDevice::renamePort( AudioPort * ) { } int AudioDevice::convertToS16(const SampleFrame* _ab, const fpp_t _frames, int_sample_t * _output_buffer, const bool _convert_endian ) { if( _convert_endian ) { for( fpp_t frame = 0; frame < _frames; ++frame ) { for( ch_cnt_t chnl = 0; chnl < channels(); ++chnl ) { auto temp = static_cast<int_sample_t>(AudioEngine::clip(_ab[frame][chnl]) * OUTPUT_SAMPLE_MULTIPLIER); ( _output_buffer + frame * channels() )[chnl] = ( temp & 0x00ff ) << 8 | ( temp & 0xff00 ) >> 8; } } } else { for( fpp_t frame = 0; frame < _frames; ++frame ) { for( ch_cnt_t chnl = 0; chnl < channels(); ++chnl ) { (_output_buffer + frame * channels())[chnl] = static_cast<int_sample_t>(AudioEngine::clip(_ab[frame][chnl]) * OUTPUT_SAMPLE_MULTIPLIER); } } } return _frames * channels() * BYTES_PER_INT_SAMPLE; } void AudioDevice::clearS16Buffer( int_sample_t * _outbuf, const fpp_t _frames ) { assert( _outbuf != nullptr ); memset( _outbuf, 0, _frames * channels() * BYTES_PER_INT_SAMPLE ); } } // namespace lmms
3,613
C++
.cpp
130
25.2
106
0.697296
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
19,862
AudioFileDevice.cpp
LMMS_lmms/src/core/audio/AudioFileDevice.cpp
/* * AudioFileDevice.cpp - base-class for audio-device-classes which write * their output into a file * * 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. * */ #include <QMessageBox> #include "AudioFileDevice.h" #include "ExportProjectDialog.h" #include "GuiApplication.h" namespace lmms { AudioFileDevice::AudioFileDevice( OutputSettings const & outputSettings, const ch_cnt_t _channels, const QString & _file, AudioEngine* _audioEngine ) : AudioDevice( _channels, _audioEngine ), m_outputFile( _file ), m_outputSettings(outputSettings) { using gui::ExportProjectDialog; setSampleRate( outputSettings.getSampleRate() ); if( m_outputFile.open( QFile::WriteOnly | QFile::Truncate ) == false ) { QString title, message; title = ExportProjectDialog::tr( "Could not open file" ); message = ExportProjectDialog::tr( "Could not open file %1 " "for writing.\nPlease make " "sure you have write " "permission to the file and " "the directory containing the " "file and try again!" ).arg( _file ); if (gui::getGUI() != nullptr) { QMessageBox::critical( nullptr, title, message, QMessageBox::Ok, QMessageBox::NoButton ); } else { fprintf( stderr, "%s\n", message.toUtf8().constData() ); exit( EXIT_FAILURE ); } } } AudioFileDevice::~AudioFileDevice() { m_outputFile.close(); } int AudioFileDevice::writeData( const void* data, int len ) { if( m_outputFile.isOpen() ) { return m_outputFile.write( (const char *) data, len ); } return -1; } } // namespace lmms
2,415
C++
.cpp
77
28.454545
77
0.715209
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,863
AudioSoundIo.cpp
LMMS_lmms/src/core/audio/AudioSoundIo.cpp
/* * AudioSoundIo.cpp - device-class that performs PCM-output via libsoundio * * Copyright (c) 2015 Andrew Kelley <superjoe30@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. * */ #include "AudioSoundIo.h" #ifdef LMMS_HAVE_SOUNDIO #include <QFormLayout> #include <QLineEdit> #include "Engine.h" #include "debug.h" #include "ConfigManager.h" #include "ComboBox.h" #include "AudioEngine.h" namespace lmms { AudioSoundIo::AudioSoundIo( bool & outSuccessful, AudioEngine * _audioEngine ) : AudioDevice(std::clamp<ch_cnt_t>( ConfigManager::inst()->value("audiosoundio", "channels").toInt(), DEFAULT_CHANNELS, DEFAULT_CHANNELS), _audioEngine) { outSuccessful = false; m_soundio = nullptr; m_outstream = nullptr; m_outBuf = nullptr; m_disconnectErr = 0; m_outBufFrameIndex = 0; m_outBufFramesTotal = 0; m_stopped = true; m_outstreamStarted = false; m_soundio = soundio_create(); if (!m_soundio) { fprintf(stderr, "Unable to initialize soundio: out of memory\n"); return; } m_soundio->app_name = "LMMS"; m_soundio->userdata = this; m_soundio->on_backend_disconnect = staticOnBackendDisconnect; const QString& configBackend = ConfigManager::inst()->value( "audiosoundio", "backend" ); const QString& configDeviceId = ConfigManager::inst()->value( "audiosoundio", "out_device_id" ); const QString& configDeviceRaw = ConfigManager::inst()->value( "audiosoundio", "out_device_raw" ); int outDeviceCount = 0; int backendCount = soundio_backend_count(m_soundio); for (int i = 0; i < backendCount; i += 1) { SoundIoBackend backend = soundio_get_backend(m_soundio, i); if (configBackend == soundio_backend_name(backend)) { if (!soundio_connect_backend(m_soundio, backend)) { soundio_flush_events(m_soundio); if (m_disconnectErr) { fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(m_disconnectErr)); return; } outDeviceCount = soundio_output_device_count(m_soundio); } break; } } if (outDeviceCount <= 0) { // try connecting to the default backend if (int err = soundio_connect(m_soundio)) { fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(err)); return; } soundio_flush_events(m_soundio); if (m_disconnectErr) { fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(m_disconnectErr)); return; } outDeviceCount = soundio_output_device_count(m_soundio); if (outDeviceCount <= 0) { fprintf(stderr, "Unable to initialize soundio: no devices found\n"); return; } } int selected_device_index = soundio_default_output_device_index(m_soundio); bool wantRaw = (configDeviceRaw == "yes"); for (int i = 0; i < outDeviceCount; i += 1) { SoundIoDevice *device = soundio_get_output_device(m_soundio, i); bool isThisOne = (configDeviceId == device->id && wantRaw == device->is_raw); soundio_device_unref(device); if (isThisOne) { selected_device_index = i; break; } } SoundIoDevice *device = soundio_get_output_device(m_soundio, selected_device_index); m_outstream = soundio_outstream_create(device); soundio_device_unref(device); if (!m_outstream) { fprintf(stderr, "Unable to initialize soundio: out of memory\n"); return; } int currentSampleRate = sampleRate(); int closestSupportedSampleRate = -1; for (int i = 0; i < device->sample_rate_count; i += 1) { SoundIoSampleRateRange *range = &device->sample_rates[i]; if (range->min <= currentSampleRate && currentSampleRate <= range->max) { closestSupportedSampleRate = currentSampleRate; break; } if (closestSupportedSampleRate == -1 || abs(range->max - currentSampleRate) < abs(closestSupportedSampleRate - currentSampleRate)) { closestSupportedSampleRate = range->max; } } if (closestSupportedSampleRate != currentSampleRate) { setSampleRate(closestSupportedSampleRate); currentSampleRate = closestSupportedSampleRate; } m_outstream->name = "LMMS"; m_outstream->software_latency = (double)audioEngine()->framesPerPeriod() / (double)currentSampleRate; m_outstream->userdata = this; m_outstream->write_callback = staticWriteCallback; m_outstream->error_callback = staticErrorCallback; m_outstream->underflow_callback = staticUnderflowCallback; m_outstream->sample_rate = currentSampleRate; m_outstream->layout = *soundio_channel_layout_get_default(channels()); m_outstream->format = SoundIoFormatFloat32NE; if (int err = soundio_outstream_open(m_outstream)) { fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(err)); return; } fprintf(stderr, "Output device: '%s' backend: '%s'\n", device->name, soundio_backend_name(m_soundio->current_backend)); outSuccessful = true; } void AudioSoundIo::onBackendDisconnect(int err) { m_disconnectErr = err; } AudioSoundIo::~AudioSoundIo() { stopProcessing(); if (m_outstream) { soundio_outstream_destroy(m_outstream); } if (m_soundio) { soundio_destroy(m_soundio); m_soundio = nullptr; } } void AudioSoundIo::startProcessing() { m_outBufFrameIndex = 0; m_outBufFramesTotal = 0; m_outBufSize = audioEngine()->framesPerPeriod(); m_outBuf = new SampleFrame[m_outBufSize]; if (! m_outstreamStarted) { if (int err = soundio_outstream_start(m_outstream)) { fprintf(stderr, "AudioSoundIo::startProcessing() :: soundio unable to start stream: %s\n", soundio_strerror(err)); } else { m_outstreamStarted = true; } } m_stopped = false; if (int err = soundio_outstream_pause(m_outstream, false)) { m_stopped = true; fprintf(stderr, "AudioSoundIo::startProcessing() :: resuming result error: %s\n", soundio_strerror(err)); } } void AudioSoundIo::stopProcessing() { m_stopped = true; if (m_outstream) { if (int err = soundio_outstream_pause(m_outstream, true)) { fprintf(stderr, "AudioSoundIo::stopProcessing() :: pausing result error: %s\n", soundio_strerror(err)); } } if (m_outBuf) { delete[] m_outBuf; m_outBuf = nullptr; } } void AudioSoundIo::errorCallback(int err) { fprintf(stderr, "soundio: error streaming: %s\n", soundio_strerror(err)); } void AudioSoundIo::underflowCallback() { fprintf(stderr, "soundio: buffer underflow reported\n"); } void AudioSoundIo::writeCallback(int frameCountMin, int frameCountMax) { if (m_stopped) {return;} const struct SoundIoChannelLayout *layout = &m_outstream->layout; SoundIoChannelArea* areas; int bytesPerSample = m_outstream->bytes_per_sample; int framesLeft = frameCountMax; while (framesLeft > 0) { int frameCount = framesLeft; if (int err = soundio_outstream_begin_write(m_outstream, &areas, &frameCount)) { errorCallback(err); return; } if (!frameCount) break; if (m_stopped) { for (int channel = 0; channel < layout->channel_count; ++channel) { memset(areas[channel].ptr, 0, bytesPerSample * frameCount); areas[channel].ptr += areas[channel].step * frameCount; } continue; } for (int frame = 0; frame < frameCount; frame += 1) { if (m_outBufFrameIndex >= m_outBufFramesTotal) { m_outBufFramesTotal = getNextBuffer(m_outBuf); if (m_outBufFramesTotal == 0) { m_stopped = true; break; } m_outBufFrameIndex = 0; } for (int channel = 0; channel < layout->channel_count; channel += 1) { float sample = m_outBuf[m_outBufFrameIndex][channel]; memcpy(areas[channel].ptr, &sample, bytesPerSample); areas[channel].ptr += areas[channel].step; } m_outBufFrameIndex += 1; } if (int err = soundio_outstream_end_write(m_outstream)) { errorCallback(err); return; } framesLeft -= frameCount; } } void AudioSoundIoSetupUtil::reconnectSoundIo() { ((AudioSoundIo::setupWidget *)m_setupWidget)->reconnectSoundIo(); } void AudioSoundIoSetupUtil::updateDevices() { ((AudioSoundIo::setupWidget *)m_setupWidget)->updateDevices(); } static void setupWidgetOnBackendDisconnect(SoundIo *soundio, int err) { AudioSoundIo::setupWidget *setupWidget = (AudioSoundIo::setupWidget *)soundio->userdata; setupWidget->reconnectSoundIo(); } static void setup_widget_on_devices_change(SoundIo *soundio) { AudioSoundIo::setupWidget *setupWidget = (AudioSoundIo::setupWidget *)soundio->userdata; setupWidget->updateDevices(); } void AudioSoundIo::setupWidget::reconnectSoundIo() { const QString& configBackend = m_isFirst ? ConfigManager::inst()->value( "audiosoundio", "backend" ) : m_backendModel.currentText(); m_isFirst = false; soundio_disconnect(m_soundio); int backend_index = m_backendModel.findText(configBackend); if (backend_index < 0) { if (int err = soundio_connect(m_soundio)) { fprintf(stderr, "soundio: unable to connect backend: %s\n", soundio_strerror(err)); return; } backend_index = m_backendModel.findText(soundio_backend_name(m_soundio->current_backend)); assert(backend_index >= 0); } else { SoundIoBackend backend = soundio_get_backend(m_soundio, backend_index); if (int err = soundio_connect_backend(m_soundio, backend)) { fprintf(stderr, "soundio: unable to connect %s backend: %s\n", soundio_backend_name(backend), soundio_strerror(err)); if (int err = soundio_connect(m_soundio)) { fprintf(stderr, "soundio: unable to connect backend: %s\n", soundio_strerror(err)); return; } backend_index = m_backendModel.findText(soundio_backend_name(m_soundio->current_backend)); assert(backend_index >= 0); } } m_backendModel.setValue(backend_index); soundio_flush_events(m_soundio); const QString& configDeviceId = ConfigManager::inst()->value( "audiosoundio", "out_device_id" ); const QString& configDeviceRaw = ConfigManager::inst()->value( "audiosoundio", "out_device_raw" ); int deviceIndex = m_defaultOutIndex; bool wantRaw = (configDeviceRaw == "yes"); for (int i = 0; i < m_deviceList.length(); i += 1) { const DeviceId *deviceId = &m_deviceList.at(i); if (deviceId->id == configDeviceId && deviceId->is_raw == wantRaw) { deviceIndex = i; break; } } m_deviceModel.setValue(deviceIndex); } void AudioSoundIo::setupWidget::updateDevices() { m_defaultOutIndex = soundio_default_output_device_index(m_soundio); // get devices for selected backend m_deviceModel.clear(); m_deviceList.clear(); int outDeviceCount = soundio_output_device_count(m_soundio); for (int i = 0; i < outDeviceCount; i += 1) { SoundIoDevice *device = soundio_get_output_device(m_soundio, i); QString raw_text = device->is_raw ? " (raw)" : ""; QString default_text = (i == m_defaultOutIndex) ? " (default)" : ""; m_deviceModel.addItem(device->name + raw_text + default_text); m_deviceList.append({device->id, device->is_raw}); } } AudioSoundIo::setupWidget::setupWidget( QWidget * _parent ) : AudioDeviceSetupWidget( AudioSoundIo::name(), _parent ) { m_setupUtil.m_setupWidget = this; QFormLayout * form = new QFormLayout(this); m_backend = new gui::ComboBox( this, "BACKEND" ); form->addRow(tr("Backend"), m_backend); m_device = new gui::ComboBox( this, "DEVICE" ); form->addRow(tr("Device"), m_device); // Setup models m_soundio = soundio_create(); if (!m_soundio) { fprintf(stderr, "Unable to initialize soundio: out of memory\n"); return; } m_soundio->userdata = this; m_soundio->on_backend_disconnect = setupWidgetOnBackendDisconnect; m_soundio->on_devices_change = setup_widget_on_devices_change; m_soundio->app_name = "LMMS"; int backendCount = soundio_backend_count(m_soundio); for (int i = 0; i < backendCount; i += 1) { SoundIoBackend backend = soundio_get_backend(m_soundio, i); m_backendModel.addItem(soundio_backend_name(backend)); } m_isFirst = true; reconnectSoundIo(); bool ok = connect( &m_backendModel, SIGNAL(dataChanged()), &m_setupUtil, SLOT(reconnectSoundIo())); assert(ok); m_backend->setModel( &m_backendModel ); m_device->setModel( &m_deviceModel ); } AudioSoundIo::setupWidget::~setupWidget() { bool ok = disconnect( &m_backendModel, SIGNAL(dataChanged()), &m_setupUtil, SLOT(reconnectSoundIo())); assert(ok); if (m_soundio) { soundio_destroy(m_soundio); m_soundio = nullptr; } } void AudioSoundIo::setupWidget::saveSettings() { int deviceIndex = m_deviceModel.value(); const DeviceId *deviceId = &m_deviceList.at(deviceIndex); QString configDeviceRaw = deviceId->is_raw ? "yes" : "no"; ConfigManager::inst()->setValue( "audiosoundio", "backend", m_backendModel.currentText()); ConfigManager::inst()->setValue( "audiosoundio", "out_device_id", deviceId->id); ConfigManager::inst()->setValue( "audiosoundio", "out_device_raw", configDeviceRaw); } } // namespace lmms #endif // LMMS_HAVE_SOUNDIO
13,401
C++
.cpp
423
28.978723
103
0.726927
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,864
AudioJack.cpp
LMMS_lmms/src/core/audio/AudioJack.cpp
/* * AudioJack.cpp - support for JACK transport * * 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. * */ #include "AudioJack.h" #ifdef LMMS_HAVE_JACK #include <QFormLayout> #include <QLineEdit> #include <QMessageBox> #include "AudioEngine.h" #include "ConfigManager.h" #include "Engine.h" #include "GuiApplication.h" #include "LcdSpinBox.h" #include "MainWindow.h" #include "MidiJack.h" namespace lmms { AudioJack::AudioJack(bool& successful, AudioEngine* audioEngineParam) : AudioDevice( // clang-format off std::clamp<int>( ConfigManager::inst()->value("audiojack", "channels").toInt(), DEFAULT_CHANNELS, DEFAULT_CHANNELS ), // clang-format on audioEngineParam) , m_client(nullptr) , m_active(false) , m_midiClient(nullptr) , m_tempOutBufs(new jack_default_audio_sample_t*[channels()]) , m_outBuf(new SampleFrame[audioEngine()->framesPerPeriod()]) , m_framesDoneInCurBuf(0) , m_framesToDoInCurBuf(0) { m_stopped = true; successful = initJackClient(); if (successful) { connect(this, SIGNAL(zombified()), this, SLOT(restartAfterZombified()), Qt::QueuedConnection); } } AudioJack::~AudioJack() { AudioJack::stopProcessing(); #ifdef AUDIO_PORT_SUPPORT while (m_portMap.size()) { unregisterPort(m_portMap.begin().key()); } #endif if (m_client != nullptr) { if (m_active) { jack_deactivate(m_client); } jack_client_close(m_client); } delete[] m_tempOutBufs; delete[] m_outBuf; } void AudioJack::restartAfterZombified() { if (initJackClient()) { m_active = false; startProcessing(); QMessageBox::information(gui::getGUI()->mainWindow(), tr("JACK client restarted"), tr( "LMMS was kicked by JACK for some reason. " "Therefore the JACK backend of LMMS has been " "restarted. You will have to make manual " "connections again.")); } else { QMessageBox::information(gui::getGUI()->mainWindow(), tr("JACK server down"), tr( "The JACK server seems to have been shutdown " "and starting a new instance failed. " "Therefore LMMS is unable to proceed. " "You should save your project and restart " "JACK and LMMS.")); } } AudioJack* AudioJack::addMidiClient(MidiJack* midiClient) { if (m_client == nullptr) { return nullptr; } m_midiClient = midiClient; return this; } bool AudioJack::initJackClient() { QString clientName = ConfigManager::inst()->value("audiojack", "clientname"); if (clientName.isEmpty()) { clientName = "lmms"; } const char* serverName = nullptr; jack_status_t status; m_client = jack_client_open(clientName.toLatin1().constData(), JackNullOption, &status, serverName); if (m_client == nullptr) { printf("jack_client_open() failed, status 0x%2.0x\n", status); if (status & JackServerFailed) { printf("Could not connect to JACK server.\n"); } return false; } if (status & JackNameNotUnique) { printf( "there's already a client with name '%s', so unique " "name '%s' was assigned\n", clientName.toLatin1().constData(), jack_get_client_name(m_client)); } // set process-callback jack_set_process_callback(m_client, staticProcessCallback, this); // set shutdown-callback jack_on_shutdown(m_client, shutdownCallback, this); if (jack_get_sample_rate(m_client) != sampleRate()) { setSampleRate(jack_get_sample_rate(m_client)); } for (ch_cnt_t ch = 0; ch < channels(); ++ch) { QString name = QString("master out ") + ((ch % 2) ? "R" : "L") + QString::number(ch / 2 + 1); m_outputPorts.push_back( jack_port_register(m_client, name.toLatin1().constData(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0)); if (m_outputPorts.back() == nullptr) { printf("no more JACK-ports available!\n"); return false; } } return true; } void AudioJack::startProcessing() { if (m_active || m_client == nullptr) { m_stopped = false; return; } if (jack_activate(m_client)) { printf("cannot activate client\n"); return; } m_active = true; // try to sync JACK's and LMMS's buffer-size // jack_set_buffer_size( m_client, audioEngine()->framesPerPeriod() ); const char** ports = jack_get_ports(m_client, nullptr, nullptr, JackPortIsPhysical | JackPortIsInput); if (ports == nullptr) { printf("no physical playback ports. you'll have to do " "connections at your own!\n"); } else { for (ch_cnt_t ch = 0; ch < channels(); ++ch) { if (jack_connect(m_client, jack_port_name(m_outputPorts[ch]), ports[ch])) { printf("cannot connect output ports. you'll " "have to do connections at your own!\n"); } } } m_stopped = false; jack_free(ports); } void AudioJack::stopProcessing() { m_stopped = true; } void AudioJack::registerPort(AudioPort* port) { #ifdef AUDIO_PORT_SUPPORT // make sure, port is not already registered unregisterPort(port); const QString name[2] = {port->name() + " L", port->name() + " R"}; for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch) { m_portMap[port].ports[ch] = jack_port_register( m_client, name[ch].toLatin1().constData(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); } #else (void)port; #endif } void AudioJack::unregisterPort(AudioPort* port) { #ifdef AUDIO_PORT_SUPPORT if (m_portMap.contains(port)) { for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch) { if (m_portMap[port].ports[ch] != nullptr) { jack_port_unregister(m_client, m_portMap[port].ports[ch]); } } m_portMap.erase(m_portMap.find(port)); } #else (void)port; #endif } void AudioJack::renamePort(AudioPort* port) { #ifdef AUDIO_PORT_SUPPORT if (m_portMap.contains(port)) { const QString name[2] = {port->name() + " L", port->name() + " R"}; for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch) { #ifdef LMMS_HAVE_JACK_PRENAME jack_port_rename(m_client, m_portMap[port].ports[ch], name[ch].toLatin1().constData()); #else jack_port_set_name(m_portMap[port].ports[ch], name[ch].toLatin1().constData()); #endif } } #else (void)port; #endif // AUDIO_PORT_SUPPORT } int AudioJack::processCallback(jack_nframes_t nframes) { // do midi processing first so that midi input can // add to the following sound processing if (m_midiClient && nframes > 0) { m_midiClient.load()->JackMidiRead(nframes); m_midiClient.load()->JackMidiWrite(nframes); } for (int c = 0; c < channels(); ++c) { m_tempOutBufs[c] = (jack_default_audio_sample_t*)jack_port_get_buffer(m_outputPorts[c], nframes); } #ifdef AUDIO_PORT_SUPPORT const int frames = std::min<int>(nframes, audioEngine()->framesPerPeriod()); for (JackPortMap::iterator it = m_portMap.begin(); it != m_portMap.end(); ++it) { for (ch_cnt_t ch = 0; ch < channels(); ++ch) { if (it.value().ports[ch] == nullptr) { continue; } jack_default_audio_sample_t* buf = (jack_default_audio_sample_t*)jack_port_get_buffer(it.value().ports[ch], nframes); for (int frame = 0; frame < frames; ++frame) { buf[frame] = it.key()->buffer()[frame][ch]; } } } #endif jack_nframes_t done = 0; while (done < nframes && !m_stopped) { jack_nframes_t todo = std::min<jack_nframes_t>(nframes - done, m_framesToDoInCurBuf - m_framesDoneInCurBuf); for (int c = 0; c < channels(); ++c) { jack_default_audio_sample_t* o = m_tempOutBufs[c]; for (jack_nframes_t frame = 0; frame < todo; ++frame) { o[done + frame] = m_outBuf[m_framesDoneInCurBuf + frame][c]; } } done += todo; m_framesDoneInCurBuf += todo; if (m_framesDoneInCurBuf == m_framesToDoInCurBuf) { m_framesToDoInCurBuf = getNextBuffer(m_outBuf); m_framesDoneInCurBuf = 0; if (!m_framesToDoInCurBuf) { m_stopped = true; break; } } } if (nframes != done) { for (int c = 0; c < channels(); ++c) { jack_default_audio_sample_t* b = m_tempOutBufs[c] + done; memset(b, 0, sizeof(*b) * (nframes - done)); } } return 0; } int AudioJack::staticProcessCallback(jack_nframes_t nframes, void* udata) { return static_cast<AudioJack*>(udata)->processCallback(nframes); } void AudioJack::shutdownCallback(void* udata) { auto thisClass = static_cast<AudioJack*>(udata); thisClass->m_client = nullptr; emit thisClass->zombified(); } AudioJack::setupWidget::setupWidget(QWidget* parent) : AudioDeviceSetupWidget(AudioJack::name(), parent) { QFormLayout * form = new QFormLayout(this); QString cn = ConfigManager::inst()->value("audiojack", "clientname"); if (cn.isEmpty()) { cn = "lmms"; } m_clientName = new QLineEdit(cn, this); form->addRow(tr("Client name"), m_clientName); auto m = new gui::LcdSpinBoxModel(/* this */); m->setRange(DEFAULT_CHANNELS, DEFAULT_CHANNELS); m->setStep(2); m->setValue(ConfigManager::inst()->value("audiojack", "channels").toInt()); m_channels = new gui::LcdSpinBox(1, this); m_channels->setModel(m); form->addRow(tr("Channels"), m_channels); } AudioJack::setupWidget::~setupWidget() { delete m_channels->model(); } void AudioJack::setupWidget::saveSettings() { ConfigManager::inst()->setValue("audiojack", "clientname", m_clientName->text()); ConfigManager::inst()->setValue("audiojack", "channels", QString::number(m_channels->value<int>())); } } // namespace lmms #endif // LMMS_HAVE_JACK
9,940
C++
.cpp
332
27.373494
110
0.702049
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
19,865
SharedMemory.cpp
LMMS_lmms/src/common/SharedMemory.cpp
/* * SharedMemory.cpp * * Copyright (c) 2022 Dominic Clark <mrdomclark/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. */ #include "SharedMemory.h" #include <system_error> #include <utility> #include "lmmsconfig.h" #include "RaiiHelpers.h" #ifdef LMMS_HAVE_UNISTD_H # include <unistd.h> #endif #if _POSIX_SHARED_MEMORY_OBJECTS > 0 || defined(LMMS_BUILD_APPLE) # include <sys/mman.h> # include <sys/stat.h> # include <fcntl.h> #elif defined(LMMS_BUILD_WIN32) # include <windows.h> #else # error "No shared memory implementation available" #endif namespace lmms::detail { #if _POSIX_SHARED_MEMORY_OBJECTS > 0 || defined(LMMS_BUILD_APPLE) namespace { [[noreturn]] void throwSystemError(const char* message) { throw std::system_error{errno, std::generic_category(), message}; } template<typename F> int retryWhileInterrupted(F&& function) noexcept(std::is_nothrow_invocable_v<F>) { while (true) { const auto result = function(); if (result != -1 || errno != EINTR) { return result; } } } void deleteFileDescriptor(int fd) noexcept { retryWhileInterrupted([fd]() noexcept { return close(fd); }); } void deleteShmObject(const char* name) noexcept { shm_unlink(name); } using FileDescriptor = UniqueNullableResource<int, -1, deleteFileDescriptor>; using ShmObject = UniqueNullableResource<const char*, nullptr, deleteShmObject>; } // namespace class SharedMemoryImpl { public: SharedMemoryImpl(const std::string& key, bool readOnly) : m_key{"/" + key} { const auto openFlags = readOnly ? O_RDONLY : O_RDWR; const auto fd = FileDescriptor{ retryWhileInterrupted([&]() noexcept { return shm_open(m_key.c_str(), openFlags, 0); }) }; if (!fd) { throwSystemError("SharedMemoryImpl: shm_open() failed"); } auto stat = (struct stat){}; if (fstat(fd.get(), &stat) == -1) { throwSystemError("SharedMemoryImpl: fstat() failed"); } m_size = stat.st_size; const auto mappingProtection = readOnly ? PROT_READ : PROT_READ | PROT_WRITE; m_mapping = mmap(nullptr, m_size, mappingProtection, MAP_SHARED, fd.get(), 0); if (m_mapping == MAP_FAILED) { throwSystemError("SharedMemoryImpl: mmap() failed"); } } SharedMemoryImpl(const std::string& key, std::size_t size, bool readOnly) : m_key{"/" + key}, m_size{size} { const auto fd = FileDescriptor{ retryWhileInterrupted([&]() noexcept { return shm_open(m_key.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600); }) }; if (fd.get() == -1) { throwSystemError("SharedMemoryImpl: shm_open() failed"); } m_object.reset(m_key.c_str()); if (retryWhileInterrupted([&]() noexcept { return ftruncate(fd.get(), m_size); }) == -1) { throwSystemError("SharedMemoryImpl: ftruncate() failed"); } const auto mappingProtection = readOnly ? PROT_READ : PROT_READ | PROT_WRITE; m_mapping = mmap(nullptr, m_size, mappingProtection, MAP_SHARED, fd.get(), 0); if (m_mapping == MAP_FAILED) { throwSystemError("SharedMemoryImpl: mmap() failed"); } } SharedMemoryImpl(const SharedMemoryImpl&) = delete; SharedMemoryImpl& operator=(const SharedMemoryImpl&) = delete; ~SharedMemoryImpl() { munmap(m_mapping, m_size); } auto get() const noexcept -> void* { return m_mapping; } private: std::string m_key; std::size_t m_size; void* m_mapping; ShmObject m_object; }; #elif defined(LMMS_BUILD_WIN32) namespace { template<typename T> auto sizeToHighAndLow(T size) -> std::pair<DWORD, DWORD> { if constexpr (sizeof(T) <= sizeof(DWORD)) { return {0, size}; } else { return {static_cast<DWORD>(size >> 32), static_cast<DWORD>(size)}; } } [[noreturn]] void throwLastError(const char* message) { throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), message}; } using UniqueHandle = UniqueNullableResource<HANDLE, nullptr, CloseHandle>; using FileView = UniqueNullableResource<void*, nullptr, UnmapViewOfFile>; } // namespace class SharedMemoryImpl { public: SharedMemoryImpl(const std::string& key, bool readOnly) { const auto access = readOnly ? FILE_MAP_READ : FILE_MAP_WRITE; m_mapping.reset(OpenFileMappingA(access, false, key.c_str())); if (!m_mapping) { throwLastError("SharedMemoryImpl: OpenFileMappingA() failed"); } m_view.reset(MapViewOfFile(m_mapping.get(), access, 0, 0, 0)); if (!m_view) { throwLastError("SharedMemoryImpl: MapViewOfFile() failed"); } } SharedMemoryImpl(const std::string& key, std::size_t size, bool readOnly) { const auto [high, low] = sizeToHighAndLow(size); m_mapping.reset(CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, high, low, key.c_str())); // This constructor is supposed to create a new shared memory object, // but passing the name of an existing object causes CreateFileMappingA // to succeed and return a handle to that object. Thus we have to check // GetLastError() too. if (!m_mapping || GetLastError() == ERROR_ALREADY_EXISTS) { throwLastError("SharedMemoryImpl: CreateFileMappingA() failed"); } const auto access = readOnly ? FILE_MAP_READ : FILE_MAP_WRITE; m_view.reset(MapViewOfFile(m_mapping.get(), access, 0, 0, 0)); if (!m_view) { throwLastError("SharedMemoryImpl: MapViewOfFile() failed"); } } SharedMemoryImpl(const SharedMemoryImpl&) = delete; auto operator=(const SharedMemoryImpl&) -> SharedMemoryImpl& = delete; auto get() const noexcept -> void* { return m_view.get(); } private: UniqueHandle m_mapping; FileView m_view; }; #endif SharedMemoryData::SharedMemoryData() noexcept = default; SharedMemoryData::SharedMemoryData(std::string&& key, bool readOnly) : m_key{std::move(key)}, m_impl{std::make_unique<SharedMemoryImpl>(m_key, readOnly)}, m_ptr{m_impl->get()} { } SharedMemoryData::SharedMemoryData(std::string&& key, std::size_t size, bool readOnly) : m_key{std::move(key)}, m_impl{std::make_unique<SharedMemoryImpl>(m_key, std::max(size, std::size_t{1}), readOnly)}, m_ptr{m_impl->get()} { } SharedMemoryData::~SharedMemoryData() = default; SharedMemoryData::SharedMemoryData(SharedMemoryData&& other) noexcept : m_key{std::move(other.m_key)}, m_impl{std::move(other.m_impl)}, m_ptr{std::exchange(other.m_ptr, nullptr)} { } } // namespace lmms::detail
6,887
C++
.cpp
176
36.965909
109
0.730204
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
19,866
SystemSemaphore.cpp
LMMS_lmms/src/common/SystemSemaphore.cpp
/* * SystemSemaphore.cpp * * Copyright (c) 2024 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. */ #include "SystemSemaphore.h" #include <limits> #include <system_error> #include <type_traits> #include <utility> #include "lmmsconfig.h" #include "RaiiHelpers.h" #ifdef LMMS_HAVE_UNISTD_H # include <unistd.h> #endif #if (_POSIX_SEMAPHORES > 0 && !defined(__MINGW32__)) || defined(LMMS_BUILD_APPLE) # include <fcntl.h> # include <semaphore.h> #elif defined(LMMS_BUILD_WIN32) # include <windows.h> #else # error "No system semaphore implementation available" #endif namespace lmms { namespace detail { #if (_POSIX_SEMAPHORES > 0 && !defined(__MINGW32__)) || defined(LMMS_BUILD_APPLE) namespace { [[noreturn]] void throwSystemError(const char* message) { throw std::system_error{errno, std::generic_category(), message}; } template<typename F> auto retryWhileInterrupted(F&& function, std::invoke_result_t<F> error = -1) noexcept(std::is_nothrow_invocable_v<F>) -> auto { while (true) { const auto result = function(); if (result != error || errno != EINTR) { return result; } } } using UniqueSemaphore = UniqueNullableResource<const char*, nullptr, sem_unlink>; } // namespace class SystemSemaphoreImpl { public: SystemSemaphoreImpl(const std::string& key, unsigned int value) : m_key{"/" + key}, m_sem{retryWhileInterrupted([&]() noexcept { return sem_open(m_key.c_str(), O_CREAT | O_EXCL, 0600, value); }, SEM_FAILED)} { if (m_sem == SEM_FAILED) { throwSystemError("SystemSemaphoreImpl: sem_open() failed"); } m_ownedSemaphore.reset(m_key.c_str()); } explicit SystemSemaphoreImpl(const std::string& key) : m_key{"/" + key}, m_sem{retryWhileInterrupted([&]() noexcept { return sem_open(m_key.c_str(), 0); }, SEM_FAILED)} { if (m_sem == SEM_FAILED) { throwSystemError("SystemSemaphoreImpl: sem_open() failed"); } } ~SystemSemaphoreImpl() { // We can't use `UniqueNullableResource` for `m_sem`, as the null value // (`SEM_FAILED`) is not a constant expression on macOS (it's defined as // `(sem_t*) -1`), so can't be used as a template parameter. sem_close(m_sem); } auto acquire() noexcept -> bool { return retryWhileInterrupted([&]() noexcept { return sem_wait(m_sem); }) == 0; } auto release() noexcept -> bool { return sem_post(m_sem) == 0; } private: std::string m_key; sem_t* m_sem; UniqueSemaphore m_ownedSemaphore; }; #elif defined(LMMS_BUILD_WIN32) namespace { [[noreturn]] void throwSystemError(const char* message) { throw std::system_error{static_cast<int>(GetLastError()), std::system_category(), message}; } using UniqueHandle = UniqueNullableResource<HANDLE, nullptr, CloseHandle>; } // namespace class SystemSemaphoreImpl { public: SystemSemaphoreImpl(const std::string& key, unsigned int value) : m_sem{CreateSemaphoreA(nullptr, value, std::numeric_limits<LONG>::max(), key.c_str())} { if (!m_sem || GetLastError() == ERROR_ALREADY_EXISTS) { throwSystemError("SystemSemaphoreImpl: CreateSemaphoreA failed"); } } explicit SystemSemaphoreImpl(const std::string& key) : m_sem{OpenSemaphoreA(SEMAPHORE_MODIFY_STATE | SYNCHRONIZE, false, key.c_str())} { if (!m_sem) { throwSystemError("SystemSemaphoreImpl: OpenSemaphoreA failed"); } } auto acquire() noexcept -> bool { return WaitForSingleObject(m_sem.get(), INFINITE) == WAIT_OBJECT_0; } auto release() noexcept -> bool { return ReleaseSemaphore(m_sem.get(), 1, nullptr); } private: UniqueHandle m_sem; }; #endif } // namespace detail SystemSemaphore::SystemSemaphore() noexcept = default; SystemSemaphore::SystemSemaphore(std::string key, unsigned int value) : m_key{std::move(key)}, m_impl{std::make_unique<detail::SystemSemaphoreImpl>(m_key, value)} {} SystemSemaphore::SystemSemaphore(std::string key) : m_key{std::move(key)}, m_impl{std::make_unique<detail::SystemSemaphoreImpl>(m_key)} {} SystemSemaphore::~SystemSemaphore() = default; SystemSemaphore::SystemSemaphore(SystemSemaphore&& other) noexcept = default; auto SystemSemaphore::operator=(SystemSemaphore&& other) noexcept -> SystemSemaphore& = default; auto SystemSemaphore::acquire() noexcept -> bool { return m_impl->acquire(); } auto SystemSemaphore::release() noexcept -> bool { return m_impl->release(); } } // namespace lmms
5,040
C++
.cpp
144
32.965278
104
0.733278
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
19,867
RemotePluginBase.cpp
LMMS_lmms/src/common/RemotePluginBase.cpp
/* * RemotePluginBase.cpp - 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. * */ #include "RemotePluginBase.h" #ifndef BUILD_REMOTE_PLUGIN_CLIENT #include <QCoreApplication> #endif namespace lmms { #ifdef SYNC_WITH_SHM_FIFO RemotePluginBase::RemotePluginBase(shmFifo * _in, shmFifo * _out) : m_in(_in), m_out(_out) #else RemotePluginBase::RemotePluginBase() : m_socket(-1), m_invalid(false) #endif { #ifdef LMMS_HAVE_LOCALE_H // make sure, we're using common ways to print/scan // floats to/from strings (',' vs. '.' for decimal point etc.) setlocale(LC_NUMERIC, "C"); #endif #ifndef SYNC_WITH_SHM_FIFO pthread_mutex_init(&m_receiveMutex, nullptr); pthread_mutex_init(&m_sendMutex, nullptr); #endif } RemotePluginBase::~RemotePluginBase() { #ifdef SYNC_WITH_SHM_FIFO delete m_in; delete m_out; #else pthread_mutex_destroy(&m_receiveMutex); pthread_mutex_destroy(&m_sendMutex); #endif } int RemotePluginBase::sendMessage(const message & _m) { #ifdef SYNC_WITH_SHM_FIFO m_out->lock(); m_out->writeInt(_m.id); m_out->writeInt(_m.data.size()); int j = 8; for (unsigned int i = 0; i < _m.data.size(); ++i) { m_out->writeString(_m.data[i]); j += 4 + _m.data[i].size(); } m_out->unlock(); m_out->messageSent(); #else pthread_mutex_lock(&m_sendMutex); writeInt(_m.id); writeInt(_m.data.size()); int j = 8; for (const auto& str : _m.data) { writeString(str); j += 4 + str.size(); } pthread_mutex_unlock(&m_sendMutex); #endif return j; } RemotePluginBase::message RemotePluginBase::receiveMessage() { #ifdef SYNC_WITH_SHM_FIFO m_in->waitForMessage(); m_in->lock(); message m; m.id = m_in->readInt(); const int s = m_in->readInt(); for (int i = 0; i < s; ++i) { m.data.push_back(m_in->readString()); } m_in->unlock(); #else pthread_mutex_lock(&m_receiveMutex); message m; m.id = readInt(); const int s = readInt(); for (int i = 0; i < s; ++i) { m.data.push_back(readString()); } pthread_mutex_unlock(&m_receiveMutex); #endif return m; } RemotePluginBase::message RemotePluginBase::waitForMessage( const message & _wm, bool _busy_waiting) { #ifndef BUILD_REMOTE_PLUGIN_CLIENT if (_busy_waiting) { // No point processing events outside of the main thread _busy_waiting = QThread::currentThread() == QCoreApplication::instance()->thread(); } struct WaitDepthCounter { WaitDepthCounter(int & depth, bool busy) : m_depth(depth), m_busy(busy) { if (m_busy) { ++m_depth; } } ~WaitDepthCounter() { if (m_busy) { --m_depth; } } int & m_depth; bool m_busy; }; WaitDepthCounter wdc(waitDepthCounter(), _busy_waiting); #endif while (!isInvalid()) { #ifndef BUILD_REMOTE_PLUGIN_CLIENT if (_busy_waiting && !messagesLeft()) { QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents, 50); continue; } #endif message m = receiveMessage(); processMessage(m); if (m.id == _wm.id) { return m; } else if (m.id == IdUndefined) { return m; } } return message(); } } // namespace lmms
3,917
C++
.cpp
165
21.454545
77
0.706151
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
19,868
AutomationTrack.cpp
LMMS_lmms/src/tracks/AutomationTrack.cpp
/* * AutomationTrack.cpp - AutomationTrack handles automation of objects without * a track * * 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. * */ #include "AutomationTrack.h" #include "AutomationTrackView.h" #include "AutomationClip.h" namespace lmms { AutomationTrack::AutomationTrack( TrackContainer* tc, bool _hidden ) : Track( _hidden ? Type::HiddenAutomation : Type::Automation, tc ) { setName( tr( "Automation track" ) ); } bool AutomationTrack::play( const TimePos & time_start, const fpp_t _frames, const f_cnt_t _frame_base, int _clip_num ) { return false; } gui::TrackView* AutomationTrack::createView( gui::TrackContainerView* tcv ) { return new gui::AutomationTrackView( this, tcv ); } Clip* AutomationTrack::createClip(const TimePos & pos) { auto p = new AutomationClip(this); p->movePosition(pos); return p; } void AutomationTrack::saveTrackSpecificSettings(QDomDocument& doc, QDomElement& _this, bool presetMode) { } void AutomationTrack::loadTrackSpecificSettings( const QDomElement & _this ) { // just in case something somehow wrent wrong... if( type() == Type::HiddenAutomation ) { setMuted( false ); } } } // namespace lmms
2,113
C++
.cpp
62
31.983871
103
0.75037
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
19,869
InstrumentTrack.cpp
LMMS_lmms/src/tracks/InstrumentTrack.cpp
/* * InstrumentTrack.cpp - implementation of InstrumentTrack 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. * */ #include "InstrumentTrack.h" #include "AudioEngine.h" #include "AutomationClip.h" #include "ConfigManager.h" #include "ControllerConnection.h" #include "DataFile.h" #include "GuiApplication.h" #include "Mixer.h" #include "InstrumentTrackView.h" #include "Instrument.h" #include "Keymap.h" #include "MidiClient.h" #include "MidiClip.h" #include "MixHelpers.h" #include "PatternStore.h" #include "PatternTrack.h" #include "PianoRoll.h" #include "Pitch.h" #include "Song.h" namespace lmms { InstrumentTrack::InstrumentTrack( TrackContainer* tc ) : Track( Track::Type::Instrument, tc ), MidiEventProcessor(), m_midiPort( tr( "unnamed_track" ), Engine::audioEngine()->midiClient(), this, this ), m_notes(), m_sustainPedalPressed( false ), m_silentBuffersProcessed( false ), m_previewMode( false ), m_baseNoteModel(0, 0, NumKeys - 1, this, tr("Base note")), m_firstKeyModel(0, 0, NumKeys - 1, this, tr("First note")), m_lastKeyModel(0, 0, NumKeys - 1, this, tr("Last note")), m_hasAutoMidiDev( false ), m_volumeModel( DefaultVolume, MinVolume, MaxVolume, 0.1f, this, tr( "Volume" ) ), m_panningModel( DefaultPanning, PanningLeft, PanningRight, 0.1f, this, tr( "Panning" ) ), m_audioPort( tr( "unnamed_track" ), true, &m_volumeModel, &m_panningModel, &m_mutedModel ), m_pitchModel( 0, MinPitchDefault, MaxPitchDefault, 1, this, tr( "Pitch" ) ), m_pitchRangeModel( 1, 1, 60, this, tr( "Pitch range" ) ), m_mixerChannelModel( 0, 0, 0, this, tr( "Mixer channel" ) ), m_useMasterPitchModel( true, this, tr( "Master pitch") ), m_instrument( nullptr ), m_soundShaping( this ), m_arpeggio( this ), m_noteStacking( this ), m_piano(this), m_microtuner() { m_pitchModel.setCenterValue( 0 ); m_pitchModel.setStrictStepSize(true); m_panningModel.setCenterValue( DefaultPanning ); m_baseNoteModel.setInitValue( DefaultKey ); m_firstKeyModel.setInitValue(0); m_lastKeyModel.setInitValue(NumKeys - 1); m_mixerChannelModel.setRange( 0, Engine::mixer()->numChannels()-1, 1); for( int i = 0; i < NumKeys; ++i ) { m_notes[i] = nullptr; m_runningMidiNotes[i] = 0; } // Initialize the m_midiCCEnabled variable, but it's actually going to be connected // to a LedButton m_midiCCEnable = std::make_unique<BoolModel>(false, nullptr, tr("Enable/Disable MIDI CC")); // Initialize the MIDI CC controller models and connect them to the method that processes // the midi cc events for (int i = 0; i < MidiControllerCount; ++i) { m_midiCCModel[i] = std::make_unique<FloatModel>(0.0f, 0.0f, 127.0f, 1.0f, nullptr, tr("CC Controller %1").arg(i)); connect(m_midiCCModel[i].get(), &FloatModel::dataChanged, this, [this, i]{ processCCEvent(i); }, Qt::DirectConnection); } setName( tr( "Default preset" ) ); connect(&m_baseNoteModel, SIGNAL(dataChanged()), this, SLOT(updateBaseNote()), Qt::DirectConnection); connect(&m_pitchModel, SIGNAL(dataChanged()), this, SLOT(updatePitch()), Qt::DirectConnection); connect(&m_pitchRangeModel, SIGNAL(dataChanged()), this, SLOT(updatePitchRange()), Qt::DirectConnection); connect(&m_mixerChannelModel, SIGNAL(dataChanged()), this, SLOT(updateMixerChannel()), Qt::DirectConnection); } bool InstrumentTrack::keyRangeImport() const { return m_microtuner.enabled() && m_microtuner.keyRangeImport(); } /** \brief Check if there is a valid mapping for the given key and it is within defined of range. */ bool InstrumentTrack::isKeyMapped(int key) const { if (key < firstKey() || key > lastKey()) {return false;} if (!m_microtuner.enabled()) {return true;} Song *song = Engine::getSong(); if (!song) {return false;} return song->getKeymap(m_microtuner.currentKeymap())->getDegree(key) != -1; } /** \brief Return first mapped key, based on currently selected keymap or user selection. * \return Number ranging from 0 to NumKeys -1 */ int InstrumentTrack::firstKey() const { if (keyRangeImport()) { return Engine::getSong()->getKeymap(m_microtuner.currentKeymap())->getFirstKey(); } else { return m_firstKeyModel.value(); } } /** \brief Return last mapped key, based on currently selected keymap or user selection. * \return Number ranging from 0 to NumKeys -1 */ int InstrumentTrack::lastKey() const { if (keyRangeImport()) { return Engine::getSong()->getKeymap(m_microtuner.currentKeymap())->getLastKey(); } else { return m_lastKeyModel.value(); } } /** \brief Return base key number, based on currently selected keymap or user selection. * \return Number ranging from 0 to NumKeys -1 */ int InstrumentTrack::baseNote() const { int mp = m_useMasterPitchModel.value() ? Engine::getSong()->masterPitch() : 0; if (keyRangeImport()) { return Engine::getSong()->getKeymap(m_microtuner.currentKeymap())->getBaseKey() - mp; } else { return m_baseNoteModel.value() - mp; } } /** \brief Return frequency assigned to the base key, based on currently selected keymap. * \return Frequency in Hz */ float InstrumentTrack::baseFreq() const { if (m_microtuner.enabled()) { return Engine::getSong()->getKeymap(m_microtuner.currentKeymap())->getBaseFreq(); } else { return DefaultBaseFreq; } } InstrumentTrack::~InstrumentTrack() { // De-assign midi device if (m_hasAutoMidiDev) { autoAssignMidiDevice(false); s_autoAssignedTrack = nullptr; } // kill all running notes and the iph silenceAllNotes( true ); // now we're save deleting the instrument if( m_instrument ) delete m_instrument; } void InstrumentTrack::processAudioBuffer( SampleFrame* buf, const fpp_t frames, NotePlayHandle* n ) { // we must not play the sound if this InstrumentTrack is muted... if( isMuted() || ( Engine::getSong()->playMode() != Song::PlayMode::MidiClip && n && n->isPatternTrackMuted() ) || ! m_instrument ) { return; } // Test for silent input data if instrument provides a single stream only (i.e. driven by InstrumentPlayHandle) // We could do that in all other cases as well but the overhead for silence test is bigger than // what we potentially save. While playing a note, a NotePlayHandle-driven instrument will produce sound in // 99 of 100 cases so that test would be a waste of time. if (m_instrument->isSingleStreamed() && MixHelpers::isSilent(buf, frames)) { // at least pass one silent buffer to allow if( m_silentBuffersProcessed ) { // skip further processing return; } m_silentBuffersProcessed = true; } else { m_silentBuffersProcessed = false; } // if effects "went to sleep" because there was no input, wake them up // now m_audioPort.effects()->startRunning(); // get volume knob data static const float DefaultVolumeRatio = 1.0f / DefaultVolume; /*ValueBuffer * volBuf = m_volumeModel.valueBuffer(); float v_scale = volBuf ? 1.0f : getVolume() * DefaultVolumeRatio;*/ // instruments using instrument-play-handles will call this method // without any knowledge about notes, so they pass NULL for n, which // is no problem for us since we just bypass the envelopes+LFOs if (!m_instrument->isSingleStreamed() && n != nullptr) { const f_cnt_t offset = n->noteOffset(); m_soundShaping.processAudioBuffer( buf + offset, frames - offset, n ); const float vol = ( (float) n->getVolume() * DefaultVolumeRatio ); const panning_t pan = std::clamp(n->getPanning(), PanningLeft, PanningRight); StereoVolumeVector vv = panningToVolumeVector( pan, vol ); for( f_cnt_t f = offset; f < frames; ++f ) { for( int c = 0; c < 2; ++c ) { buf[f][c] *= vv.vol[c]; } } } } MidiEvent InstrumentTrack::applyMasterKey( const MidiEvent& event ) { MidiEvent copy( event ); switch( event.type() ) { case MidiNoteOn: case MidiNoteOff: case MidiKeyPressure: copy.setKey( masterKey( event.key() ) ); break; default: break; } return copy; } void InstrumentTrack::processCCEvent(int controller) { // Does nothing if the LED is disabled if (!m_midiCCEnable->value()) { return; } auto channel = static_cast<uint8_t>(midiPort()->realOutputChannel()); auto cc = static_cast<uint16_t>(controller); auto value = static_cast<uint16_t>(m_midiCCModel[controller]->value()); // Process the MIDI CC event as an input event but with source set to Internal // so we can know LMMS generated the event, not a controller, and can process it during // the project export processInEvent(MidiEvent(MidiControlChange, channel, cc, value, nullptr, MidiEvent::Source::Internal)); } void InstrumentTrack::processInEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset ) { if (Engine::getSong()->isExporting() && event.source() == MidiEvent::Source::External) { return; } bool eventHandled = false; switch( event.type() ) { // we don't send MidiNoteOn, MidiNoteOff and MidiKeyPressure // events to instrument as NotePlayHandle will send them on its // own case MidiNoteOn: if( event.velocity() > 0 ) { // play a note only if it is not already playing and if it is within configured bounds if (m_notes[event.key()] == nullptr && event.key() >= firstKey() && event.key() <= lastKey()) { NotePlayHandle* nph = NotePlayHandleManager::acquire( this, offset, std::numeric_limits<f_cnt_t>::max() / 2, Note(TimePos(), Engine::getSong()->getPlayPos(Engine::getSong()->playMode()), event.key(), event.volume(midiPort()->baseVelocity())), nullptr, event.channel(), NotePlayHandle::Origin::MidiInput); m_notes[event.key()] = nph; if( ! Engine::audioEngine()->addPlayHandle( nph ) ) { m_notes[event.key()] = nullptr; } } eventHandled = true; break; } case MidiNoteOff: if( m_notes[event.key()] != nullptr ) { // do actual note off and remove internal reference to NotePlayHandle (which itself will // be deleted later automatically) Engine::audioEngine()->requestChangeInModel(); m_notes[event.key()]->noteOff( offset ); if (isSustainPedalPressed() && m_notes[event.key()]->origin() == NotePlayHandle::Origin::MidiInput) { m_sustainedNotes << m_notes[event.key()]; } m_notes[event.key()] = nullptr; Engine::audioEngine()->doneChangeInModel(); } eventHandled = true; break; case MidiKeyPressure: if( m_notes[event.key()] != nullptr ) { // setVolume() calls processOutEvent() with MidiKeyPressure so the // attached instrument will receive the event as well m_notes[event.key()]->setVolume( event.volume( midiPort()->baseVelocity() ) ); } eventHandled = true; break; case MidiPitchBend: // updatePitch() is connected to m_pitchModel::dataChanged() which will send out // MidiPitchBend events m_pitchModel.setValue( m_pitchModel.minValue() + event.pitchBend() * m_pitchModel.range() / MidiMaxPitchBend ); break; case MidiControlChange: if( event.controllerNumber() == MidiControllerSustain ) { if( event.controllerValue() > MidiMaxControllerValue/2 ) { m_sustainPedalPressed = true; } else if (isSustainPedalPressed()) { for (NotePlayHandle* nph : m_sustainedNotes) { if (nph && nph->isReleased()) { if( nph->origin() == NotePlayHandle::Origin::MidiInput) { nph->setLength( TimePos( static_cast<f_cnt_t>( nph->totalFramesPlayed() / Engine::framesPerTick() ) ) ); midiNoteOff( *nph ); } } } m_sustainedNotes.clear(); m_sustainPedalPressed = false; } } if( event.controllerNumber() == MidiControllerAllSoundOff || event.controllerNumber() == MidiControllerAllNotesOff || event.controllerNumber() == MidiControllerOmniOn || event.controllerNumber() == MidiControllerOmniOff || event.controllerNumber() == MidiControllerMonoOn || event.controllerNumber() == MidiControllerPolyOn ) { silenceAllNotes(); } break; case MidiMetaEvent: // handle special cases such as note panning switch( event.metaEvent() ) { case MidiNotePanning: if( m_notes[event.key()] != nullptr ) { eventHandled = true; m_notes[event.key()]->setPanning( event.panning() ); } break; default: qWarning( "InstrumentTrack: unhandled MIDI meta event: %i", event.metaEvent() ); break; } break; default: break; } // If the event wasn't handled, check if there's a loaded instrument and if so send the // event to it. If it returns false means the instrument didn't handle the event, so we trigger a warning. if (eventHandled == false && !(instrument() && instrument()->handleMidiEvent(event, time, offset))) { qWarning("InstrumentTrack: unhandled MIDI event %d", event.type()); } } void InstrumentTrack::processOutEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset ) { // do nothing if we do not have an instrument instance (e.g. when loading settings) if( m_instrument == nullptr ) { return; } const MidiEvent transposedEvent = applyMasterKey( event ); const int key = transposedEvent.key(); // If we have a selected output midi channel between 1-16, we will use that channel to handle the midi event. // But if our selected midi output channel is 0 ("--"), we will use the event channel instead. const auto handleEventOutputChannel = midiPort()->outputChannel() == 0 ? event.channel() : midiPort()->realOutputChannel(); switch( event.type() ) { case MidiNoteOn: m_midiNotesMutex.lock(); m_piano.setKeyState( event.key(), true ); // event.key() = original key if( key >= 0 && key < NumKeys ) { if( m_runningMidiNotes[key] > 0 ) { m_instrument->handleMidiEvent( MidiEvent( MidiNoteOff, handleEventOutputChannel, key, 0 ), time, offset ); } ++m_runningMidiNotes[key]; m_instrument->handleMidiEvent( MidiEvent( MidiNoteOn, handleEventOutputChannel, key, event.velocity() ), time, offset ); } m_midiNotesMutex.unlock(); emit newNote(); break; case MidiNoteOff: m_midiNotesMutex.lock(); m_piano.setKeyState( event.key(), false ); // event.key() = original key if( key >= 0 && key < NumKeys && --m_runningMidiNotes[key] <= 0 ) { m_instrument->handleMidiEvent( MidiEvent( MidiNoteOff, handleEventOutputChannel, key, 0 ), time, offset ); } m_midiNotesMutex.unlock(); emit endNote(); break; default: m_instrument->handleMidiEvent( transposedEvent, time, offset ); break; } // if appropriate, midi-port does futher routing m_midiPort.processOutEvent( event, time ); } void InstrumentTrack::silenceAllNotes( bool removeIPH ) { m_midiNotesMutex.lock(); for( int i = 0; i < NumKeys; ++i ) { m_notes[i] = nullptr; m_runningMidiNotes[i] = 0; } m_midiNotesMutex.unlock(); Engine::audioEngine()->requestChangeInModel(); // invalidate all NotePlayHandles and PresetPreviewHandles linked to this track m_processHandles.clear(); auto flags = PlayHandle::Type::NotePlayHandle | PlayHandle::Type::PresetPreviewHandle; if( removeIPH ) { flags |= PlayHandle::Type::InstrumentPlayHandle; } Engine::audioEngine()->removePlayHandlesOfTypes( this, flags ); Engine::audioEngine()->doneChangeInModel(); } f_cnt_t InstrumentTrack::beatLen( NotePlayHandle * _n ) const { if( m_instrument != nullptr ) { const f_cnt_t len = m_instrument->beatLen( _n ); if( len > 0 ) { return len; } } return m_soundShaping.envFrames(); } void InstrumentTrack::playNote( NotePlayHandle* n, SampleFrame* workingBuffer ) { // Note: under certain circumstances the working buffer is a nullptr. // These cases are triggered in PlayHandle::doProcessing when the play method is called with a nullptr. // TODO: Find out if we can skip processing at a higher level if the buffer is nullptr. // arpeggio- and chord-widget has to do its work -> adding sub-notes // for chords/arpeggios m_noteStacking.processNote( n ); m_arpeggio.processNote( n ); if( n->isMasterNote() == false && m_instrument != nullptr ) { // all is done, so now lets play the note! m_instrument->playNote( n, workingBuffer ); // This is effectively the same as checking if workingBuffer is not a nullptr. // Calling processAudioBuffer with a nullptr leads to crashes. Hence the check. if (n->usesBuffer()) { const fpp_t frames = n->framesLeftForCurrentPeriod(); const f_cnt_t offset = n->noteOffset(); processAudioBuffer(workingBuffer, frames + offset, n); } } } QString InstrumentTrack::instrumentName() const { if( m_instrument != nullptr ) { return m_instrument->displayName(); } return QString(); } void InstrumentTrack::deleteNotePluginData( NotePlayHandle* n ) { if( m_instrument != nullptr ) { m_instrument->deleteNotePluginData( n ); } } void InstrumentTrack::setName( const QString & _new_name ) { Track::setName( _new_name ); m_midiPort.setName( name() ); m_audioPort.setName( name() ); } void InstrumentTrack::updateBaseNote() { Engine::audioEngine()->requestChangeInModel(); for (const auto& processHandle : m_processHandles) { processHandle->setFrequencyUpdate(); } Engine::audioEngine()->doneChangeInModel(); } void InstrumentTrack::updatePitch() { updateBaseNote(); processOutEvent( MidiEvent( MidiPitchBend, midiPort()->realOutputChannel(), midiPitch() ) ); } void InstrumentTrack::updatePitchRange() { const int r = m_pitchRangeModel.value(); m_pitchModel.setRange( MinPitchDefault * r, MaxPitchDefault * r ); processOutEvent( MidiEvent( MidiControlChange, midiPort()->realOutputChannel(), MidiControllerRegisteredParameterNumberLSB, MidiPitchBendSensitivityRPN & 0x7F ) ); processOutEvent( MidiEvent( MidiControlChange, midiPort()->realOutputChannel(), MidiControllerRegisteredParameterNumberMSB, ( MidiPitchBendSensitivityRPN >> 8 ) & 0x7F ) ); processOutEvent( MidiEvent( MidiControlChange, midiPort()->realOutputChannel(), MidiControllerDataEntry, midiPitchRange() ) ); } void InstrumentTrack::updateMixerChannel() { m_audioPort.setNextMixerChannel( m_mixerChannelModel.value() ); } int InstrumentTrack::masterKey( int _midi_key ) const { int key = baseNote(); return std::clamp(_midi_key - (key - DefaultKey), 0, NumKeys); } void InstrumentTrack::removeMidiPortNode( DataFile & _dataFile ) { QDomNodeList n = _dataFile.elementsByTagName( "midiport" ); n.item( 0 ).parentNode().removeChild( n.item( 0 ) ); } bool InstrumentTrack::play( const TimePos & _start, const fpp_t _frames, const f_cnt_t _offset, int _clip_num ) { if( ! m_instrument || ! tryLock() ) { return false; } const float frames_per_tick = Engine::framesPerTick(); clipVector clips; class PatternTrack * pattern_track = nullptr; if( _clip_num >= 0 ) { Clip * clip = getClip( _clip_num ); clips.push_back( clip ); if (trackContainer() == Engine::patternStore()) { pattern_track = PatternTrack::findPatternTrack(_clip_num); } } else { getClipsInRange( clips, _start, _start + static_cast<int>( _frames / frames_per_tick ) ); } // Handle automation: detuning for (const auto& processHandle : m_processHandles) { processHandle->processTimePos( _start, m_pitchModel.value(), gui::getGUI() && gui::getGUI()->pianoRoll()->isRecording()); } if ( clips.size() == 0 ) { unlock(); return false; } bool played_a_note = false; // will be return variable for (const auto& clip : clips) { auto c = dynamic_cast<MidiClip*>(clip); // everything which is not a MIDI clip won't be played // A MIDI clip playing in the Piano Roll window will always play if (c == nullptr || (Engine::getSong()->playMode() != Song::PlayMode::MidiClip && clip->isMuted())) { continue; } TimePos cur_start = _start; if( _clip_num < 0 ) { cur_start -= c->startPosition(); } // get all notes from the given clip... const NoteVector & notes = c->notes(); // ...and set our index to zero auto nit = notes.begin(); // very effective algorithm for playing notes that are // posated within the current sample-frame if( cur_start > 0 ) { // skip notes which are posated before start-bar while( nit != notes.end() && ( *nit )->pos() < cur_start ) { ++nit; } } while (nit != notes.end() && (*nit)->pos() == cur_start) { const auto currentNote = *nit; // If the note is a Step Note, frames will be 0 so the NotePlayHandle // plays for the whole length of the sample const auto noteFrames = currentNote->type() == Note::Type::Step ? 0 : currentNote->length().frames(frames_per_tick); NotePlayHandle* notePlayHandle = NotePlayHandleManager::acquire(this, _offset, noteFrames, *currentNote); notePlayHandle->setPatternTrack(pattern_track); // are we playing global song? if( _clip_num < 0 ) { // then set song-global offset of clip in order to // properly perform the note detuning notePlayHandle->setSongGlobalParentOffset( c->startPosition() ); } Engine::audioEngine()->addPlayHandle( notePlayHandle ); played_a_note = true; ++nit; } } unlock(); return played_a_note; } Clip* InstrumentTrack::createClip(const TimePos & pos) { auto p = new MidiClip(this); p->movePosition(pos); return p; } gui::TrackView* InstrumentTrack::createView( gui::TrackContainerView* tcv ) { return new gui::InstrumentTrackView( this, tcv ); } void InstrumentTrack::saveTrackSpecificSettings(QDomDocument& doc, QDomElement& thisElement, bool presetMode) { m_volumeModel.saveSettings( doc, thisElement, "vol" ); m_panningModel.saveSettings( doc, thisElement, "pan" ); m_pitchModel.saveSettings( doc, thisElement, "pitch" ); m_pitchRangeModel.saveSettings( doc, thisElement, "pitchrange" ); m_mixerChannelModel.saveSettings( doc, thisElement, "mixch" ); m_baseNoteModel.saveSettings( doc, thisElement, "basenote" ); m_firstKeyModel.saveSettings(doc, thisElement, "firstkey"); m_lastKeyModel.saveSettings(doc, thisElement, "lastkey"); m_useMasterPitchModel.saveSettings( doc, thisElement, "usemasterpitch"); m_microtuner.saveSettings(doc, thisElement); // Save MIDI CC stuff m_midiCCEnable->saveSettings(doc, thisElement, "enablecc"); QDomElement midiCC = doc.createElement("midicontrollers"); thisElement.appendChild(midiCC); for (int i = 0; i < MidiControllerCount; ++i) { m_midiCCModel[i]->saveSettings(doc, midiCC, "cc" + QString::number(i)); } if( m_instrument != nullptr ) { QDomElement i = doc.createElement( "instrument" ); i.setAttribute( "name", m_instrument->descriptor()->name ); QDomElement ins = m_instrument->saveState( doc, i ); if(m_instrument->key().isValid()) { ins.appendChild( m_instrument->key().saveXML( doc ) ); } thisElement.appendChild( i ); } m_soundShaping.saveState( doc, thisElement ); m_noteStacking.saveState( doc, thisElement ); m_arpeggio.saveState( doc, thisElement ); // Save the midi port info if we are not in song saving mode, e.g. in // track cloning mode or if we are in song saving mode and the user // has chosen not to discard the MIDI connections. if (!Engine::getSong()->isSavingProject() || !Engine::getSong()->getSaveOptions().discardMIDIConnections.value()) { // Don't save auto assigned midi device connection bool hasAuto = m_hasAutoMidiDev; autoAssignMidiDevice(false); // Only save the MIDI port information if we are not saving a preset. if (!presetMode) { m_midiPort.saveState(doc, thisElement); } autoAssignMidiDevice(hasAuto); } m_audioPort.effects()->saveState( doc, thisElement ); } void InstrumentTrack::loadTrackSpecificSettings( const QDomElement & thisElement ) { // don't delete instrument in preview mode if it's the same // we can't do this for other situations due to some issues with linked models bool reuseInstrument = m_previewMode && m_instrument && m_instrument->nodeName() == getSavedInstrumentName(thisElement); // remove the InstrumentPlayHandle if and only if we need to delete the instrument silenceAllNotes(!reuseInstrument); lock(); m_volumeModel.loadSettings( thisElement, "vol" ); m_panningModel.loadSettings( thisElement, "pan" ); m_pitchRangeModel.loadSettings( thisElement, "pitchrange" ); m_pitchModel.loadSettings( thisElement, "pitch" ); m_mixerChannelModel.setRange( 0, Engine::mixer()->numChannels()-1 ); if ( !m_previewMode ) { m_mixerChannelModel.loadSettings( thisElement, "mixch" ); } m_baseNoteModel.loadSettings( thisElement, "basenote" ); m_firstKeyModel.loadSettings(thisElement, "firstkey"); m_lastKeyModel.loadSettings(thisElement, "lastkey"); m_useMasterPitchModel.loadSettings( thisElement, "usemasterpitch"); m_microtuner.loadSettings(thisElement); // clear effect-chain just in case we load an old preset without FX-data m_audioPort.effects()->clear(); // We set MIDI CC enable to false so the knobs don't trigger MIDI CC events while // they are being loaded. After all knobs are loaded we load the right value of m_midiCCEnable. m_midiCCEnable->setValue(false); QDomNode node = thisElement.firstChild(); while( !node.isNull() ) { if( node.isElement() ) { if( m_soundShaping.nodeName() == node.nodeName() ) { m_soundShaping.restoreState( node.toElement() ); } else if( m_noteStacking.nodeName() == node.nodeName() ) { m_noteStacking.restoreState( node.toElement() ); } else if( m_arpeggio.nodeName() == node.nodeName() ) { m_arpeggio.restoreState( node.toElement() ); } else if( m_midiPort.nodeName() == node.nodeName() ) { m_midiPort.restoreState( node.toElement() ); } else if( m_audioPort.effects()->nodeName() == node.nodeName() ) { m_audioPort.effects()->restoreState( node.toElement() ); } else if(node.nodeName() == "instrument") { using PluginKey = Plugin::Descriptor::SubPluginFeatures::Key; PluginKey key(node.toElement().elementsByTagName("key").item(0).toElement()); if (reuseInstrument) { m_instrument->restoreState(node.firstChildElement()); } else { delete m_instrument; m_instrument = nullptr; m_instrument = Instrument::instantiate( node.toElement().attribute("name"), this, &key); m_instrument->restoreState(node.firstChildElement()); emit instrumentChanged(); } } else if (node.nodeName() == "midicontrollers") { for (int i = 0; i < MidiControllerCount; ++i) { m_midiCCModel[i]->loadSettings(node.toElement(), "cc" + QString::number(i)); } } // compat code - if node-name doesn't match any known // one, we assume that it is an instrument-plugin // which we'll try to load else if(AutomationClip::classNodeName() != node.nodeName() && ControllerConnection::classNodeName() != node.nodeName() && !node.toElement().hasAttribute( "id" )) { delete m_instrument; m_instrument = nullptr; m_instrument = Instrument::instantiate( node.nodeName(), this, nullptr, true); if (m_instrument->nodeName() == node.nodeName()) { m_instrument->restoreState(node.toElement()); } emit instrumentChanged(); } } node = node.nextSibling(); } // Load the right value of m_midiCCEnable m_midiCCEnable->loadSettings(thisElement, "enablecc"); updatePitchRange(); unlock(); } void InstrumentTrack::setPreviewMode( const bool value ) { m_previewMode = value; } void InstrumentTrack::replaceInstrument(DataFile dataFile) { // loadSettings clears the mixer channel, so we save it here and set it back later int mixerChannel = mixerChannelModel()->value(); InstrumentTrack::removeMidiPortNode(dataFile); //Replacing an instrument shouldn't change the solo/mute state. bool oldMute = isMuted(); bool oldSolo = isSolo(); bool oldMutedBeforeSolo = isMutedBeforeSolo(); loadPreset(dataFile.content().toElement()); setMuted(oldMute); setSolo(oldSolo); setMutedBeforeSolo(oldMutedBeforeSolo); m_mixerChannelModel.setValue(mixerChannel); Engine::getSong()->setModified(); } QString InstrumentTrack::getSavedInstrumentName(const QDomElement &thisElement) const { QDomElement elem = thisElement.firstChildElement("instrument"); if (!elem.isNull()) { return elem.attribute("name"); } return ""; } Instrument * InstrumentTrack::loadInstrument(const QString & _plugin_name, const Plugin::Descriptor::SubPluginFeatures::Key *key, bool keyFromDnd) { if(keyFromDnd) Q_ASSERT(!key); silenceAllNotes( true ); lock(); delete m_instrument; m_instrument = Instrument::instantiate(_plugin_name, this, key, keyFromDnd); unlock(); setName(m_instrument->displayName()); emit instrumentChanged(); return m_instrument; } InstrumentTrack *InstrumentTrack::s_autoAssignedTrack = nullptr; /*! \brief Automatically assign a midi controller to this track, based on the midiautoassign setting * * \param assign set to true to connect the midi device, set to false to disconnect */ void InstrumentTrack::autoAssignMidiDevice(bool assign) { if (assign) { if (s_autoAssignedTrack) { s_autoAssignedTrack->autoAssignMidiDevice(false); } s_autoAssignedTrack = this; } const QString &device = ConfigManager::inst()->value("midi", "midiautoassign"); if ( Engine::audioEngine()->midiClient()->isRaw() && device != "none" ) { m_midiPort.setReadable( assign ); return; } // Check if the device exists if ( Engine::audioEngine()->midiClient()->readablePorts().indexOf(device) >= 0 ) { m_midiPort.subscribeReadablePort(device, assign); m_hasAutoMidiDev = assign; } } } // namespace lmms
30,410
C++
.cpp
884
31.309955
127
0.716816
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,870
MidiClip.cpp
LMMS_lmms/src/tracks/MidiClip.cpp
/* * MidiClip.cpp - implementation of class MidiClip, which holds notes * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * Copyright (c) 2005-2007 Danny McRae <khjklujn/at/yahoo.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. * */ #include "MidiClip.h" #include <algorithm> #include <QDomElement> #include "GuiApplication.h" #include "InstrumentTrack.h" #include "MidiClipView.h" #include "PatternStore.h" #include "PianoRoll.h" namespace lmms { MidiClip::MidiClip( InstrumentTrack * _instrument_track ) : Clip( _instrument_track ), m_instrumentTrack( _instrument_track ), m_clipType( Type::BeatClip ), m_steps( TimePos::stepsPerBar() ) { if (_instrument_track->trackContainer() == Engine::patternStore()) { resizeToFirstTrack(); } init(); setAutoResize( true ); } MidiClip::MidiClip( const MidiClip& other ) : Clip( other.m_instrumentTrack ), m_instrumentTrack( other.m_instrumentTrack ), m_clipType( other.m_clipType ), m_steps( other.m_steps ) { for (const auto& note : other.m_notes) { m_notes.push_back(new Note(*note)); } init(); switch( getTrack()->trackContainer()->type() ) { case TrackContainer::Type::Pattern: setAutoResize( true ); break; case TrackContainer::Type::Song: // move down default: setAutoResize( false ); break; } } MidiClip::~MidiClip() { emit destroyedMidiClip( this ); for (const auto& note : m_notes) { delete note; } m_notes.clear(); } void MidiClip::resizeToFirstTrack() { // Resize this track to be the same as existing tracks in the pattern const TrackContainer::TrackList & tracks = m_instrumentTrack->trackContainer()->tracks(); for (const auto& track : tracks) { if (track->type() == Track::Type::Instrument) { if (track != m_instrumentTrack) { const auto& instrumentTrackClips = m_instrumentTrack->getClips(); const auto currentClipIt = std::find(instrumentTrackClips.begin(), instrumentTrackClips.end(), this); unsigned int currentClip = currentClipIt != instrumentTrackClips.end() ? std::distance(instrumentTrackClips.begin(), currentClipIt) : -1; m_steps = static_cast<MidiClip*>(track->getClip(currentClip))->m_steps; } break; } } } void MidiClip::init() { connect( Engine::getSong(), SIGNAL(timeSignatureChanged(int,int)), this, SLOT(changeTimeSignature())); saveJournallingState( false ); updateLength(); restoreJournallingState(); } void MidiClip::updateLength() { if( m_clipType == Type::BeatClip ) { changeLength( beatClipLength() ); updatePatternTrack(); return; } tick_t max_length = TimePos::ticksPerBar(); for (const auto& note : m_notes) { if (note->length() > 0) { max_length = std::max<tick_t>(max_length, note->endPos()); } } changeLength( TimePos( max_length ).nextFullBar() * TimePos::ticksPerBar() ); updatePatternTrack(); } TimePos MidiClip::beatClipLength() const { tick_t max_length = TimePos::ticksPerBar(); for (const auto& note : m_notes) { if (note->type() == Note::Type::Step) { max_length = std::max<tick_t>(max_length, note->pos() + 1); } } if (m_steps != TimePos::stepsPerBar()) { max_length = m_steps * TimePos::ticksPerBar() / TimePos::stepsPerBar(); } return TimePos{max_length}.nextFullBar() * TimePos::ticksPerBar(); } Note * MidiClip::addNote( const Note & _new_note, const bool _quant_pos ) { auto new_note = new Note(_new_note); if (_quant_pos && gui::getGUI()->pianoRoll()) { new_note->quantizePos(gui::getGUI()->pianoRoll()->quantization()); } instrumentTrack()->lock(); m_notes.insert(std::upper_bound(m_notes.begin(), m_notes.end(), new_note, Note::lessThan), new_note); instrumentTrack()->unlock(); checkType(); updateLength(); emit dataChanged(); return new_note; } NoteVector::const_iterator MidiClip::removeNote(NoteVector::const_iterator it) { instrumentTrack()->lock(); delete *it; auto new_it = m_notes.erase(it); instrumentTrack()->unlock(); checkType(); updateLength(); emit dataChanged(); return new_it; } NoteVector::const_iterator MidiClip::removeNote(Note* note) { instrumentTrack()->lock(); auto it = std::find(m_notes.begin(), m_notes.end(), note); if (it != m_notes.end()) { delete *it; it = m_notes.erase(it); } instrumentTrack()->unlock(); checkType(); updateLength(); emit dataChanged(); return it; } // Returns a pointer to the note at specified step, or nullptr if note doesn't exist Note * MidiClip::noteAtStep(int step) { for (const auto& note : m_notes) { if (note->pos() == TimePos::stepPosition(step) && note->type() == Note::Type::Step) { return note; } } return nullptr; } void MidiClip::rearrangeAllNotes() { // sort notes by start time std::sort(m_notes.begin(), m_notes.end(), Note::lessThan); } void MidiClip::clearNotes() { instrumentTrack()->lock(); for (const auto& note : m_notes) { delete note; } m_notes.clear(); instrumentTrack()->unlock(); checkType(); emit dataChanged(); } Note * MidiClip::addStepNote( int step ) { Note stepNote = Note(TimePos(DefaultTicksPerBar / 16), TimePos::stepPosition(step)); stepNote.setType(Note::Type::Step); return addNote(stepNote, false); } void MidiClip::setStep( int step, bool enabled ) { if( enabled ) { if ( !noteAtStep( step ) ) { addStepNote( step ); } return; } while( Note * note = noteAtStep( step ) ) { removeNote( note ); } } void MidiClip::splitNotes(const NoteVector& notes, TimePos pos) { if (notes.empty()) { return; } addJournalCheckPoint(); for (const auto& note : notes) { int leftLength = pos.getTicks() - note->pos(); int rightLength = note->length() - leftLength; // Split out of bounds if (leftLength <= 0 || rightLength <= 0) { continue; } // Reduce note length note->setLength(leftLength); // Add new note with the remaining length Note newNote = Note(*note); newNote.setLength(rightLength); newNote.setPos(note->pos() + leftLength); addNote(newNote, false); } } void MidiClip::setType( Type _new_clip_type ) { if( _new_clip_type == Type::BeatClip || _new_clip_type == Type::MelodyClip ) { m_clipType = _new_clip_type; } } void MidiClip::checkType() { // If all notes are StepNotes, we have a BeatClip const auto beatClip = std::all_of(m_notes.begin(), m_notes.end(), [](auto note) { return note->type() == Note::Type::Step; }); setType(beatClip ? Type::BeatClip : Type::MelodyClip); } void MidiClip::saveSettings( QDomDocument & _doc, QDomElement & _this ) { _this.setAttribute( "type", static_cast<int>(m_clipType) ); _this.setAttribute( "name", name() ); if (const auto& c = color()) { _this.setAttribute("color", c->name()); } // as the target of copied/dragged MIDI clip is always an existing // MIDI clip, we must not store actual position, instead we store -1 // which tells loadSettings() not to mess around with position if( _this.parentNode().nodeName() == "clipboard" || _this.parentNode().nodeName() == "dnddata" ) { _this.setAttribute( "pos", -1 ); } else { _this.setAttribute( "pos", startPosition() ); } _this.setAttribute( "muted", isMuted() ); _this.setAttribute( "steps", m_steps ); // now save settings of all notes for (auto& note : m_notes) { note->saveState(_doc, _this); } } void MidiClip::loadSettings( const QDomElement & _this ) { m_clipType = static_cast<Type>( _this.attribute( "type" ).toInt() ); setName( _this.attribute( "name" ) ); if (_this.hasAttribute("color")) { setColor(QColor{_this.attribute("color")}); } if( _this.attribute( "pos" ).toInt() >= 0 ) { movePosition( _this.attribute( "pos" ).toInt() ); } if (static_cast<bool>(_this.attribute("muted").toInt()) != isMuted()) { toggleMute(); } clearNotes(); QDomNode node = _this.firstChild(); while( !node.isNull() ) { if( node.isElement() && !node.toElement().attribute( "metadata" ).toInt() ) { auto n = new Note; n->restoreState( node.toElement() ); m_notes.push_back( n ); } node = node.nextSibling(); } m_steps = _this.attribute( "steps" ).toInt(); if( m_steps == 0 ) { m_steps = TimePos::stepsPerBar(); } checkType(); updateLength(); emit dataChanged(); } MidiClip * MidiClip::previousMidiClip() const { return adjacentMidiClipByOffset(-1); } MidiClip * MidiClip::nextMidiClip() const { return adjacentMidiClipByOffset(1); } MidiClip * MidiClip::adjacentMidiClipByOffset(int offset) const { auto& clips = m_instrumentTrack->getClips(); int clipNum = m_instrumentTrack->getClipNum(this) + offset; if (clipNum < 0 || static_cast<size_t>(clipNum) >= clips.size()) { return nullptr; } return dynamic_cast<MidiClip*>(clips[clipNum]); } void MidiClip::clear() { addJournalCheckPoint(); clearNotes(); } void MidiClip::addSteps() { m_steps += TimePos::stepsPerBar(); updateLength(); emit dataChanged(); } void MidiClip::cloneSteps() { int oldLength = m_steps; m_steps *= 2; // cloning doubles the track for(int i = 0; i < oldLength; ++i ) { Note *toCopy = noteAtStep( i ); if( toCopy ) { setStep( oldLength + i, true ); Note *newNote = noteAtStep( oldLength + i ); newNote->setKey( toCopy->key() ); newNote->setLength( toCopy->length() ); newNote->setPanning( toCopy->getPanning() ); newNote->setVolume( toCopy->getVolume() ); } } updateLength(); emit dataChanged(); } void MidiClip::removeSteps() { int n = TimePos::stepsPerBar(); if( n < m_steps ) { for( int i = m_steps - n; i < m_steps; ++i ) { setStep( i, false ); } m_steps -= n; updateLength(); emit dataChanged(); } } gui::ClipView * MidiClip::createView( gui::TrackView * _tv ) { return new gui::MidiClipView( this, _tv ); } void MidiClip::updatePatternTrack() { if (getTrack()->trackContainer() == Engine::patternStore()) { Engine::patternStore()->updatePatternTrack(this); } if (gui::getGUI() != nullptr && gui::getGUI()->pianoRoll() && gui::getGUI()->pianoRoll()->currentMidiClip() == this) { gui::getGUI()->pianoRoll()->update(); } } bool MidiClip::empty() { for (const auto& note : m_notes) { if (note->length() != 0) { return false; } } return true; } void MidiClip::changeTimeSignature() { TimePos last_pos = TimePos::ticksPerBar() - 1; for (const auto& note : m_notes) { if (note->length() < 0 && note->pos() > last_pos) { last_pos = note->pos() + TimePos::ticksPerBar() / TimePos::stepsPerBar(); } } last_pos = last_pos.nextFullBar() * TimePos::ticksPerBar(); m_steps = std::max<tick_t>(TimePos::stepsPerBar(), last_pos.getBar() * TimePos::stepsPerBar()); updateLength(); } } // namespace lmms
11,460
C++
.cpp
443
23.345372
127
0.692237
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,871
PatternTrack.cpp
LMMS_lmms/src/tracks/PatternTrack.cpp
/* * PatternTrack.cpp - a track representing a pattern in the PatternStore * * 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. * */ #include "PatternTrack.h" #include <QDomElement> #include "AudioEngine.h" #include "Engine.h" #include "PatternClip.h" #include "PatternStore.h" #include "PatternTrackView.h" #include "PlayHandle.h" namespace lmms { PatternTrack::infoMap PatternTrack::s_infoMap; PatternTrack::PatternTrack(TrackContainer* tc) : Track(Track::Type::Pattern, tc) { int patternNum = s_infoMap.size(); s_infoMap[this] = patternNum; setName(tr("Pattern %1").arg(patternNum)); Engine::patternStore()->createClipsForPattern(patternNum); Engine::patternStore()->setCurrentPattern(patternNum); Engine::patternStore()->updateComboBox(); connect( this, SIGNAL(nameChanged()), Engine::patternStore(), SLOT(updateComboBox())); } PatternTrack::~PatternTrack() { Engine::audioEngine()->removePlayHandlesOfTypes( this, PlayHandle::Type::NotePlayHandle | PlayHandle::Type::InstrumentPlayHandle | PlayHandle::Type::SamplePlayHandle ); const int pattern = s_infoMap[this]; Engine::patternStore()->removePattern(pattern); for( infoMap::iterator it = s_infoMap.begin(); it != s_infoMap.end(); ++it ) { if (it.value() > pattern) { --it.value(); } } s_infoMap.remove( this ); // remove us from the Song and update the pattern selection combobox to reflect the change trackContainer()->removeTrack( this ); Engine::patternStore()->updateComboBox(); } // play _frames frames of given Clip within starting with _start bool PatternTrack::play( const TimePos & _start, const fpp_t _frames, const f_cnt_t _offset, int _clip_num ) { if( isMuted() ) { return false; } if( _clip_num >= 0 ) { return Engine::patternStore()->play(_start, _frames, _offset, s_infoMap[this]); } clipVector clips; getClipsInRange( clips, _start, _start + static_cast<int>( _frames / Engine::framesPerTick() ) ); if( clips.size() == 0 ) { return false; } TimePos lastPosition; TimePos lastLength; tick_t lastOffset = 0; for (const auto& clip : clips) { if (!clip->isMuted() && clip->startPosition() >= lastPosition) { lastPosition = clip->startPosition(); lastLength = clip->length(); tick_t patternLength = Engine::patternStore()->lengthOfPattern(static_cast<PatternClip*>(clip)->patternIndex()) * TimePos::ticksPerBar(); lastOffset = patternLength - (clip->startTimeOffset() % patternLength); if (lastOffset == patternLength) { lastOffset = 0; } } } if( _start - lastPosition < lastLength ) { return Engine::patternStore()->play(_start - lastPosition + lastOffset, _frames, _offset, s_infoMap[this]); } return false; } gui::TrackView* PatternTrack::createView(gui::TrackContainerView* tcv) { return new gui::PatternTrackView(this, tcv); } Clip* PatternTrack::createClip(const TimePos & pos) { auto pc = new PatternClip(this); pc->movePosition(pos); return pc; } void PatternTrack::saveTrackSpecificSettings(QDomDocument& doc, QDomElement& _this, bool presetMode) { // _this.setAttribute( "icon", m_trackLabel->pixmapFile() ); /* _this.setAttribute( "current", s_infoMap[this] == engine::getPatternEditor()->currentPattern() );*/ if( s_infoMap[this] == 0 && _this.parentNode().parentNode().nodeName() != "clonedtrack" && _this.parentNode().parentNode().nodeName() != "journaldata" ) { Engine::patternStore()->saveState(doc, _this); } // If we are creating drag-n-drop data for Track::clone() only save pattern ID, not pattern content if (_this.parentNode().parentNode().nodeName() == "clonedtrack") { _this.setAttribute("sourcepattern", s_infoMap[this]); } } void PatternTrack::loadTrackSpecificSettings(const QDomElement& _this) { /* if( _this.attribute( "icon" ) != "" ) { m_trackLabel->setPixmapFile( _this.attribute( "icon" ) ); }*/ // If data was created by Track::clone(), do not add any tracks to the pattern(-editor) // instead create a new copy of the clip on each track if (_this.hasAttribute("sourcepattern")) { const int src = _this.attribute("sourcepattern").toInt(); const int dst = s_infoMap[this]; // copy clips of all tracks from source pattern (at bar "src") to destination // clips (which are created if they do not exist yet) for (const auto& track : Engine::patternStore()->tracks()) { Clip::copyStateTo(track->getClip(src), track->getClip(dst)); } setName( tr( "Clone of %1" ).arg( _this.parentNode().toElement().attribute( "name" ) ) ); } else { QDomNode node = _this.namedItem( TrackContainer::classNodeName() ); if( node.isElement() ) { Engine::patternStore()->restoreState(node.toElement()); } } /* doesn't work yet because PatternTrack-ctor also sets current pattern so if pattern tracks are created after this function is called, this doesn't help at all.... if( _this.attribute( "current" ).toInt() ) { engine::getPatternEditor()->setCurrentPattern( s_infoMap[this] ); }*/ } // return pointer to PatternTrack specified by pattern_num PatternTrack* PatternTrack::findPatternTrack(int pattern_num) { for( infoMap::iterator it = s_infoMap.begin(); it != s_infoMap.end(); ++it ) { if (it.value() == pattern_num) { return it.key(); } } return nullptr; } void PatternTrack::swapPatternTracks(Track* track1, Track* track2) { auto t1 = dynamic_cast<PatternTrack*>(track1); auto t2 = dynamic_cast<PatternTrack*>(track2); if( t1 != nullptr && t2 != nullptr ) { qSwap( s_infoMap[t1], s_infoMap[t2] ); Engine::patternStore()->swapPattern(s_infoMap[t1], s_infoMap[t2]); Engine::patternStore()->setCurrentPattern(s_infoMap[t1]); } } } // namespace lmms
6,541
C++
.cpp
199
30.286432
114
0.717329
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
19,872
SampleTrack.cpp
LMMS_lmms/src/tracks/SampleTrack.cpp
/* * SampleTrack.cpp - implementation of class SampleTrack, a track which * provides arrangement of samples * * 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. * */ #include "SampleTrack.h" #include <QDomElement> #include "EffectChain.h" #include "Mixer.h" #include "panning_constants.h" #include "PatternStore.h" #include "PatternTrack.h" #include "SampleClip.h" #include "SamplePlayHandle.h" #include "SampleRecordHandle.h" #include "SampleTrackView.h" #include "Song.h" #include "volume.h" namespace lmms { SampleTrack::SampleTrack(TrackContainer* tc) : Track(Track::Type::Sample, tc), m_volumeModel(DefaultVolume, MinVolume, MaxVolume, 0.1f, this, tr("Volume")), m_panningModel(DefaultPanning, PanningLeft, PanningRight, 0.1f, this, tr("Panning")), m_mixerChannelModel(0, 0, 0, this, tr("Mixer channel")), m_audioPort(tr("Sample track"), true, &m_volumeModel, &m_panningModel, &m_mutedModel), m_isPlaying(false) { setName(tr("Sample track")); m_panningModel.setCenterValue(DefaultPanning); m_mixerChannelModel.setRange(0, Engine::mixer()->numChannels()-1, 1); connect(&m_mixerChannelModel, SIGNAL(dataChanged()), this, SLOT(updateMixerChannel())); } SampleTrack::~SampleTrack() { Engine::audioEngine()->removePlayHandlesOfTypes( this, PlayHandle::Type::SamplePlayHandle ); } bool SampleTrack::play( const TimePos & _start, const fpp_t _frames, const f_cnt_t _offset, int _clip_num ) { m_audioPort.effects()->startRunning(); bool played_a_note = false; // will be return variable clipVector clips; class PatternTrack * pattern_track = nullptr; if( _clip_num >= 0 ) { if (_start > getClip(_clip_num)->length()) { setPlaying(false); } if( _start != 0 ) { return false; } clips.push_back( getClip( _clip_num ) ); if (trackContainer() == Engine::patternStore()) { pattern_track = PatternTrack::findPatternTrack(_clip_num); setPlaying(true); } } else { bool nowPlaying = false; for( int i = 0; i < numOfClips(); ++i ) { Clip * clip = getClip( i ); auto sClip = dynamic_cast<SampleClip*>(clip); if( _start >= sClip->startPosition() && _start < sClip->endPosition() ) { if( sClip->isPlaying() == false && _start >= (sClip->startPosition() + sClip->startTimeOffset()) ) { auto bufferFramesPerTick = Engine::framesPerTick(sClip->sample().sampleRate()); f_cnt_t sampleStart = bufferFramesPerTick * ( _start - sClip->startPosition() - sClip->startTimeOffset() ); f_cnt_t clipFrameLength = bufferFramesPerTick * ( sClip->endPosition() - sClip->startPosition() - sClip->startTimeOffset() ); f_cnt_t sampleBufferLength = sClip->sample().sampleSize(); //if the Clip smaller than the sample length we play only until Clip end //else we play the sample to the end but nothing more f_cnt_t samplePlayLength = clipFrameLength > sampleBufferLength ? sampleBufferLength : clipFrameLength; //we only play within the sampleBuffer limits if( sampleStart < sampleBufferLength ) { sClip->setSampleStartFrame( sampleStart ); sClip->setSamplePlayLength( samplePlayLength ); clips.push_back( sClip ); sClip->setIsPlaying( true ); nowPlaying = true; } } } else { sClip->setIsPlaying( false ); } nowPlaying = nowPlaying || sClip->isPlaying(); } setPlaying(nowPlaying); } for (const auto& clip : clips) { auto st = dynamic_cast<SampleClip*>(clip); if( !st->isMuted() ) { PlayHandle* handle; if( st->isRecord() ) { if( !Engine::getSong()->isRecording() ) { return played_a_note; } auto smpHandle = new SampleRecordHandle(st); handle = smpHandle; } else { auto smpHandle = new SamplePlayHandle(st); smpHandle->setVolumeModel( &m_volumeModel ); smpHandle->setPatternTrack(pattern_track); handle = smpHandle; } handle->setOffset( _offset ); // send it to the audio engine Engine::audioEngine()->addPlayHandle( handle ); played_a_note = true; } } return played_a_note; } gui::TrackView * SampleTrack::createView( gui::TrackContainerView* tcv ) { return new gui::SampleTrackView( this, tcv ); } Clip * SampleTrack::createClip(const TimePos & pos) { auto sClip = new SampleClip(this); sClip->movePosition(pos); return sClip; } void SampleTrack::saveTrackSpecificSettings(QDomDocument& _doc, QDomElement& _this, bool presetMode) { m_audioPort.effects()->saveState( _doc, _this ); m_volumeModel.saveSettings( _doc, _this, "vol" ); m_panningModel.saveSettings( _doc, _this, "pan" ); m_mixerChannelModel.saveSettings( _doc, _this, "mixch" ); } void SampleTrack::loadTrackSpecificSettings( const QDomElement & _this ) { QDomNode node = _this.firstChild(); m_audioPort.effects()->clear(); while( !node.isNull() ) { if( node.isElement() ) { if( m_audioPort.effects()->nodeName() == node.nodeName() ) { m_audioPort.effects()->restoreState( node.toElement() ); } } node = node.nextSibling(); } m_volumeModel.loadSettings( _this, "vol" ); m_panningModel.loadSettings( _this, "pan" ); m_mixerChannelModel.setRange( 0, Engine::mixer()->numChannels() - 1 ); m_mixerChannelModel.loadSettings( _this, "mixch" ); } void SampleTrack::updateClips() { Engine::audioEngine()->removePlayHandlesOfTypes( this, PlayHandle::Type::SamplePlayHandle ); setPlayingClips( false ); } void SampleTrack::setPlayingClips( bool isPlaying ) { for( int i = 0; i < numOfClips(); ++i ) { Clip * clip = getClip( i ); auto sClip = dynamic_cast<SampleClip*>(clip); sClip->setIsPlaying( isPlaying ); } } void SampleTrack::updateMixerChannel() { m_audioPort.setNextMixerChannel( m_mixerChannelModel.value() ); } } // namespace lmms
6,575
C++
.cpp
203
29.384236
130
0.70981
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,873
SideBarWidget.cpp
LMMS_lmms/src/gui/SideBarWidget.cpp
/* * SideBarWidget.cpp - implementation of base-widget for side-bar * * 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. * */ #include "SideBarWidget.h" #include <QFontMetrics> #include <QPainter> #include <QPushButton> #include "embed.h" #include "FontHelper.h" namespace lmms::gui { SideBarWidget::SideBarWidget( const QString & _title, const QPixmap & _icon, QWidget * _parent ) : QWidget( _parent ), m_title( _title ), m_icon(_icon), m_buttonSize(17, 17) { m_contents = new QWidget( this ); m_layout = new QVBoxLayout( m_contents ); m_layout->setSpacing( 5 ); m_layout->setContentsMargins(0, 0, 0, 0); m_closeBtn = new QPushButton(embed::getIconPixmap("close"), QString(), this); m_closeBtn->resize(m_buttonSize); m_closeBtn->setToolTip(tr("Close")); connect(m_closeBtn, &QPushButton::clicked, [=]() { this->closeButtonClicked(); }); } void SideBarWidget::paintEvent( QPaintEvent * ) { QPainter p( this ); p.fillRect( 0, 0, width(), 27, palette().highlight().color() ); QFont f = p.font(); f.setBold( true ); f.setUnderline(false); p.setFont(adjustedToPixelSize(f, LARGE_FONT_SIZE)); p.setPen( palette().highlightedText().color() ); const int tx = m_icon.width() + 8; QFontMetrics metrics( f ); const int ty = (metrics.ascent() + m_icon.height()) / 2; p.drawText( tx, ty, m_title ); p.drawPixmap( 2, 2, m_icon.transformed( QTransform().rotate( -90 ) ) ); } void SideBarWidget::resizeEvent( QResizeEvent * ) { const int MARGIN = 6; m_contents->setGeometry( MARGIN, 40 + MARGIN, width() - MARGIN * 2, height() - MARGIN * 2 - 40 ); m_closeBtn->move(m_contents->geometry().width() - MARGIN - 5, 5); } } // namespace lmms::gui
2,506
C++
.cpp
71
33.112676
78
0.713872
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,874
SampleWaveform.cpp
LMMS_lmms/src/gui/SampleWaveform.cpp
/* * SampleWaveform.cpp * * Copyright (c) 2023 saker <sakertooth@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. * */ #include "SampleWaveform.h" namespace lmms::gui { void SampleWaveform::visualize(Parameters parameters, QPainter& painter, const QRect& rect) { const int x = rect.x(); const int height = rect.height(); const int width = rect.width(); const int centerY = rect.center().y(); const int halfHeight = height / 2; const auto color = painter.pen().color(); const auto rmsColor = color.lighter(123); const float framesPerPixel = std::max(1.0f, static_cast<float>(parameters.size) / width); constexpr float maxFramesPerPixel = 512.0f; const float resolution = std::max(1.0f, framesPerPixel / maxFramesPerPixel); const float framesPerResolution = framesPerPixel / resolution; size_t numPixels = std::min(parameters.size, static_cast<size_t>(width)); auto min = std::vector<float>(numPixels, 1); auto max = std::vector<float>(numPixels, -1); auto squared = std::vector<float>(numPixels, 0); const size_t maxFrames = static_cast<size_t>(numPixels * framesPerPixel); auto pixelIndex = std::size_t{0}; for (auto i = std::size_t{0}; i < maxFrames; i += static_cast<std::size_t>(resolution)) { pixelIndex = i / framesPerPixel; const auto frameIndex = !parameters.reversed ? i : maxFrames - i; const auto& frame = parameters.buffer[frameIndex]; const auto value = frame.average(); if (value > max[pixelIndex]) { max[pixelIndex] = value; } if (value < min[pixelIndex]) { min[pixelIndex] = value; } squared[pixelIndex] += value * value; } if (pixelIndex < numPixels) { numPixels = pixelIndex; } for (auto i = std::size_t{0}; i < numPixels; i++) { const int lineY1 = centerY - max[i] * halfHeight * parameters.amplification; const int lineY2 = centerY - min[i] * halfHeight * parameters.amplification; const int lineX = static_cast<int>(i) + x; painter.drawLine(lineX, lineY1, lineX, lineY2); const float rms = std::sqrt(squared[i] / framesPerResolution); const float maxRMS = std::clamp(rms, min[i], max[i]); const float minRMS = std::clamp(-rms, min[i], max[i]); const int rmsLineY1 = centerY - maxRMS * halfHeight * parameters.amplification; const int rmsLineY2 = centerY - minRMS * halfHeight * parameters.amplification; painter.setPen(rmsColor); painter.drawLine(lineX, rmsLineY1, lineX, rmsLineY2); painter.setPen(color); } } } // namespace lmms::gui
3,197
C++
.cpp
75
40.173333
91
0.728475
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
19,875
SendButtonIndicator.cpp
LMMS_lmms/src/gui/SendButtonIndicator.cpp
#include "SendButtonIndicator.h" #include "embed.h" #include "Mixer.h" #include "MixerChannelView.h" #include "MixerView.h" namespace lmms::gui { SendButtonIndicator:: SendButtonIndicator(QWidget* parent, MixerChannelView* owner, MixerView* mv) : QLabel(parent), m_parent(owner), m_mv(mv) { // don't do any initializing yet, because the MixerView and MixerChannelView // that were passed to this constructor are not done with their constructors // yet. setPixmap(m_qpmOff); } void SendButtonIndicator::mousePressEvent(QMouseEvent* e) { Mixer* mix = Engine::mixer(); int from = m_mv->currentMixerChannel()->channelIndex(); int to = m_parent->channelIndex(); FloatModel* sendModel = mix->channelSendModel(from, to); if (sendModel == nullptr) { // not sending. create a mixer send. mix->createChannelSend(from, to); } else { // sending. delete the mixer send. mix->deleteChannelSend(from, to); } m_mv->updateMixerChannel(m_parent->channelIndex()); updateLightStatus(); } FloatModel* SendButtonIndicator::getSendModel() { Mixer* mix = Engine::mixer(); return mix->channelSendModel(m_mv->currentMixerChannel()->channelIndex(), m_parent->channelIndex()); } void SendButtonIndicator::updateLightStatus() { setPixmap(!getSendModel() ? m_qpmOff : m_qpmOn); } } // namespace lmms::gui
1,314
C++
.cpp
46
26.717391
101
0.75695
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
19,876
SampleTrackWindow.cpp
LMMS_lmms/src/gui/SampleTrackWindow.cpp
/* * SampleTrackWindow.cpp * * 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. * */ #include "SampleTrackWindow.h" #include <QCloseEvent> #include <QGridLayout> #include <QLabel> #include <QLineEdit> #include <QMenu> #include <QVBoxLayout> #include "EffectRackView.h" #include "embed.h" #include "GuiApplication.h" #include "Knob.h" #include "MainWindow.h" #include "MixerChannelLcdSpinBox.h" #include "SampleTrackView.h" #include "Song.h" #include "SubWindow.h" #include "TrackLabelButton.h" namespace lmms::gui { SampleTrackWindow::SampleTrackWindow(SampleTrackView * tv) : QWidget(), ModelView(nullptr, this), m_track(tv->model()), m_stv(tv) { #if QT_VERSION < 0x50C00 // Workaround for a bug in Qt versions below 5.12, // where argument-dependent-lookup fails for QFlags operators // declared inside a namepsace. // This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h // See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348 using ::operator|; #endif // init own layout + widgets setFocusPolicy(Qt::StrongFocus); auto vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(0, 0, 0, 0); vlayout->setSpacing(0); auto generalSettingsWidget = new QWidget(this); auto generalSettingsLayout = new QVBoxLayout(generalSettingsWidget); auto nameWidget = new QWidget(generalSettingsWidget); auto nameLayout = new QHBoxLayout(nameWidget); nameLayout->setContentsMargins(0, 0, 0, 0); nameLayout->setSpacing(2); // setup line edit for changing sample track name m_nameLineEdit = new QLineEdit; connect(m_nameLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); m_nameLineEdit->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred)); nameLayout->addWidget(m_nameLineEdit); generalSettingsLayout->addWidget(nameWidget); auto basicControlsLayout = new QGridLayout; basicControlsLayout->setHorizontalSpacing(3); basicControlsLayout->setVerticalSpacing(0); basicControlsLayout->setContentsMargins(0, 0, 0, 0); QString labelStyleSheet = "font-size: 10px;"; Qt::Alignment labelAlignment = Qt::AlignHCenter | Qt::AlignTop; Qt::Alignment widgetAlignment = Qt::AlignHCenter | Qt::AlignCenter; // set up volume knob m_volumeKnob = new Knob(KnobType::Bright26, nullptr, tr("Sample volume")); m_volumeKnob->setVolumeKnob(true); m_volumeKnob->setHintText(tr("Volume:"), "%"); basicControlsLayout->addWidget(m_volumeKnob, 0, 0); basicControlsLayout->setAlignment(m_volumeKnob, widgetAlignment); auto label = new QLabel(tr("VOL"), this); label->setStyleSheet(labelStyleSheet); basicControlsLayout->addWidget(label, 1, 0); basicControlsLayout->setAlignment(label, labelAlignment); // set up panning knob m_panningKnob = new Knob(KnobType::Bright26, nullptr, tr("Panning")); m_panningKnob->setHintText(tr("Panning:"), ""); basicControlsLayout->addWidget(m_panningKnob, 0, 1); basicControlsLayout->setAlignment(m_panningKnob, widgetAlignment); label = new QLabel(tr("PAN"),this); label->setStyleSheet(labelStyleSheet); basicControlsLayout->addWidget(label, 1, 1); basicControlsLayout->setAlignment(label, labelAlignment); basicControlsLayout->setColumnStretch(2, 1); // setup spinbox for selecting Mixer-channel m_mixerChannelNumber = new MixerChannelLcdSpinBox(2, nullptr, tr("Mixer channel"), m_stv); basicControlsLayout->addWidget(m_mixerChannelNumber, 0, 3); basicControlsLayout->setAlignment(m_mixerChannelNumber, widgetAlignment); label = new QLabel(tr("CHANNEL"), this); label->setStyleSheet(labelStyleSheet); basicControlsLayout->addWidget(label, 1, 3); basicControlsLayout->setAlignment(label, labelAlignment); generalSettingsLayout->addLayout(basicControlsLayout); m_effectRack = new EffectRackView(tv->model()->audioPort()->effects()); m_effectRack->setFixedSize(EffectRackView::DEFAULT_WIDTH, 242); vlayout->addWidget(generalSettingsWidget); vlayout->addWidget(m_effectRack); setModel(tv->model()); QMdiSubWindow * subWin = getGUI()->mainWindow()->addWindowedWidget(this); Qt::WindowFlags flags = subWin->windowFlags(); flags |= Qt::MSWindowsFixedSizeDialogHint; flags &= ~Qt::WindowMaximizeButtonHint; subWin->setWindowFlags(flags); // Hide the Size and Maximize options from the system menu // since the dialog size is fixed. QMenu * systemMenu = subWin->systemMenu(); systemMenu->actions().at(2)->setVisible(false); // Size systemMenu->actions().at(4)->setVisible(false); // Maximize subWin->setWindowIcon(embed::getIconPixmap("sample_track")); subWin->setFixedSize(subWin->size()); subWin->hide(); } void SampleTrackWindow::setSampleTrackView(SampleTrackView* tv) { if(m_stv && tv) { m_stv->m_tlb->setChecked(false); } m_stv = tv; } void SampleTrackWindow::modelChanged() { m_track = castModel<SampleTrack>(); m_nameLineEdit->setText(m_track->name()); m_track->disconnect(SIGNAL(nameChanged()), this); connect(m_track, SIGNAL(nameChanged()), this, SLOT(updateName())); m_volumeKnob->setModel(&m_track->m_volumeModel); m_panningKnob->setModel(&m_track->m_panningModel); m_mixerChannelNumber->setModel(&m_track->m_mixerChannelModel); updateName(); } void SampleTrackWindow::updateName() { setWindowTitle(m_track->name().length() > 25 ? (m_track->name().left(24) + "...") : m_track->name()); if(m_nameLineEdit->text() != m_track->name()) { m_nameLineEdit->setText(m_track->name()); } } void SampleTrackWindow::textChanged(const QString& new_name) { m_track->setName(new_name); Engine::getSong()->setModified(); } void SampleTrackWindow::toggleVisibility(bool on) { if(on) { show(); parentWidget()->show(); parentWidget()->raise(); } else { parentWidget()->hide(); } } void SampleTrackWindow::closeEvent(QCloseEvent* ce) { ce->ignore(); if(getGUI()->mainWindow()->workspace()) { parentWidget()->hide(); } else { hide(); } m_stv->m_tlb->setFocus(); m_stv->m_tlb->setChecked(false); } void SampleTrackWindow::saveSettings(QDomDocument& doc, QDomElement & element) { MainWindow::saveWidgetState(this, element); Q_UNUSED(element) } void SampleTrackWindow::loadSettings(const QDomElement& element) { MainWindow::restoreWidgetState(this, element); if(isVisible()) { m_stv->m_tlb->setChecked(true); } } } // namespace lmms::gui
7,132
C++
.cpp
203
32.950739
102
0.763711
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,877
EffectView.cpp
LMMS_lmms/src/gui/EffectView.cpp
/* * EffectView.cpp - view-component for an effect * * Copyright (c) 2006-2007 Danny McRae <khjklujn/at/users.sourceforge.net> * Copyright (c) 2007-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. * */ #include <QGraphicsOpacityEffect> #include <QLayout> #include <QMouseEvent> #include <QPushButton> #include <QPainter> #include "EffectView.h" #include "DummyEffect.h" #include "CaptionMenu.h" #include "embed.h" #include "GuiApplication.h" #include "FontHelper.h" #include "Knob.h" #include "LedCheckBox.h" #include "MainWindow.h" #include "SubWindow.h" #include "TempoSyncKnob.h" namespace lmms::gui { EffectView::EffectView( Effect * _model, QWidget * _parent ) : PluginView( _model, _parent ), m_bg( embed::getIconPixmap( "effect_plugin" ) ), m_subWindow( nullptr ), m_controlView(nullptr), m_dragging(false) { setFixedSize(EffectView::DEFAULT_WIDTH, EffectView::DEFAULT_HEIGHT); setFocusPolicy(Qt::StrongFocus); // Disable effects that are of type "DummyEffect" bool isEnabled = !dynamic_cast<DummyEffect *>( effect() ); m_bypass = new LedCheckBox( this, "", isEnabled ? LedCheckBox::LedColor::Green : LedCheckBox::LedColor::Red ); m_bypass->move( 3, 3 ); m_bypass->setEnabled( isEnabled ); m_bypass->setToolTip(tr("On/Off")); m_wetDry = new Knob( KnobType::Bright26, this ); m_wetDry->setLabel( tr( "W/D" ) ); m_wetDry->move( 40 - m_wetDry->width() / 2, 5 ); m_wetDry->setEnabled( isEnabled ); m_wetDry->setHintText( tr( "Wet Level:" ), "" ); m_autoQuit = new TempoSyncKnob( KnobType::Bright26, this ); m_autoQuit->setLabel( tr( "DECAY" ) ); m_autoQuit->move( 78 - m_autoQuit->width() / 2, 5 ); m_autoQuit->setEnabled( isEnabled && !effect()->m_autoQuitDisabled ); m_autoQuit->setHintText( tr( "Time:" ), "ms" ); m_gate = new Knob( KnobType::Bright26, this ); m_gate->setLabel( tr( "GATE" ) ); m_gate->move( 116 - m_gate->width() / 2, 5 ); m_gate->setEnabled( isEnabled && !effect()->m_autoQuitDisabled ); m_gate->setHintText( tr( "Gate:" ), "" ); setModel( _model ); if( effect()->controls()->controlCount() > 0 ) { auto ctls_btn = new QPushButton(tr("Controls"), this); QFont f = ctls_btn->font(); ctls_btn->setFont(adjustedToPixelSize(f, DEFAULT_FONT_SIZE)); ctls_btn->setGeometry( 150, 14, 50, 20 ); connect( ctls_btn, SIGNAL(clicked()), this, SLOT(editControls())); m_controlView = effect()->controls()->createView(); if( m_controlView ) { m_subWindow = getGUI()->mainWindow()->addWindowedWidget( m_controlView ); if ( !m_controlView->isResizable() ) { m_subWindow->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); if (m_subWindow->layout()) { m_subWindow->layout()->setSizeConstraint(QLayout::SetFixedSize); } } Qt::WindowFlags flags = m_subWindow->windowFlags(); flags &= ~Qt::WindowMaximizeButtonHint; m_subWindow->setWindowFlags( flags ); connect( m_controlView, SIGNAL(closed()), this, SLOT(closeEffects())); m_subWindow->hide(); } } m_opacityEffect = new QGraphicsOpacityEffect(this); m_opacityEffect->setOpacity(1); setGraphicsEffect(m_opacityEffect); //move above vst effect view creation //setModel( _model ); } EffectView::~EffectView() { delete m_subWindow; } void EffectView::editControls() { if( m_subWindow ) { if( !m_subWindow->isVisible() ) { m_subWindow->show(); m_subWindow->raise(); effect()->controls()->setViewVisible( true ); } else { m_subWindow->hide(); effect()->controls()->setViewVisible( false ); } } } void EffectView::moveUp() { emit movedUp(this); } void EffectView::moveDown() { emit movedDown(this); } void EffectView::deletePlugin() { emit deletedPlugin(this); } void EffectView::closeEffects() { if( m_subWindow ) { m_subWindow->hide(); } effect()->controls()->setViewVisible( false ); } void EffectView::contextMenuEvent( QContextMenuEvent * ) { QPointer<CaptionMenu> contextMenu = new CaptionMenu( model()->displayName(), this ); contextMenu->addAction( embed::getIconPixmap( "arp_up" ), tr( "Move &up" ), this, SLOT(moveUp())); contextMenu->addAction( embed::getIconPixmap( "arp_down" ), tr( "Move &down" ), this, SLOT(moveDown())); contextMenu->addSeparator(); contextMenu->addAction( embed::getIconPixmap( "cancel" ), tr( "&Remove this plugin" ), this, SLOT(deletePlugin())); contextMenu->addSeparator(); contextMenu->exec( QCursor::pos() ); delete contextMenu; } void EffectView::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton) { m_dragging = true; m_opacityEffect->setOpacity(0.3); QCursor c(Qt::SizeVerCursor); QApplication::setOverrideCursor(c); update(); } } void EffectView::mouseReleaseEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton) { m_dragging = false; m_opacityEffect->setOpacity(1); QApplication::restoreOverrideCursor(); update(); } } void EffectView::mouseMoveEvent(QMouseEvent* event) { if (!m_dragging) { return; } if (event->pos().y() < 0) { moveUp(); } else if (event->pos().y() > EffectView::DEFAULT_HEIGHT) { moveDown(); } } void EffectView::paintEvent( QPaintEvent * ) { QPainter p( this ); p.drawPixmap( 0, 0, m_bg ); QFont f = adjustedToPixelSize(font(), DEFAULT_FONT_SIZE); f.setBold( true ); p.setFont( f ); QString elidedText = p.fontMetrics().elidedText( model()->displayName(), Qt::ElideRight, width() - 22 ); p.setPen( palette().shadow().color() ); p.drawText( 6, 55, elidedText ); p.setPen( palette().text().color() ); p.drawText( 5, 54, elidedText ); } void EffectView::modelChanged() { m_bypass->setModel( &effect()->m_enabledModel ); m_wetDry->setModel( &effect()->m_wetDryModel ); m_autoQuit->setModel( &effect()->m_autoQuitModel ); m_gate->setModel( &effect()->m_gateModel ); } } // namespace lmms::gui
6,658
C++
.cpp
219
27.872146
111
0.702966
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
19,878
ActionGroup.cpp
LMMS_lmms/src/gui/ActionGroup.cpp
/* * ActionGroup.cpp - wrapper around QActionGroup to provide a more useful triggered(int) slot * * 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. * */ #include "ActionGroup.h" namespace lmms::gui { ActionGroup::ActionGroup(QObject* parent) : QActionGroup(parent) { connect(this, SIGNAL(triggered(QAction*)), this, SLOT(actionTriggered_(QAction*))); } QAction* ActionGroup::addAction(QAction* a) { a->setCheckable(true); return QActionGroup::addAction(a); } QAction* ActionGroup::addAction(const QString& text) { return addAction(new QAction(text, this)); } QAction* ActionGroup::addAction(const QIcon& icon, const QString& text) { return addAction(new QAction(icon, text, this)); } void ActionGroup::actionTriggered_(QAction* action) { Q_ASSERT(action != 0); Q_ASSERT(actions().contains(action)); emit triggered(actions().indexOf(action)); } } // namespace lmms::gui
1,681
C++
.cpp
50
31.84
93
0.759556
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,879
Lv2ViewBase.cpp
LMMS_lmms/src/gui/Lv2ViewBase.cpp
/* * Lv2ViewBase.cpp - base class for Lv2 plugin views * * 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. * */ #include "Lv2ViewBase.h" #ifdef LMMS_HAVE_LV2 #include <QGridLayout> #include <QPushButton> #include <QHBoxLayout> #include <QLabel> #include <lilv/lilv.h> #include <lv2/port-props/port-props.h> #include "AudioEngine.h" #include "Controls.h" #include "Engine.h" #include "GuiApplication.h" #include "embed.h" #include "FontHelper.h" #include "lmms_math.h" #include "Lv2ControlBase.h" #include "Lv2Manager.h" #include "Lv2Proc.h" #include "Lv2Ports.h" #include "MainWindow.h" #include "SubWindow.h" namespace lmms::gui { Lv2ViewProc::Lv2ViewProc(QWidget* parent, Lv2Proc* proc, int colNum) : LinkedModelGroupView (parent, proc, colNum) { class SetupTheWidget : public Lv2Ports::ConstVisitor { public: QWidget* m_parent; // input const LilvNode* m_commentUri; // input Control* m_control = nullptr; // output void visit(const Lv2Ports::Control& port) override { if (port.m_flow == Lv2Ports::Flow::Input) { using PortVis = Lv2Ports::Vis; switch (port.m_vis) { case PortVis::Generic: m_control = new KnobControl(m_parent); break; case PortVis::Integer: { sample_rate_t sr = Engine::audioEngine()->outputSampleRate(); auto pMin = port.min(sr); auto pMax = port.max(sr); int numDigits = std::max(numDigitsAsInt(pMin), numDigitsAsInt(pMax)); m_control = new LcdControl(numDigits, m_parent); break; } case PortVis::Enumeration: m_control = new ComboControl(m_parent); break; case PortVis::Toggled: m_control = new CheckControl(m_parent); break; } m_control->setText(port.name()); AutoLilvNodes props(lilv_port_get_value( port.m_plugin, port.m_port, m_commentUri)); LILV_FOREACH(nodes, itr, props.get()) { const LilvNode* nod = lilv_nodes_get(props.get(), itr); m_control->topWidget()->setToolTip(lilv_node_as_string(nod)); break; } } } }; AutoLilvNode commentUri = uri(LILV_NS_RDFS "comment"); proc->foreach_port( [this, &commentUri](const Lv2Ports::PortBase* port) { if(!lilv_port_has_property(port->m_plugin, port->m_port, uri(LV2_PORT_PROPS__notOnGUI).get())) { SetupTheWidget setup; setup.m_parent = this; setup.m_commentUri = commentUri.get(); port->accept(setup); if (setup.m_control) { addControl(setup.m_control, lilv_node_as_string(lilv_port_get_symbol( port->m_plugin, port->m_port)), port->name().toUtf8().data(), false); } } }); } AutoLilvNode Lv2ViewProc::uri(const char *uriStr) { return Engine::getLv2Manager()->uri(uriStr); } Lv2ViewBase::Lv2ViewBase(QWidget* meAsWidget, Lv2ControlBase *ctrlBase) : m_helpWindowEventFilter(this) { auto grid = new QGridLayout(meAsWidget); auto btnBox = new QHBoxLayout(); if (/* DISABLES CODE */ (false)) { m_reloadPluginButton = new QPushButton(QObject::tr("Reload Plugin"), meAsWidget); btnBox->addWidget(m_reloadPluginButton, 0); } if (/* DISABLES CODE */ (false)) // TODO: check if the plugin has the UI extension { m_toggleUIButton = new QPushButton(QObject::tr("Show GUI"), meAsWidget); m_toggleUIButton->setCheckable(true); m_toggleUIButton->setChecked(false); m_toggleUIButton->setIcon(embed::getIconPixmap("zoom")); m_toggleUIButton->setFont(adjustedToPixelSize(m_toggleUIButton->font(), SMALL_FONT_SIZE)); btnBox->addWidget(m_toggleUIButton, 0); } btnBox->addStretch(1); meAsWidget->setAcceptDrops(true); // note: the lifetime of C++ objects ends after the top expression in the // expression syntax tree, so the AutoLilvNode gets freed after the function // has been called AutoLilvNodes props(lilv_plugin_get_value(ctrlBase->getPlugin(), uri(LILV_NS_RDFS "comment").get())); LILV_FOREACH(nodes, itr, props.get()) { const LilvNode* node = lilv_nodes_get(props.get(), itr); auto infoLabel = new QLabel(QString(lilv_node_as_string(node)).trimmed() + "\n"); infoLabel->setWordWrap(true); infoLabel->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); m_helpButton = new QPushButton(QObject::tr("Help")); m_helpButton->setCheckable(true); btnBox->addWidget(m_helpButton); m_helpWindow = getGUI()->mainWindow()->addWindowedWidget(infoLabel); m_helpWindow->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_helpWindow->installEventFilter(&m_helpWindowEventFilter); m_helpWindow->setAttribute(Qt::WA_DeleteOnClose, false); m_helpWindow->hide(); break; } if (m_reloadPluginButton || m_toggleUIButton || m_helpButton) { grid->addLayout(btnBox, Rows::ButtonRow, 0, 1, m_colNum); } else { delete btnBox; } m_procView = new Lv2ViewProc(meAsWidget, ctrlBase->control(0), m_colNum); grid->addWidget(m_procView, Rows::ProcRow, 0); } Lv2ViewBase::~Lv2ViewBase() { closeHelpWindow(); // TODO: hide UI if required } void Lv2ViewBase::toggleUI() { } void Lv2ViewBase::toggleHelp(bool visible) { if (m_helpWindow) { if (visible) { m_helpWindow->show(); m_helpWindow->raise(); } else { m_helpWindow->hide(); } } } void Lv2ViewBase::closeHelpWindow() { if (m_helpWindow) { m_helpWindow->close(); } } void Lv2ViewBase::modelChanged(Lv2ControlBase *ctrlBase) { // reconnect models if (m_toggleUIButton) { m_toggleUIButton->setChecked(ctrlBase->hasGui()); } LinkedModelGroupsView::modelChanged(ctrlBase); } AutoLilvNode Lv2ViewBase::uri(const char *uriStr) { return Engine::getLv2Manager()->uri(uriStr); } void Lv2ViewBase::onHelpWindowClosed() { m_helpButton->setChecked(true); } HelpWindowEventFilter::HelpWindowEventFilter(Lv2ViewBase* viewBase) : m_viewBase(viewBase) {} bool HelpWindowEventFilter::eventFilter(QObject* , QEvent* event) { if (event->type() == QEvent::Close) { m_viewBase->m_helpButton->setChecked(false); return true; } return false; } } // namespace lmms::gui #endif // LMMS_HAVE_LV2
6,853
C++
.cpp
220
27.954545
92
0.72014
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,880
SampleLoader.cpp
LMMS_lmms/src/gui/SampleLoader.cpp
/* * SampleLoader.cpp - Static functions that open audio files * * Copyright (c) 2023 saker <sakertooth@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. * */ #include "SampleLoader.h" #include <QFileInfo> #include <QMessageBox> #include <memory> #include "ConfigManager.h" #include "FileDialog.h" #include "GuiApplication.h" #include "PathUtil.h" #include "SampleDecoder.h" #include "Song.h" namespace lmms::gui { QString SampleLoader::openAudioFile(const QString& previousFile) { auto openFileDialog = FileDialog(nullptr, QObject::tr("Open audio file")); auto dir = !previousFile.isEmpty() ? PathUtil::toAbsolute(previousFile) : ConfigManager::inst()->userSamplesDir(); // change dir to position of previously opened file openFileDialog.setDirectory(dir); openFileDialog.setFileMode(FileDialog::ExistingFiles); // set filters auto fileTypes = QStringList{}; auto allFileTypes = QStringList{}; auto nameFilters = QStringList{}; const auto& supportedAudioTypes = SampleDecoder::supportedAudioTypes(); for (const auto& audioType : supportedAudioTypes) { const auto name = QString::fromStdString(audioType.name); const auto extension = QString::fromStdString(audioType.extension); const auto displayExtension = QString{"*.%1"}.arg(extension); fileTypes.append(QString{"%1 (%2)"}.arg(FileDialog::tr("%1 files").arg(name), displayExtension)); allFileTypes.append(displayExtension); } nameFilters.append(QString{"%1 (%2)"}.arg(FileDialog::tr("All audio files"), allFileTypes.join(" "))); nameFilters.append(fileTypes); nameFilters.append(QString("%1 (*)").arg(FileDialog::tr("Other files"))); openFileDialog.setNameFilters(nameFilters); if (!previousFile.isEmpty()) { // select previously opened file openFileDialog.selectFile(QFileInfo{previousFile}.fileName()); } if (openFileDialog.exec() == QDialog::Accepted) { if (openFileDialog.selectedFiles().isEmpty()) { return ""; } return PathUtil::toShortestRelative(openFileDialog.selectedFiles()[0]); } return ""; } QString SampleLoader::openWaveformFile(const QString& previousFile) { return openAudioFile( previousFile.isEmpty() ? ConfigManager::inst()->factorySamplesDir() + "waveforms/10saw.flac" : previousFile); } std::shared_ptr<const SampleBuffer> SampleLoader::createBufferFromFile(const QString& filePath) { if (filePath.isEmpty()) { return SampleBuffer::emptyBuffer(); } try { return std::make_shared<SampleBuffer>(filePath); } catch (const std::runtime_error& error) { if (getGUI()) { displayError(QString::fromStdString(error.what())); } return SampleBuffer::emptyBuffer(); } } std::shared_ptr<const SampleBuffer> SampleLoader::createBufferFromBase64(const QString& base64, int sampleRate) { if (base64.isEmpty()) { return SampleBuffer::emptyBuffer(); } try { return std::make_shared<SampleBuffer>(base64, sampleRate); } catch (const std::runtime_error& error) { if (getGUI()) { displayError(QString::fromStdString(error.what())); } return SampleBuffer::emptyBuffer(); } } void SampleLoader::displayError(const QString& message) { QMessageBox::critical(nullptr, QObject::tr("Error loading sample"), message); } } // namespace lmms::gui
3,937
C++
.cpp
106
35.066038
115
0.761218
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
19,881
ControllerDialog.cpp
LMMS_lmms/src/gui/ControllerDialog.cpp
/* * ControllerDialog.cpp - per-controller-specific view for changing a * controller's settings * * Copyright (c) 2008 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. * */ #include <QCloseEvent> #include "ControllerDialog.h" #include "Controller.h" namespace lmms::gui { ControllerDialog::ControllerDialog( Controller * _controller, QWidget * _parent ) : QWidget( _parent ), ModelView( _controller, this ) { } void ControllerDialog::closeEvent( QCloseEvent * _ce ) { _ce->ignore(); emit closed(); } } // namespace lmms::gui
1,350
C++
.cpp
41
30.829268
70
0.735747
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,882
EffectRackView.cpp
LMMS_lmms/src/gui/EffectRackView.cpp
/* * EffectRackView.cpp - view for effectChain model * * Copyright (c) 2006-2007 Danny McRae <khjklujn@netscape.net> * 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. * */ #include <QApplication> #include <QAction> #include <QPushButton> #include <QScrollArea> #include <QVBoxLayout> #include "EffectRackView.h" #include "EffectSelectDialog.h" #include "EffectView.h" #include "GroupBox.h" namespace lmms::gui { EffectRackView::EffectRackView( EffectChain* model, QWidget* parent ) : QWidget( parent ), ModelView( nullptr, this ) { auto mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(5, 5, 5, 5); m_effectsGroupBox = new GroupBox( tr( "EFFECTS CHAIN" ) ); mainLayout->addWidget( m_effectsGroupBox ); auto effectsLayout = new QVBoxLayout(m_effectsGroupBox); effectsLayout->setSpacing( 0 ); effectsLayout->setContentsMargins( 2, m_effectsGroupBox->titleBarHeight() + 2, 2, 2 ); m_scrollArea = new QScrollArea; m_scrollArea->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn ); m_scrollArea->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_scrollArea->setPalette( QApplication::palette( m_scrollArea ) ); m_scrollArea->setFrameStyle( QFrame::NoFrame ); m_scrollArea->setWidget( new QWidget ); effectsLayout->addWidget( m_scrollArea ); auto addButton = new QPushButton; addButton->setText( tr( "Add effect" ) ); effectsLayout->addWidget( addButton ); connect( addButton, SIGNAL(clicked()), this, SLOT(addEffect())); m_lastY = 0; setModel( model ); } EffectRackView::~EffectRackView() { clearViews(); } void EffectRackView::clearViews() { while( m_effectViews.size() ) { EffectView * e = m_effectViews[m_effectViews.size() - 1]; m_effectViews.pop_back(); delete e; } } void EffectRackView::moveUp( EffectView* view ) { fxChain()->moveUp( view->effect() ); if( view != m_effectViews.first() ) { int i = 0; for( QVector<EffectView *>::Iterator it = m_effectViews.begin(); it != m_effectViews.end(); it++, i++ ) { if( *it == view ) { break; } } EffectView * temp = m_effectViews[ i - 1 ]; m_effectViews[i - 1] = view; m_effectViews[i] = temp; update(); } } void EffectRackView::moveDown( EffectView* view ) { if( view != m_effectViews.last() ) { // moving next effect up is the same moveUp( *( std::find( m_effectViews.begin(), m_effectViews.end(), view ) + 1 ) ); } } void EffectRackView::deletePlugin( EffectView* view ) { Effect * e = view->effect(); m_effectViews.erase( std::find( m_effectViews.begin(), m_effectViews.end(), view ) ); delete view; fxChain()->removeEffect( e ); e->deleteLater(); update(); } void EffectRackView::update() { QWidget * w = m_scrollArea->widget(); QVector<bool> view_map( qMax<int>( fxChain()->m_effects.size(), m_effectViews.size() ), false ); for (const auto& effect : fxChain()->m_effects) { int i = 0; for (const auto& effectView : m_effectViews) { if (effectView->model() == effect) { view_map[i] = true; break; } ++i; } if( i >= m_effectViews.size() ) { auto view = new EffectView(effect, w); connect(view, &EffectView::movedUp, this, &EffectRackView::moveUp); connect(view, &EffectView::movedDown, this, &EffectRackView::moveDown); connect(view, &EffectView::deletedPlugin, this, &EffectRackView::deletePlugin, Qt::QueuedConnection); QAction* moveUpAction = new QAction(view); moveUpAction->setShortcut(Qt::Key_Up | Qt::AltModifier); moveUpAction->setShortcutContext(Qt::WidgetShortcut); connect(moveUpAction, &QAction::triggered, view, &EffectView::moveUp); view->addAction(moveUpAction); QAction* moveDownAction = new QAction(view); moveDownAction->setShortcut(Qt::Key_Down | Qt::AltModifier); moveDownAction->setShortcutContext(Qt::WidgetShortcut); connect(moveDownAction, &QAction::triggered, view, &EffectView::moveDown); view->addAction(moveDownAction); view->show(); m_effectViews.append( view ); if( i < view_map.size() ) { view_map[i] = true; } else { view_map.append( true ); } } } int i = 0, nView = 0; const int EffectViewMargin = 3; m_lastY = EffectViewMargin; for( QVector<EffectView *>::Iterator it = m_effectViews.begin(); it != m_effectViews.end(); i++ ) { if( i < view_map.size() && view_map[i] == false ) { delete m_effectViews[nView]; it = m_effectViews.erase( it ); } else { ( *it )->move( EffectViewMargin, m_lastY ); m_lastY += ( *it )->height(); ++nView; ++it; } } w->setFixedSize(EffectView::DEFAULT_WIDTH + 2 * EffectViewMargin, m_lastY); QWidget::update(); } void EffectRackView::addEffect() { EffectSelectDialog esd( this ); esd.exec(); if( esd.result() == QDialog::Rejected ) { return; } Effect * fx = esd.instantiateSelectedPlugin( fxChain() ); fxChain()->appendEffect( fx ); update(); // Find the effectView, and show the controls for (const auto& effectView : m_effectViews) { if (effectView->effect() == fx) { effectView->editControls(); break; } } } void EffectRackView::modelChanged() { //clearViews(); m_effectsGroupBox->setModel( &fxChain()->m_enabledModel ); connect( fxChain(), SIGNAL(aboutToClear()), this, SLOT(clearViews())); update(); } QSize EffectRackView::sizeHint() const { // Use the formula from InstrumentTrackWindow.cpp return QSize{EffectRackView::DEFAULT_WIDTH, 254 /* INSTRUMENT_HEIGHT */ - 4 - 1}; } } // namespace lmms::gui
6,317
C++
.cpp
211
27.156398
104
0.706897
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,883
LmmsPalette.cpp
LMMS_lmms/src/gui/LmmsPalette.cpp
/* * LmmsPalette.cpp - dummy class for fetching palette qproperties from CSS * * * Copyright (c) 2007-2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi> * * 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. * */ #include <QApplication> #include <QStyle> #include "LmmsPalette.h" namespace lmms::gui { LmmsPalette::LmmsPalette( QWidget * parent, QStyle * stylearg ) : QWidget( parent ), /* sane defaults in case fetching from stylesheet fails*/ m_background( 91, 101, 113 ), m_windowText( 240, 240, 240 ), m_base( 128, 128, 128 ), m_text( 224, 224, 224 ), m_button( 201, 201, 201 ), m_shadow( 0,0,0 ), m_buttonText( 0,0,0 ), m_brightText( 74, 253, 133 ), m_highlight( 100, 100, 100 ), m_highlightedText( 255, 255, 255 ) { setStyle( stylearg ); stylearg->polish( this ); ensurePolished(); } #define ACCESSMET( read, write ) \ QColor LmmsPalette:: read () const \ { return m_##read ; } \ void LmmsPalette:: write ( const QColor & c ) \ { m_##read = QColor( c ); } ACCESSMET( background, setBackground ) ACCESSMET( windowText, setWindowText ) ACCESSMET( base, setBase ) ACCESSMET( text, setText ) ACCESSMET( button, setButton ) ACCESSMET( shadow, setShadow ) ACCESSMET( buttonText, setButtonText ) ACCESSMET( brightText, setBrightText ) ACCESSMET( highlight, setHighlight ) ACCESSMET( highlightedText, setHighlightedText ) QPalette LmmsPalette::palette() const { QPalette pal = QApplication::style()->standardPalette(); pal.setColor( QPalette::Window, background() ); pal.setColor( QPalette::WindowText, windowText() ); pal.setColor( QPalette::Base, base() ); pal.setColor( QPalette::ButtonText, buttonText() ); pal.setColor( QPalette::BrightText, brightText() ); pal.setColor( QPalette::Text, text() ); pal.setColor( QPalette::Button, button() ); pal.setColor( QPalette::Shadow, shadow() ); pal.setColor( QPalette::Highlight, highlight() ); pal.setColor( QPalette::HighlightedText, highlightedText() ); return pal; } } // namespace lmms::gui
2,793
C++
.cpp
78
33.435897
75
0.717835
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,884
ToolPluginView.cpp
LMMS_lmms/src/gui/ToolPluginView.cpp
/* * ToolPluginView.cpp - implementation of ToolPluginView * * Copyright (c) 2006-2008 Javier Serrano Polo <jasp00/at/users.sourceforge.net> * Copyright (c) 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. * */ #include "ToolPlugin.h" #include "ToolPluginView.h" #include <QIcon> #include "embed.h" #include "GuiApplication.h" #include "MainWindow.h" namespace lmms::gui { ToolPluginView::ToolPluginView( ToolPlugin * _toolPlugin ) : PluginView( _toolPlugin, nullptr ) { getGUI()->mainWindow()->addWindowedWidget( this ); parentWidget()->setAttribute( Qt::WA_DeleteOnClose, false ); setWindowTitle( _toolPlugin->displayName() ); setWindowIcon( _toolPlugin->descriptor()->logo->pixmap() ); } } // namespace lmms::gui
1,530
C++
.cpp
41
35.414634
80
0.758108
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,885
MidiCCRackView.cpp
LMMS_lmms/src/gui/MidiCCRackView.cpp
/* * MidiCCRackView.cpp - implementation of the MIDI CC rack widget * * Copyright (c) 2020 Ian Caio <iancaio_dev/at/hotmail.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. * */ #include "MidiCCRackView.h" #include <QGridLayout> #include <QScrollArea> #include <QVBoxLayout> #include <QWidget> #include "embed.h" #include "GroupBox.h" #include "GuiApplication.h" #include "InstrumentTrack.h" #include "Knob.h" #include "MainWindow.h" #include "SubWindow.h" namespace lmms::gui { MidiCCRackView::MidiCCRackView(InstrumentTrack * track) : QWidget(), m_track(track) { setWindowIcon(embed::getIconPixmap("midi_cc_rack")); setWindowTitle(tr("MIDI CC Rack - %1").arg(m_track->name())); QMdiSubWindow * subWin = getGUI()->mainWindow()->addWindowedWidget(this); // Remove maximize button Qt::WindowFlags flags = subWin->windowFlags(); flags &= ~Qt::WindowMaximizeButtonHint; subWin->setWindowFlags(flags); // Adjust window attributes, sizing and position subWin->setAttribute(Qt::WA_DeleteOnClose, false); subWin->resize(350, 300); subWin->setFixedWidth(350); subWin->setMinimumHeight(300); subWin->hide(); // Main window layout auto mainLayout = new QVBoxLayout(this); // Knobs GroupBox - Here we have the MIDI CC controller knobs for the selected track m_midiCCGroupBox = new GroupBox(tr("MIDI CC Knobs:")); // Layout to keep scrollable area under the GroupBox header auto knobsGroupBoxLayout = new QVBoxLayout(); knobsGroupBoxLayout->setContentsMargins(5, 16, 5, 5); m_midiCCGroupBox->setLayout(knobsGroupBoxLayout); // Scrollable area + widget + its layout that will have all the knobs auto knobsScrollArea = new QScrollArea(); auto knobsArea = new QWidget(); auto knobsAreaLayout = new QGridLayout(); knobsArea->setLayout(knobsAreaLayout); knobsScrollArea->setWidget(knobsArea); knobsScrollArea->setWidgetResizable(true); knobsGroupBoxLayout->addWidget(knobsScrollArea); // Adds the controller knobs for (int i = 0; i < MidiControllerCount; ++i) { m_controllerKnob[i] = new Knob(KnobType::Bright26); m_controllerKnob[i]->setLabel(tr("CC %1").arg(i)); knobsAreaLayout->addWidget(m_controllerKnob[i], i/4, i%4); } // Set all the models // Set the LED button to enable/disable the track midi cc m_midiCCGroupBox->setModel(m_track->m_midiCCEnable.get()); // Set the model for each Knob for (int i = 0; i < MidiControllerCount; ++i) { m_controllerKnob[i]->setModel(m_track->m_midiCCModel[i].get()); } // Connection to update the name of the track on the label connect(m_track, SIGNAL(nameChanged()), this, SLOT(renameWindow())); // Adding everything to the main layout mainLayout->addWidget(m_midiCCGroupBox); } MidiCCRackView::~MidiCCRackView() { if(parentWidget()) { parentWidget()->hide(); parentWidget()->deleteLater(); } } void MidiCCRackView::renameWindow() { setWindowTitle(tr("MIDI CC Rack - %1").arg(m_track->name())); } void MidiCCRackView::saveSettings(QDomDocument & doc, QDomElement & parent) { } void MidiCCRackView::loadSettings(const QDomElement &) { } } // namespace lmms::gui
3,826
C++
.cpp
110
32.745455
85
0.755694
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,886
ControllerRackView.cpp
LMMS_lmms/src/gui/ControllerRackView.cpp
/* * ControllerRackView.cpp - view for song's controllers * * Copyright (c) 2008-2009 Paul Giblock <drfaygo/at/gmail.com> * Copyright (c) 2010-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. * */ #include <QApplication> #include <QAction> #include <QPushButton> #include <QScrollArea> #include <QMessageBox> #include <QVBoxLayout> #include "Song.h" #include "embed.h" #include "GuiApplication.h" #include "MainWindow.h" #include "ControllerRackView.h" #include "ControllerView.h" #include "LfoController.h" #include "SubWindow.h" namespace lmms::gui { ControllerRackView::ControllerRackView() : QWidget(), m_nextIndex(0) { setWindowIcon( embed::getIconPixmap( "controller" ) ); setWindowTitle( tr( "Controller Rack" ) ); m_scrollArea = new QScrollArea( this ); m_scrollArea->setPalette( QApplication::palette( m_scrollArea ) ); m_scrollArea->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); auto scrollAreaWidget = new QWidget(m_scrollArea); m_scrollAreaLayout = new QVBoxLayout( scrollAreaWidget ); m_scrollAreaLayout->addStretch(); scrollAreaWidget->setLayout( m_scrollAreaLayout ); m_scrollArea->setWidget( scrollAreaWidget ); m_scrollArea->setWidgetResizable( true ); m_addButton = new QPushButton( this ); m_addButton->setText( tr( "Add" ) ); connect( m_addButton, SIGNAL(clicked()), this, SLOT(addController())); Song * song = Engine::getSong(); connect(song, &Song::controllerAdded, this, qOverload<Controller*>(&ControllerRackView::addController)); connect(song, &Song::controllerRemoved, this, &ControllerRackView::removeController); auto layout = new QVBoxLayout(); layout->addWidget( m_scrollArea ); layout->addWidget( m_addButton ); this->setLayout( layout ); QMdiSubWindow * subWin = getGUI()->mainWindow()->addWindowedWidget( this ); // No maximize button Qt::WindowFlags flags = subWin->windowFlags(); flags &= ~Qt::WindowMaximizeButtonHint; subWin->setWindowFlags( flags ); subWin->setAttribute( Qt::WA_DeleteOnClose, false ); subWin->move( 680, 310 ); subWin->resize( 350, 200 ); subWin->setFixedWidth( 350 ); subWin->setMinimumHeight( 200 ); } void ControllerRackView::saveSettings( QDomDocument & _doc, QDomElement & _this ) { MainWindow::saveWidgetState( this, _this ); } void ControllerRackView::loadSettings( const QDomElement & _this ) { MainWindow::restoreWidgetState( this, _this ); } void ControllerRackView::deleteController( ControllerView * _view ) { Controller * c = _view->getController(); if( c->connectionCount() > 0 ) { QMessageBox msgBox; msgBox.setIcon( QMessageBox::Question ); msgBox.setWindowTitle( tr("Confirm Delete") ); msgBox.setText( tr("Confirm delete? There are existing connection(s) " "associated with this controller. There is no way to undo.") ); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); if( msgBox.exec() != QMessageBox::Ok ) { return; } } Song * song = Engine::getSong(); song->removeController( c ); } void ControllerRackView::moveUp(ControllerView* view) { if (view == m_controllerViews.first()) { return; } const auto storedView = std::find(m_controllerViews.begin(), m_controllerViews.end(), view); assert(storedView != m_controllerViews.end()); const auto index = std::distance(m_controllerViews.begin(), storedView); std::swap(m_controllerViews[index - 1], m_controllerViews[index]); m_scrollAreaLayout->removeWidget(view); m_scrollAreaLayout->insertWidget(index - 1, view); } void ControllerRackView::moveDown(ControllerView* view) { if (view == m_controllerViews.last()) { return; } const auto storedView = std::find(m_controllerViews.begin(), m_controllerViews.end(), view); assert(storedView != m_controllerViews.end()); moveUp(*std::next(storedView)); } void ControllerRackView::addController(Controller* controller) { QWidget * scrollAreaWidget = m_scrollArea->widget(); auto controllerView = new ControllerView(controller, scrollAreaWidget); connect(controllerView, &ControllerView::movedUp, this, &ControllerRackView::moveUp); connect(controllerView, &ControllerView::movedDown, this, &ControllerRackView::moveDown); connect(controllerView, &ControllerView::removedController, this, &ControllerRackView::deleteController, Qt::QueuedConnection); auto moveUpAction = new QAction(controllerView); moveUpAction->setShortcut(Qt::Key_Up | Qt::AltModifier); moveUpAction->setShortcutContext(Qt::WidgetShortcut); connect(moveUpAction, &QAction::triggered, controllerView, &ControllerView::moveUp); controllerView->addAction(moveUpAction); auto moveDownAction = new QAction(controllerView); moveDownAction->setShortcut(Qt::Key_Down | Qt::AltModifier); moveDownAction->setShortcutContext(Qt::WidgetShortcut); connect(moveDownAction, &QAction::triggered, controllerView, &ControllerView::moveDown); controllerView->addAction(moveDownAction); m_controllerViews.append( controllerView ); m_scrollAreaLayout->insertWidget( m_nextIndex, controllerView ); ++m_nextIndex; } void ControllerRackView::removeController(Controller* removedController) { ControllerView * viewOfRemovedController = 0; QVector<ControllerView *>::const_iterator end = m_controllerViews.end(); for ( QVector<ControllerView *>::const_iterator it = m_controllerViews.begin(); it != end; ++it) { ControllerView *currentControllerView = *it; if ( currentControllerView->getController() == removedController ) { viewOfRemovedController = currentControllerView; break; } } if (viewOfRemovedController ) { m_controllerViews.erase( std::find( m_controllerViews.begin(), m_controllerViews.end(), viewOfRemovedController ) ); delete viewOfRemovedController; --m_nextIndex; } } void ControllerRackView::addController() { // TODO: Eventually let the user pick from available controller types Engine::getSong()->addController( new LfoController( Engine::getSong() ) ); // fix bug which always made ControllerRackView loose focus when adding // new controller setFocus(); } void ControllerRackView::closeEvent( QCloseEvent * _ce ) { if( parentWidget() ) { parentWidget()->hide(); } else { hide(); } _ce->ignore(); } } // namespace lmms::gui
7,000
C++
.cpp
185
35.540541
128
0.764514
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,887
AudioDeviceSetupWidget.cpp
LMMS_lmms/src/gui/AudioDeviceSetupWidget.cpp
/* * AudioDeviceSetupWidget.cpp - Base class for audio device setup widgets * * Copyright (c) 2004-2015 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. * */ #include "AudioDeviceSetupWidget.h" namespace lmms::gui { AudioDeviceSetupWidget::AudioDeviceSetupWidget(const QString & caption, QWidget * parent) : QGroupBox(QGroupBox::tr("Settings for %1").arg(tr(caption.toUtf8())), parent) { } void AudioDeviceSetupWidget::show() { parentWidget()->show(); QWidget::show(); } } // namespace lmms::gui
1,298
C++
.cpp
36
34.222222
91
0.759745
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,888
MainWindow.cpp
LMMS_lmms/src/gui/MainWindow.cpp
/* * MainWindow.cpp - implementation of LMMS-main-window * * 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. * */ #include "MainWindow.h" #include <QApplication> #include <QCloseEvent> #include <QDesktopServices> #include <QDomElement> #include <QFileInfo> #include <QMdiArea> #include <QMenuBar> #include <QMessageBox> #include <QShortcut> #include <QSplitter> #include "AboutDialog.h" #include "AutomationEditor.h" #include "ControllerRackView.h" #include "embed.h" #include "Engine.h" #include "ExportProjectDialog.h" #include "FileBrowser.h" #include "FileDialog.h" #include "Metronome.h" #include "MixerView.h" #include "GuiApplication.h" #include "ImportFilter.h" #include "InstrumentTrackView.h" #include "InstrumentTrackWindow.h" #include "MicrotunerConfig.h" #include "PatternEditor.h" #include "PianoRoll.h" #include "PianoView.h" #include "PluginBrowser.h" #include "PluginFactory.h" #include "PluginView.h" #include "ProjectJournal.h" #include "ProjectNotes.h" #include "ProjectRenderer.h" #include "RecentProjectsMenu.h" #include "RemotePlugin.h" #include "SetupDialog.h" #include "SideBar.h" #include "SongEditor.h" #include "SubWindow.h" #include "TemplatesMenu.h" #include "TextFloat.h" #include "TimeLineWidget.h" #include "ToolButton.h" #include "ToolPlugin.h" #include "VersionedSaveDialog.h" #include "lmmsversion.h" namespace lmms::gui { MainWindow::MainWindow() : m_workspace( nullptr ), m_toolsMenu( nullptr ), m_autoSaveTimer( this ), m_viewMenu( nullptr ), m_metronomeToggle( 0 ), m_session( SessionState::Normal ) { setAttribute( Qt::WA_DeleteOnClose ); auto main_widget = new QWidget(this); auto vbox = new QVBoxLayout(main_widget); vbox->setSpacing( 0 ); vbox->setContentsMargins(0, 0, 0, 0); auto w = new QWidget(main_widget); auto hbox = new QHBoxLayout(w); hbox->setSpacing( 0 ); hbox->setContentsMargins(0, 0, 0, 0); auto sideBar = new SideBar(Qt::Vertical, w); auto splitter = new QSplitter(Qt::Horizontal, w); splitter->setChildrenCollapsible( false ); ConfigManager* confMgr = ConfigManager::inst(); bool sideBarOnRight = confMgr->value("ui", "sidebaronright").toInt(); emit initProgress(tr("Preparing plugin browser")); sideBar->appendTab( new PluginBrowser( splitter ) ); emit initProgress(tr("Preparing file browsers")); sideBar->appendTab( new FileBrowser( confMgr->userProjectsDir() + "*" + confMgr->factoryProjectsDir(), "*.mmp *.mmpz *.xml *.mid *.mpt", tr( "My Projects" ), embed::getIconPixmap( "project_file" ).transformed( QTransform().rotate( 90 ) ), splitter, false, confMgr->userProjectsDir(), confMgr->factoryProjectsDir())); sideBar->appendTab( new FileBrowser(confMgr->userSamplesDir() + "*" + confMgr->factorySamplesDir(), FileItem::defaultFilters(), tr("My Samples"), embed::getIconPixmap("sample_file").transformed(QTransform().rotate(90)), splitter, false, confMgr->userSamplesDir(), confMgr->factorySamplesDir())); sideBar->appendTab( new FileBrowser( confMgr->userPresetsDir() + "*" + confMgr->factoryPresetsDir(), "*.xpf *.cs.xml *.xiz *.lv2", tr( "My Presets" ), embed::getIconPixmap( "preset_file" ).transformed( QTransform().rotate( 90 ) ), splitter , false, confMgr->userPresetsDir(), confMgr->factoryPresetsDir())); sideBar->appendTab(new FileBrowser(QDir::homePath(), FileItem::defaultFilters(), tr("My Home"), embed::getIconPixmap("home").transformed(QTransform().rotate(90)), splitter, false)); QStringList root_paths; QString title = tr("Root Directory"); bool dirs_as_items = false; #ifdef LMMS_BUILD_APPLE title = tr( "Volumes" ); root_paths += "/Volumes"; #elif defined(LMMS_BUILD_WIN32) title = tr( "My Computer" ); dirs_as_items = true; #endif #if ! defined(LMMS_BUILD_APPLE) QFileInfoList drives = QDir::drives(); for( const QFileInfo & drive : drives ) { root_paths += drive.absolutePath(); } #endif sideBar->appendTab(new FileBrowser(root_paths.join("*"), FileItem::defaultFilters(), title, embed::getIconPixmap("computer").transformed(QTransform().rotate(90)), splitter, dirs_as_items)); m_workspace = new QMdiArea(splitter); // Load background emit initProgress(tr("Loading background picture")); QString backgroundPicFile = ConfigManager::inst()->backgroundPicFile(); QImage backgroundPic; if( !backgroundPicFile.isEmpty() ) { backgroundPic = QImage( backgroundPicFile ); } if( !backgroundPicFile.isNull() ) { m_workspace->setBackground( backgroundPic ); } else { m_workspace->setBackground( Qt::NoBrush ); } m_workspace->setOption( QMdiArea::DontMaximizeSubWindowOnActivation ); m_workspace->setHorizontalScrollBarPolicy( Qt::ScrollBarAsNeeded ); m_workspace->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded ); hbox->addWidget(sideBar); hbox->addWidget(splitter); // If the user wants the sidebar on the right, we move the workspace and // the splitter to the "left" side, or the first widgets in their list if (sideBarOnRight) { splitter->insertWidget(0, m_workspace); hbox->insertWidget(0, splitter); } // create global-toolbar at the top of our window m_toolBar = new QWidget( main_widget ); m_toolBar->setObjectName( "mainToolbar" ); m_toolBar->setFixedHeight( 64 ); m_toolBar->move( 0, 0 ); // add layout for organizing quite complex toolbar-layouting m_toolBarLayout = new QGridLayout( m_toolBar/*, 2, 1*/ ); m_toolBarLayout->setContentsMargins(0, 0, 0, 0); m_toolBarLayout->setSpacing( 0 ); vbox->addWidget( m_toolBar ); vbox->addWidget( w ); setCentralWidget( main_widget ); m_updateTimer.start( 1000 / 60, this ); // 60 fps if( ConfigManager::inst()->value( "ui", "enableautosave" ).toInt() ) { // connect auto save connect(&m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSave())); m_autoSaveInterval = ConfigManager::inst()->value( "ui", "saveinterval" ).toInt() < 1 ? DEFAULT_AUTO_SAVE_INTERVAL : ConfigManager::inst()->value( "ui", "saveinterval" ).toInt(); // The auto save function mustn't run until there is a project // to save or it will run over recover.mmp if you hesitate at the // recover messagebox for a minute. It is now started in main. // See autoSaveTimerReset() in MainWindow.h } connect( Engine::getSong(), SIGNAL(playbackStateChanged()), this, SLOT(updatePlayPauseIcons())); connect(Engine::getSong(), SIGNAL(modified()), SLOT(onSongModified())); connect(Engine::getSong(), SIGNAL(projectFileNameChanged()), SLOT(onProjectFileNameChanged())); maximized = isMaximized(); new QShortcut(QKeySequence(Qt::Key_F11), this, SLOT(toggleFullscreen())); if (ConfigManager::inst()->value("tooltips", "disabled").toInt()) { qApp->installEventFilter(this); } } MainWindow::~MainWindow() { for( PluginView *view : m_tools ) { delete view->model(); delete view; } // TODO: Close tools // dependencies are such that the editors must be destroyed BEFORE Song is deletect in Engine::destroy // see issue #2015 on github delete getGUI()->automationEditor(); delete getGUI()->pianoRoll(); delete getGUI()->songEditor(); // destroy engine which will do further cleanups etc. Engine::destroy(); } void MainWindow::finalize() { resetWindowTitle(); setWindowIcon( embed::getIconPixmap( "icon_small" ) ); // project-popup-menu auto project_menu = new QMenu(this); menuBar()->addMenu( project_menu )->setText( tr( "&File" ) ); project_menu->addAction( embed::getIconPixmap( "project_new" ), tr( "&New" ), this, SLOT(createNewProject()), QKeySequence::New ); auto templates_menu = new TemplatesMenu( this ); project_menu->addMenu(templates_menu); project_menu->addAction( embed::getIconPixmap( "project_open" ), tr( "&Open..." ), this, SLOT(openProject()), QKeySequence::Open ); project_menu->addMenu(new RecentProjectsMenu(this)); project_menu->addAction( embed::getIconPixmap( "project_save" ), tr( "&Save" ), this, SLOT(saveProject()), QKeySequence::Save ); project_menu->addAction( embed::getIconPixmap( "project_save" ), tr( "Save &As..." ), this, SLOT(saveProjectAs()), Qt::CTRL + Qt::SHIFT + Qt::Key_S ); project_menu->addAction( embed::getIconPixmap( "project_save" ), tr( "Save as New &Version" ), this, SLOT(saveProjectAsNewVersion()), Qt::CTRL + Qt::ALT + Qt::Key_S ); project_menu->addAction( embed::getIconPixmap( "project_save" ), tr( "Save as default template" ), this, SLOT(saveProjectAsDefaultTemplate())); project_menu->addSeparator(); project_menu->addAction( embed::getIconPixmap( "project_import" ), tr( "Import..." ), this, SLOT(onImportProject())); project_menu->addAction( embed::getIconPixmap( "project_export" ), tr( "E&xport..." ), this, SLOT(onExportProject()), Qt::CTRL + Qt::Key_E ); project_menu->addAction( embed::getIconPixmap( "project_export" ), tr( "E&xport Tracks..." ), this, SLOT(onExportProjectTracks()), Qt::CTRL + Qt::SHIFT + Qt::Key_E ); project_menu->addAction( embed::getIconPixmap( "midi_file" ), tr( "Export &MIDI..." ), this, SLOT(onExportProjectMidi()), Qt::CTRL + Qt::Key_M ); project_menu->addSeparator(); project_menu->addAction( embed::getIconPixmap( "exit" ), tr( "&Quit" ), qApp, SLOT(closeAllWindows()), Qt::CTRL + Qt::Key_Q ); auto edit_menu = new QMenu(this); menuBar()->addMenu( edit_menu )->setText( tr( "&Edit" ) ); m_undoAction = edit_menu->addAction( embed::getIconPixmap( "edit_undo" ), tr( "Undo" ), this, SLOT(undo()), QKeySequence::Undo ); m_redoAction = edit_menu->addAction( embed::getIconPixmap( "edit_redo" ), tr( "Redo" ), this, SLOT(redo()), QKeySequence::Redo ); // Ensure that both (Ctrl+Y) and (Ctrl+Shift+Z) activate redo shortcut regardless of OS defaults if (QKeySequence(QKeySequence::Redo) != QKeySequence(Qt::CTRL + Qt::Key_Y)) { new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_Y ), this, SLOT(redo())); } if (QKeySequence(QKeySequence::Redo) != QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Z )) { new QShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_Z ), this, SLOT(redo())); } edit_menu->addSeparator(); edit_menu->addAction(embed::getIconPixmap("microtuner"), tr("Scales and keymaps"), this, SLOT(toggleMicrotunerWin())); edit_menu->addAction(embed::getIconPixmap("setup_general"), tr("Settings"), this, SLOT(showSettingsDialog())); connect(edit_menu, SIGNAL(aboutToShow()), this, SLOT(updateUndoRedoButtons())); m_viewMenu = new QMenu( this ); menuBar()->addMenu( m_viewMenu )->setText( tr( "&View" ) ); connect( m_viewMenu, SIGNAL(aboutToShow()), this, SLOT(updateViewMenu())); connect( m_viewMenu, SIGNAL(triggered(QAction*)), this, SLOT(updateConfig(QAction*))); m_toolsMenu = new QMenu( this ); for( const Plugin::Descriptor* desc : getPluginFactory()->descriptors(Plugin::Type::Tool) ) { m_toolsMenu->addAction( desc->logo->pixmap(), desc->displayName ); m_tools.push_back( ToolPlugin::instantiate( desc->name, /*this*/nullptr ) ->createView(this) ); } if( !m_toolsMenu->isEmpty() ) { menuBar()->addMenu( m_toolsMenu )->setText( tr( "&Tools" ) ); connect( m_toolsMenu, SIGNAL(triggered(QAction*)), this, SLOT(showTool(QAction*))); } // help-popup-menu auto help_menu = new QMenu(this); menuBar()->addMenu( help_menu )->setText( tr( "&Help" ) ); // May use offline help if( true ) { help_menu->addAction( embed::getIconPixmap( "help" ), tr( "Online Help" ), this, SLOT(browseHelp())); } else { help_menu->addAction( embed::getIconPixmap( "help" ), tr( "Help" ), this, SLOT(help())); } help_menu->addSeparator(); help_menu->addAction( embed::getIconPixmap( "icon_small" ), tr( "About" ), this, SLOT(aboutLMMS())); // create tool-buttons auto project_new = new ToolButton( embed::getIconPixmap("project_new"), tr("Create new project"), this, SLOT(createNewProject()), m_toolBar); auto project_new_from_template = new ToolButton(embed::getIconPixmap("project_new_from_template"), tr("Create new project from template"), this, SLOT(emptySlot()), m_toolBar); project_new_from_template->setMenu( templates_menu ); project_new_from_template->setPopupMode( ToolButton::InstantPopup ); auto project_open = new ToolButton( embed::getIconPixmap("project_open"), tr("Open existing project"), this, SLOT(openProject()), m_toolBar); auto project_open_recent = new ToolButton(embed::getIconPixmap("project_open_recent"), tr("Recently opened projects"), this, SLOT(emptySlot()), m_toolBar); project_open_recent->setMenu( new RecentProjectsMenu(this) ); project_open_recent->setPopupMode( ToolButton::InstantPopup ); auto project_save = new ToolButton( embed::getIconPixmap("project_save"), tr("Save current project"), this, SLOT(saveProject()), m_toolBar); auto project_export = new ToolButton( embed::getIconPixmap("project_export"), tr("Export current project"), this, SLOT(onExportProject()), m_toolBar); m_metronomeToggle = new ToolButton( embed::getIconPixmap( "metronome" ), tr( "Metronome" ), this, SLOT(onToggleMetronome()), m_toolBar ); m_metronomeToggle->setCheckable(true); m_metronomeToggle->setChecked(Engine::getSong()->metronome().active()); m_toolBarLayout->setColumnMinimumWidth( 0, 5 ); m_toolBarLayout->addWidget( project_new, 0, 1 ); m_toolBarLayout->addWidget( project_new_from_template, 0, 2 ); m_toolBarLayout->addWidget( project_open, 0, 3 ); m_toolBarLayout->addWidget( project_open_recent, 0, 4 ); m_toolBarLayout->addWidget( project_save, 0, 5 ); m_toolBarLayout->addWidget( project_export, 0, 6 ); m_toolBarLayout->addWidget( m_metronomeToggle, 0, 7 ); // window-toolbar auto song_editor_window = new ToolButton(embed::getIconPixmap("songeditor"), tr("Song Editor") + " (Ctrl+1)", this, SLOT(toggleSongEditorWin()), m_toolBar); song_editor_window->setShortcut( Qt::CTRL + Qt::Key_1 ); auto pattern_editor_window = new ToolButton(embed::getIconPixmap("pattern_track_btn"), tr("Pattern Editor") + " (Ctrl+2)", this, SLOT(togglePatternEditorWin()), m_toolBar); pattern_editor_window->setShortcut(Qt::CTRL + Qt::Key_2); auto piano_roll_window = new ToolButton( embed::getIconPixmap("piano"), tr("Piano Roll") + " (Ctrl+3)", this, SLOT(togglePianoRollWin()), m_toolBar); piano_roll_window->setShortcut( Qt::CTRL + Qt::Key_3 ); auto automation_editor_window = new ToolButton(embed::getIconPixmap("automation"), tr("Automation Editor") + " (Ctrl+4)", this, SLOT(toggleAutomationEditorWin()), m_toolBar); automation_editor_window->setShortcut( Qt::CTRL + Qt::Key_4 ); auto mixer_window = new ToolButton( embed::getIconPixmap("mixer"), tr("Mixer") + " (Ctrl+5)", this, SLOT(toggleMixerWin()), m_toolBar); mixer_window->setShortcut( Qt::CTRL + Qt::Key_5 ); auto controllers_window = new ToolButton(embed::getIconPixmap("controller"), tr("Show/hide controller rack") + " (Ctrl+6)", this, SLOT(toggleControllerRack()), m_toolBar); controllers_window->setShortcut( Qt::CTRL + Qt::Key_6 ); auto project_notes_window = new ToolButton(embed::getIconPixmap("project_notes"), tr("Show/hide project notes") + " (Ctrl+7)", this, SLOT(toggleProjectNotesWin()), m_toolBar); project_notes_window->setShortcut( Qt::CTRL + Qt::Key_7 ); m_toolBarLayout->addWidget( song_editor_window, 1, 1 ); m_toolBarLayout->addWidget( pattern_editor_window, 1, 2 ); m_toolBarLayout->addWidget( piano_roll_window, 1, 3 ); m_toolBarLayout->addWidget( automation_editor_window, 1, 4 ); m_toolBarLayout->addWidget( mixer_window, 1, 5 ); m_toolBarLayout->addWidget( controllers_window, 1, 6 ); m_toolBarLayout->addWidget( project_notes_window, 1, 7 ); m_toolBarLayout->setColumnStretch( 100, 1 ); // setup-dialog opened before? if( !ConfigManager::inst()->value( "app", "configured" ).toInt() ) { ConfigManager::inst()->setValue( "app", "configured", "1" ); // no, so show it that user can setup everything SetupDialog sd; sd.exec(); } // look whether the audio engine failed to start the audio device selected by the // user and is using AudioDummy as a fallback // or the audio device is set to invalid one else if( Engine::audioEngine()->audioDevStartFailed() || !AudioEngine::isAudioDevNameValid( ConfigManager::inst()->value( "audioengine", "audiodev" ) ) ) { // if so, offer the audio settings section of the setup dialog SetupDialog sd( SetupDialog::ConfigTab::AudioSettings ); sd.exec(); } // Add editor subwindows for (QWidget* widget : std::list<QWidget*>{ getGUI()->automationEditor(), getGUI()->patternEditor(), getGUI()->pianoRoll(), getGUI()->songEditor() }) { QMdiSubWindow* window = addWindowedWidget(widget); window->setWindowIcon(widget->windowIcon()); window->setAttribute(Qt::WA_DeleteOnClose, false); window->resize(widget->sizeHint()); } getGUI()->automationEditor()->parentWidget()->hide(); getGUI()->patternEditor()->parentWidget()->move(610, 5); getGUI()->patternEditor()->parentWidget()->hide(); getGUI()->pianoRoll()->parentWidget()->move(5, 5); getGUI()->pianoRoll()->parentWidget()->hide(); getGUI()->songEditor()->parentWidget()->move(5, 5); getGUI()->songEditor()->parentWidget()->show(); // reset window title every time we change the state of a subwindow to show the correct title for( const QMdiSubWindow * subWindow : workspace()->subWindowList() ) { connect( subWindow, SIGNAL(windowStateChanged(Qt::WindowStates,Qt::WindowStates)), this, SLOT(resetWindowTitle())); } } int MainWindow::addWidgetToToolBar( QWidget * _w, int _row, int _col ) { int col = ( _col == -1 ) ? m_toolBarLayout->columnCount() + 7 : _col; if( _w->height() > 32 || _row == -1 ) { m_toolBarLayout->addWidget( _w, 0, col, 2, 1 ); } else { m_toolBarLayout->addWidget( _w, _row, col ); } return( col ); } void MainWindow::addSpacingToToolBar( int _size ) { m_toolBarLayout->setColumnMinimumWidth( m_toolBarLayout->columnCount() + 7, _size ); } SubWindow* MainWindow::addWindowedWidget(QWidget *w, Qt::WindowFlags windowFlags) { // wrap the widget in our own *custom* window that patches some errors in QMdiSubWindow auto win = new SubWindow(m_workspace->viewport(), windowFlags); win->setAttribute(Qt::WA_DeleteOnClose); win->setWidget(w); if (w && w->sizeHint().isValid()) { auto titleBarHeight = win->titleBarHeight(); auto frameWidth = win->frameWidth(); QSize delta(2* frameWidth, titleBarHeight + frameWidth); win->resize(delta + w->sizeHint()); } m_workspace->addSubWindow(win); return win; } void MainWindow::resetWindowTitle() { QString title(tr( "Untitled" )); if( Engine::getSong()->projectFileName() != "" ) { title = QFileInfo( Engine::getSong()->projectFileName() ).completeBaseName(); } if( Engine::getSong()->isModified() ) { title += '*'; } if( getSession() == SessionState::Recover ) { title += " - " + tr( "Recover session. Please save your work!" ); } setWindowTitle( title + " - " + tr( "LMMS %1" ).arg( LMMS_VERSION ) ); } bool MainWindow::mayChangeProject(bool stopPlayback) { if( stopPlayback ) { Engine::getSong()->stop(); } if( !Engine::getSong()->isModified() && getSession() != SessionState::Recover ) { return( true ); } // Separate message strings for modified and recovered files QString messageTitleRecovered = tr( "Recovered project not saved" ); QString messageRecovered = tr( "This project was recovered from the " "previous session. It is currently " "unsaved and will be lost if you don't " "save it. Do you want to save it now?" ); QString messageTitleUnsaved = tr( "Project not saved" ); QString messageUnsaved = tr( "The current project was modified since " "last saving. Do you want to save it " "now?" ); QMessageBox mb( ( getSession() == SessionState::Recover ? messageTitleRecovered : messageTitleUnsaved ), ( getSession() == SessionState::Recover ? messageRecovered : messageUnsaved ), QMessageBox::Question, QMessageBox::Save, QMessageBox::Discard, QMessageBox::Cancel, this ); int answer = mb.exec(); if( answer == QMessageBox::Save ) { return( saveProject() ); } else if( answer == QMessageBox::Discard ) { if( getSession() == SessionState::Recover ) { sessionCleanup(); } return( true ); } return( false ); } void MainWindow::clearKeyModifiers() { m_keyMods.m_ctrl = false; m_keyMods.m_shift = false; m_keyMods.m_alt = false; } void MainWindow::saveWidgetState( QWidget * _w, QDomElement & _de ) { // If our widget is the main content of a window (e.g. piano roll, Mixer, etc), // we really care about the position of the *window* - not the position of the widget within its window if( _w->parentWidget() != nullptr && _w->parentWidget()->inherits( "QMdiSubWindow" ) ) { _w = _w->parentWidget(); } // If the widget is a SubWindow, then we can make use of the getTrueNormalGeometry() method that // performs the same as normalGeometry, but isn't broken on X11 ( see https://bugreports.qt.io/browse/QTBUG-256 ) auto asSubWindow = qobject_cast<SubWindow*>(_w); QRect normalGeom = asSubWindow != nullptr ? asSubWindow->getTrueNormalGeometry() : _w->normalGeometry(); bool visible = _w->isVisible(); _de.setAttribute( "visible", visible ); _de.setAttribute( "minimized", _w->isMinimized() ); _de.setAttribute( "maximized", _w->isMaximized() ); _de.setAttribute( "x", normalGeom.x() ); _de.setAttribute( "y", normalGeom.y() ); QSize sizeToStore = normalGeom.size(); _de.setAttribute( "width", sizeToStore.width() ); _de.setAttribute( "height", sizeToStore.height() ); } void MainWindow::restoreWidgetState( QWidget * _w, const QDomElement & _de ) { QRect r( qMax( 1, _de.attribute( "x" ).toInt() ), qMax( 1, _de.attribute( "y" ).toInt() ), qMax( _w->sizeHint().width(), _de.attribute( "width" ).toInt() ), qMax( _w->minimumHeight(), _de.attribute( "height" ).toInt() ) ); if( _de.hasAttribute( "visible" ) && !r.isNull() ) { // If our widget is the main content of a window (e.g. piano roll, Mixer, etc), // we really care about the position of the *window* - not the position of the widget within its window if ( _w->parentWidget() != nullptr && _w->parentWidget()->inherits( "QMdiSubWindow" ) ) { _w = _w->parentWidget(); } // first restore the window, as attempting to resize a maximized window causes graphics glitching _w->setWindowState( _w->windowState() & ~(Qt::WindowMaximized | Qt::WindowMinimized) ); // Check isEmpty() to work around corrupt project files with empty size if ( ! r.size().isEmpty() ) { _w->resize( r.size() ); } _w->move( r.topLeft() ); // set the window to its correct minimized/maximized/restored state Qt::WindowStates flags = _w->windowState(); flags = _de.attribute( "minimized" ).toInt() ? ( flags | Qt::WindowMinimized ) : ( flags & ~Qt::WindowMinimized ); flags = _de.attribute( "maximized" ).toInt() ? ( flags | Qt::WindowMaximized ) : ( flags & ~Qt::WindowMaximized ); _w->setWindowState( flags ); _w->setVisible( _de.attribute( "visible" ).toInt() ); } } void MainWindow::emptySlot() { } void MainWindow::createNewProject() { if( mayChangeProject(true) ) { Engine::getSong()->createNewProject(); } } void MainWindow::openProject() { if( mayChangeProject(false) ) { FileDialog ofd( this, tr( "Open Project" ), "", tr( "LMMS (*.mmp *.mmpz)" ) ); ofd.setDirectory( ConfigManager::inst()->userProjectsDir() ); ofd.setFileMode( FileDialog::ExistingFiles ); if( ofd.exec () == QDialog::Accepted && !ofd.selectedFiles().isEmpty() ) { Song *song = Engine::getSong(); song->stop(); setCursor( Qt::WaitCursor ); song->loadProject( ofd.selectedFiles()[0] ); setCursor( Qt::ArrowCursor ); } } } bool MainWindow::saveProject() { if( Engine::getSong()->projectFileName() == "" ) { return( saveProjectAs() ); } else if( this->guiSaveProject() ) { if( getSession() == SessionState::Recover ) { sessionCleanup(); } return true; } return false; } bool MainWindow::saveProjectAs() { auto optionsWidget = new SaveOptionsWidget(Engine::getSong()->getSaveOptions()); VersionedSaveDialog sfd( this, optionsWidget, tr( "Save Project" ), "", tr( "LMMS Project" ) + " (*.mmpz *.mmp);;" + tr( "LMMS Project Template" ) + " (*.mpt)" ); QString f = Engine::getSong()->projectFileName(); if( f != "" ) { sfd.setDirectory( QFileInfo( f ).absolutePath() ); sfd.selectFile( QFileInfo( f ).fileName() ); } else { sfd.setDirectory( ConfigManager::inst()->userProjectsDir() ); } // Don't write over file with suffix if no suffix is provided. QString suffix = ConfigManager::inst()->value( "app", "nommpz" ).toInt() == 0 ? "mmpz" : "mmp" ; sfd.setDefaultSuffix( suffix ); if( sfd.exec () == FileDialog::Accepted && !sfd.selectedFiles().isEmpty() && sfd.selectedFiles()[0] != "" ) { QString fname = sfd.selectedFiles()[0] ; if( sfd.selectedNameFilter().contains( "(*.mpt)" ) ) { // Remove the default suffix fname.remove( "." + suffix ); if( !sfd.selectedFiles()[0].endsWith( ".mpt" ) ) { if( VersionedSaveDialog::fileExistsQuery( fname + ".mpt", tr( "Save project template" ) ) ) { fname += ".mpt"; } } } if( this->guiSaveProjectAs( fname ) ) { if( getSession() == SessionState::Recover ) { sessionCleanup(); } return true; } } return false; } bool MainWindow::saveProjectAsNewVersion() { QString fileName = Engine::getSong()->projectFileName(); if( fileName == "" ) { return saveProjectAs(); } else { do VersionedSaveDialog::changeFileNameVersion( fileName, true ); while ( QFile( fileName ).exists() ); return this->guiSaveProjectAs( fileName ); } } void MainWindow::saveProjectAsDefaultTemplate() { QString defaultTemplate = ConfigManager::inst()->userTemplateDir() + "default.mpt"; QFileInfo fileInfo(defaultTemplate); if (fileInfo.exists()) { if (QMessageBox::warning(this, tr("Overwrite default template?"), tr("This will overwrite your current default template."), QMessageBox::Ok, QMessageBox::Cancel) != QMessageBox::Ok) { return; } } Engine::getSong()->saveProjectFile( defaultTemplate ); } void MainWindow::showSettingsDialog() { SetupDialog sd; sd.exec(); } void MainWindow::aboutLMMS() { AboutDialog(this).exec(); } void MainWindow::help() { QMessageBox::information( this, tr( "Help not available" ), tr( "Currently there's no help " "available in LMMS.\n" "Please visit " "http://lmms.sf.net/wiki " "for documentation on LMMS." ), QMessageBox::Ok ); } void MainWindow::toggleWindow( QWidget *window, bool forceShow ) { QWidget *parent = window->parentWidget(); if( forceShow || m_workspace->activeSubWindow() != parent || parent->isHidden() ) { parent->show(); window->show(); window->setFocus(); } else { parent->hide(); refocus(); } // Workaround for Qt Bug #260116 m_workspace->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_workspace->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); m_workspace->setHorizontalScrollBarPolicy( Qt::ScrollBarAsNeeded ); m_workspace->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded ); } void MainWindow::toggleFullscreen() { if ( !isFullScreen() ) { maximized = isMaximized(); showFullScreen(); } else { maximized ? showMaximized() : showNormal(); } } /* * When an editor window with focus is toggled off, attempt to set focus * to the next visible editor window, or if none are visible, set focus * to the parent window. */ void MainWindow::refocus() { const auto gui = getGUI(); // Attempt to set the focus on the first of these editors that is not hidden... for (auto editorParent : { gui->songEditor()->parentWidget(), gui->patternEditor()->parentWidget(), gui->pianoRoll()->parentWidget(), gui->automationEditor()->parentWidget() }) { if (!editorParent->isHidden()) { editorParent->setFocus(); return; } } // ... otherwise set the focus on the main window. this->setFocus(); } void MainWindow::togglePatternEditorWin( bool forceShow ) { toggleWindow( getGUI()->patternEditor(), forceShow ); } void MainWindow::toggleSongEditorWin() { toggleWindow( getGUI()->songEditor() ); } void MainWindow::toggleProjectNotesWin() { toggleWindow( getGUI()->getProjectNotes() ); } void MainWindow::togglePianoRollWin() { toggleWindow( getGUI()->pianoRoll() ); } void MainWindow::toggleAutomationEditorWin() { toggleWindow( getGUI()->automationEditor() ); } void MainWindow::toggleMixerWin() { toggleWindow( getGUI()->mixerView() ); } void MainWindow::toggleMicrotunerWin() { toggleWindow( getGUI()->getMicrotunerConfig() ); } void MainWindow::updateViewMenu() { m_viewMenu->clear(); // TODO: get current visibility for these and indicate in menu? // Not that it's straight visible <-> invisible, more like // not on top -> top <-> invisible m_viewMenu->addAction(embed::getIconPixmap( "songeditor" ), tr( "Song Editor" ) + "\tCtrl+1", this, SLOT(toggleSongEditorWin()) ); m_viewMenu->addAction(embed::getIconPixmap("pattern_track"), tr("Pattern Editor") + "\tCtrl+2", this, SLOT(togglePatternEditorWin()) ); m_viewMenu->addAction(embed::getIconPixmap( "piano" ), tr( "Piano Roll" ) + "\tCtrl+3", this, SLOT(togglePianoRollWin()) ); m_viewMenu->addAction(embed::getIconPixmap( "automation" ), tr( "Automation Editor" ) + "\tCtrl+4", this, SLOT(toggleAutomationEditorWin()) ); m_viewMenu->addAction(embed::getIconPixmap( "mixer" ), tr( "Mixer" ) + "\tCtrl+5", this, SLOT(toggleMixerWin()) ); m_viewMenu->addAction(embed::getIconPixmap( "controller" ), tr( "Controller Rack" ) + "\tCtrl+6", this, SLOT(toggleControllerRack()) ); m_viewMenu->addAction(embed::getIconPixmap( "project_notes" ), tr( "Project Notes" ) + "\tCtrl+7", this, SLOT(toggleProjectNotesWin()) ); m_viewMenu->addSeparator(); m_viewMenu->addAction(embed::getIconPixmap( "fullscreen" ), tr( "Fullscreen" ) + "\tF11", this, SLOT(toggleFullscreen()) ); m_viewMenu->addSeparator(); // Here we should put all look&feel -stuff from configmanager // that is safe to change on the fly. There is probably some // more elegant way to do this. auto qa = new QAction(tr("Volume as dBFS"), this); qa->setData("displaydbfs"); qa->setCheckable( true ); qa->setChecked( ConfigManager::inst()->value( "app", "displaydbfs" ).toInt() ); m_viewMenu->addAction(qa); qa = new QAction(tr( "Smooth scroll" ), this); qa->setData("smoothscroll"); qa->setCheckable( true ); qa->setChecked( ConfigManager::inst()->value( "ui", "smoothscroll" ).toInt() ); m_viewMenu->addAction(qa); // Not yet. /* qa = new QAction(tr( "One instrument track window" ), this); qa->setData("oneinstrument"); qa->setCheckable( true ); qa->setChecked( ConfigManager::inst()->value( "ui", "oneinstrumenttrackwindow" ).toInt() ); m_viewMenu->addAction(qa); */ qa = new QAction(tr( "Enable note labels in piano roll" ), this); qa->setData("printnotelabels"); qa->setCheckable( true ); qa->setChecked( ConfigManager::inst()->value( "ui", "printnotelabels" ).toInt() ); m_viewMenu->addAction(qa); } void MainWindow::updateConfig( QAction * _who ) { QString tag = _who->data().toString(); bool checked = _who->isChecked(); if( tag == "displaydbfs" ) { ConfigManager::inst()->setValue( "app", "displaydbfs", QString::number(checked) ); } else if ( tag == "tooltips" ) { ConfigManager::inst()->setValue( "tooltips", "disabled", QString::number(!checked) ); if (checked) { qApp->removeEventFilter(this); } else { qApp->installEventFilter(this); } } else if ( tag == "smoothscroll" ) { ConfigManager::inst()->setValue( "ui", "smoothscroll", QString::number(checked) ); } else if ( tag == "oneinstrument" ) { ConfigManager::inst()->setValue( "ui", "oneinstrumenttrackwindow", QString::number(checked) ); } else if ( tag == "printnotelabels" ) { ConfigManager::inst()->setValue( "ui", "printnotelabels", QString::number(checked) ); } } void MainWindow::onToggleMetronome() { Engine::getSong()->metronome().setActive(m_metronomeToggle->isChecked()); } void MainWindow::toggleControllerRack() { toggleWindow( getGUI()->getControllerRackView() ); } void MainWindow::updatePlayPauseIcons() { getGUI()->songEditor()->setPauseIcon( false ); getGUI()->automationEditor()->setPauseIcon( false ); getGUI()->patternEditor()->setPauseIcon( false ); getGUI()->pianoRoll()->setPauseIcon( false ); if( Engine::getSong()->isPlaying() ) { switch( Engine::getSong()->playMode() ) { case Song::PlayMode::Song: getGUI()->songEditor()->setPauseIcon( true ); break; case Song::PlayMode::AutomationClip: getGUI()->automationEditor()->setPauseIcon( true ); break; case Song::PlayMode::Pattern: getGUI()->patternEditor()->setPauseIcon( true ); break; case Song::PlayMode::MidiClip: getGUI()->pianoRoll()->setPauseIcon( true ); break; default: break; } } } void MainWindow::updateUndoRedoButtons() { // when the edit menu is shown, grey out the undo/redo buttons if there's nothing to undo/redo // else, un-grey them m_undoAction->setEnabled(Engine::projectJournal()->canUndo()); m_redoAction->setEnabled(Engine::projectJournal()->canRedo()); } void MainWindow::undo() { Engine::projectJournal()->undo(); } void MainWindow::redo() { Engine::projectJournal()->redo(); } void MainWindow::closeEvent( QCloseEvent * _ce ) { if( mayChangeProject(true) ) { // delete recovery file if( ConfigManager::inst()-> value( "ui", "enableautosave" ).toInt() ) { sessionCleanup(); _ce->accept(); } } else { _ce->ignore(); } } void MainWindow::sessionCleanup() { // delete recover session files QFile::remove( ConfigManager::inst()->recoveryFile() ); setSession( SessionState::Normal ); } bool MainWindow::eventFilter(QObject* watched, QEvent* event) { // For now this function is only used to globally block tooltips // It must be installed to QApplication through installEventFilter if (event->type() == QEvent::ToolTip) { return true; } return QObject::eventFilter(watched, event); } void MainWindow::focusOutEvent( QFocusEvent * _fe ) { // TODO Remove this function, since it is apparently never actually called! // when loosing focus we do not receive key-(release!)-events anymore, // so we might miss release-events of one the modifiers we're watching! clearKeyModifiers(); QMainWindow::leaveEvent( _fe ); } void MainWindow::keyPressEvent( QKeyEvent * _ke ) { switch( _ke->key() ) { case Qt::Key_Control: m_keyMods.m_ctrl = true; break; case Qt::Key_Shift: m_keyMods.m_shift = true; break; case Qt::Key_Alt: m_keyMods.m_alt = true; break; default: { InstrumentTrackWindow * w = InstrumentTrackView::topLevelInstrumentTrackWindow(); if( w ) { w->pianoView()->keyPressEvent( _ke ); } if( !_ke->isAccepted() ) { QMainWindow::keyPressEvent( _ke ); } } } } void MainWindow::keyReleaseEvent( QKeyEvent * _ke ) { switch( _ke->key() ) { case Qt::Key_Control: m_keyMods.m_ctrl = false; break; case Qt::Key_Shift: m_keyMods.m_shift = false; break; case Qt::Key_Alt: m_keyMods.m_alt = false; break; default: if( InstrumentTrackView::topLevelInstrumentTrackWindow() ) { InstrumentTrackView::topLevelInstrumentTrackWindow()-> pianoView()->keyReleaseEvent( _ke ); } if( !_ke->isAccepted() ) { QMainWindow::keyReleaseEvent( _ke ); } } } void MainWindow::timerEvent( QTimerEvent * _te) { emit periodicUpdate(); } void MainWindow::showTool( QAction * _idx ) { PluginView * p = m_tools[m_toolsMenu->actions().indexOf( _idx )]; p->show(); p->parentWidget()->show(); p->setFocus(); } void MainWindow::browseHelp() { // file:// alternative for offline help QString url = "https://lmms.io/documentation/"; QDesktopServices::openUrl( url ); // TODO: Handle error } void MainWindow::autoSave() { if( !Engine::getSong()->isExporting() && !Engine::getSong()->isLoadingProject() && !RemotePluginBase::isMainThreadWaiting() && !QApplication::mouseButtons() && ( ConfigManager::inst()->value( "ui", "enablerunningautosave" ).toInt() || ! Engine::getSong()->isPlaying() ) ) { Engine::getSong()->saveProjectFile(ConfigManager::inst()->recoveryFile()); autoSaveTimerReset(); // Reset timer } else { // try again in 10 seconds if( getAutoSaveTimerInterval() != m_autoSaveShortTime ) { autoSaveTimerReset( m_autoSaveShortTime ); } } } void MainWindow::onExportProjectMidi() { FileDialog efd( this ); efd.setFileMode( FileDialog::AnyFile ); QStringList types; types << tr("MIDI File (*.mid)"); efd.setNameFilters( types ); QString base_filename; QString const & projectFileName = Engine::getSong()->projectFileName(); if( !projectFileName.isEmpty() ) { efd.setDirectory( QFileInfo( projectFileName ).absolutePath() ); base_filename = QFileInfo( projectFileName ).completeBaseName(); } else { efd.setDirectory( ConfigManager::inst()->userProjectsDir() ); base_filename = tr( "untitled" ); } efd.selectFile( base_filename + ".mid" ); efd.setDefaultSuffix( "mid"); efd.setWindowTitle( tr( "Select file for project-export..." ) ); efd.setAcceptMode( FileDialog::AcceptSave ); if( efd.exec() == QDialog::Accepted && !efd.selectedFiles().isEmpty() && !efd.selectedFiles()[0].isEmpty() ) { const QString suffix = ".mid"; QString export_filename = efd.selectedFiles()[0]; if (!export_filename.endsWith(suffix)) export_filename += suffix; Engine::getSong()->exportProjectMidi(export_filename); } } void MainWindow::exportProject(bool multiExport) { QString const & projectFileName = Engine::getSong()->projectFileName(); FileDialog efd( getGUI()->mainWindow() ); if ( multiExport ) { efd.setFileMode( FileDialog::Directory); efd.setWindowTitle( tr( "Select directory for writing exported tracks..." ) ); if( !projectFileName.isEmpty() ) { efd.setDirectory( QFileInfo( projectFileName ).absolutePath() ); } } else { efd.setFileMode( FileDialog::AnyFile ); int idx = 0; QStringList types; while( ProjectRenderer::fileEncodeDevices[idx].m_fileFormat != ProjectRenderer::ExportFileFormat::Count) { if(ProjectRenderer::fileEncodeDevices[idx].isAvailable()) { types << tr(ProjectRenderer::fileEncodeDevices[idx].m_description); } ++idx; } efd.setNameFilters( types ); QString baseFilename; if( !projectFileName.isEmpty() ) { efd.setDirectory( QFileInfo( projectFileName ).absolutePath() ); baseFilename = QFileInfo( projectFileName ).completeBaseName(); } else { efd.setDirectory( ConfigManager::inst()->userProjectsDir() ); baseFilename = tr( "untitled" ); } efd.selectFile( baseFilename + ProjectRenderer::fileEncodeDevices[0].m_extension ); efd.setWindowTitle( tr( "Select file for project-export..." ) ); } QString suffix = "wav"; efd.setDefaultSuffix( suffix ); efd.setAcceptMode( FileDialog::AcceptSave ); if( efd.exec() == QDialog::Accepted && !efd.selectedFiles().isEmpty() && !efd.selectedFiles()[0].isEmpty() ) { QString exportFileName = efd.selectedFiles()[0]; if ( !multiExport ) { int stx = efd.selectedNameFilter().indexOf( "(*." ); int etx = efd.selectedNameFilter().indexOf( ")" ); if ( stx > 0 && etx > stx ) { // Get first extension from selected dropdown. // i.e. ".wav" from "WAV-File (*.wav), Dummy-File (*.dum)" suffix = efd.selectedNameFilter().mid( stx + 2, etx - stx - 2 ).split( " " )[0].trimmed(); Qt::CaseSensitivity cs = Qt::CaseSensitive; #if defined(LMMS_BUILD_APPLE) || defined(LMMS_BUILD_WIN32) cs = Qt::CaseInsensitive; #endif exportFileName.remove( "." + suffix, cs ); if ( efd.selectedFiles()[0].endsWith( suffix ) ) { if( VersionedSaveDialog::fileExistsQuery( exportFileName + suffix, tr( "Save project" ) ) ) { exportFileName += suffix; } } } } ExportProjectDialog epd( exportFileName, getGUI()->mainWindow(), multiExport ); epd.exec(); } } void MainWindow::handleSaveResult(QString const & filename, bool songSavedSuccessfully) { if (songSavedSuccessfully) { TextFloat::displayMessage( tr( "Project saved" ), tr( "The project %1 is now saved.").arg( filename ), embed::getIconPixmap( "project_save", 24, 24 ), 2000 ); ConfigManager::inst()->addRecentlyOpenedProject(filename); resetWindowTitle(); } else { TextFloat::displayMessage( tr( "Project NOT saved." ), tr( "The project %1 was not saved!" ).arg(filename), embed::getIconPixmap( "error" ), 4000 ); } } bool MainWindow::guiSaveProject() { Song * song = Engine::getSong(); bool const songSaveResult = song->guiSaveProject(); handleSaveResult(song->projectFileName(), songSaveResult); return songSaveResult; } bool MainWindow::guiSaveProjectAs( const QString & filename ) { Song * song = Engine::getSong(); bool const songSaveResult = song->guiSaveProjectAs(filename); handleSaveResult(filename, songSaveResult); return songSaveResult; } void MainWindow::onExportProject() { this->exportProject(); } void MainWindow::onExportProjectTracks() { this->exportProject(true); } void MainWindow::onImportProject() { Song * song = Engine::getSong(); if (song) { FileDialog ofd( nullptr, tr( "Import file" ), ConfigManager::inst()->userProjectsDir(), tr("MIDI sequences") + " (*.mid *.midi *.rmi);;" + tr("Hydrogen projects") + " (*.h2song);;" + tr("All file types") + " (*.*)"); ofd.setFileMode( FileDialog::ExistingFiles ); if( ofd.exec () == QDialog::Accepted && !ofd.selectedFiles().isEmpty() ) { ImportFilter::import( ofd.selectedFiles()[0], song ); } song->setLoadOnLaunch(false); } } void MainWindow::onSongModified() { // Only update the window title if the code is executed from the GUI main thread. // The assumption seems to be that the Song can also be set as modified from other // threads. This is not a good design! Copied from the original implementation of // Song::setModified. if(QThread::currentThread() == this->thread()) { this->resetWindowTitle(); } } void MainWindow::onProjectFileNameChanged() { this->resetWindowTitle(); } } // namespace lmms::gui
43,539
C++
.cpp
1,283
30.988309
117
0.699361
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,889
MicrotunerConfig.cpp
LMMS_lmms/src/gui/MicrotunerConfig.cpp
/* * MicrotunerConfig.cpp - configuration widget for scales and keymaps * * 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. * */ #include "MicrotunerConfig.h" #include <QFile> #include <QGridLayout> #include <QLabel> #include <QLineEdit> #include <QMessageBox> #include <QPlainTextEdit> #include <QPushButton> #include <QRegularExpression> #include <QTextStream> #include "ComboBox.h" #include "embed.h" #include "Engine.h" #include "FileDialog.h" #include "GuiApplication.h" #include "Keymap.h" #include "LcdFloatSpinBox.h" #include "LcdSpinBox.h" #include "lmms_constants.h" #include "lmmsversion.h" #include "MainWindow.h" #include "Note.h" #include "Scale.h" #include "Song.h" #include "SubWindow.h" namespace lmms::gui { MicrotunerConfig::MicrotunerConfig() : QWidget(), m_scaleComboModel(nullptr, tr("Selected scale slot")), m_keymapComboModel(nullptr, tr("Selected keymap slot")), m_firstKeyModel(0, 0, NumKeys - 1, nullptr, tr("First key")), m_lastKeyModel(NumKeys - 1, 0, NumKeys - 1, nullptr, tr("Last key")), m_middleKeyModel(DefaultMiddleKey, 0, NumKeys - 1, nullptr, tr("Middle key")), m_baseKeyModel(DefaultBaseKey, 0, NumKeys - 1, nullptr, tr("Base key")), m_baseFreqModel(DefaultBaseFreq, 0.1f, 9999.999f, 0.001f, nullptr, tr("Base note frequency")) { #if QT_VERSION < 0x50C00 // Workaround for a bug in Qt versions below 5.12, // where argument-dependent-lookup fails for QFlags operators // declared inside a namepsace. // This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h // See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348 using ::operator|; #endif setWindowIcon(embed::getIconPixmap("microtuner")); setWindowTitle(tr("Microtuner Configuration")); // Organize into 2 main columns: scales and keymaps auto microtunerLayout = new QGridLayout(); microtunerLayout->setSpacing(2); // ---------------------------------- // Scale sub-column // auto scaleLabel = new QLabel(tr("Scale slot to edit:")); microtunerLayout->addWidget(scaleLabel, 0, 0, 1, 2, Qt::AlignBottom); for (unsigned int i = 0; i < MaxScaleCount; i++) { m_scaleComboModel.addItem(QString::number(i) + ": " + Engine::getSong()->getScale(i)->getDescription()); } auto scaleCombo = new ComboBox(); scaleCombo->setModel(&m_scaleComboModel); microtunerLayout->addWidget(scaleCombo, 1, 0, 1, 2); connect(&m_scaleComboModel, &ComboBoxModel::dataChanged, [=] {updateScaleForm();}); m_scaleNameEdit = new QLineEdit("12-TET"); m_scaleNameEdit->setToolTip(tr("Scale description. Cannot start with \"!\" and cannot contain a newline character.")); microtunerLayout->addWidget(m_scaleNameEdit, 2, 0, 1, 2); auto loadScaleButton = new QPushButton(tr("Load")); auto saveScaleButton = new QPushButton(tr("Save")); loadScaleButton->setToolTip(tr("Load scale definition from a file.")); saveScaleButton->setToolTip(tr("Save scale definition to a file.")); microtunerLayout->addWidget(loadScaleButton, 3, 0, 1, 1); microtunerLayout->addWidget(saveScaleButton, 3, 1, 1, 1); connect(loadScaleButton, &QPushButton::clicked, [=] {loadScaleFromFile();}); connect(saveScaleButton, &QPushButton::clicked, [=] {saveScaleToFile();}); m_scaleTextEdit = new QPlainTextEdit(); m_scaleTextEdit->setPlainText("100.0\n200.0\n300.0\n400.0\n500.0\n600.0\n700.0\n800.0\n900.0\n1000.0\n1100.0\n1200.0"); m_scaleTextEdit->setToolTip(tr("Enter intervals on separate lines. Numbers containing a decimal point are treated as cents.\nOther inputs are treated as integer ratios and must be in the form of \'a/b\' or \'a\'.\nUnity (0.0 cents or ratio 1/1) is always present as a hidden first value; do not enter it manually.")); microtunerLayout->addWidget(m_scaleTextEdit, 4, 0, 2, 2); auto applyScaleButton = new QPushButton(tr("Apply scale changes")); applyScaleButton->setToolTip(tr("Verify and apply changes made to the selected scale. To use the scale, select it in the settings of a supported instrument.")); microtunerLayout->addWidget(applyScaleButton, 6, 0, 1, 2); connect(applyScaleButton, &QPushButton::clicked, [=] {applyScale();}); // ---------------------------------- // Mapping sub-column // auto keymapLabel = new QLabel(tr("Keymap slot to edit:")); microtunerLayout->addWidget(keymapLabel, 0, 2, 1, 2, Qt::AlignBottom); for (unsigned int i = 0; i < MaxKeymapCount; i++) { m_keymapComboModel.addItem(QString::number(i) + ": " + Engine::getSong()->getKeymap(i)->getDescription()); } auto keymapCombo = new ComboBox(); keymapCombo->setModel(&m_keymapComboModel); microtunerLayout->addWidget(keymapCombo, 1, 2, 1, 2); connect(&m_keymapComboModel, &ComboBoxModel::dataChanged, [=] {updateKeymapForm();}); m_keymapNameEdit = new QLineEdit("default"); m_keymapNameEdit->setToolTip(tr("Keymap description. Cannot start with \"!\" and cannot contain a newline character.")); microtunerLayout->addWidget(m_keymapNameEdit, 2, 2, 1, 2); auto loadKeymapButton = new QPushButton(tr("Load")); auto saveKeymapButton = new QPushButton(tr("Save")); loadKeymapButton->setToolTip(tr("Load key mapping definition from a file.")); saveKeymapButton->setToolTip(tr("Save key mapping definition to a file.")); microtunerLayout->addWidget(loadKeymapButton, 3, 2, 1, 1); microtunerLayout->addWidget(saveKeymapButton, 3, 3, 1, 1); connect(loadKeymapButton, &QPushButton::clicked, [=] {loadKeymapFromFile();}); connect(saveKeymapButton, &QPushButton::clicked, [=] {saveKeymapToFile();}); m_keymapTextEdit = new QPlainTextEdit(); m_keymapTextEdit->setPlainText("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11"); m_keymapTextEdit->setToolTip(tr("Enter key mappings on separate lines. Each line assigns a scale degree to a MIDI key,\nstarting with the middle key and continuing in sequence.\nThe pattern repeats for keys outside of the explicit keymap range.\nMultiple keys can be mapped to the same scale degree.\nEnter \'x\' if you wish to leave the key disabled / not mapped.")); microtunerLayout->addWidget(m_keymapTextEdit, 4, 2, 1, 2); // Mapping ranges auto keymapRangeLayout = new QGridLayout(); microtunerLayout->addLayout(keymapRangeLayout, 5, 2, 1, 2, Qt::AlignCenter | Qt::AlignTop); auto firstKeySpin = new LcdSpinBox(3, nullptr, tr("First key")); firstKeySpin->setLabel(tr("FIRST")); firstKeySpin->setToolTip(tr("First MIDI key that will be mapped")); firstKeySpin->setModel(&m_firstKeyModel); keymapRangeLayout->addWidget(firstKeySpin, 0, 0); auto lastKeySpin = new LcdSpinBox(3, nullptr, tr("Last key")); lastKeySpin->setLabel(tr("LAST")); lastKeySpin->setToolTip(tr("Last MIDI key that will be mapped")); lastKeySpin->setModel(&m_lastKeyModel); keymapRangeLayout->addWidget(lastKeySpin, 0, 1); auto middleKeySpin = new LcdSpinBox(3, nullptr, tr("Middle key")); middleKeySpin->setLabel(tr("MIDDLE")); middleKeySpin->setToolTip(tr("First line in the keymap refers to this MIDI key")); middleKeySpin->setModel(&m_middleKeyModel); keymapRangeLayout->addWidget(middleKeySpin, 0, 2); auto baseKeySpin = new LcdSpinBox(3, nullptr, tr("Base key")); baseKeySpin->setLabel(tr("BASE N.")); baseKeySpin->setToolTip(tr("Base note frequency will be assigned to this MIDI key")); baseKeySpin->setModel(&m_baseKeyModel); keymapRangeLayout->addWidget(baseKeySpin, 1, 0); auto baseFreqSpin = new LcdFloatSpinBox(4, 3, tr("Base note frequency")); baseFreqSpin->setLabel(tr("BASE NOTE FREQ")); baseFreqSpin->setModel(&m_baseFreqModel); baseFreqSpin->setToolTip(tr("Base note frequency")); keymapRangeLayout->addWidget(baseFreqSpin, 1, 1, 1, 2); auto applyKeymapButton = new QPushButton(tr("Apply keymap changes")); applyKeymapButton->setToolTip(tr("Verify and apply changes made to the selected key mapping. To use the mapping, select it in the settings of a supported instrument.")); microtunerLayout->addWidget(applyKeymapButton, 6, 2, 1, 2); connect(applyKeymapButton, &QPushButton::clicked, [=] {applyKeymap();}); updateScaleForm(); updateKeymapForm(); connect(Engine::getSong(), SIGNAL(scaleListChanged(int)), this, SLOT(updateScaleList(int))); connect(Engine::getSong(), SIGNAL(scaleListChanged(int)), this, SLOT(updateScaleForm())); connect(Engine::getSong(), SIGNAL(keymapListChanged(int)), this, SLOT(updateKeymapList(int))); connect(Engine::getSong(), SIGNAL(keymapListChanged(int)), this, SLOT(updateKeymapForm())); microtunerLayout->setRowStretch(4, 10); this->setLayout(microtunerLayout); // Add to the main window and setup fixed size etc. QMdiSubWindow *subWin = getGUI()->mainWindow()->addWindowedWidget(this); subWin->setAttribute(Qt::WA_DeleteOnClose, false); subWin->setMinimumWidth(300); subWin->setMinimumHeight(300); subWin->setMaximumWidth(500); subWin->setMaximumHeight(700); subWin->hide(); // No maximize button Qt::WindowFlags flags = subWin->windowFlags(); flags &= ~Qt::WindowMaximizeButtonHint; subWin->setWindowFlags(flags); } /** * \brief Update list of available scales. * \param index Index of the scale to update; update all scales if -1 or out of range. */ void MicrotunerConfig::updateScaleList(int index) { if (index >= 0 && static_cast<std::size_t>(index) < MaxScaleCount) { m_scaleComboModel.replaceItem(index, QString::number(index) + ": " + Engine::getSong()->getScale(index)->getDescription()); } else { for (auto i = std::size_t{0}; i < MaxScaleCount; i++) { m_scaleComboModel.replaceItem(i, QString::number(i) + ": " + Engine::getSong()->getScale(i)->getDescription()); } } } /** * \brief Update list of available keymaps. * \param index Index of the keymap to update; update all keymaps if -1 or out of range. */ void MicrotunerConfig::updateKeymapList(int index) { if (index >= 0 && static_cast<std::size_t>(index) < MaxKeymapCount) { m_keymapComboModel.replaceItem(index, QString::number(index) + ": " + Engine::getSong()->getKeymap(index)->getDescription()); } else { for (auto i = std::size_t{0}; i < MaxKeymapCount; i++) { m_keymapComboModel.replaceItem(i, QString::number(i) + ": " + Engine::getSong()->getKeymap(i)->getDescription()); } } } /** * \brief Fill all the scale-related values based on currently selected scale */ void MicrotunerConfig::updateScaleForm() { Song *song = Engine::getSong(); if (song == nullptr) {return;} auto newScale = song->getScale(m_scaleComboModel.value()); m_scaleNameEdit->setText(newScale->getDescription()); // fill in the intervals m_scaleTextEdit->setPlainText(""); const std::vector<Interval> &intervals = newScale->getIntervals(); for (std::size_t i = 1; i < intervals.size(); i++) { m_scaleTextEdit->appendPlainText(intervals[i].getString()); } // scroll back to the top QTextCursor tmp = m_scaleTextEdit->textCursor(); tmp.movePosition(QTextCursor::Start); m_scaleTextEdit->setTextCursor(tmp); } /** * \brief Fill all the keymap-related values based on currently selected keymap */ void MicrotunerConfig::updateKeymapForm() { Song *song = Engine::getSong(); if (song == nullptr) {return;} auto newMap = song->getKeymap(m_keymapComboModel.value()); m_keymapNameEdit->setText(newMap->getDescription()); m_keymapTextEdit->setPlainText(""); const std::vector<int> &map = newMap->getMap(); for (int value : map) { if (value >= 0) {m_keymapTextEdit->appendPlainText(QString::number(value));} else {m_keymapTextEdit->appendPlainText("x");} } QTextCursor tmp = m_keymapTextEdit->textCursor(); tmp.movePosition(QTextCursor::Start); m_keymapTextEdit->setTextCursor(tmp); m_firstKeyModel.setValue(newMap->getFirstKey()); m_lastKeyModel.setValue(newMap->getLastKey()); m_middleKeyModel.setValue(newMap->getMiddleKey()); m_baseKeyModel.setValue(newMap->getBaseKey()); m_baseFreqModel.setValue(newMap->getBaseFreq()); } /** * \brief Validate the scale name and entered interval definitions * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::validateScaleForm() { auto fail = [=](QString message) {QMessageBox::critical(this, tr("Scale parsing error"), message);}; // check name QString name = m_scaleNameEdit->text(); if (name.length() > 0 && name[0] == '!') {fail(tr("Scale name cannot start with an exclamation mark")); return false;} if (name.contains('\n')) {fail(tr("Scale name cannot contain a new-line character")); return false;} // check intervals #if (QT_VERSION >= QT_VERSION_CHECK(5,14,0)) QStringList input = m_scaleTextEdit->toPlainText().split('\n', Qt::SkipEmptyParts); #else QStringList input = m_scaleTextEdit->toPlainText().split('\n', QString::SkipEmptyParts); #endif for (auto &line: input) { if (line.isEmpty()) {continue;} if (line[0] == '!') {continue;} // comment QString firstSection = line.section(QRegularExpression("\\s+|/"), 0, 0, QString::SectionSkipEmpty); if (firstSection.contains('.')) // cent mode { bool ok = true; firstSection.toFloat(&ok); if (!ok) {fail(tr("Interval defined in cents cannot be converted to a number")); return false;} } else // ratio mode { bool ok = true; int num = 1, den = 1; num = firstSection.toInt(&ok); if (!ok) {fail(tr("Numerator of an interval defined as a ratio cannot be converted to a number")); return false;} if (line.contains('/')) { den = line.split('/').at(1).section(QRegularExpression("\\s+"), 0, 0, QString::SectionSkipEmpty).toInt(&ok); } if (!ok) {fail(tr("Denominator of an interval defined as a ratio cannot be converted to a number")); return false;} if (num * den < 0) {fail(tr("Interval defined as a ratio cannot be negative")); return false;} } } return true; } /** * \brief Validate the entered key mapping and other values * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::validateKeymapForm() { auto fail = [=](QString message) {QMessageBox::critical(this, tr("Keymap parsing error"), message);}; // check name QString name = m_keymapNameEdit->text(); if (name.length() > 0 && name[0] == '!') {fail(tr("Keymap name cannot start with an exclamation mark")); return false;} if (name.contains('\n')) {fail(tr("Keymap name cannot contain a new-line character")); return false;} // check key mappings #if (QT_VERSION >= QT_VERSION_CHECK(5,14,0)) QStringList input = m_keymapTextEdit->toPlainText().split('\n', Qt::SkipEmptyParts); #else QStringList input = m_keymapTextEdit->toPlainText().split('\n', QString::SkipEmptyParts); #endif for (auto &line: input) { if (line.isEmpty()) {continue;} if (line[0] == '!') {continue;} // comment QString firstSection = line.section(QRegularExpression("\\s+"), 0, 0, QString::SectionSkipEmpty); if (firstSection == "x") {continue;} // not mapped // otherwise must contain a number bool ok = true; int deg = 0; deg = firstSection.toInt(&ok); if (!ok) {fail(tr("Scale degree cannot be converted to a whole number")); return false;} if (deg < 0) {fail(tr("Scale degree cannot be negative")); return false;} } return true; } /** * \brief Parse and apply the entered scale definition * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::applyScale() { if (!validateScaleForm()) {return false;}; std::vector<Interval> newIntervals; newIntervals.emplace_back(1, 1); #if (QT_VERSION >= QT_VERSION_CHECK(5,14,0)) QStringList input = m_scaleTextEdit->toPlainText().split('\n', Qt::SkipEmptyParts); #else QStringList input = m_scaleTextEdit->toPlainText().split('\n', QString::SkipEmptyParts); #endif for (auto &line: input) { if (line.isEmpty()) {continue;} if (line[0] == '!') {continue;} // comment QString firstSection = line.section(QRegularExpression("\\s+|/"), 0, 0, QString::SectionSkipEmpty); if (firstSection.contains('.')) // cent mode { newIntervals.emplace_back(firstSection.toFloat()); } else // ratio mode { int num = 1, den = 1; num = firstSection.toInt(); if (line.contains('/')) { den = line.split('/').at(1).section(QRegularExpression("\\s+"), 0, 0, QString::SectionSkipEmpty).toInt(); } newIntervals.emplace_back(num, den); } } Song *song = Engine::getSong(); if (song == nullptr) {return false;} auto newScale = std::make_shared<Scale>(m_scaleNameEdit->text(), std::move(newIntervals)); song->setScale(m_scaleComboModel.value(), newScale); return true; } /** * \brief Parse and apply the entered keymap definition * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::applyKeymap() { if (!validateKeymapForm()) {return false;} std::vector<int> newMap; #if (QT_VERSION >= QT_VERSION_CHECK(5,14,0)) QStringList input = m_keymapTextEdit->toPlainText().split('\n', Qt::SkipEmptyParts); #else QStringList input = m_keymapTextEdit->toPlainText().split('\n', QString::SkipEmptyParts); #endif for (auto &line: input) { if (line.isEmpty()) {continue;} if (line[0] == '!') {continue;} // comment QString firstSection = line.section(QRegularExpression("\\s+"), 0, 0, QString::SectionSkipEmpty); if (firstSection == "x") { newMap.push_back(-1); // not mapped continue; } newMap.push_back(firstSection.toInt()); } Song *song = Engine::getSong(); if (song == nullptr) {return false;} auto newKeymap = std::make_shared<Keymap>( m_keymapNameEdit->text(), std::move(newMap), m_firstKeyModel.value(), m_lastKeyModel.value(), m_middleKeyModel.value(), m_baseKeyModel.value(), m_baseFreqModel.value() ); song->setKeymap(m_keymapComboModel.value(), newKeymap); if (newKeymap->getDegree(newKeymap->getBaseKey()) == -1) { QMessageBox::warning(this, tr("Invalid keymap"), tr("Base key is not mapped to any scale degree. No sound will be produced as there is no way to assign reference frequency to any note."));} return true; } /** * \brief Parse an .scl file and apply the loaded scale if it is valid * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::loadScaleFromFile() { QString fileName = FileDialog::getOpenFileName(this, tr("Open scale"), "", tr("Scala scale definition (*.scl)")); if (fileName == "") {return false;} QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::critical(this, tr("Scale load failure"), tr("Unable to open selected file.")); return false; } QTextStream stream(&file); int i = -2, limit = 0; m_scaleNameEdit->setText(""); m_scaleTextEdit->clear(); while (!stream.atEnd() && i < limit) { QString line = stream.readLine(); if (line != "" && line[0] == '!') {continue;} // comment switch(i) { case -2: m_scaleNameEdit->setText(line); break; // first non-comment line = name or description case -1: limit = line.toInt(); break; // second non-comment line = degree count default: m_scaleTextEdit->appendPlainText(line); break; // all other lines = interval definitions } i++; } return applyScale(); } /** * \brief Parse a .kbm file and apply the loaded keymap if it is valid * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::loadKeymapFromFile() { QString fileName = FileDialog::getOpenFileName(this, tr("Open keymap"), "", tr("Scala keymap definition (*.kbm)")); if (fileName == "") {return false;} QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::critical(this, tr("Keymap load failure"), tr("Unable to open selected file.")); return false; } QTextStream stream(&file); int i = -7, limit = 0; m_keymapNameEdit->setText(QFileInfo(fileName).baseName()); // .kbm does not store description, use file name m_keymapTextEdit->clear(); while (!stream.atEnd() && i < limit) { QString line = stream.readLine(); if (line != "" && line[0] == '!') { if (line.length() > 1 && line[1] == '!' && i == -7) // LMMS extension: double "!" occuring before any { // value is loaded marks a description field. m_keymapNameEdit->setText(line.mid(2)); } continue; } switch(i) { case -7: limit = line.toInt(); break; // first non-comment line = keymap size case -6: m_firstKeyModel.setValue(line.toInt()); break; // second non-comment line = first key case -5: m_lastKeyModel.setValue(line.toInt()); break; // third non-comment line = last key case -4: m_middleKeyModel.setValue(line.toInt()); break; // fourth non-comment line = middle key case -3: m_baseKeyModel.setValue(line.toInt()); break; // fifth non-comment line = base key case -2: m_baseFreqModel.setValue(line.toDouble()); break; // sixth non-comment line = base freq case -1: break; // ignored // seventh non-comment line = octave degree default: m_keymapTextEdit->appendPlainText(line); break; // all other lines = mapping definitions } i++; } return applyKeymap(); } /** * \brief Save currently entered scale definition as .scl file * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::saveScaleToFile() { if (!applyScale()) {return false;} QString fileName = FileDialog::getSaveFileName(this, tr("Save scale"), "", tr("Scala scale definition (*.scl)")); if (fileName == "") {return false;} if (QFileInfo(fileName).suffix() != "scl") {fileName = fileName + ".scl";} QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::critical(this, tr("Scale save failure"), tr("Unable to open selected file for writing.")); return false; } Song *song = Engine::getSong(); if (song == nullptr) {return false;} QTextStream stream(&file); stream << "! " << QFileInfo(fileName).fileName() << "\n"; stream << "! Exported from LMMS " LMMS_VERSION "\n"; stream << "!\n"; stream << "! Scale description:\n"; stream << m_scaleNameEdit->text() << "\n"; stream << "!\n"; stream << "! Number of degrees:\n"; stream << song->getScale(m_scaleComboModel.value())->getIntervals().size() - 1 << "\n"; stream << "!\n"; stream << "! Intervals:\n"; stream << m_scaleTextEdit->toPlainText() << "\n"; return true; } /** * \brief Save currently entered keymap definition as .kbm file * \return true if input is valid, false if problems were detected */ bool MicrotunerConfig::saveKeymapToFile() { if (!applyKeymap()) {return false;} QString fileName = FileDialog::getSaveFileName(this, tr("Save keymap"), "", tr("Scala keymap definition (*.kbm)")); if (fileName == "") {return false;} if (QFileInfo(fileName).suffix() != "kbm") {fileName = fileName + ".kbm";} QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::critical(this, tr("Keymap save failure"), tr("Unable to open selected file for writing.")); return false; } Song *song = Engine::getSong(); if (song == nullptr) {return false;} QTextStream stream(&file); stream << "! " << QFileInfo(fileName).fileName() << "\n"; stream << "! Exported from LMMS " LMMS_VERSION "\n"; stream << "!\n"; stream << "! Keymap description:\n"; stream << "!!" << m_keymapNameEdit->text() << "\n"; stream << "!\n"; stream << "! Keymap size:\n"; stream << song->getKeymap(m_keymapComboModel.value())->getMap().size() << "\n"; stream << "!\n"; stream << "! First key:\n"; stream << m_firstKeyModel.value() << "\n"; stream << "! Last key:\n"; stream << m_lastKeyModel.value() << "\n"; stream << "! Middle key:\n"; stream << m_middleKeyModel.value() << "\n"; stream << "! Base key:\n"; stream << m_baseKeyModel.value() << "\n"; stream << "! Base frequency:\n"; stream << m_baseFreqModel.value() << "\n"; stream << "! Octave degree (always using the last scale degree):\n"; stream << "0\n"; stream << "!\n"; stream << "! Key mappings:\n"; stream << m_keymapTextEdit->toPlainText() << "\n"; return true; } void MicrotunerConfig::saveSettings(QDomDocument &document, QDomElement &element) { MainWindow::saveWidgetState(this, element); } void MicrotunerConfig::loadSettings(const QDomElement &element) { MainWindow::restoreWidgetState(this, element); } void MicrotunerConfig::closeEvent(QCloseEvent *ce) { if (parentWidget()) {parentWidget()->hide();} else {hide();} ce->ignore(); } } // namespace lmms::gui
24,925
C++
.cpp
595
39.598319
369
0.712511
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,890
LadspaControlView.cpp
LMMS_lmms/src/gui/LadspaControlView.cpp
/* * LadspaControlView.cpp - widget for controlling a LADSPA port * * Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net> * Copyright (c) 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. * */ #include <QHBoxLayout> #include "LadspaControl.h" #include "LadspaControlView.h" #include "LadspaBase.h" #include "LedCheckBox.h" #include "TempoSyncKnob.h" namespace lmms::gui { LadspaControlView::LadspaControlView( QWidget * _parent, LadspaControl * _ctl ) : QWidget( _parent ), ModelView( _ctl, this ), m_ctl( _ctl ) { auto layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing( 0 ); LedCheckBox * link = nullptr; if( m_ctl->m_link ) { link = new LedCheckBox( "", this ); link->setModel( &m_ctl->m_linkEnabledModel ); link->setToolTip(tr("Link channels")); layout->addWidget( link ); } Knob * knb = nullptr; switch( m_ctl->port()->data_type ) { case BufferDataType::Toggled: { auto toggle = new LedCheckBox(m_ctl->port()->name, this, QString(), LedCheckBox::LedColor::Green); toggle->setModel( m_ctl->toggledModel() ); layout->addWidget( toggle ); if( link != nullptr ) { setFixedSize( link->width() + toggle->width(), toggle->height() ); } else { setFixedSize( toggle->width(), toggle->height() ); } break; } case BufferDataType::Integer: case BufferDataType::Enum: case BufferDataType::Floating: knb = new Knob( KnobType::Bright26, this, m_ctl->port()->name ); break; case BufferDataType::Time: knb = new TempoSyncKnob( KnobType::Bright26, this, m_ctl->port()->name ); break; default: break; } if( knb != nullptr ) { if( m_ctl->port()->data_type != BufferDataType::Time ) { knb->setModel( m_ctl->knobModel() ); } else { knb->setModel( m_ctl->tempoSyncKnobModel() ); } knb->setLabel( m_ctl->port()->name ); knb->setHintText( tr( "Value:" ), "" ); layout->addWidget( knb ); if( link != nullptr ) { setFixedSize( link->width() + knb->width(), knb->height() ); } else { setFixedSize( knb->width(), knb->height() ); } } } } // namespace lmms::gui
2,977
C++
.cpp
105
25.409524
101
0.686055
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,891
AutomatableModelView.cpp
LMMS_lmms/src/gui/AutomatableModelView.cpp
/* * AutomatableModelView.cpp - implementation of AutomatableModelView * * Copyright (c) 2011-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. * */ #include <QMenu> #include <QMouseEvent> #include "AutomatableModelView.h" #include "AutomationClip.h" #include "ControllerConnectionDialog.h" #include "ControllerConnection.h" #include "embed.h" #include "GuiApplication.h" #include "MainWindow.h" #include "StringPairDrag.h" #include "Clipboard.h" #include "AutomationEditor.h" namespace lmms::gui { static float floatFromClipboard(bool* ok=nullptr); AutomatableModelView::AutomatableModelView( Model* model, QWidget* _this ) : ModelView( model, _this ), m_conversionFactor( 1.0 ) { widget()->setAcceptDrops( true ); widget()->setCursor( QCursor( embed::getIconPixmap( "hand" ), 3, 3 ) ); } void AutomatableModelView::addDefaultActions( QMenu* menu ) { AutomatableModel* model = modelUntyped(); auto amvSlots = new AutomatableModelViewSlots(this, menu); menu->addAction( embed::getIconPixmap( "reload" ), AutomatableModel::tr( "&Reset (%1%2)" ). arg( model->initValue<float>() * m_conversionFactor ). arg( m_unit ), model, SLOT(reset())); menu->addSeparator(); menu->addAction( embed::getIconPixmap( "edit_copy" ), AutomatableModel::tr( "&Copy value (%1%2)" ). arg( model->value<float>() * m_conversionFactor ). arg( m_unit ), amvSlots, SLOT(copyToClipboard())); bool canPaste = true; const float valueToPaste = floatFromClipboard(&canPaste); const QString pasteDesc = canPaste ? AutomatableModel::tr( "&Paste value (%1%2)"). arg( valueToPaste ). arg( m_unit ) : AutomatableModel::tr( "&Paste value"); QAction* pasteAction = menu->addAction( embed::getIconPixmap( "edit_paste" ), pasteDesc, amvSlots, SLOT(pasteFromClipboard())); pasteAction->setEnabled(canPaste); menu->addSeparator(); menu->addAction( embed::getIconPixmap( "automation" ), AutomatableModel::tr( "Edit song-global automation" ), amvSlots, SLOT(editSongGlobalAutomation())); menu->addAction( QPixmap(), AutomatableModel::tr( "Remove song-global automation" ), amvSlots, SLOT(removeSongGlobalAutomation())); menu->addSeparator(); if( model->hasLinkedModels() ) { menu->addAction( embed::getIconPixmap( "edit-delete" ), AutomatableModel::tr( "Remove all linked controls" ), amvSlots, SLOT(unlinkAllModels())); menu->addSeparator(); } QString controllerTxt; if( model->controllerConnection() ) { Controller* cont = model->controllerConnection()->getController(); if( cont ) { controllerTxt = AutomatableModel::tr( "Connected to %1" ).arg( cont->name() ); } else { controllerTxt = AutomatableModel::tr( "Connected to controller" ); } QMenu* contMenu = menu->addMenu( embed::getIconPixmap( "controller" ), controllerTxt ); contMenu->addAction( embed::getIconPixmap( "controller" ), AutomatableModel::tr("Edit connection..."), amvSlots, SLOT(execConnectionDialog())); contMenu->addAction( embed::getIconPixmap( "cancel" ), AutomatableModel::tr("Remove connection"), amvSlots, SLOT(removeConnection())); } else { menu->addAction( embed::getIconPixmap( "controller" ), AutomatableModel::tr("Connect to controller..."), amvSlots, SLOT(execConnectionDialog())); } } void AutomatableModelView::setModel( Model* model, bool isOldModelValid ) { ModelView::setModel( model, isOldModelValid ); } // Unsets the current model by setting a dummy empty model. The dummy model is marked as // "defaultConstructed", so the next call to setModel will delete it. void AutomatableModelView::unsetModel() { if (dynamic_cast<FloatModelView*>(this)) { setModel(new FloatModel(0, 0, 0, 1, nullptr, QString(), true)); } else if (dynamic_cast<IntModelView*>(this)) { setModel(new IntModel(0, 0, 0, nullptr, QString(), true)); } else if (dynamic_cast<BoolModelView*>(this)) { setModel(new BoolModel(false, nullptr, QString(), true)); } else { ModelView::unsetModel(); } } void AutomatableModelView::mousePressEvent( QMouseEvent* event ) { if( event->button() == Qt::LeftButton && event->modifiers() & Qt::ControlModifier ) { new gui::StringPairDrag( "automatable_model", QString::number( modelUntyped()->id() ), QPixmap(), widget() ); event->accept(); } else if( event->button() == Qt::MiddleButton ) { modelUntyped()->reset(); } } void AutomatableModelView::setConversionFactor( float factor ) { if( factor != 0.0 ) { m_conversionFactor = factor; } } float AutomatableModelView::getConversionFactor() { return m_conversionFactor; } AutomatableModelViewSlots::AutomatableModelViewSlots( AutomatableModelView* amv, QObject* parent ) : QObject(), m_amv( amv ) { connect( parent, SIGNAL(destroyed()), this, SLOT(deleteLater()), Qt::QueuedConnection ); } void AutomatableModelViewSlots::execConnectionDialog() { // TODO[pg]: Display a dialog with list of controllers currently in the song // in addition to any system MIDI controllers AutomatableModel* m = m_amv->modelUntyped(); m->displayName(); gui::ControllerConnectionDialog d( getGUI()->mainWindow(), m ); if( d.exec() == 1 ) { // Actually chose something if( d.chosenController() ) { // Update if( m->controllerConnection() ) { m->controllerConnection()->setController( d.chosenController() ); } // New else { auto cc = new ControllerConnection(d.chosenController()); m->setControllerConnection( cc ); //cc->setTargetName( m->displayName() ); } } // no controller, so delete existing connection else { removeConnection(); } } } void AutomatableModelViewSlots::removeConnection() { AutomatableModel* m = m_amv->modelUntyped(); if( m->controllerConnection() ) { delete m->controllerConnection(); m->setControllerConnection( nullptr ); } } void AutomatableModelViewSlots::editSongGlobalAutomation() { getGUI()->automationEditor()->open( AutomationClip::globalAutomationClip(m_amv->modelUntyped()) ); } void AutomatableModelViewSlots::removeSongGlobalAutomation() { delete AutomationClip::globalAutomationClip( m_amv->modelUntyped() ); } void AutomatableModelViewSlots::unlinkAllModels() { m_amv->modelUntyped()->unlinkAllModels(); } void AutomatableModelViewSlots::copyToClipboard() { // For copyString() and MimeType enum class using namespace Clipboard; copyString( QString::number( m_amv->value<float>() * m_amv->getConversionFactor() ), MimeType::Default ); } void AutomatableModelViewSlots::pasteFromClipboard() { bool isNumber = false; const float number = floatFromClipboard(&isNumber); if (isNumber) { m_amv->modelUntyped()->setValue(number / m_amv->getConversionFactor()); } } /// Attempt to parse a float from the clipboard static float floatFromClipboard(bool* ok) { // For getString() and MimeType enum class using namespace Clipboard; return getString( MimeType::Default ).toFloat(ok); } } // namespace lmms::gui
7,849
C++
.cpp
245
29.15102
111
0.728877
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,892
Controls.cpp
LMMS_lmms/src/gui/Controls.cpp
/* * Controls.cpp - labeled control widgets * * Copyright (c) 2019-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. * */ #include "Controls.h" #include <QLabel> #include <QString> #include <QVBoxLayout> #include "ComboBox.h" #include "LcdSpinBox.h" #include "LedCheckBox.h" #include "Knob.h" namespace lmms::gui { void KnobControl::setText(const QString &text) { m_knob->setLabel(text); } QWidget *KnobControl::topWidget() { return m_knob; } void KnobControl::setModel(AutomatableModel *model) { m_knob->setModel(model->dynamicCast<FloatModel>(true)); } FloatModel *KnobControl::model() { return m_knob->model(); } AutomatableModelView* KnobControl::modelView() { return m_knob; } KnobControl::KnobControl(QWidget *parent) : m_knob(new Knob(parent)) {} void ComboControl::setText(const QString &text) { m_label->setText(text); } void ComboControl::setModel(AutomatableModel *model) { m_combo->setModel(model->dynamicCast<ComboBoxModel>(true)); } ComboBoxModel *ComboControl::model() { return m_combo->model(); } AutomatableModelView* ComboControl::modelView() { return m_combo; } ComboControl::ComboControl(QWidget *parent) : m_widget(new QWidget(parent)), m_combo(new ComboBox(nullptr)), m_label(new QLabel(m_widget)) { m_combo->setFixedSize(64, ComboBox::DEFAULT_HEIGHT); auto vbox = new QVBoxLayout(m_widget); vbox->addWidget(m_combo); vbox->addWidget(m_label); m_combo->repaint(); } void CheckControl::setText(const QString &text) { m_label->setText(text); } QWidget *CheckControl::topWidget() { return m_widget; } void CheckControl::setModel(AutomatableModel *model) { m_checkBox->setModel(model->dynamicCast<BoolModel>(true)); } BoolModel *CheckControl::model() { return m_checkBox->model(); } AutomatableModelView* CheckControl::modelView() { return m_checkBox; } CheckControl::CheckControl(QWidget *parent) : m_widget(new QWidget(parent)), m_checkBox(new LedCheckBox(nullptr, QString(), LedCheckBox::LedColor::Green)), m_label(new QLabel(m_widget)) { auto vbox = new QVBoxLayout(m_widget); vbox->addWidget(m_checkBox); vbox->addWidget(m_label); } void LcdControl::setText(const QString &text) { m_lcd->setLabel(text); } QWidget *LcdControl::topWidget() { return m_lcd; } void LcdControl::setModel(AutomatableModel *model) { m_lcd->setModel(model->dynamicCast<IntModel>(true)); } IntModel *LcdControl::model() { return m_lcd->model(); } AutomatableModelView* LcdControl::modelView() { return m_lcd; } LcdControl::LcdControl(int numDigits, QWidget *parent) : m_lcd(new LcdSpinBox(numDigits, parent)) { } } // namespace lmms::gui
3,386
C++
.cpp
91
35.340659
79
0.755064
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,893
GuiApplication.cpp
LMMS_lmms/src/gui/GuiApplication.cpp
/* * GuiApplication.cpp * * 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. * */ #include "GuiApplication.h" #include "lmmsversion.h" #include "LmmsStyle.h" #include "LmmsPalette.h" #include "AutomationEditor.h" #include "ConfigManager.h" #include "ControllerRackView.h" #include "MixerView.h" #include "MainWindow.h" #include "MicrotunerConfig.h" #include "PatternEditor.h" #include "PianoRoll.h" #include "ProjectNotes.h" #include "SongEditor.h" #include <QApplication> #include <QDir> #include <QtGlobal> #include <QLabel> #include <QMessageBox> #include <QSplashScreen> #ifdef LMMS_BUILD_WIN32 #include <windows.h> #endif namespace lmms { namespace gui { GuiApplication* getGUI() { return GuiApplication::instance(); } GuiApplication* GuiApplication::s_instance = nullptr; GuiApplication* GuiApplication::instance() { return s_instance; } GuiApplication::GuiApplication() { // prompt the user to create the LMMS working directory (e.g. ~/Documents/lmms) if it doesn't exist if ( !ConfigManager::inst()->hasWorkingDir() && QMessageBox::question( nullptr, tr( "Working directory" ), tr( "The LMMS working directory %1 does not " "exist. Create it now? You can change the directory " "later via Edit -> Settings." ).arg( ConfigManager::inst()->workingDir() ), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ) == QMessageBox::Yes) { ConfigManager::inst()->createWorkingDir(); } // Init style and palette QDir::addSearchPath("artwork", ConfigManager::inst()->themeDir()); QDir::addSearchPath("artwork", ConfigManager::inst()->defaultThemeDir()); QDir::addSearchPath("artwork", ":/artwork"); auto lmmsstyle = new LmmsStyle(); QApplication::setStyle(lmmsstyle); auto lmmspal = new LmmsPalette(nullptr, lmmsstyle); auto lpal = new QPalette(lmmspal->palette()); QApplication::setPalette( *lpal ); LmmsStyle::s_palette = lpal; #ifdef LMMS_BUILD_APPLE QApplication::setAttribute(Qt::AA_DontShowIconsInMenus, true); #endif // Show splash screen QSplashScreen splashScreen( embed::getIconPixmap( "splash" ) ); splashScreen.show(); QHBoxLayout layout; layout.setAlignment(Qt::AlignBottom); splashScreen.setLayout(&layout); // Create a left-aligned label for loading progress // & a right-aligned label for version info QLabel loadingProgressLabel; m_loadingProgressLabel = &loadingProgressLabel; QLabel versionLabel(MainWindow::tr( "Version %1" ).arg( LMMS_VERSION )); loadingProgressLabel.setAlignment(Qt::AlignLeft); versionLabel.setAlignment(Qt::AlignRight); layout.addWidget(&loadingProgressLabel); layout.addWidget(&versionLabel); // may have long gaps between future frames, so force update now splashScreen.update(); qApp->processEvents(); connect(Engine::inst(), SIGNAL(initProgress(const QString&)), this, SLOT(displayInitProgress(const QString&))); // Init central engine which handles all components of LMMS Engine::init(false); s_instance = this; displayInitProgress(tr("Preparing UI")); m_mainWindow = new MainWindow; connect(m_mainWindow, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); connect(m_mainWindow, SIGNAL(initProgress(const QString&)), this, SLOT(displayInitProgress(const QString&))); displayInitProgress(tr("Preparing song editor")); m_songEditor = new SongEditorWindow(Engine::getSong()); connect(m_songEditor, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); displayInitProgress(tr("Preparing mixer")); m_mixerView = new MixerView(Engine::mixer()); connect(m_mixerView, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); displayInitProgress(tr("Preparing controller rack")); m_controllerRackView = new ControllerRackView; connect(m_controllerRackView, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); displayInitProgress(tr("Preparing project notes")); m_projectNotes = new ProjectNotes; connect(m_projectNotes, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); displayInitProgress(tr("Preparing microtuner")); m_microtunerConfig = new MicrotunerConfig; connect(m_microtunerConfig, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); displayInitProgress(tr("Preparing pattern editor")); m_patternEditor = new PatternEditorWindow(Engine::patternStore()); connect(m_patternEditor, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); displayInitProgress(tr("Preparing piano roll")); m_pianoRoll = new PianoRollWindow(); connect(m_pianoRoll, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); displayInitProgress(tr("Preparing automation editor")); m_automationEditor = new AutomationEditorWindow; connect(m_automationEditor, SIGNAL(destroyed(QObject*)), this, SLOT(childDestroyed(QObject*))); splashScreen.finish(m_mainWindow); m_mainWindow->finalize(); m_loadingProgressLabel = nullptr; } GuiApplication::~GuiApplication() { s_instance = nullptr; } void GuiApplication::displayInitProgress(const QString &msg) { Q_ASSERT(m_loadingProgressLabel != nullptr); m_loadingProgressLabel->setText(msg); // must force a UI update and process events, as there may be long gaps between processEvents() calls during init m_loadingProgressLabel->repaint(); qApp->processEvents(); } void GuiApplication::childDestroyed(QObject *obj) { // when any object that can be reached via getGUI()->mainWindow(), getGUI()->mixerView(), etc // is destroyed, ensure that their accessor functions will return null instead of a garbage pointer. if (obj == m_mainWindow) { m_mainWindow = nullptr; } else if (obj == m_mixerView) { m_mixerView = nullptr; } else if (obj == m_songEditor) { m_songEditor = nullptr; } else if (obj == m_automationEditor) { m_automationEditor = nullptr; } else if (obj == m_patternEditor) { m_patternEditor = nullptr; } else if (obj == m_pianoRoll) { m_pianoRoll = nullptr; } else if (obj == m_projectNotes) { m_projectNotes = nullptr; } else if (obj == m_microtunerConfig) { m_microtunerConfig = nullptr; } else if (obj == m_controllerRackView) { m_controllerRackView = nullptr; } } #ifdef LMMS_BUILD_WIN32 /*! * @brief Returns the Windows System font. */ QFont GuiApplication::getWin32SystemFont() { NONCLIENTMETRICS metrics = { sizeof( NONCLIENTMETRICS ) }; SystemParametersInfo( SPI_GETNONCLIENTMETRICS, sizeof( NONCLIENTMETRICS ), &metrics, 0 ); int pointSize = metrics.lfMessageFont.lfHeight; if ( pointSize < 0 ) { // height is in pixels, convert to points HDC hDC = GetDC( nullptr ); pointSize = MulDiv( abs( pointSize ), 72, GetDeviceCaps( hDC, LOGPIXELSY ) ); ReleaseDC( nullptr, hDC ); } return QFont( QString::fromUtf8( metrics.lfMessageFont.lfFaceName ), pointSize ); } #endif } // namespace gui } // namespace lmms
7,612
C++
.cpp
215
33.260465
114
0.761879
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,894
FileBrowser.cpp
LMMS_lmms/src/gui/FileBrowser.cpp
/* * FileBrowser.cpp - implementation of the project-, preset- and * sample-file-browser * * 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. * */ #include "FileBrowser.h" #include <QApplication> #include <QDesktopServices> #include <QDirIterator> #include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> #include <QMdiArea> #include <QMdiSubWindow> #include <QMenu> #include <QMessageBox> #include <QPushButton> #include <QShortcut> #include <QStringList> #include <cassert> #include <queue> #include "AudioEngine.h" #include "ConfigManager.h" #include "DataFile.h" #include "Engine.h" #include "FileBrowser.h" #include "FileSearch.h" #include "GuiApplication.h" #include "ImportFilter.h" #include "Instrument.h" #include "InstrumentTrack.h" #include "InstrumentTrackWindow.h" #include "MainWindow.h" #include "PatternStore.h" #include "PluginFactory.h" #include "PresetPreviewPlayHandle.h" #include "Sample.h" #include "SampleClip.h" #include "SampleLoader.h" #include "SamplePlayHandle.h" #include "SampleTrack.h" #include "Song.h" #include "StringPairDrag.h" #include "TextFloat.h" #include "ThreadPool.h" #include "embed.h" namespace lmms::gui { enum TreeWidgetItemTypes { TypeFileItem = QTreeWidgetItem::UserType, TypeDirectoryItem } ; FileBrowser::FileBrowser(const QString & directories, const QString & filter, const QString & title, const QPixmap & pm, QWidget * parent, bool dirs_as_items, const QString& userDir, const QString& factoryDir): SideBarWidget( title, pm, parent ), m_directories( directories ), m_filter( filter ), m_dirsAsItems( dirs_as_items ), m_userDir(userDir), m_factoryDir(factoryDir) { setWindowTitle( tr( "Browser" ) ); addContentCheckBox(); auto searchWidget = new QWidget(contentParent()); searchWidget->setFixedHeight( 24 ); auto searchWidgetLayout = new QHBoxLayout(searchWidget); searchWidgetLayout->setContentsMargins(0, 0, 0, 0); searchWidgetLayout->setSpacing( 0 ); m_filterEdit = new QLineEdit(searchWidget); m_filterEdit->setPlaceholderText(tr("Search")); m_filterEdit->setClearButtonEnabled(true); m_filterEdit->addAction(embed::getIconPixmap("zoom"), QLineEdit::LeadingPosition); connect(m_filterEdit, &QLineEdit::textEdited, this, &FileBrowser::onSearch); auto reload_btn = new QPushButton(embed::getIconPixmap("reload"), QString(), searchWidget); reload_btn->setToolTip( tr( "Refresh list" ) ); connect( reload_btn, SIGNAL(clicked()), this, SLOT(reloadTree())); searchWidgetLayout->addWidget( m_filterEdit ); searchWidgetLayout->addSpacing( 5 ); searchWidgetLayout->addWidget( reload_btn ); addContentWidget( searchWidget ); m_fileBrowserTreeWidget = new FileBrowserTreeWidget( contentParent() ); addContentWidget( m_fileBrowserTreeWidget ); m_searchTreeWidget = new FileBrowserTreeWidget(contentParent()); m_searchTreeWidget->hide(); addContentWidget(m_searchTreeWidget); m_searchIndicator = new QProgressBar(this); m_searchIndicator->setMinimum(0); m_searchIndicator->setMaximum(100); addContentWidget(m_searchIndicator); // Whenever the FileBrowser has focus, Ctrl+F should direct focus to its filter box. auto filterFocusShortcut = new QShortcut(QKeySequence(QKeySequence::Find), this, SLOT(giveFocusToFilter())); filterFocusShortcut->setContext(Qt::WidgetWithChildrenShortcut); m_previousFilterValue = ""; reloadTree(); show(); } void FileBrowser::addContentCheckBox() { // user dir and factory dir checkboxes will display individually depending on whether they are empty. const bool user_checkbox = !m_userDir.isEmpty(); const bool factory = !m_factoryDir.isEmpty(); auto filterWidget = new QWidget(contentParent()); outerLayout = new QBoxLayout(QBoxLayout::Direction::TopToBottom, filterWidget); outerLayout->setSpacing(0); if (user_checkbox || factory){ filterWidgetLayout = new QBoxLayout(QBoxLayout::Direction::LeftToRight); filterWidgetLayout->setContentsMargins(0, 0, 0, 0); filterWidgetLayout->setSpacing(0); outerLayout->addLayout(filterWidgetLayout); } hiddenWidgetLayout = new QBoxLayout(QBoxLayout::Direction::LeftToRight); hiddenWidgetLayout->setContentsMargins(0, 0, 0, 0); hiddenWidgetLayout->setSpacing(0); outerLayout->addLayout(hiddenWidgetLayout); auto configCheckBox = [this](QBoxLayout* boxLayout, QCheckBox* box, Qt::CheckState checkState) { box->setCheckState(checkState); connect(box, SIGNAL(stateChanged(int)), this, SLOT(reloadTree())); boxLayout->addWidget(box); }; if (user_checkbox) { m_showUserContent = new QCheckBox(tr("User content")); configCheckBox(filterWidgetLayout, m_showUserContent, Qt::Checked); } if (factory) { m_showFactoryContent = new QCheckBox(tr("Factory content")); configCheckBox(filterWidgetLayout, m_showFactoryContent, Qt::Checked); } m_showHiddenContent = new QCheckBox(tr("Hidden content")); configCheckBox(hiddenWidgetLayout, m_showHiddenContent, Qt::Unchecked); addContentWidget(filterWidget); } void FileBrowser::saveDirectoriesStates() { m_savedExpandedDirs = m_fileBrowserTreeWidget->expandedDirs(); } void FileBrowser::restoreDirectoriesStates() { expandItems(m_savedExpandedDirs); } void FileBrowser::foundSearchMatch(FileSearch* search, const QString& match) { assert(search != nullptr); if (m_currentSearch.get() != search) { return; } auto basePath = QString{}; for (const auto& path : m_directories.split('*')) { if (!match.startsWith(QDir{path}.absolutePath())) { continue; } basePath = path; break; } if (basePath.isEmpty()) { return; } const auto baseDir = QDir{basePath}; const auto matchInfo = QFileInfo{match}; const auto matchRelativeToBasePath = baseDir.relativeFilePath(match); auto pathParts = QDir::cleanPath(matchRelativeToBasePath).split("/"); auto currentItem = static_cast<QTreeWidgetItem*>(nullptr); auto currentDir = baseDir; for (const auto& pathPart : pathParts) { auto childCount = currentItem ? currentItem->childCount() : m_searchTreeWidget->topLevelItemCount(); auto childItem = static_cast<QTreeWidgetItem*>(nullptr); for (int i = 0; i < childCount; ++i) { auto item = currentItem ? currentItem->child(i) : m_searchTreeWidget->topLevelItem(i); if (item->text(0) == pathPart) { childItem = item; break; } } if (!childItem) { auto pathPartInfo = QFileInfo(currentDir, pathPart); if (pathPartInfo.isDir()) { // Only update directory (i.e., add entries) when it is the matched directory (so do not update // parents since entries would be added to them that did not match the filter) const auto disablePopulation = pathParts.indexOf(pathPart) < pathParts.size() - 1; auto item = new Directory(pathPart, currentDir.path(), m_filter, disablePopulation); currentItem ? currentItem->addChild(item) : m_searchTreeWidget->addTopLevelItem(item); item->update(); if (disablePopulation) { m_searchTreeWidget->expandItem(item); } childItem = item; } else { auto item = new FileItem(pathPart, currentDir.path()); currentItem ? currentItem->addChild(item) : m_searchTreeWidget->addTopLevelItem(item); childItem = item; } } currentItem = childItem; if (!currentDir.cd(pathPart)) { break; } } } void FileBrowser::searchCompleted(FileSearch* search) { assert(search != nullptr); if (m_currentSearch.get() != search) { return; } m_currentSearch.reset(); m_searchIndicator->setMaximum(100); } void FileBrowser::onSearch(const QString& filter) { if (m_currentSearch) { m_currentSearch->cancel(); } if (filter.isEmpty()) { displaySearch(false); return; } auto directories = m_directories.split('*'); if (m_showUserContent && !m_showUserContent->isChecked()) { directories.removeAll(m_userDir); } if (m_showFactoryContent && !m_showFactoryContent->isChecked()) { directories.removeAll(m_factoryDir); } if (directories.isEmpty()) { return; } m_searchTreeWidget->clear(); displaySearch(true); auto browserExtensions = m_filter; const auto searchExtensions = browserExtensions.remove("*.").split(' '); auto search = std::make_shared<FileSearch>( filter, directories, searchExtensions, excludedPaths(), dirFilters(), sortFlags()); connect(search.get(), &FileSearch::foundMatch, this, &FileBrowser::foundSearchMatch, Qt::QueuedConnection); connect(search.get(), &FileSearch::searchCompleted, this, &FileBrowser::searchCompleted, Qt::QueuedConnection); m_currentSearch = search; ThreadPool::instance().enqueue([search] { (*search)(); }); } void FileBrowser::displaySearch(bool on) { if (on) { m_searchTreeWidget->show(); m_fileBrowserTreeWidget->hide(); m_searchIndicator->setMaximum(0); return; } m_searchTreeWidget->hide(); m_fileBrowserTreeWidget->show(); m_searchIndicator->setMaximum(100); } void FileBrowser::reloadTree() { if (m_filterEdit->text().isEmpty()) { saveDirectoriesStates(); } m_fileBrowserTreeWidget->clear(); QStringList paths = m_directories.split('*'); if (m_showUserContent && !m_showUserContent->isChecked()) { paths.removeAll(m_userDir); } if (m_showFactoryContent && !m_showFactoryContent->isChecked()) { paths.removeAll(m_factoryDir); } if (!paths.isEmpty()) { for (const auto& path : paths) { addItems(path); } } if (m_filterEdit->text().isEmpty()) { restoreDirectoriesStates(); } else { onSearch(m_filterEdit->text()); } } void FileBrowser::expandItems(const QList<QString>& expandedDirs, QTreeWidgetItem* item) { if (expandedDirs.isEmpty()) { return; } int numChildren = item ? item->childCount() : m_fileBrowserTreeWidget->topLevelItemCount(); for (int i = 0; i < numChildren; ++i) { auto it = item ? item->child(i) : m_fileBrowserTreeWidget->topLevelItem(i); auto d = dynamic_cast<Directory*>(it); if (d) { d->setExpanded(expandedDirs.contains(d->fullName())); if (it->childCount() > 0) { expandItems(expandedDirs, it); } } it->setHidden(false); } } void FileBrowser::giveFocusToFilter() { if (!m_filterEdit->hasFocus()) { // give focus to filter text box and highlight its text for quick editing if not previously focused m_filterEdit->setFocus(); m_filterEdit->selectAll(); } } void FileBrowser::addItems(const QString & path ) { if (FileBrowser::excludedPaths().contains(path)) { return; } if( m_dirsAsItems ) { m_fileBrowserTreeWidget->addTopLevelItem( new Directory( path, QString(), m_filter ) ); return; } // try to add all directories from file system alphabetically into the tree QDir cdir(path); if (!cdir.isReadable()) { return; } QFileInfoList entries = cdir.entryInfoList( m_filter.split(' '), dirFilters(), QDir::LocaleAware | QDir::DirsFirst | QDir::Name | QDir::IgnoreCase); for (const auto& entry : entries) { if (FileBrowser::excludedPaths().contains(entry.absoluteFilePath())) { continue; } QString fileName = entry.fileName(); if (entry.isHidden() && m_showHiddenContent && !m_showHiddenContent->isChecked()) continue; if (entry.isDir()) { // Merge dir's together bool orphan = true; for (int i = 0; i < m_fileBrowserTreeWidget->topLevelItemCount(); ++i) { auto d = dynamic_cast<Directory*>(m_fileBrowserTreeWidget->topLevelItem(i)); if (d == nullptr || fileName < d->text(0)) { // insert before item, we're done auto dd = new Directory(fileName, path, m_filter); m_fileBrowserTreeWidget->insertTopLevelItem(i,dd); dd->update(); // add files to the directory orphan = false; break; } else if (fileName == d->text(0)) { // imagine we have subdirs named "TripleOscillator/xyz" in // two directories from m_directories // then only add one tree widget for both // so we don't add a new Directory - we just // add the path to the current directory d->addDirectory(path); d->update(); orphan = false; break; } } if (orphan) { // it has not yet been added yet, so it's (lexically) // larger than all other dirs => append it at the bottom auto d = new Directory(fileName, path, m_filter); d->update(); m_fileBrowserTreeWidget->addTopLevelItem(d); } } else if (entry.isFile()) { // TODO: don't insert instead of removing, order changed // remove existing file-items QList<QTreeWidgetItem *> existing = m_fileBrowserTreeWidget->findItems(fileName, Qt::MatchFixedString); if (!existing.empty()) { delete existing.front(); } (void) new FileItem(m_fileBrowserTreeWidget, fileName, path); } } } void FileBrowser::keyPressEvent(QKeyEvent * ke ) { switch( ke->key() ){ case Qt::Key_F5: reloadTree(); break; default: ke->ignore(); } } FileBrowserTreeWidget::FileBrowserTreeWidget(QWidget * parent ) : QTreeWidget( parent ), m_mousePressed( false ), m_pressPos(), m_previewPlayHandle( nullptr ) #if (QT_VERSION < QT_VERSION_CHECK(5,14,0)) ,m_pphMutex(QMutex::Recursive) #endif { setColumnCount( 1 ); headerItem()->setHidden( true ); setSortingEnabled( false ); connect( this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), SLOT(activateListItem(QTreeWidgetItem*,int))); connect( this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), SLOT(updateDirectory(QTreeWidgetItem*))); connect( this, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(updateDirectory(QTreeWidgetItem*))); #if QT_VERSION < QT_VERSION_CHECK(5, 12, 2) && defined LMMS_BUILD_WIN32 // Set the font for the QTreeWidget to the Windows System font to make sure that // truncated (elided) items use the same font as non-truncated items. // This is a workaround for this qt bug, fixed in 5.12.2: https://bugreports.qt.io/browse/QTBUG-29232 // TODO: remove this when all builds use a recent enough version of qt. setFont( GuiApplication::getWin32SystemFont() ); #endif } QList<QString> FileBrowserTreeWidget::expandedDirs( QTreeWidgetItem * item ) const { int numChildren = item ? item->childCount() : topLevelItemCount(); QList<QString> dirs; for (int i = 0; i < numChildren; ++i) { QTreeWidgetItem * it = item ? item->child(i) : topLevelItem(i); // Add expanded top level directories. if (it->isExpanded() && (it->type() == TypeDirectoryItem)) { auto d = static_cast<Directory*>(it); dirs.append( d->fullName() ); } // Add expanded child directories (recurse). if (it->childCount()) { dirs.append( expandedDirs( it ) ); } } return dirs; } void FileBrowserTreeWidget::keyPressEvent(QKeyEvent * ke ) { // Shorter names for some commonly used properties of the event const auto key = ke->key(); const bool vertical = (key == Qt::Key_Up || key == Qt::Key_Down); const bool horizontal = (key == Qt::Key_Left || key == Qt::Key_Right); const bool insert = (key == Qt::Key_Enter || key == Qt::Key_Return); const bool preview = (key == Qt::Key_Space); // First of all, forward all keypresses QTreeWidget::keyPressEvent(ke); // Then, ignore all autorepeats (they would spam new tracks or previews) if (ke->isAutoRepeat()) { return; } // We should stop any running previews before we do anything new else if (vertical || horizontal || preview || insert) { stopPreview(); } // Try to get the currently selected item as a FileItem auto file = dynamic_cast<FileItem*>(currentItem()); // If it's null (folder, separator, etc.), there's nothing left for us to do if (file == nullptr) { return; } // When moving to a new sound, preview it. Skip presets, they can play forever if (vertical && file->type() == FileItem::FileType::Sample) { previewFileItem(file); } // When enter is pressed, add the selected item... if (insert) { // ...to the song editor by default, or to the pattern editor if ctrl is held bool songEditor = !(ke->modifiers() & Qt::ControlModifier); // If shift is held, we send the item to a new sample track... bool sampleTrack = ke->modifiers() & Qt::ShiftModifier; // ...but only in the song editor. So, ctrl+shift enter does nothing if (sampleTrack && songEditor){ openInNewSampleTrack(file); } // Otherwise we send the item as a new instrument track else if (!sampleTrack){ openInNewInstrumentTrack(file, songEditor); } } // When space is pressed, start a preview of the selected item if (preview) { previewFileItem(file); } } void FileBrowserTreeWidget::keyReleaseEvent(QKeyEvent* ke) { // Cancel previews when the space key is released if (ke->key() == Qt::Key_Space && !ke->isAutoRepeat()) { stopPreview(); } } void FileBrowserTreeWidget::hideEvent(QHideEvent* he) { // Cancel previews when the user switches tabs or hides the sidebar stopPreview(); QTreeWidget::hideEvent(he); } void FileBrowserTreeWidget::focusOutEvent(QFocusEvent* fe) { // Cancel previews when the user clicks outside the browser stopPreview(); QTreeWidget::focusOutEvent(fe); } void FileBrowserTreeWidget::contextMenuEvent(QContextMenuEvent * e ) { auto file = dynamic_cast<FileItem*>(itemAt(e->pos())); if( file != nullptr && file->isTrack() ) { QMenu contextMenu( this ); contextMenu.addAction( tr( "Send to active instrument-track" ), [=]{ sendToActiveInstrumentTrack(file); } ); contextMenu.addSeparator(); contextMenu.addAction( QIcon(embed::getIconPixmap("folder")), tr("Open containing folder"), [=]{ openContainingFolder(file); } ); auto songEditorHeader = new QAction(tr("Song Editor"), nullptr); songEditorHeader->setDisabled(true); contextMenu.addAction( songEditorHeader ); contextMenu.addActions( getContextActions(file, true) ); auto patternEditorHeader = new QAction(tr("Pattern Editor"), nullptr); patternEditorHeader->setDisabled(true); contextMenu.addAction(patternEditorHeader); contextMenu.addActions( getContextActions(file, false) ); // We should only show the menu if it contains items if (!contextMenu.isEmpty()) { contextMenu.exec( e->globalPos() ); } } } QList<QAction*> FileBrowserTreeWidget::getContextActions(FileItem* file, bool songEditor) { QList<QAction*> result = QList<QAction*>(); const bool fileIsSample = file->type() == FileItem::FileType::Sample; QString instrumentAction = fileIsSample ? tr("Send to new AudioFileProcessor instance") : tr("Send to new instrument track"); QString shortcutMod = songEditor ? "" : UI_CTRL_KEY + QString(" + "); auto toInstrument = new QAction(instrumentAction + tr(" (%2Enter)").arg(shortcutMod), nullptr); connect(toInstrument, &QAction::triggered, [=]{ openInNewInstrumentTrack(file, songEditor); }); result.append(toInstrument); if (songEditor && fileIsSample) { auto toSampleTrack = new QAction(tr("Send to new sample track (Shift + Enter)"), nullptr); connect(toSampleTrack, &QAction::triggered, [=]{ openInNewSampleTrack(file); }); result.append(toSampleTrack); } return result; } void FileBrowserTreeWidget::mousePressEvent(QMouseEvent * me ) { // Forward the event QTreeWidgetItem * i = itemAt(me->pos()); QTreeWidget::mousePressEvent(me); // QTreeWidget handles right clicks for us, so we only care about left clicks if(me->button() != Qt::LeftButton) { return; } if (i) { // TODO: Restrict to visible selection // if ( _me->x() > header()->cellPos( header()->mapToActual( 0 ) ) // + treeStepSize() * ( i->depth() + ( rootIsDecorated() ? // 1 : 0 ) ) + itemMargin() || // _me->x() < header()->cellPos( // header()->mapToActual( 0 ) ) ) // { m_pressPos = me->pos(); m_mousePressed = true; // } } auto f = dynamic_cast<FileItem*>(i); if(f != nullptr) { previewFileItem(f); } } void FileBrowserTreeWidget::previewFileItem(FileItem* file) { // TODO: We should do this work outside the event thread // Lock the preview mutex QMutexLocker previewLocker(&m_pphMutex); // If something is already playing, stop it before we continue stopPreview(); PlayHandle* newPPH = nullptr; const QString fileName = file->fullName(); const QString ext = file->extension(); // In special case of sample-files we do not care about // handling() rather than directly creating a SamplePlayHandle if (file->type() == FileItem::FileType::Sample) { TextFloat * tf = TextFloat::displayMessage( tr("Loading sample"), tr("Please wait, loading sample for preview..."), embed::getIconPixmap("sample_file", 24, 24), 0); // TODO: this can be removed once we do this outside the event thread qApp->processEvents(QEventLoop::ExcludeUserInputEvents); if (auto buffer = SampleLoader::createBufferFromFile(fileName)) { auto s = new SamplePlayHandle(new lmms::Sample{std::move(buffer)}); s->setDoneMayReturnTrue(false); newPPH = s; } delete tf; } else if ( (ext == "xiz" || ext == "sf2" || ext == "sf3" || ext == "gig" || ext == "pat") && !getPluginFactory()->pluginSupportingExtension(ext).isNull()) { const bool isPlugin = file->handling() == FileItem::FileHandling::LoadByPlugin; newPPH = new PresetPreviewPlayHandle(fileName, isPlugin); } else if (file->type() != FileItem::FileType::VstPlugin && file->isTrack()) { DataFile dataFile(fileName); if (dataFile.validate(ext)) { const bool isPlugin = file->handling() == FileItem::FileHandling::LoadByPlugin; newPPH = new PresetPreviewPlayHandle(fileName, isPlugin, &dataFile); } else { QMessageBox::warning(0, tr ("Error"), tr("%1 does not appear to be a valid %2 file") .arg(fileName, ext), QMessageBox::Ok, QMessageBox::NoButton); } } if (newPPH != nullptr) { if (Engine::audioEngine()->addPlayHandle(newPPH)) { m_previewPlayHandle = newPPH; } else { m_previewPlayHandle = nullptr; } } } void FileBrowserTreeWidget::stopPreview() { QMutexLocker previewLocker(&m_pphMutex); if (m_previewPlayHandle != nullptr) { Engine::audioEngine()->removePlayHandle(m_previewPlayHandle); m_previewPlayHandle = nullptr; } } void FileBrowserTreeWidget::mouseMoveEvent( QMouseEvent * me ) { if( m_mousePressed == true && ( m_pressPos - me->pos() ).manhattanLength() > QApplication::startDragDistance() ) { // make sure any playback is stopped mouseReleaseEvent( nullptr ); auto f = dynamic_cast<FileItem*>(itemAt(m_pressPos)); if( f != nullptr ) { switch( f->type() ) { case FileItem::FileType::Preset: new StringPairDrag( f->handling() == FileItem::FileHandling::LoadAsPreset ? "presetfile" : "pluginpresetfile", f->fullName(), embed::getIconPixmap( "preset_file" ), this ); break; case FileItem::FileType::Sample: new StringPairDrag( "samplefile", f->fullName(), embed::getIconPixmap( "sample_file" ), this ); break; case FileItem::FileType::SoundFont: new StringPairDrag( "soundfontfile", f->fullName(), embed::getIconPixmap( "soundfont_file" ), this ); break; case FileItem::FileType::Patch: new StringPairDrag( "patchfile", f->fullName(), embed::getIconPixmap( "sample_file" ), this ); break; case FileItem::FileType::VstPlugin: new StringPairDrag( "vstpluginfile", f->fullName(), embed::getIconPixmap( "vst_plugin_file" ), this ); break; case FileItem::FileType::Midi: new StringPairDrag( "importedproject", f->fullName(), embed::getIconPixmap( "midi_file" ), this ); break; case FileItem::FileType::Project: new StringPairDrag( "projectfile", f->fullName(), embed::getIconPixmap( "project_file" ), this ); break; default: break; } } } } void FileBrowserTreeWidget::mouseReleaseEvent(QMouseEvent * me ) { m_mousePressed = false; // If a preview is running, we may need to stop it. Otherwise, we're done QMutexLocker previewLocker(&m_pphMutex); if (m_previewPlayHandle == nullptr) { return; } // Only sample previews may continue after mouse up. Is this a sample preview? bool isSample = m_previewPlayHandle->type() == PlayHandle::Type::SamplePlayHandle; // Even sample previews should only continue if the user wants them to. Do they? bool shouldContinue = ConfigManager::inst()->value("ui", "letpreviewsfinish").toInt(); // If both are true the preview may continue, otherwise we stop it if (!(isSample && shouldContinue)) { stopPreview(); } } void FileBrowserTreeWidget::handleFile(FileItem * f, InstrumentTrack * it) { Engine::audioEngine()->requestChangeInModel(); switch( f->handling() ) { case FileItem::FileHandling::LoadAsProject: if( getGUI()->mainWindow()->mayChangeProject(true) ) { Engine::getSong()->loadProject( f->fullName() ); } break; case FileItem::FileHandling::LoadByPlugin: { const QString e = f->extension(); Instrument * i = it->instrument(); if( i == nullptr || !i->descriptor()->supportsFileType( e ) ) { PluginFactory::PluginInfoAndKey piakn = getPluginFactory()->pluginSupportingExtension(e); i = it->loadInstrument(piakn.info.name(), &piakn.key); } i->loadFile( f->fullName() ); break; } case FileItem::FileHandling::LoadAsPreset: { DataFile dataFile(f->fullName()); it->replaceInstrument(dataFile); break; } case FileItem::FileHandling::ImportAsProject: ImportFilter::import( f->fullName(), Engine::getSong() ); break; case FileItem::FileHandling::NotSupported: default: break; } Engine::audioEngine()->doneChangeInModel(); } void FileBrowserTreeWidget::activateListItem(QTreeWidgetItem * item, int column ) { auto f = dynamic_cast<FileItem*>(item); if( f == nullptr ) { return; } if( f->handling() == FileItem::FileHandling::LoadAsProject || f->handling() == FileItem::FileHandling::ImportAsProject ) { handleFile( f, nullptr ); } else if( f->handling() != FileItem::FileHandling::NotSupported ) { auto it = dynamic_cast<InstrumentTrack*>(Track::create(Track::Type::Instrument, Engine::patternStore())); handleFile( f, it ); } } void FileBrowserTreeWidget::openInNewInstrumentTrack(TrackContainer* tc, FileItem* item) { if(item->isTrack()) { auto it = dynamic_cast<InstrumentTrack*>(Track::create(Track::Type::Instrument, tc)); handleFile(item, it); } } void FileBrowserTreeWidget::openInNewInstrumentTrack(FileItem* item, bool songEditor) { // Get the correct TrackContainer. Ternary doesn't compile here TrackContainer* tc = Engine::getSong(); if (!songEditor) { tc = Engine::patternStore(); } openInNewInstrumentTrack(tc, item); } bool FileBrowserTreeWidget::openInNewSampleTrack(FileItem* item) { // Can't add non-samples to a sample track if (item->type() != FileItem::FileType::Sample) { return false; } // Create a new sample track for this sample auto sampleTrack = static_cast<SampleTrack*>(Track::create(Track::Type::Sample, Engine::getSong())); // Add the sample clip to the track Engine::audioEngine()->requestChangeInModel(); SampleClip* clip = static_cast<SampleClip*>(sampleTrack->createClip(0)); clip->setSampleFile(item->fullName()); Engine::audioEngine()->doneChangeInModel(); return true; } void FileBrowserTreeWidget::openContainingFolder(FileItem* item) { // Delegate to QDesktopServices::openUrl with the directory of the selected file. Please note that // this will only open the directory but not select the file as this is much more complicated due // to different implementations that are needed for different platforms (Linux/Windows/MacOS). // Using QDesktopServices::openUrl seems to be the most simple cross platform way which uses // functionality that's already available in Qt. QFileInfo fileInfo(item->fullName()); QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.dir().path())); } void FileBrowserTreeWidget::sendToActiveInstrumentTrack( FileItem* item ) { // get all windows opened in the workspace QList<QMdiSubWindow*> pl = getGUI()->mainWindow()->workspace()-> subWindowList( QMdiArea::StackingOrder ); QListIterator<QMdiSubWindow *> w( pl ); w.toBack(); // now we travel through the window-list until we find an // instrument-track while( w.hasPrevious() ) { auto itw = dynamic_cast<InstrumentTrackWindow*>(w.previous()->widget()); if( itw != nullptr && itw->isHidden() == false ) { handleFile( item, itw->model() ); break; } } } void FileBrowserTreeWidget::updateDirectory(QTreeWidgetItem * item ) { auto dir = dynamic_cast<Directory*>(item); if( dir != nullptr ) { dir->update(); } } Directory::Directory(const QString& filename, const QString& path, const QString& filter, bool disableEntryPopulation) : QTreeWidgetItem(QStringList(filename), TypeDirectoryItem) , m_directories(path) , m_filter(filter) , m_dirCount(0) , m_disableEntryPopulation(disableEntryPopulation) { setIcon(0, !QDir{fullName()}.isReadable() ? m_folderLockedPixmap : m_folderPixmap); setChildIndicatorPolicy( QTreeWidgetItem::ShowIndicator ); } void Directory::update() { if( !isExpanded() ) { setIcon(0, m_folderPixmap); return; } setIcon(0, m_folderOpenedPixmap); if (!m_disableEntryPopulation && !childCount()) { m_dirCount = 0; // for all paths leading here, add their items for (const auto& directory : m_directories) { int filesBeforeAdd = childCount() - m_dirCount; if(addItems(fullName(directory)) && directory.contains(ConfigManager::inst()->dataDir())) { // factory file directory is added // note: those are always added last int filesNow = childCount() - m_dirCount; if(filesNow > filesBeforeAdd) // any file appended? { auto sep = new QTreeWidgetItem; sep->setText( 0, FileBrowserTreeWidget::tr( "--- Factory files ---" ) ); sep->setIcon( 0, embed::getIconPixmap( "factory_files" ) ); // add delimeter after last file before appending our files insertChild( filesBeforeAdd + m_dirCount, sep ); } } } } } bool Directory::addItems(const QString& path) { if (FileBrowser::excludedPaths().contains(path)) { return false; } QDir thisDir(path); if (!thisDir.isReadable()) { return false; } treeWidget()->setUpdatesEnabled(false); QFileInfoList entries = thisDir.entryInfoList(m_filter.split(' '), FileBrowser::dirFilters(), FileBrowser::sortFlags()); for (const auto& entry : entries) { if (FileBrowser::excludedPaths().contains(entry.absoluteFilePath())) { continue; } QString fileName = entry.fileName(); if (entry.isDir()) { auto dir = new Directory(fileName, path, m_filter); addChild(dir); m_dirCount++; } else if (entry.isFile()) { auto fileItem = new FileItem(fileName, path); addChild(fileItem); } } treeWidget()->setUpdatesEnabled(true); // return true if we added any child items return childCount() > 0; } FileItem::FileItem(QTreeWidget * parent, const QString & name, const QString & path ) : QTreeWidgetItem( parent, QStringList( name) , TypeFileItem ), m_path( path ) { determineFileType(); initPixmaps(); } FileItem::FileItem(const QString & name, const QString & path ) : QTreeWidgetItem( QStringList( name ), TypeFileItem ), m_path( path ) { determineFileType(); initPixmaps(); } void FileItem::initPixmaps() { static auto s_projectFilePixmap = embed::getIconPixmap("project_file", 16, 16); static auto s_presetFilePixmap = embed::getIconPixmap("preset_file", 16, 16); static auto s_sampleFilePixmap = embed::getIconPixmap("sample_file", 16, 16); static auto s_soundfontFilePixmap = embed::getIconPixmap("soundfont_file", 16, 16); static auto s_vstPluginFilePixmap = embed::getIconPixmap("vst_plugin_file", 16, 16); static auto s_midiFilePixmap = embed::getIconPixmap("midi_file", 16, 16); static auto s_unknownFilePixmap = embed::getIconPixmap("unknown_file"); switch( m_type ) { case FileType::Project: setIcon(0, s_projectFilePixmap); break; case FileType::Preset: setIcon(0, s_presetFilePixmap); break; case FileType::SoundFont: setIcon(0, s_soundfontFilePixmap); break; case FileType::VstPlugin: setIcon(0, s_vstPluginFilePixmap); break; case FileType::Sample: case FileType::Patch: // TODO setIcon(0, s_sampleFilePixmap); break; case FileType::Midi: setIcon(0, s_midiFilePixmap); break; case FileType::Unknown: default: setIcon(0, s_unknownFilePixmap); break; } } void FileItem::determineFileType() { m_handling = FileHandling::NotSupported; const QString ext = extension(); if( ext == "mmp" || ext == "mpt" || ext == "mmpz" ) { m_type = FileType::Project; m_handling = FileHandling::LoadAsProject; } else if( ext == "xpf" || ext == "xml" ) { m_type = FileType::Preset; m_handling = FileHandling::LoadAsPreset; } else if( ext == "xiz" && ! getPluginFactory()->pluginSupportingExtension(ext).isNull() ) { m_type = FileType::Preset; m_handling = FileHandling::LoadByPlugin; } else if( ext == "sf2" || ext == "sf3" ) { m_type = FileType::SoundFont; } else if( ext == "pat" ) { m_type = FileType::Patch; } else if( ext == "mid" || ext == "midi" || ext == "rmi" ) { m_type = FileType::Midi; m_handling = FileHandling::ImportAsProject; } else if( ext == "dll" #ifdef LMMS_BUILD_LINUX || ext == "so" #endif ) { m_type = FileType::VstPlugin; m_handling = FileHandling::LoadByPlugin; } else if ( ext == "lv2" ) { m_type = FileType::Preset; m_handling = FileHandling::LoadByPlugin; } else { m_type = FileType::Unknown; } if( m_handling == FileHandling::NotSupported && !ext.isEmpty() && ! getPluginFactory()->pluginSupportingExtension(ext).isNull() ) { m_handling = FileHandling::LoadByPlugin; // classify as sample if not classified by anything yet but can // be handled by a certain plugin if( m_type == FileType::Unknown ) { m_type = FileType::Sample; } } } QString FileItem::extension() { return extension( fullName() ); } QString FileItem::extension(const QString & file ) { return QFileInfo( file ).suffix().toLower(); } QString FileItem::defaultFilters() { const auto projectFilters = QStringList{"*.mmp", "*.mpt", "*.mmpz"}; const auto presetFilters = QStringList{"*.xpf", "*.xml", "*.xiz", "*.lv2"}; const auto soundFontFilters = QStringList{"*.sf2", "*.sf3"}; const auto patchFilters = QStringList{"*.pat"}; const auto midiFilters = QStringList{"*.mid", "*.midi", "*.rmi"}; auto vstPluginFilters = QStringList{"*.dll"}; #ifdef LMMS_BUILD_LINUX vstPluginFilters.append("*.so"); #endif auto audioFilters = QStringList{"*.wav", "*.ogg", "*.ds", "*.flac", "*.spx", "*.voc", "*.aif", "*.aiff", "*.au", "*.raw"}; #ifdef LMMS_HAVE_SNDFILE_MP3 audioFilters.append("*.mp3"); #endif const auto extensions = projectFilters + presetFilters + soundFontFilters + patchFilters + midiFilters + vstPluginFilters + audioFilters; return extensions.join(" "); } } // namespace lmms::gui
35,496
C++
.cpp
1,048
31.027672
118
0.721766
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
19,895
RowTableView.cpp
LMMS_lmms/src/gui/RowTableView.cpp
/* * RowTableView.cpp - table with rows that act like single cells * * 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. * */ #include "RowTableView.h" #include <QKeyEvent> #include <QPainter> #include <QStyledItemDelegate> namespace lmms::gui { class RowDelegate : public QStyledItemDelegate { public: RowDelegate( QAbstractItemView * table, QObject * parent = 0 ) : QStyledItemDelegate( parent ), m_table( table ) { } void paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const override; protected: void initStyleOption( QStyleOptionViewItem * option, const QModelIndex & index ) const override; private: QAbstractItemView * m_table; } ; void RowDelegate::initStyleOption( QStyleOptionViewItem * option, const QModelIndex & index ) const { QStyledItemDelegate::initStyleOption( option, index ); option->state &= ~QStyle::State_HasFocus; } void RowDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { QStyledItemDelegate::paint( painter, option, index ); if ( index.row() == m_table->currentIndex().row() ) { const QRect rect( option.rect ); painter->drawLine( rect.topLeft(), rect.topRight() ); painter->drawLine( rect.bottomLeft(), rect.bottomRight() ); if ( index.column() == 0 ) { painter->drawLine( rect.topLeft(), rect.bottomLeft() ); } if ( index.column() == index.model()->columnCount() - 1 ) { painter->drawLine( rect.topRight(), rect.bottomRight() ); } } } RowTableView::RowTableView( QWidget * parent ) : QTableView( parent ) { m_rowDelegate = new RowDelegate( this, this ); } RowTableView::~RowTableView() { delete m_rowDelegate; } void RowTableView::setModel( QAbstractItemModel * model ) { QTableView::setModel( model ); for ( int i = 0; i < model->rowCount(); i++ ) { setItemDelegateForRow( i, m_rowDelegate ); } } void RowTableView::keyPressEvent( QKeyEvent * event ) { switch( event->key() ) { case Qt::Key_Tab: case Qt::Key_Backtab: for( int i = 0; i < model()->columnCount() - 1; i++ ) { QTableView::keyPressEvent( event ); } default: QTableView::keyPressEvent( event ); } } } // namespace lmms::gui
3,061
C++
.cpp
104
26.855769
71
0.724221
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,896
LmmsStyle.cpp
LMMS_lmms/src/gui/LmmsStyle.cpp
/* * LmmsStyle.cpp - the graphical style used by LMMS to create a consistent * interface * * Copyright (c) 2007-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. * */ #include <array> #include <QFile> #include <QApplication> #include <QPainter> #include <QPainterPath> #include <QStyleFactory> #include <QStyleOption> #include "LmmsStyle.h" namespace lmms::gui { QPalette * LmmsStyle::s_palette = nullptr; QLinearGradient getGradient( const QColor & _col, const QRectF & _rect ) { QLinearGradient g( _rect.topLeft(), _rect.bottomLeft() ); qreal hue = _col.hueF(); qreal value = _col.valueF(); qreal saturation = _col.saturationF(); QColor c = _col; c.setHsvF( hue, 0.42 * saturation, 0.98 * value ); // TODO: MIDI clip: 1.08 g.setColorAt( 0, c ); c.setHsvF( hue, 0.58 * saturation, 0.95 * value ); // TODO: MIDI clip: 1.05 g.setColorAt( 0.25, c ); c.setHsvF( hue, 0.70 * saturation, 0.93 * value ); // TODO: MIDI clip: 1.03 g.setColorAt( 0.5, c ); c.setHsvF( hue, 0.95 * saturation, 0.9 * value ); g.setColorAt( 0.501, c ); c.setHsvF( hue * 0.95, 0.95 * saturation, 0.95 * value ); g.setColorAt( 0.75, c ); c.setHsvF( hue * 0.90, 0.95 * saturation, 1 * value ); g.setColorAt( 1.0, c ); return g; } QLinearGradient darken( const QLinearGradient & _gradient ) { QGradientStops stops = _gradient.stops(); for (auto& stop : stops) { QColor color = stop.second; stop.second = color.lighter(133); } QLinearGradient g = _gradient; g.setStops(stops); return g; } void drawPath( QPainter *p, const QPainterPath &path, const QColor &col, const QColor &borderCol, bool dark = false ) { const QRectF pathRect = path.boundingRect(); const QLinearGradient baseGradient = getGradient(col, pathRect); const QLinearGradient darkGradient = darken(baseGradient); p->setOpacity(0.25); // glow if (dark) p->strokePath(path, QPen(darkGradient, 4)); else p->strokePath(path, QPen(baseGradient, 4)); p->setOpacity(1.0); // fill if (dark) p->fillPath(path, darkGradient); else p->fillPath(path, baseGradient); // TODO: Remove?? /* QLinearGradient g(pathRect.topLeft(), pathRect.topRight()); g.setCoordinateMode(QGradient::ObjectBoundingMode); p->setOpacity(0.2); p->fillPath(path, g);*/ // END: Remove?? p->setOpacity(0.5); // highlight (pattern) if (dark) p->strokePath(path, QPen(borderCol.lighter(133), 2)); else p->strokePath(path, QPen(borderCol, 2)); } LmmsStyle::LmmsStyle() : QProxyStyle() { QFile file( "resources:style.css" ); file.open( QIODevice::ReadOnly ); qApp->setStyleSheet( file.readAll() ); if( s_palette != nullptr ) { qApp->setPalette( *s_palette ); } setBaseStyle( QStyleFactory::create( "Fusion" ) ); } QPalette LmmsStyle::standardPalette() const { if( s_palette != nullptr) { return * s_palette; } QPalette pal = QProxyStyle::standardPalette(); return( pal ); } void LmmsStyle::drawComplexControl( ComplexControl control, const QStyleOptionComplex * option, QPainter *painter, const QWidget *widget ) const { // fix broken titlebar styling on win32 if( control == CC_TitleBar ) { const auto titleBar = qstyleoption_cast<const QStyleOptionTitleBar*>(option); if( titleBar ) { QStyleOptionTitleBar so( *titleBar ); so.palette = standardPalette(); so.palette.setColor( QPalette::HighlightedText, ( titleBar->titleBarState & State_Active ) ? QColor( 255, 255, 255 ) : QColor( 192, 192, 192 ) ); so.palette.setColor( QPalette::Text, QColor( 64, 64, 64 ) ); QProxyStyle::drawComplexControl( control, &so, painter, widget ); return; } } else if (control == CC_MdiControls) { QStyleOptionComplex so(*option); so.palette.setColor(QPalette::Button, QColor(223, 228, 236)); QProxyStyle::drawComplexControl(control, &so, painter, widget); return; } /* else if( control == CC_ScrollBar ) { painter->fillRect( option->rect, QApplication::palette().color( QPalette::Active, QPalette::Window ) ); }*/ QProxyStyle::drawComplexControl( control, option, painter, widget ); } void LmmsStyle::drawPrimitive( PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { if( element == QStyle::PE_Frame || element == QStyle::PE_FrameLineEdit || element == QStyle::PE_PanelLineEdit ) { const QRect rect = option->rect; QColor black = QColor( 0, 0, 0 ); QColor shadow = option->palette.shadow().color(); QColor highlight = option->palette.highlight().color(); int a100 = 165; int a75 = static_cast<int>( a100 * .75 ); int a50 = static_cast<int>( a100 * .6 ); int a25 = static_cast<int>( a100 * .33 ); auto lines = std::array<QLine, 4>{}; auto points = std::array<QPoint, 4>{}; // black inside lines // 50% black.setAlpha(a100); painter->setPen(QPen(black, 0)); lines[0] = QLine(rect.left() + 2, rect.top() + 1, rect.right() - 2, rect.top() + 1); lines[1] = QLine(rect.left() + 2, rect.bottom() - 1, rect.right() - 2, rect.bottom() - 1); lines[2] = QLine(rect.left() + 1, rect.top() + 2, rect.left() + 1, rect.bottom() - 2); lines[3] = QLine(rect.right() - 1, rect.top() + 2, rect.right() - 1, rect.bottom() - 2); painter->drawLines(lines.data(), 4); // black inside dots black.setAlpha(a50); painter->setPen(QPen(black, 0)); points[0] = QPoint(rect.left() + 2, rect.top() + 2); points[1] = QPoint(rect.left() + 2, rect.bottom() - 2); points[2] = QPoint(rect.right() - 2, rect.top() + 2); points[3] = QPoint(rect.right() - 2, rect.bottom() - 2); painter->drawPoints(points.data(), 4); // outside lines - shadow // 100% shadow.setAlpha(a75); painter->setPen(QPen(shadow, 0)); lines[0] = QLine(rect.left() + 2, rect.top(), rect.right() - 2, rect.top()); lines[1] = QLine(rect.left(), rect.top() + 2, rect.left(), rect.bottom() - 2); painter->drawLines(lines.data(), 2); // outside corner dots - shadow // 75% shadow.setAlpha(a50); painter->setPen(QPen(shadow, 0)); points[0] = QPoint(rect.left() + 1, rect.top() + 1); points[1] = QPoint(rect.right() - 1, rect.top() + 1); painter->drawPoints(points.data(), 2); // outside end dots - shadow // 50% shadow.setAlpha(a25); painter->setPen(QPen(shadow, 0)); points[0] = QPoint(rect.left() + 1, rect.top()); points[1] = QPoint(rect.left(), rect.top() + 1); points[2] = QPoint(rect.right() - 1, rect.top()); points[3] = QPoint(rect.left(), rect.bottom() - 1); painter->drawPoints(points.data(), 4); // outside lines - highlight // 100% highlight.setAlpha(a75); painter->setPen(QPen(highlight, 0)); lines[0] = QLine(rect.left() + 2, rect.bottom(), rect.right() - 2, rect.bottom()); lines[1] = QLine(rect.right(), rect.top() + 2, rect.right(), rect.bottom() - 2); painter->drawLines(lines.data(), 2); // outside corner dots - highlight // 75% highlight.setAlpha(a50); painter->setPen(QPen(highlight, 0)); points[0] = QPoint(rect.left() + 1, rect.bottom() - 1); points[1] = QPoint(rect.right() - 1, rect.bottom() - 1); painter->drawPoints(points.data(), 2); // outside end dots - highlight // 50% highlight.setAlpha(a25); painter->setPen(QPen(highlight, 0)); points[0] = QPoint(rect.right() - 1, rect.bottom()); points[1] = QPoint(rect.right(), rect.bottom() - 1); points[2] = QPoint(rect.left() + 1, rect.bottom()); points[3] = QPoint(rect.right(), rect.top() + 1); painter->drawPoints(points.data(), 4); } else { QProxyStyle::drawPrimitive( element, option, painter, widget ); } } int LmmsStyle::pixelMetric( PixelMetric _metric, const QStyleOption * _option, const QWidget * _widget ) const { switch( _metric ) { case QStyle::PM_ButtonMargin: return 3; case QStyle::PM_ButtonIconSize: return 20; case QStyle::PM_ToolBarItemMargin: return 1; case QStyle::PM_ToolBarItemSpacing: return 2; case QStyle::PM_TitleBarHeight: return 24; default: return QProxyStyle::pixelMetric( _metric, _option, _widget ); } } QImage LmmsStyle::colorizeXpm( const char * const * xpm, const QBrush& fill ) const { QImage arrowXpm( xpm ); QImage arrow( arrowXpm.size(), QImage::Format_ARGB32 ); QPainter arrowPainter( &arrow ); arrowPainter.fillRect( arrow.rect(), fill ); arrowPainter.end(); arrow.setAlphaChannel( arrowXpm ); return arrow; } void LmmsStyle::hoverColors( bool sunken, bool hover, bool active, QColor& color, QColor& blend ) const { if( active ) { if( sunken ) { color = QColor( 75, 75, 75 ); blend = QColor( 65, 65, 65 ); } else if( hover ) { color = QColor( 100, 100, 100 ); blend = QColor( 75, 75, 75 ); } else { color = QColor( 21, 21, 21 ); blend = QColor( 33, 33, 33 ); } } else { color = QColor( 21, 21, 21 ); blend = QColor( 33, 33, 33 ); } } } // namespace lmms::gui
9,684
C++
.cpp
305
28.859016
103
0.675121
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,897
SubWindow.cpp
LMMS_lmms/src/gui/SubWindow.cpp
/* * SubWindow.cpp - Implementation of QMdiSubWindow that correctly tracks * the geometry that windows should be restored to. * Workaround for https://bugreports.qt.io/browse/QTBUG-256 * This implementation adds a custom themed title bar to * the subwindow. * * Copyright (c) 2015 Colin Wallace <wallace.colin.a@gmail.com> * Copyright (c) 2016 Steffen Baranowsky <baramgb@freenet.de> * 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. * */ #include "SubWindow.h" #include <QGraphicsDropShadowEffect> #include <QLabel> #include <QMdiArea> #include <QMoveEvent> #include <QPainter> #include <QPushButton> #include <QStyleOption> #include "embed.h" namespace lmms::gui { SubWindow::SubWindow(QWidget *parent, Qt::WindowFlags windowFlags) : QMdiSubWindow(parent, windowFlags), m_buttonSize(17, 17), m_titleBarHeight(titleBarHeight()), m_hasFocus(false) { // initialize the tracked geometry to whatever Qt thinks the normal geometry currently is. // this should always work, since QMdiSubWindows will not start as maximized m_trackedNormalGeom = normalGeometry(); // inits the colors m_activeColor = Qt::SolidPattern; m_textShadowColor = Qt::black; m_borderColor = Qt::black; // close, maximize and restore (after maximizing) buttons m_closeBtn = addTitleButton("close", tr("Close")); connect( m_closeBtn, SIGNAL(clicked(bool)), this, SLOT(close())); m_maximizeBtn = addTitleButton("maximize", tr("Maximize")); connect( m_maximizeBtn, SIGNAL(clicked(bool)), this, SLOT(showMaximized())); m_restoreBtn = addTitleButton("restore", tr("Restore")); connect( m_restoreBtn, SIGNAL(clicked(bool)), this, SLOT(showNormal())); // QLabel for the window title and the shadow effect m_shadow = new QGraphicsDropShadowEffect(); m_shadow->setColor( m_textShadowColor ); m_shadow->setXOffset( 1 ); m_shadow->setYOffset( 1 ); m_windowTitle = new QLabel( this ); m_windowTitle->setFocusPolicy( Qt::NoFocus ); m_windowTitle->setAttribute( Qt::WA_TransparentForMouseEvents, true ); m_windowTitle->setGraphicsEffect( m_shadow ); // Disable the minimize button and make sure that the custom window hint is set setWindowFlags((this->windowFlags() & ~Qt::WindowMinimizeButtonHint) | Qt::CustomizeWindowHint); connect( mdiArea(), SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(focusChanged(QMdiSubWindow*))); } /** * @brief SubWindow::paintEvent * * This draws our new title bar with custom colors * and draws a window icon on the left upper corner. */ void SubWindow::paintEvent( QPaintEvent * ) { // Don't paint any of the other stuff if the sub window is maximized // so that only its child content is painted. if (isMaximized()) { return; } QPainter p( this ); QRect rect( 0, 0, width(), m_titleBarHeight ); const bool isActive = windowState() & Qt::WindowActive; p.fillRect( rect, isActive ? activeColor() : p.pen().brush() ); // window border p.setPen( borderColor() ); // bottom, left, and right lines p.drawLine( 0, height() - 1, width(), height() - 1 ); p.drawLine( 0, m_titleBarHeight, 0, height() - 1 ); p.drawLine( width() - 1, m_titleBarHeight, width() - 1, height() - 1 ); // window icon if( widget() ) { QPixmap winicon( widget()->windowIcon().pixmap( m_buttonSize ) ); p.drawPixmap( 3, 3, m_buttonSize.width(), m_buttonSize.height(), winicon ); } } /** * @brief SubWindow::changeEvent * * Triggers if the window title changes and calls adjustTitleBar(). * @param event */ void SubWindow::changeEvent( QEvent *event ) { QMdiSubWindow::changeEvent( event ); if( event->type() == QEvent::WindowTitleChange ) { adjustTitleBar(); } } /** * @brief SubWindow::elideText * * Stores the given text into the given label. * Shorts the text if it's too big for the labels width * ans adds three dots (...) * * @param label - holds a pointer to the QLabel * @param text - the text which will be stored (and if needed breaked down) into the QLabel. */ void SubWindow::elideText( QLabel *label, QString text ) { QFontMetrics metrix( label->font() ); int width = label->width() - 2; QString clippedText = metrix.elidedText( text, Qt::ElideRight, width ); label->setText( clippedText ); } /** * @brief SubWindow::getTrueNormalGeometry * * same as QWidet::normalGeometry, but works properly under X11 * see https://bugreports.qt.io/browse/QTBUG-256 */ QRect SubWindow::getTrueNormalGeometry() const { return m_trackedNormalGeom; } QBrush SubWindow::activeColor() const { return m_activeColor; } QColor SubWindow::textShadowColor() const { return m_textShadowColor; } QColor SubWindow::borderColor() const { return m_borderColor; } void SubWindow::setActiveColor( const QBrush & b ) { m_activeColor = b; } void SubWindow::setTextShadowColor( const QColor & c ) { m_textShadowColor = c; } void SubWindow::setBorderColor( const QColor &c ) { m_borderColor = c; } int SubWindow::titleBarHeight() const { QStyleOptionTitleBar so; so.titleBarState = Qt::WindowActive; // kThemeStateActiv so.titleBarFlags = Qt::Window; return style()->pixelMetric(QStyle::PM_TitleBarHeight, &so, this); } int SubWindow::frameWidth() const { QStyleOptionFrame so; return style()->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth, &so, this); } /** * @brief SubWindow::moveEvent * * overides the QMdiSubWindow::moveEvent() for saving the position * of the subwindow into m_trackedNormalGeom. This position * will be saved with the project because of an Qt bug wich doesn't * save the right position. look at: https://bugreports.qt.io/browse/QTBUG-256 * @param event */ void SubWindow::moveEvent( QMoveEvent * event ) { QMdiSubWindow::moveEvent( event ); // if the window was moved and ISN'T minimized/maximized/fullscreen, // then save the current position if( !isMaximized() && !isMinimized() && !isFullScreen() ) { m_trackedNormalGeom.moveTopLeft( event->pos() ); } } /** * @brief SubWindow::adjustTitleBar * * Our title bar needs buttons for maximize/restore and close in the right upper corner. * We check if the subwindow is maximizable and put the buttons on the right positions. * At next we calculate the width of the title label and call elideText() for adding * the window title to m_windowTitle (which is a QLabel) */ void SubWindow::adjustTitleBar() { // Don't show the title or any button if the sub window is maximized. Otherwise they // might show up behind the actual maximized content of the child widget. if (isMaximized()) { m_closeBtn->hide(); m_maximizeBtn->hide(); m_restoreBtn->hide(); m_windowTitle->hide(); return; } // The sub window is not maximized, i.e. the title must be shown // as well as some buttons. // Title adjustments m_windowTitle->show(); // button adjustments m_maximizeBtn->hide(); m_restoreBtn->hide(); m_closeBtn->show(); const int rightSpace = 3; const int buttonGap = 1; const int menuButtonSpace = 24; QPoint rightButtonPos( width() - rightSpace - m_buttonSize.width(), 3 ); QPoint middleButtonPos( width() - rightSpace - ( 2 * m_buttonSize.width() ) - buttonGap, 3 ); QPoint leftButtonPos( width() - rightSpace - ( 3 * m_buttonSize.width() ) - ( 2 * buttonGap ), 3 ); // the buttonBarWidth depends on the number of buttons. // we need it to calculate the width of window title label int buttonBarWidth = rightSpace + m_buttonSize.width(); // set the buttons on their positions. // the close button is always needed and on the rightButtonPos m_closeBtn->move( rightButtonPos ); // here we ask: is the Subwindow maximizable and // then we set the buttons and show them if needed if( windowFlags() & Qt::WindowMaximizeButtonHint ) { buttonBarWidth = buttonBarWidth + m_buttonSize.width() + buttonGap; m_maximizeBtn->move( middleButtonPos ); m_restoreBtn->move( middleButtonPos ); m_maximizeBtn->setVisible(true); } // we're keeping the restore button around if we open projects // from older versions that have saved minimized windows m_restoreBtn->setVisible(isMinimized()); if( isMinimized() ) { m_restoreBtn->move( m_maximizeBtn->isHidden() ? middleButtonPos : leftButtonPos ); } if( widget() ) { // title QLabel adjustments m_windowTitle->setAlignment( Qt::AlignHCenter ); m_windowTitle->setFixedWidth( widget()->width() - ( menuButtonSpace + buttonBarWidth ) ); m_windowTitle->move( menuButtonSpace, ( m_titleBarHeight / 2 ) - ( m_windowTitle->sizeHint().height() / 2 ) - 1 ); // if minimized we can't use widget()->width(). We have to hard code the width, // as the width of all minimized windows is the same. if( isMinimized() ) { m_windowTitle->setFixedWidth( 120 ); } // truncate the label string if the window is to small. Adds "..." elideText( m_windowTitle, widget()->windowTitle() ); m_windowTitle->setTextInteractionFlags( Qt::NoTextInteraction ); m_windowTitle->adjustSize(); } } void SubWindow::focusChanged( QMdiSubWindow *subWindow ) { if( m_hasFocus && subWindow != this ) { m_hasFocus = false; emit focusLost(); } else if( subWindow == this ) { m_hasFocus = true; } } /** * @brief SubWindow::resizeEvent * * At first we give the event to QMdiSubWindow::resizeEvent() which handles * the event on its behavior. * * On every resize event we have to adjust our title label. * * At last we store the current size into m_trackedNormalGeom. This size * will be saved with the project because of an Qt bug wich doesn't * save the right size. look at: https://bugreports.qt.io/browse/QTBUG-256 * * @param event */ void SubWindow::resizeEvent( QResizeEvent * event ) { // When the parent QMdiArea gets resized, maximized subwindows also gets resized, if any. // In that case, we should call QMdiSubWindow::resizeEvent first // to ensure we get the correct window state. QMdiSubWindow::resizeEvent( event ); adjustTitleBar(); // if the window was resized and ISN'T minimized/maximized/fullscreen, // then save the current size if( !isMaximized() && !isMinimized() && !isFullScreen() ) { m_trackedNormalGeom.setSize( event->size() ); } } QPushButton* SubWindow::addTitleButton(const std::string& iconName, const QString& toolTip) { auto button = new QPushButton(embed::getIconPixmap(iconName), QString(), this); button->resize(m_buttonSize); button->setFocusPolicy(Qt::NoFocus); button->setCursor(Qt::ArrowCursor); button->setAttribute(Qt::WA_NoMousePropagation); button->setToolTip(toolTip); return button; } } // namespace lmms::gui
11,281
C++
.cpp
321
32.912773
107
0.737404
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,898
ModelView.cpp
LMMS_lmms/src/gui/ModelView.cpp
/* * ModelView.cpp - implementation of ModelView * * Copyright (c) 2007-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. * */ #include <QWidget> #include "ModelView.h" namespace lmms::gui { ModelView::ModelView( Model* model, QWidget* widget ) : m_widget( widget ), m_model( model ) { } ModelView::~ModelView() { if( m_model != nullptr && m_model->isDefaultConstructed() ) { delete m_model; } } void ModelView::setModel( Model* model, bool isOldModelValid ) { if( isOldModelValid && m_model != nullptr ) { if( m_model->isDefaultConstructed() ) { delete m_model; } else { m_model->disconnect( widget() ); } } m_model = model; doConnections(); widget()->update(); modelChanged(); } // Unsets the current model by setting a dummy empty model. The dummy model is marked as // "defaultConstructed", so the next call to setModel will delete it. void ModelView::unsetModel() { setModel(new Model(nullptr, QString(), true)); } void ModelView::doConnections() { if( m_model != nullptr ) { QObject::connect( m_model, SIGNAL(dataChanged()), widget(), SLOT(update())); QObject::connect( m_model, SIGNAL(propertiesChanged()), widget(), SLOT(update())); } } } // namespace lmms::gui
2,035
C++
.cpp
72
26.027778
88
0.72624
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,899
PeakControllerDialog.cpp
LMMS_lmms/src/gui/PeakControllerDialog.cpp
/* * PeakControllerDialog.cpp - 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. * */ #include <QLabel> #include <QPainter> #include <QIcon> #include "embed.h" #include "PeakController.h" namespace lmms::gui { PeakControllerDialog::PeakControllerDialog( Controller * _model, QWidget * _parent ) : ControllerDialog( _model, _parent ) { setWindowTitle( tr( "PEAK" ) ); setWindowIcon( embed::getIconPixmap( "controller" ) ); setFixedSize( 256, 64 ); setToolTip(tr("LFO Controller")); auto l = new QLabel(this); l->setText( "Use FX's controls" ); l->move(10, 10); setModel( _model ); } /* void effectView::closeEffects() { m_subWindow->hide(); m_show = true; } */ void PeakControllerDialog::contextMenuEvent( QContextMenuEvent * ) { } void PeakControllerDialog::paintEvent( QPaintEvent * ) { QPainter p( this ); } void PeakControllerDialog::modelChanged() { m_peakController = castModel<PeakController>(); } } // namespace lmms::gui
1,844
C++
.cpp
62
27.741935
86
0.747866
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,900
ControlLayout.cpp
LMMS_lmms/src/gui/ControlLayout.cpp
/* * ControlLayout.cpp - implementation for ControlLayout.h * * Copyright (c) 2019-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. * */ /**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "ControlLayout.h" #include <QWidget> #include <QLayoutItem> #include <QLineEdit> #include <QRect> #include <QString> #include <utility> namespace lmms::gui { constexpr const int ControlLayout::m_minWidth; ControlLayout::ControlLayout(QWidget *parent, int margin, int hSpacing, int vSpacing) : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing), m_searchBar(new QLineEdit(parent)) { setContentsMargins(margin, margin, margin, margin); m_searchBar->setPlaceholderText("filter"); m_searchBar->setObjectName(s_searchBarName); connect(m_searchBar, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString& ))); addWidget(m_searchBar); m_searchBar->setHidden(true); // nothing to filter yet } ControlLayout::~ControlLayout() { while (auto item = takeAt(0)) { delete item; } } void ControlLayout::onTextChanged(const QString&) { invalidate(); update(); } void ControlLayout::addItem(QLayoutItem *item) { QWidget* widget = item->widget(); const QString str = widget ? widget->objectName() : QString("unnamed"); m_itemMap.insert(str, item); invalidate(); } int ControlLayout::horizontalSpacing() const { if (m_hSpace >= 0) { return m_hSpace; } else { return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); } } int ControlLayout::verticalSpacing() const { if (m_vSpace >= 0) { return m_vSpace; } else { return smartSpacing(QStyle::PM_LayoutVerticalSpacing); } } int ControlLayout::count() const { return m_itemMap.size() - 1; } QMap<QString, QLayoutItem*>::const_iterator ControlLayout::pairAt(int index) const { if (index < 0) { return m_itemMap.cend(); } auto skip = [&](QLayoutItem* item) -> bool { return item->widget()->objectName() == s_searchBarName; }; QMap<QString, QLayoutItem*>::const_iterator itr = m_itemMap.cbegin(); for (; itr != m_itemMap.cend() && (index > 0 || skip(itr.value())); ++itr) { if(!skip(itr.value())) { index--; } } return itr; } // linear time :-( QLayoutItem *ControlLayout::itemAt(int index) const { auto itr = pairAt(index); return (itr == m_itemMap.end()) ? nullptr : itr.value(); } QLayoutItem *ControlLayout::itemByString(const QString &key) const { auto itr = m_itemMap.find(key); return (itr == m_itemMap.end()) ? nullptr : *itr; } // linear time :-( QLayoutItem *ControlLayout::takeAt(int index) { auto itr = pairAt(index); return (itr == m_itemMap.end()) ? nullptr : m_itemMap.take(itr.key()); } void ControlLayout::removeFocusFromSearchBar() { m_searchBar->clearFocus(); } Qt::Orientations ControlLayout::expandingDirections() const { return Qt::Orientations(); } bool ControlLayout::hasHeightForWidth() const { return true; } int ControlLayout::heightForWidth(int width) const { int height = doLayout(QRect(0, 0, width, 0), true); return height; } void ControlLayout::setGeometry(const QRect &rect) { QLayout::setGeometry(rect); doLayout(rect, false); } QSize ControlLayout::sizeHint() const { return minimumSize(); } QSize ControlLayout::minimumSize() const { // original formula from Qt's FlowLayout example: // get maximum height and width for all children. // as Qt will later call heightForWidth, only the width here really matters QSize size; for (const QLayoutItem *item : std::as_const(m_itemMap)) { size = size.expandedTo(item->minimumSize()); } const QMargins margins = contentsMargins(); size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom()); // the original formula would leed to ~1 widget per row // bash it at least to 400 so we have ~4 knobs per row size.setWidth(qMax(size.width(), m_minWidth)); return size; } int ControlLayout::doLayout(const QRect &rect, bool testOnly) const { int left, top, right, bottom; getContentsMargins(&left, &top, &right, &bottom); QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); int x = effectiveRect.x(); int y = effectiveRect.y(); int lineHeight = 0; const QString filterText = m_searchBar->text(); bool first = true; QMapIterator<QString, QLayoutItem*> itr(m_itemMap); while (itr.hasNext()) { itr.next(); QLayoutItem* item = itr.value(); QWidget *wid = item->widget(); if (wid) { if ( first || // do not filter search bar filterText.isEmpty() || // no filter - pass all itr.key().contains(filterText, Qt::CaseInsensitive)) { if (first) { // for the search bar, only show it if there are at least // five control widgets (i.e. at least 6 widgets) if (m_itemMap.size() > 5) { wid->show(); } else { wid->hide(); } } else { wid->show(); } int spaceX = horizontalSpacing(); if (spaceX == -1) { spaceX = wid->style()->layoutSpacing( QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); } int spaceY = verticalSpacing(); if (spaceY == -1) { spaceY = wid->style()->layoutSpacing( QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical); } int nextX = x + item->sizeHint().width() + spaceX; if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { x = effectiveRect.x(); y = y + lineHeight + spaceY; nextX = x + item->sizeHint().width() + spaceX; lineHeight = 0; } if (!testOnly) { item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); } x = nextX; lineHeight = qMax(lineHeight, item->sizeHint().height()); first = false; } else { wid->hide(); } } } return y + lineHeight - rect.y() + bottom; } int ControlLayout::smartSpacing(QStyle::PixelMetric pm) const { QObject *parent = this->parent(); if (!parent) { return -1; } else if (parent->isWidgetType()) { auto pw = static_cast<QWidget*>(parent); return pw->style()->pixelMetric(pm, nullptr, pw); } else { return static_cast<QLayout *>(parent)->spacing(); } } } // namespace lmms::gui
9,180
C++
.cpp
281
30.412811
85
0.708079
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,901
MidiSetupWidget.cpp
LMMS_lmms/src/gui/MidiSetupWidget.cpp
/* * MidiSetupWidget - class for configuring midi sources in the settings window * * 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. * */ #include "MidiSetupWidget.h" #include <QFormLayout> #include <QLineEdit> #include "ConfigManager.h" namespace lmms::gui { MidiSetupWidget::MidiSetupWidget(const QString & caption, const QString & configSection, const QString & devName, QWidget * parent) : QGroupBox(QGroupBox::tr("Settings for %1").arg(tr(caption.toUtf8())), parent), m_configSection(configSection), m_device(nullptr) { // supply devName=QString() (distinct from QString("")) // to indicate that there is no editable device field if (!devName.isNull()) { QFormLayout * form = new QFormLayout(this); m_device = new QLineEdit(devName, this); form->addRow(tr("Device"), m_device); } } void MidiSetupWidget::saveSettings() { if (!m_configSection.isEmpty() && m_device) { ConfigManager::inst()->setValue(m_configSection, "device", m_device->text()); } } void MidiSetupWidget::show() { // the setup widget should only be visible if the device has some configurable attributes bool visible = !m_configSection.isEmpty(); parentWidget()->setVisible(visible); QWidget::setVisible(visible); } } // namespace lmms::gui
2,072
C++
.cpp
60
32.483333
90
0.751876
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
19,902
ControllerView.cpp
LMMS_lmms/src/gui/ControllerView.cpp
/* * ControllerView.cpp - view-component for an controller * * Copyright (c) 2008-2009 Paul Giblock <drfaygo/at/gmail.com> * Copyright (c) 2011-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. * */ #include <QLabel> #include <QPushButton> #include <QHBoxLayout> #include <QMdiArea> #include <QInputDialog> #include <QVBoxLayout> #include "ControllerView.h" #include "CaptionMenu.h" #include "ControllerDialog.h" #include "embed.h" #include "GuiApplication.h" #include "MainWindow.h" #include "SubWindow.h" namespace lmms::gui { ControllerView::ControllerView( Controller * _model, QWidget * _parent ) : QFrame( _parent ), ModelView( _model, this ), m_subWindow( nullptr ), m_controllerDlg( nullptr ), m_show( true ) { this->setFrameStyle( QFrame::StyledPanel ); this->setFrameShadow( QFrame::Raised ); setFocusPolicy(Qt::StrongFocus); auto vBoxLayout = new QVBoxLayout(this); auto hBox = new QHBoxLayout(); vBoxLayout->addLayout(hBox); auto label = new QLabel("<b>" + _model->displayName() + "</b>", this); QSizePolicy sizePolicy = label->sizePolicy(); sizePolicy.setHorizontalStretch(1); label->setSizePolicy(sizePolicy); hBox->addWidget(label); auto controlsButton = new QPushButton(tr("Controls"), this); connect( controlsButton, SIGNAL(clicked()), SLOT(editControls())); hBox->addWidget(controlsButton); m_nameLabel = new QLabel(_model->name(), this); vBoxLayout->addWidget(m_nameLabel); m_controllerDlg = getController()->createDialog( getGUI()->mainWindow()->workspace() ); m_subWindow = getGUI()->mainWindow()->addWindowedWidget( m_controllerDlg ); Qt::WindowFlags flags = m_subWindow->windowFlags(); flags &= ~Qt::WindowMaximizeButtonHint; m_subWindow->setWindowFlags( flags ); m_subWindow->setFixedSize( m_subWindow->size() ); m_subWindow->setWindowIcon( m_controllerDlg->windowIcon() ); connect( m_controllerDlg, SIGNAL(closed()), this, SLOT(closeControls())); m_subWindow->hide(); setModel( _model ); } ControllerView::~ControllerView() { if (m_subWindow) { delete m_subWindow; } } void ControllerView::editControls() { if( m_show ) { m_subWindow->show(); m_subWindow->raise(); m_show = false; } else { m_subWindow->hide(); m_show = true; } } void ControllerView::closeControls() { m_subWindow->hide(); m_show = true; } void ControllerView::moveUp() { emit movedUp(this); } void ControllerView::moveDown() { emit movedDown(this); } void ControllerView::removeController() { emit removedController(this); } void ControllerView::renameController() { bool ok; auto c = castModel<Controller>(); QString new_name = QInputDialog::getText( this, tr( "Rename controller" ), tr( "Enter the new name for this controller" ), QLineEdit::Normal, c->name() , &ok ); if( ok && !new_name.isEmpty() ) { c->setName( new_name ); if( getController()->type() == Controller::ControllerType::Lfo ) { m_controllerDlg->setWindowTitle( tr( "LFO" ) + " (" + new_name + ")" ); } m_nameLabel->setText( new_name ); } } void ControllerView::mouseDoubleClickEvent( QMouseEvent * event ) { renameController(); } void ControllerView::modelChanged() { } void ControllerView::contextMenuEvent( QContextMenuEvent * ) { Controller* c = castModel<Controller>(); QPointer<CaptionMenu> contextMenu = new CaptionMenu(c->name(), this); contextMenu->addAction(embed::getIconPixmap("arp_up"), tr("Move &up"), this, &ControllerView::moveUp); contextMenu->addAction(embed::getIconPixmap("arp_down"), tr("Move &down"), this, &ControllerView::moveDown); contextMenu->addSeparator(); contextMenu->addAction( embed::getIconPixmap("cancel"), tr("&Remove this controller"), this, &ControllerView::removeController); contextMenu->addAction( tr("Re&name this controller"), this, SLOT(renameController())); contextMenu->addSeparator(); contextMenu->exec( QCursor::pos() ); delete contextMenu; } } // namespace lmms::gui
4,720
C++
.cpp
143
30.832168
109
0.737911
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,903
StringPairDrag.cpp
LMMS_lmms/src/gui/StringPairDrag.cpp
/* * StringPairDrag.cpp - class StringPairDrag which provides general support * for drag'n'drop of string-pairs and which is the base * for all drag'n'drop-actions within LMMS * * 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. * */ #include <QMimeData> #include <QDragEnterEvent> #include "StringPairDrag.h" #include "GuiApplication.h" #include "MainWindow.h" #include "Clipboard.h" namespace lmms::gui { StringPairDrag::StringPairDrag( const QString & _key, const QString & _value, const QPixmap & _icon, QWidget * _w ) : QDrag( _w ) { // For mimeType() and MimeType enum class using namespace Clipboard; if( _icon.isNull() && _w ) { setPixmap( _w->grab().scaled( 64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation ) ); } else { setPixmap( _icon ); } QString txt = _key + ":" + _value; auto m = new QMimeData(); m->setData( mimeType( MimeType::StringPair ), txt.toUtf8() ); setMimeData( m ); exec( Qt::LinkAction, Qt::LinkAction ); } StringPairDrag::~StringPairDrag() { // during a drag, we might have lost key-press-events, so reset // modifiers of main-win if( getGUI()->mainWindow() ) { getGUI()->mainWindow()->clearKeyModifiers(); } } bool StringPairDrag::processDragEnterEvent( QDragEnterEvent * _dee, const QString & _allowed_keys ) { // For mimeType() and MimeType enum class using namespace Clipboard; if( !_dee->mimeData()->hasFormat( mimeType( MimeType::StringPair ) ) ) { return( false ); } QString txt = _dee->mimeData()->data( mimeType( MimeType::StringPair ) ); if( _allowed_keys.split( ',' ).contains( txt.section( ':', 0, 0 ) ) ) { _dee->acceptProposedAction(); return( true ); } _dee->ignore(); return( false ); } QString StringPairDrag::decodeKey( QDropEvent * _de ) { return Clipboard::decodeKey( _de->mimeData() ); } QString StringPairDrag::decodeValue( QDropEvent * _de ) { return Clipboard::decodeValue( _de->mimeData() ); } } // namespace lmms::gui
2,844
C++
.cpp
92
28.565217
79
0.704587
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,904
SideBar.cpp
LMMS_lmms/src/gui/SideBar.cpp
/* * SideBar.cpp - side-bar in LMMS' MainWindow * * 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. * */ #include <QStyleOptionToolButton> #include <QStylePainter> #include <QToolButton> #include "SideBar.h" #include "SideBarWidget.h" namespace lmms::gui { // internal helper class allowing to create QToolButtons with // vertical orientation class SideBarButton : public QToolButton { public: SideBarButton( Qt::Orientation _orientation, QWidget * _parent ) : QToolButton( _parent ), m_orientation( _orientation ) { } ~SideBarButton() override = default; Qt::Orientation orientation() const { return m_orientation; } QSize sizeHint() const override { QSize s = QToolButton::sizeHint(); s.setWidth( s.width() + 8 ); if( orientation() == Qt::Horizontal ) { return s; } return QSize( s.height(), s.width() ); } protected: void paintEvent( QPaintEvent * ) override { QStylePainter p( this ); QStyleOptionToolButton opt; initStyleOption( &opt ); if( orientation() == Qt::Vertical ) { const QSize s = sizeHint(); p.rotate( 270 ); p.translate( -s.height(), 0 ); opt.rect = QRect( 0, 0, s.height(), s.width() ); } p.drawComplexControl( QStyle::CC_ToolButton, opt ); } private: Qt::Orientation m_orientation; } ; SideBar::SideBar( Qt::Orientation _orientation, QWidget * _parent ) : QToolBar( _parent ), m_btnGroup( this ) { setOrientation( _orientation ); setIconSize( QSize( 16, 16 ) ); m_btnGroup.setExclusive( false ); connect( &m_btnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(toggleButton(QAbstractButton*))); } void SideBar::appendTab( SideBarWidget *widget ) { auto button = new SideBarButton(orientation(), this); button->setText( " " + widget->title() ); button->setIcon( widget->icon() ); button->setLayoutDirection( Qt::RightToLeft ); button->setCheckable( true ); m_widgets[button] = widget; m_btnGroup.addButton( button ); addWidget( button ); widget->hide(); widget->setMinimumWidth( 200 ); button->setToolTip(widget->title()); connect(widget, &SideBarWidget::closeButtonClicked, [=]() { button->click(); }); } void SideBar::toggleButton( QAbstractButton * button ) { QToolButton *toolButton = nullptr; QWidget *activeWidget = nullptr; for( auto it = m_widgets.begin(); it != m_widgets.end(); ++it ) { QToolButton *curBtn = it.key(); QWidget *curWidget = it.value(); if( curBtn == button ) { toolButton = curBtn; activeWidget = curWidget; } else { curBtn->setChecked( false ); curBtn->setToolButtonStyle( Qt::ToolButtonIconOnly ); } if( curWidget ) { curWidget->hide(); } } if( toolButton && activeWidget ) { activeWidget->setVisible( button->isChecked() ); toolButton->setToolButtonStyle( button->isChecked() ? Qt::ToolButtonTextBesideIcon : Qt::ToolButtonIconOnly ); } } } // namespace lmms::gui
3,710
C++
.cpp
130
26.053846
77
0.719481
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,905
LfoControllerDialog.cpp
LMMS_lmms/src/gui/LfoControllerDialog.cpp
/* * LfoControllerDialog.cpp - 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. * */ #include "embed.h" #include "LfoController.h" #include "Knob.h" #include "TempoSyncKnob.h" #include "PixmapButton.h" #include "SampleLoader.h" namespace lmms::gui { const int CD_ENV_KNOBS_LBL_Y = 11; const int CD_KNOB_X_SPACING = 32; const int CD_LFO_SHAPES_X = 6; const int CD_LFO_SHAPES_Y = CD_ENV_KNOBS_LBL_Y + 4; const int CD_LFO_GRAPH_Y = CD_ENV_KNOBS_LBL_Y+3; const int CD_LFO_CD_KNOB_Y = CD_LFO_GRAPH_Y-2; const int CD_LFO_BASE_CD_KNOB_X = CD_LFO_SHAPES_X + 68; const int CD_LFO_SPEED_CD_KNOB_X = CD_LFO_BASE_CD_KNOB_X+CD_KNOB_X_SPACING; const int CD_LFO_AMOUNT_CD_KNOB_X = CD_LFO_SPEED_CD_KNOB_X+CD_KNOB_X_SPACING; const int CD_LFO_PHASE_CD_KNOB_X = CD_LFO_AMOUNT_CD_KNOB_X+CD_KNOB_X_SPACING; const int CD_LFO_MULTIPLIER_X = CD_LFO_PHASE_CD_KNOB_X+CD_KNOB_X_SPACING+3; LfoControllerDialog::LfoControllerDialog( Controller * _model, QWidget * _parent ) : ControllerDialog( _model, _parent ) { QString title = tr( "LFO" ); title.append( " (" ); title.append( _model->name() ); title.append( ")" ); setWindowTitle( title ); setWindowIcon( embed::getIconPixmap( "controller" ) ); setFixedSize( 240, 58 ); m_baseKnob = new Knob( KnobType::Bright26, this ); m_baseKnob->setLabel( tr( "BASE" ) ); m_baseKnob->move( CD_LFO_BASE_CD_KNOB_X, CD_LFO_CD_KNOB_Y ); m_baseKnob->setHintText( tr( "Base:" ), "" ); m_speedKnob = new TempoSyncKnob( KnobType::Bright26, this ); m_speedKnob->setLabel( tr( "FREQ" ) ); m_speedKnob->move( CD_LFO_SPEED_CD_KNOB_X, CD_LFO_CD_KNOB_Y ); m_speedKnob->setHintText( tr( "LFO frequency:" ), "" ); m_amountKnob = new Knob( KnobType::Bright26, this ); m_amountKnob->setLabel( tr( "AMNT" ) ); m_amountKnob->move( CD_LFO_AMOUNT_CD_KNOB_X, CD_LFO_CD_KNOB_Y ); m_amountKnob->setHintText( tr( "Modulation amount:" ), "" ); m_phaseKnob = new Knob( KnobType::Bright26, this ); m_phaseKnob->setLabel( tr( "PHS" ) ); m_phaseKnob->move( CD_LFO_PHASE_CD_KNOB_X, CD_LFO_CD_KNOB_Y ); m_phaseKnob->setHintText( tr( "Phase offset:" ) , "" + tr( " degrees" ) ); auto sin_wave_btn = new PixmapButton(this, nullptr); sin_wave_btn->move( CD_LFO_SHAPES_X, CD_LFO_SHAPES_Y ); sin_wave_btn->setActiveGraphic( embed::getIconPixmap( "sin_wave_active" ) ); sin_wave_btn->setInactiveGraphic( embed::getIconPixmap( "sin_wave_inactive" ) ); sin_wave_btn->setToolTip( tr( "Sine wave" ) ); auto triangle_wave_btn = new PixmapButton(this, nullptr); triangle_wave_btn->move( CD_LFO_SHAPES_X + 15, CD_LFO_SHAPES_Y ); triangle_wave_btn->setActiveGraphic( embed::getIconPixmap( "triangle_wave_active" ) ); triangle_wave_btn->setInactiveGraphic( embed::getIconPixmap( "triangle_wave_inactive" ) ); triangle_wave_btn->setToolTip( tr( "Triangle wave" ) ); auto saw_wave_btn = new PixmapButton(this, nullptr); saw_wave_btn->move( CD_LFO_SHAPES_X + 30, CD_LFO_SHAPES_Y ); saw_wave_btn->setActiveGraphic( embed::getIconPixmap( "saw_wave_active" ) ); saw_wave_btn->setInactiveGraphic( embed::getIconPixmap( "saw_wave_inactive" ) ); saw_wave_btn->setToolTip( tr( "Saw wave" ) ); auto sqr_wave_btn = new PixmapButton(this, nullptr); sqr_wave_btn->move( CD_LFO_SHAPES_X + 45, CD_LFO_SHAPES_Y ); sqr_wave_btn->setActiveGraphic( embed::getIconPixmap( "square_wave_active" ) ); sqr_wave_btn->setInactiveGraphic( embed::getIconPixmap( "square_wave_inactive" ) ); sqr_wave_btn->setToolTip( tr( "Square wave" ) ); auto moog_saw_wave_btn = new PixmapButton(this, nullptr); moog_saw_wave_btn->move( CD_LFO_SHAPES_X, CD_LFO_SHAPES_Y + 15 ); moog_saw_wave_btn->setActiveGraphic( embed::getIconPixmap( "moog_saw_wave_active" ) ); moog_saw_wave_btn->setInactiveGraphic( embed::getIconPixmap( "moog_saw_wave_inactive" ) ); moog_saw_wave_btn->setToolTip( tr( "Moog saw wave" ) ); auto exp_wave_btn = new PixmapButton(this, nullptr); exp_wave_btn->move( CD_LFO_SHAPES_X + 15, CD_LFO_SHAPES_Y + 15 ); exp_wave_btn->setActiveGraphic( embed::getIconPixmap( "exp_wave_active" ) ); exp_wave_btn->setInactiveGraphic( embed::getIconPixmap( "exp_wave_inactive" ) ); exp_wave_btn->setToolTip( tr( "Exponential wave" ) ); auto white_noise_btn = new PixmapButton(this, nullptr); white_noise_btn->move( CD_LFO_SHAPES_X + 30, CD_LFO_SHAPES_Y + 15 ); white_noise_btn->setActiveGraphic( embed::getIconPixmap( "white_noise_wave_active" ) ); white_noise_btn->setInactiveGraphic( embed::getIconPixmap( "white_noise_wave_inactive" ) ); white_noise_btn->setToolTip( tr( "White noise" ) ); m_userWaveBtn = new PixmapButton( this, nullptr ); m_userWaveBtn->move( CD_LFO_SHAPES_X + 45, CD_LFO_SHAPES_Y + 15 ); m_userWaveBtn->setActiveGraphic( embed::getIconPixmap( "usr_wave_active" ) ); m_userWaveBtn->setInactiveGraphic( embed::getIconPixmap( "usr_wave_inactive" ) ); connect( m_userWaveBtn, SIGNAL(doubleClicked()), this, SLOT(askUserDefWave())); m_userWaveBtn->setToolTip( tr( "User-defined shape.\nDouble click to pick a file." ) ); m_waveBtnGrp = new automatableButtonGroup( this ); m_waveBtnGrp->addButton( sin_wave_btn ); m_waveBtnGrp->addButton( triangle_wave_btn ); m_waveBtnGrp->addButton( saw_wave_btn ); m_waveBtnGrp->addButton( sqr_wave_btn ); m_waveBtnGrp->addButton( moog_saw_wave_btn ); m_waveBtnGrp->addButton( exp_wave_btn ); m_waveBtnGrp->addButton( white_noise_btn ); m_waveBtnGrp->addButton( m_userWaveBtn ); auto x1 = new PixmapButton(this, nullptr); x1->move(CD_LFO_MULTIPLIER_X, CD_LFO_SHAPES_Y + 7); x1->setActiveGraphic(embed::getIconPixmap("lfo_x1_active")); x1->setInactiveGraphic(embed::getIconPixmap("lfo_x1_inactive")); x1->setToolTip(tr("Multiply modulation frequency by 1")); auto x100 = new PixmapButton(this, nullptr); x100->move(CD_LFO_MULTIPLIER_X, CD_LFO_SHAPES_Y - 8); x100->setActiveGraphic(embed::getIconPixmap("lfo_x100_active")); x100->setInactiveGraphic(embed::getIconPixmap("lfo_x100_inactive")); x100->setToolTip(tr("Multiply modulation frequency by 100")); auto d100 = new PixmapButton(this, nullptr); d100->move(CD_LFO_MULTIPLIER_X, CD_LFO_SHAPES_Y + 22); d100->setActiveGraphic(embed::getIconPixmap("lfo_d100_active")); d100->setInactiveGraphic(embed::getIconPixmap("lfo_d100_inactive")); d100->setToolTip(tr("Divide modulation frequency by 100")); m_multiplierBtnGrp = new automatableButtonGroup( this ); m_multiplierBtnGrp->addButton( x1 ); m_multiplierBtnGrp->addButton( x100 ); m_multiplierBtnGrp->addButton( d100 ); setModel( _model ); setAutoFillBackground( true ); QPalette pal; pal.setBrush( backgroundRole(), embed::getIconPixmap( "lfo_controller_artwork" ) ); setPalette( pal ); } LfoControllerDialog::~LfoControllerDialog() { m_userWaveBtn->disconnect( this ); } void LfoControllerDialog::askUserDefWave() { const auto fileName = SampleLoader::openWaveformFile(); if (fileName.isEmpty()) { return; } auto lfoModel = dynamic_cast<LfoController*>(model()); auto& buffer = lfoModel->m_userDefSampleBuffer; buffer = SampleLoader::createBufferFromFile(fileName); m_userWaveBtn->setToolTip(buffer->audioFile()); } void LfoControllerDialog::contextMenuEvent( QContextMenuEvent * ) { /* QPointer<captionMenu> contextMenu = new captionMenu( getEffect()->publicName() ); // ^ if this ever gets activated again: // a47a36c86e4473af862df58d2b59f6cb8620b9ee says that publicName // should be replaced by Model::displayName contextMenu->addAction( embed::getIconPixmap( "arp_up_on" ), tr( "Move &up" ), this, SLOT(moveUp())); contextMenu->addAction( embed::getIconPixmap( "arp_down_on" ), tr( "Move &down" ), this, SLOT(moveDown())); contextMenu->addSeparator(); contextMenu->addAction( embed::getIconPixmap( "cancel" ), tr( "&Remove this plugin" ), this, SLOT(deletePlugin())); contextMenu->exec( QCursor::pos() ); delete contextMenu; */ } void LfoControllerDialog::modelChanged() { m_lfo = castModel<LfoController>(); m_baseKnob->setModel( &m_lfo->m_baseModel ); m_speedKnob->setModel( &m_lfo->m_speedModel ); m_amountKnob->setModel( &m_lfo->m_amountModel ); m_phaseKnob->setModel( &m_lfo->m_phaseModel ); m_waveBtnGrp->setModel( &m_lfo->m_waveModel ); m_multiplierBtnGrp->setModel( &m_lfo->m_multiplierModel ); } } // namespace lmms::gui
9,244
C++
.cpp
216
40.194444
84
0.719091
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,906
PluginBrowser.cpp
LMMS_lmms/src/gui/PluginBrowser.cpp
/* * PluginBrowser.cpp - implementation of the plugin-browser * * 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. * */ #include "PluginBrowser.h" #include <QHeaderView> #include <QLabel> #include <QLineEdit> #include <QMenu> #include <QMouseEvent> #include <QPainter> #include <QStyleOption> #include <QTreeWidget> #include "embed.h" #include "Engine.h" #include "InstrumentTrack.h" #include "Song.h" #include "StringPairDrag.h" #include "TrackContainerView.h" #include "PluginFactory.h" namespace lmms::gui { PluginBrowser::PluginBrowser( QWidget * _parent ) : SideBarWidget( tr( "Instrument Plugins" ), embed::getIconPixmap( "plugins" ).transformed( QTransform().rotate( 90 ) ), _parent ) { setWindowTitle( tr( "Instrument browser" ) ); m_view = new QWidget( contentParent() ); //m_view->setFrameShape( QFrame::NoFrame ); addContentWidget( m_view ); auto view_layout = new QVBoxLayout(m_view); view_layout->setContentsMargins(5, 5, 5, 5); view_layout->setSpacing( 5 ); auto hint = new QLabel( tr( "Drag an instrument " "into either the Song Editor, the " "Pattern Editor or an " "existing instrument track." ), m_view ); hint->setWordWrap( true ); auto searchBar = new QLineEdit(m_view); searchBar->setPlaceholderText(tr("Search")); searchBar->setMaxLength(64); searchBar->setClearButtonEnabled(true); searchBar->addAction(embed::getIconPixmap("zoom"), QLineEdit::LeadingPosition); m_descTree = new QTreeWidget( m_view ); m_descTree->setColumnCount( 1 ); m_descTree->header()->setVisible( false ); m_descTree->setIndentation( 10 ); m_descTree->setSelectionMode( QAbstractItemView::NoSelection ); connect( searchBar, SIGNAL( textEdited( const QString& ) ), this, SLOT( onFilterChanged( const QString& ) ) ); view_layout->addWidget( hint ); view_layout->addWidget( searchBar ); view_layout->addWidget( m_descTree ); // Add plugins to the tree addPlugins(); // Resize m_descTree->header()->setSectionResizeMode( QHeaderView::ResizeToContents ); // Hide empty roots updateRootVisibilities(); } void PluginBrowser::updateRootVisibility( int rootIndex ) { QTreeWidgetItem * root = m_descTree->topLevelItem( rootIndex ); root->setHidden( !root->childCount() ); } void PluginBrowser::updateRootVisibilities() { int rootCount = m_descTree->topLevelItemCount(); for (int rootIndex = 0; rootIndex < rootCount; ++rootIndex) { updateRootVisibility( rootIndex ); } } void PluginBrowser::onFilterChanged( const QString & filter ) { int rootCount = m_descTree->topLevelItemCount(); for (int rootIndex = 0; rootIndex < rootCount; ++rootIndex) { QTreeWidgetItem * root = m_descTree->topLevelItem( rootIndex ); int itemCount = root->childCount(); for (int itemIndex = 0; itemIndex < itemCount; ++itemIndex) { QTreeWidgetItem * item = root->child( itemIndex ); auto descWidget = static_cast<PluginDescWidget*>(m_descTree->itemWidget(item, 0)); if (descWidget->name().contains(filter, Qt::CaseInsensitive)) { item->setHidden( false ); } else { item->setHidden( true ); } } } } void PluginBrowser::addPlugins() { // Add a root node to the plugin tree with the specified `label` and return it const auto addRoot = [this](auto label) { const auto root = new QTreeWidgetItem(); root->setText(0, label); m_descTree->addTopLevelItem(root); return root; }; // Add the plugin identified by `key` to the tree under the root node `root` const auto addPlugin = [this](const auto& key, auto root) { const auto item = new QTreeWidgetItem(); root->addChild(item); m_descTree->setItemWidget(item, 0, new PluginDescWidget(key, m_descTree)); }; // Remove any existing plugins from the tree m_descTree->clear(); // Fetch and sort all instrument plugin descriptors auto descs = getPluginFactory()->descriptors(Plugin::Type::Instrument); std::sort(descs.begin(), descs.end(), [](auto d1, auto d2) { return qstricmp(d1->displayName, d2->displayName) < 0; } ); // Add a root node to the tree for native LMMS plugins const auto lmmsRoot = addRoot("LMMS"); lmmsRoot->setExpanded(true); // Add all of the descriptors to the tree for (const auto desc : descs) { if (desc->subPluginFeatures) { // Fetch and sort all subplugins for this plugin descriptor auto subPluginKeys = Plugin::Descriptor::SubPluginFeatures::KeyList{}; desc->subPluginFeatures->listSubPluginKeys(desc, subPluginKeys); std::sort(subPluginKeys.begin(), subPluginKeys.end(), [](const auto& l, const auto& r) { return QString::compare(l.displayName(), r.displayName(), Qt::CaseInsensitive) < 0; } ); // Create a root node for this plugin and add the subplugins under it const auto root = addRoot(desc->displayName); for (const auto& key : subPluginKeys) { addPlugin(key, root); } } else { addPlugin(Plugin::Descriptor::SubPluginFeatures::Key(desc, desc->name), lmmsRoot); } } } PluginDescWidget::PluginDescWidget(const PluginKey &_pk, QWidget * _parent ) : QWidget( _parent ), m_pluginKey( _pk ), m_logo( _pk.logo()->pixmap() ), m_mouseOver( false ) { setFixedHeight( DEFAULT_HEIGHT ); setMouseTracking( true ); setCursor( Qt::PointingHandCursor ); setToolTip(_pk.desc->subPluginFeatures ? _pk.description() : tr(_pk.desc->description)); } QString PluginDescWidget::name() const { return m_pluginKey.displayName(); } void PluginDescWidget::paintEvent( QPaintEvent * ) { QPainter p( this ); // Paint everything according to the style sheet QStyleOption o; o.initFrom( this ); style()->drawPrimitive( QStyle::PE_Widget, &o, &p, this ); // Draw the rest const int s = 16 + ( 32 * ( qBound( 24, height(), 60 ) - 24 ) ) / ( 60 - 24 ); const QSize logo_size( s, s ); QPixmap logo = m_logo.scaled( logo_size, Qt::KeepAspectRatio, Qt::SmoothTransformation ); p.drawPixmap( 4, 4, logo ); QFont f = p.font(); if ( m_mouseOver ) { f.setBold( true ); } p.setFont( f ); p.drawText( 10 + logo_size.width(), 15, m_pluginKey.displayName()); } void PluginDescWidget::enterEvent( QEvent * _e ) { m_mouseOver = true; QWidget::enterEvent( _e ); } void PluginDescWidget::leaveEvent( QEvent * _e ) { m_mouseOver = false; QWidget::leaveEvent( _e ); } void PluginDescWidget::mousePressEvent( QMouseEvent * _me ) { Engine::setDndPluginKey(&m_pluginKey); if ( _me->button() == Qt::LeftButton ) { new StringPairDrag("instrument", QString::fromUtf8(m_pluginKey.desc->name), m_logo, this); leaveEvent( _me ); } } void PluginDescWidget::contextMenuEvent(QContextMenuEvent* e) { QMenu contextMenu(this); contextMenu.addAction( tr("Send to new instrument track"), [=]{ openInNewInstrumentTrack(m_pluginKey.desc->name); } ); contextMenu.exec(e->globalPos()); } void PluginDescWidget::openInNewInstrumentTrack(QString value) { TrackContainer* tc = Engine::getSong(); auto it = dynamic_cast<InstrumentTrack*>(Track::create(Track::Type::Instrument, tc)); auto ilt = new InstrumentLoaderThread(this, it, value); ilt->start(); } } // namespace lmms::gui
7,919
C++
.cpp
246
29.630081
89
0.725145
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,907
MixerView.cpp
LMMS_lmms/src/gui/MixerView.cpp
/* * MixerView.cpp - effect-mixer-view for LMMS * * 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. * */ #include <QLayout> #include <QPushButton> #include <QScrollArea> #include <QStyle> #include <QKeyEvent> #include "lmms_math.h" #include "MixerChannelView.h" #include "MixerView.h" #include "Knob.h" #include "Mixer.h" #include "GuiApplication.h" #include "MainWindow.h" #include "AudioEngine.h" #include "InstrumentTrack.h" #include "PatternStore.h" #include "SampleTrack.h" #include "SendButtonIndicator.h" #include "Song.h" #include "SubWindow.h" #include "TrackContainer.h" // For TrackContainer::TrackList typedef namespace lmms::gui { MixerView::MixerView(Mixer* mixer) : QWidget(), ModelView(nullptr, this), SerializingObjectHook(), m_mixer(mixer) { #if QT_VERSION < 0x50C00 // Workaround for a bug in Qt versions below 5.12, // where argument-dependent-lookup fails for QFlags operators // declared inside a namepsace. // This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h // See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348 using ::operator|; #endif mixer->setHook(this); //QPalette pal = palette(); //pal.setColor(QPalette::Window, QColor(72, 76, 88)); //setPalette(pal); setAutoFillBackground(true); setWindowTitle(tr("Mixer")); setWindowIcon(embed::getIconPixmap("mixer")); // main-layout auto ml = new QHBoxLayout{this}; // Set margins ml->setContentsMargins(0, 4, 0, 0); // Channel area m_channelAreaWidget = new QWidget; chLayout = new QHBoxLayout(m_channelAreaWidget); chLayout->setSizeConstraint(QLayout::SetMinimumSize); chLayout->setSpacing(0); chLayout->setContentsMargins(0, 0, 0, 0); chLayout->setAlignment(Qt::AlignLeft); m_channelAreaWidget->setLayout(chLayout); // create rack layout before creating the first channel m_racksWidget = new QWidget; m_racksLayout = new QStackedLayout(m_racksWidget); m_racksLayout->setContentsMargins(0, 0, 0, 0); m_racksWidget->setLayout(m_racksLayout); // add master channel m_mixerChannelViews.resize(mixer->numChannels()); MixerChannelView * masterView = new MixerChannelView(this, this, 0); connectToSoloAndMute(0); m_mixerChannelViews[0] = masterView; m_racksLayout->addWidget(m_mixerChannelViews[0]->m_effectRackView); ml->addWidget(masterView, 0); auto mixerChannelSize = masterView->sizeHint(); // add mixer channels for (int i = 1; i < m_mixerChannelViews.size(); ++i) { m_mixerChannelViews[i] = new MixerChannelView(m_channelAreaWidget, this, i); connectToSoloAndMute(i); chLayout->addWidget(m_mixerChannelViews[i]); } // add the scrolling section to the main layout // class solely for scroll area to pass key presses down class ChannelArea : public QScrollArea { public: ChannelArea(QWidget* parent, MixerView* mv) : QScrollArea(parent), m_mv(mv) {} ~ChannelArea() override = default; void keyPressEvent(QKeyEvent* e) override { m_mv->keyPressEvent(e); } private: MixerView* m_mv; }; channelArea = new ChannelArea(this, this); channelArea->setWidget(m_channelAreaWidget); channelArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); channelArea->setFrameStyle(QFrame::NoFrame); channelArea->setMinimumWidth(mixerChannelSize.width() * 6); channelArea->setWidgetResizable(true); int const scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent); channelArea->setMinimumHeight(mixerChannelSize.height() + scrollBarExtent); ml->addWidget(channelArea, 1); // show the add new mixer channel button auto newChannelBtn = new QPushButton(embed::getIconPixmap("new_channel"), QString(), this); newChannelBtn->setObjectName("newChannelBtn"); newChannelBtn->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding); newChannelBtn->setFixedWidth(mixerChannelSize.width()); connect(newChannelBtn, SIGNAL(clicked()), this, SLOT(addNewChannel())); ml->addWidget(newChannelBtn, 0); // add the stacked layout for the effect racks of mixer channels ml->addWidget(m_racksWidget); setCurrentMixerChannel(m_mixerChannelViews[0]); updateGeometry(); auto* mainWindow = getGUI()->mainWindow(); // timer for updating faders connect(mainWindow, &MainWindow::periodicUpdate, this, &MixerView::updateFaders); // add ourself to workspace QMdiSubWindow* subWin = mainWindow->addWindowedWidget(this); layout()->setSizeConstraint(QLayout::SetMinimumSize); subWin->layout()->setSizeConstraint(QLayout::SetMinAndMaxSize); parentWidget()->setAttribute(Qt::WA_DeleteOnClose, false); parentWidget()->move(5, 310); // we want to receive dataChanged-signals in order to update setModel(mixer); } int MixerView::addNewChannel() { // add new mixer channel and redraw the form. Mixer * mix = getMixer(); int newChannelIndex = mix->createChannel(); m_mixerChannelViews.push_back(new MixerChannelView(m_channelAreaWidget, this, newChannelIndex)); connectToSoloAndMute(newChannelIndex); chLayout->addWidget(m_mixerChannelViews[newChannelIndex]); m_racksLayout->addWidget(m_mixerChannelViews[newChannelIndex]->m_effectRackView); updateMixerChannel(newChannelIndex); updateMaxChannelSelector(); return newChannelIndex; } void MixerView::refreshDisplay() { // delete all views and re-add them for (int i = 1; i<m_mixerChannelViews.size(); ++i) { // First disconnect from the solo/mute models. disconnectFromSoloAndMute(i); auto * mixerChannelView = m_mixerChannelViews[i]; chLayout->removeWidget(mixerChannelView); m_racksLayout->removeWidget(mixerChannelView->m_effectRackView); delete mixerChannelView; } m_channelAreaWidget->adjustSize(); // re-add the views m_mixerChannelViews.resize(getMixer()->numChannels()); for (int i = 1; i < m_mixerChannelViews.size(); ++i) { m_mixerChannelViews[i] = new MixerChannelView(m_channelAreaWidget, this, i); connectToSoloAndMute(i); chLayout->addWidget(m_mixerChannelViews[i]); m_racksLayout->addWidget(m_mixerChannelViews[i]->m_effectRackView); } // set selected mixer channel to 0 setCurrentMixerChannel(0); // update all mixer lines for (int i = 0; i < m_mixerChannelViews.size(); ++i) { updateMixerChannel(i); } updateMaxChannelSelector(); } // update the and max. channel number for every instrument void MixerView::updateMaxChannelSelector() { const TrackContainer::TrackList& songTracks = Engine::getSong()->tracks(); const TrackContainer::TrackList& patternStoreTracks = Engine::patternStore()->tracks(); for (const auto& trackList : {songTracks, patternStoreTracks}) { for (const auto& track : trackList) { if (track->type() == Track::Type::Instrument) { auto inst = (InstrumentTrack*)track; inst->mixerChannelModel()->setRange(0, m_mixerChannelViews.size()-1,1); } else if (track->type() == Track::Type::Sample) { auto strk = (SampleTrack*)track; strk->mixerChannelModel()->setRange(0, m_mixerChannelViews.size()-1,1); } } } } void MixerView::saveSettings(QDomDocument& doc, QDomElement& domElement) { MainWindow::saveWidgetState(this, domElement); } void MixerView::loadSettings(const QDomElement& domElement) { MainWindow::restoreWidgetState(this, domElement); } void MixerView::toggledSolo() { getMixer()->toggledSolo(); updateAllMixerChannels(); } void MixerView::toggledMute() { updateAllMixerChannels(); } Mixer* MixerView::getMixer() const { return m_mixer; } void MixerView::updateAllMixerChannels() { for (int i = 0; i < m_mixerChannelViews.size(); ++i) { m_mixerChannelViews[i]->update(); } } void MixerView::connectToSoloAndMute(int channelIndex) { auto * mixerChannel = getMixer()->mixerChannel(channelIndex); connect(&mixerChannel->m_muteModel, &BoolModel::dataChanged, this, &MixerView::toggledMute, Qt::DirectConnection); connect(&mixerChannel->m_soloModel, &BoolModel::dataChanged, this, &MixerView::toggledSolo, Qt::DirectConnection); } void MixerView::disconnectFromSoloAndMute(int channelIndex) { auto * mixerChannel = getMixer()->mixerChannel(channelIndex); disconnect(&mixerChannel->m_muteModel, &BoolModel::dataChanged, this, &MixerView::toggledMute); disconnect(&mixerChannel->m_soloModel, &BoolModel::dataChanged, this, &MixerView::toggledSolo); } void MixerView::setCurrentMixerChannel(MixerChannelView* channel) { // select m_currentMixerChannel = channel; m_racksLayout->setCurrentWidget(m_mixerChannelViews[channel->channelIndex()]->m_effectRackView); // set up send knob for (int i = 0; i < m_mixerChannelViews.size(); ++i) { updateMixerChannel(i); } } void MixerView::updateMixerChannel(int index) { const auto mixer = getMixer(); const auto currentIndex = m_currentMixerChannel->channelIndex(); const auto thisLine = m_mixerChannelViews[index]; thisLine->setToolTip(getMixer()->mixerChannel(index)->m_name); const auto sendModelCurrentToThis = mixer->channelSendModel(currentIndex, index); if (sendModelCurrentToThis == nullptr) { thisLine->m_sendKnob->setVisible(false); thisLine->m_sendArrow->setVisible(false); } else { thisLine->m_sendKnob->setVisible(true); thisLine->m_sendKnob->setModel(sendModelCurrentToThis); thisLine->m_sendArrow->setVisible(true); } const auto sendModelThisToCurrent = mixer->channelSendModel(index, currentIndex); if (sendModelThisToCurrent) { thisLine->m_receiveArrowOrSendButton->setVisible(true); thisLine->m_receiveArrowOrSendButton->setCurrentIndex(thisLine->m_receiveArrowStackedIndex); } else { thisLine->m_receiveArrowOrSendButton->setVisible(!mixer->isInfiniteLoop(currentIndex, index)); thisLine->m_receiveArrowOrSendButton->setCurrentIndex(thisLine->m_sendButtonStackedIndex); } thisLine->m_sendButton->updateLightStatus(); thisLine->update(); } void MixerView::deleteChannel(int index) { // can't delete master if (index == 0) return; // Disconnect from the solo/mute models of the channel we are about to delete disconnectFromSoloAndMute(index); // remember selected line int selLine = m_currentMixerChannel->channelIndex(); Mixer* mixer = getMixer(); // in case the deleted channel is soloed or the remaining // channels will be left in a muted state mixer->clearChannel(index); // delete the real channel mixer->deleteChannel(index); chLayout->removeWidget(m_mixerChannelViews[index]); m_racksLayout->removeWidget(m_mixerChannelViews[index]); // delete MixerChannelView later to prevent a crash when deleting from context menu m_mixerChannelViews[index]->hide(); m_mixerChannelViews[index]->deleteLater(); m_channelAreaWidget->adjustSize(); // make sure every channel knows what index it is for (int i = index + 1; i < m_mixerChannelViews.size(); ++i) { m_mixerChannelViews[i]->setChannelIndex(i - 1); } m_mixerChannelViews.remove(index); // select the next channel if (selLine >= m_mixerChannelViews.size()) { selLine = m_mixerChannelViews.size() - 1; } setCurrentMixerChannel(selLine); updateMaxChannelSelector(); } void MixerView::deleteUnusedChannels() { Mixer* mix = getMixer(); // Check all channels except master, delete those with no incoming sends for (int i = m_mixerChannelViews.size() - 1; i > 0; --i) { if (!mix->isChannelInUse(i)) { deleteChannel(i); } } } void MixerView::moveChannelLeft(int index, int focusIndex) { // can't move master or first channel left or last channel right if (index <= 1 || index >= m_mixerChannelViews.size()) return; Mixer *m = getMixer(); // Move instruments channels m->moveChannelLeft(index); // Update widgets models m_mixerChannelViews[index]->setChannelIndex(index); m_mixerChannelViews[index - 1]->setChannelIndex(index - 1); // Focus on new position setCurrentMixerChannel(focusIndex); } void MixerView::moveChannelLeft(int index) { moveChannelLeft(index, index - 1); } void MixerView::moveChannelRight(int index) { moveChannelLeft(index + 1, index + 1); } void MixerView::renameChannel(int index) { m_mixerChannelViews[index]->renameChannel(); } void MixerView::keyPressEvent(QKeyEvent * e) { switch(e->key()) { case Qt::Key_Delete: deleteChannel(m_currentMixerChannel->channelIndex()); break; case Qt::Key_Left: if (e->modifiers() & Qt::AltModifier) { moveChannelLeft(m_currentMixerChannel->channelIndex()); } else { // select channel to the left setCurrentMixerChannel(m_currentMixerChannel->channelIndex() - 1); } break; case Qt::Key_Right: if (e->modifiers() & Qt::AltModifier) { moveChannelRight(m_currentMixerChannel->channelIndex()); } else { // select channel to the right setCurrentMixerChannel(m_currentMixerChannel->channelIndex() + 1); } break; case Qt::Key_Insert: if (e->modifiers() & Qt::ShiftModifier) { addNewChannel(); } break; case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_F2: renameChannel(m_currentMixerChannel->channelIndex()); break; } } void MixerView::closeEvent(QCloseEvent * ce) { if (parentWidget()) { parentWidget()->hide(); } else { hide(); } ce->ignore(); } void MixerView::setCurrentMixerChannel(int channel) { if (channel >= 0 && channel < m_mixerChannelViews.size()) { setCurrentMixerChannel(m_mixerChannelViews[channel]); } } void MixerView::clear() { for (auto i = m_mixerChannelViews.size() - 1; i > 0; --i) { deleteChannel(i); } getMixer()->clearChannel(0); m_mixerChannelViews[0]->reset(); refreshDisplay(); } void MixerView::updateFaders() { Mixer * m = getMixer(); for (int i = 0; i < m_mixerChannelViews.size(); ++i) { const float opl = m_mixerChannelViews[i]->m_fader->getPeak_L(); const float opr = m_mixerChannelViews[i]->m_fader->getPeak_R(); const float fallOff = 1.25; if (m->mixerChannel(i)->m_peakLeft >= opl/fallOff) { m_mixerChannelViews[i]->m_fader->setPeak_L(m->mixerChannel(i)->m_peakLeft); // Set to -1 so later we'll know if this value has been refreshed yet. m->mixerChannel(i)->m_peakLeft = -1; } else if (m->mixerChannel(i)->m_peakLeft != -1) { m_mixerChannelViews[i]->m_fader->setPeak_L(opl/fallOff); } if (m->mixerChannel(i)->m_peakRight >= opr/fallOff) { m_mixerChannelViews[i]->m_fader->setPeak_R(m->mixerChannel(i)->m_peakRight); // Set to -1 so later we'll know if this value has been refreshed yet. m->mixerChannel(i)->m_peakRight = -1; } else if (m->mixerChannel(i)->m_peakRight != -1) { m_mixerChannelViews[i]->m_fader->setPeak_R(opr/fallOff); } } } } // namespace lmms::gui
15,303
C++
.cpp
466
30.356223
115
0.754097
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,908
ProjectNotes.cpp
LMMS_lmms/src/gui/ProjectNotes.cpp
/* * ProjectNotes.cpp - implementation of project-notes-editor * * 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. * */ #include "ProjectNotes.h" #include <QAction> #include <QApplication> #include <QCloseEvent> #include <QColorDialog> #include <QComboBox> #include <QFontDatabase> #include <QLineEdit> #include <QMdiArea> #include <QTextEdit> #include <QToolBar> #include <QDomCDATASection> #include "embed.h" #include "Engine.h" #include "GuiApplication.h" #include "MainWindow.h" #include "Song.h" namespace lmms::gui { ProjectNotes::ProjectNotes() : QMainWindow( getGUI()->mainWindow()->workspace() ) { m_edit = new QTextEdit( this ); m_edit->setAutoFillBackground( true ); QPalette pal; pal.setColor( m_edit->backgroundRole(), QColor( 64, 64, 64 ) ); m_edit->setPalette( pal ); m_edit->show(); clear(); connect( m_edit, SIGNAL( currentCharFormatChanged( const QTextCharFormat& ) ), this, SLOT( formatChanged( const QTextCharFormat& ) ) ); // connect( m_edit, SIGNAL(currentAlignmentChanged(int)), // this, SLOT(alignmentChanged(int))); connect( m_edit, SIGNAL(textChanged()), Engine::getSong(), SLOT(setModified())); setupActions(); setCentralWidget( m_edit ); setWindowTitle( tr( "Project Notes" ) ); setWindowIcon( embed::getIconPixmap( "project_notes" ) ); getGUI()->mainWindow()->addWindowedWidget( this ); parentWidget()->setAttribute( Qt::WA_DeleteOnClose, false ); parentWidget()->move( 700, 10 ); parentWidget()->resize( 400, 300 ); parentWidget()->hide(); } void ProjectNotes::clear() { m_edit->setHtml( tr( "Enter project notes here" ) ); m_edit->selectAll(); m_edit->setTextColor( QColor( 224, 224, 224 ) ); QTextCursor cursor = m_edit->textCursor(); cursor.clearSelection(); m_edit->setTextCursor( cursor ); } void ProjectNotes::setText( const QString & _text ) { m_edit->setHtml( _text ); } void ProjectNotes::setupActions() { QToolBar * tb = addToolBar( tr( "Edit Actions" ) ); auto a = new QAction(embed::getIconPixmap("edit_undo"), tr("&Undo"), this); a->setShortcut( tr( "%1+Z" ).arg(UI_CTRL_KEY) ); connect( a, SIGNAL(triggered()), m_edit, SLOT(undo())); tb->addAction( a ); a = new QAction( embed::getIconPixmap( "edit_redo" ), tr( "&Redo" ), this ); a->setShortcut( tr( "%1+Y" ).arg(UI_CTRL_KEY) ); connect( a, SIGNAL(triggered()), m_edit, SLOT(redo())); tb->addAction( a ); a = new QAction( embed::getIconPixmap( "edit_copy" ), tr( "&Copy" ), this ); a->setShortcut( tr( "%1+C" ).arg(UI_CTRL_KEY) ); connect( a, SIGNAL(triggered()), m_edit, SLOT(copy())); tb->addAction( a ); a = new QAction( embed::getIconPixmap( "edit_cut" ), tr( "Cu&t" ), this ); a->setShortcut( tr( "%1+X" ).arg(UI_CTRL_KEY) ); connect( a, SIGNAL(triggered()), m_edit, SLOT(cut())); tb->addAction( a ); a = new QAction( embed::getIconPixmap( "edit_paste" ), tr( "&Paste" ), this ); a->setShortcut( tr( "%1+V" ).arg(UI_CTRL_KEY) ); connect( a, SIGNAL(triggered()), m_edit, SLOT(paste())); tb->addAction( a ); tb = addToolBar( tr( "Format Actions" ) ); m_comboFont = new QComboBox( tb ); m_comboFont->setEditable( true ); QFontDatabase db; m_comboFont->addItems( db.families() ); connect( m_comboFont, SIGNAL( activated( const QString& ) ), m_edit, SLOT( setFontFamily( const QString& ) ) ); m_comboFont->lineEdit()->setText( QApplication::font().family() ); m_comboSize = new QComboBox( tb ); m_comboSize->setEditable( true ); QList<int> sizes = db.standardSizes(); QList<int>::Iterator it = sizes.begin(); for ( ; it != sizes.end(); ++it ) { m_comboSize->addItem( QString::number( *it ) ); } connect( m_comboSize, SIGNAL( activated( const QString& ) ), this, SLOT( textSize( const QString& ) ) ); m_comboSize->lineEdit()->setText( QString::number( QApplication::font().pointSize() ) ); m_actionTextBold = new QAction( embed::getIconPixmap( "text_bold" ), tr( "&Bold" ), this ); m_actionTextBold->setShortcut( tr( "%1+B" ).arg(UI_CTRL_KEY) ); m_actionTextBold->setCheckable( true ); connect( m_actionTextBold, SIGNAL(triggered()), this, SLOT(textBold())); m_actionTextItalic = new QAction( embed::getIconPixmap( "text_italic" ), tr( "&Italic" ), this ); m_actionTextItalic->setShortcut( tr( "%1+I" ).arg(UI_CTRL_KEY) ); m_actionTextItalic->setCheckable( true ); connect( m_actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic())); m_actionTextUnderline = new QAction( embed::getIconPixmap( "text_under" ), tr( "&Underline" ), this ); m_actionTextUnderline->setShortcut( tr( "%1+U" ).arg(UI_CTRL_KEY) ); m_actionTextUnderline->setCheckable( true ); connect( m_actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline())); auto grp = new QActionGroup(tb); connect( grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*))); m_actionAlignLeft = new QAction( embed::getIconPixmap( "text_left" ), tr( "&Left" ), m_edit ); m_actionAlignLeft->setShortcut( tr( "%1+L" ).arg(UI_CTRL_KEY) ); m_actionAlignLeft->setCheckable( true ); grp->addAction( m_actionAlignLeft ); m_actionAlignCenter = new QAction( embed::getIconPixmap( "text_center" ), tr( "C&enter" ), m_edit ); m_actionAlignCenter->setShortcutContext( Qt::WidgetShortcut ); m_actionAlignCenter->setShortcut( tr( "%1+E" ).arg(UI_CTRL_KEY) ); m_actionAlignCenter->setCheckable( true ); grp->addAction( m_actionAlignCenter ); m_actionAlignRight = new QAction( embed::getIconPixmap( "text_right" ), tr( "&Right" ), m_edit ); m_actionAlignRight->setShortcutContext( Qt::WidgetShortcut ); m_actionAlignRight->setShortcut( tr( "%1+R" ).arg(UI_CTRL_KEY) ); m_actionAlignRight->setCheckable( true ); grp->addAction( m_actionAlignRight ); m_actionAlignJustify = new QAction( embed::getIconPixmap( "text_block" ), tr( "&Justify" ), m_edit ); m_actionAlignJustify->setShortcut( tr( "%1+J" ).arg(UI_CTRL_KEY) ); m_actionAlignJustify->setCheckable( true ); grp->addAction( m_actionAlignJustify ); QPixmap pix( 16, 16 ); pix.fill( Qt::black ); m_actionTextColor = new QAction( pix, tr( "&Color..." ), this ); connect( m_actionTextColor, SIGNAL(triggered()), this, SLOT(textColor())); tb->addWidget( m_comboFont ); tb->addWidget( m_comboSize ); tb->addAction( m_actionTextBold ); tb->addAction( m_actionTextItalic ); tb->addAction( m_actionTextUnderline ); tb->addAction( m_actionAlignLeft ); tb->addAction( m_actionAlignCenter ); tb->addAction( m_actionAlignRight ); tb->addAction( m_actionAlignJustify ); tb->addAction( m_actionTextColor ); } void ProjectNotes::textBold() { m_edit->setFontWeight( m_actionTextBold->isChecked() ? QFont::Bold : QFont::Normal ); Engine::getSong()->setModified(); } void ProjectNotes::textUnderline() { m_edit->setFontUnderline( m_actionTextUnderline->isChecked() ); Engine::getSong()->setModified(); } void ProjectNotes::textItalic() { m_edit->setFontItalic( m_actionTextItalic->isChecked() ); Engine::getSong()->setModified(); } void ProjectNotes::textFamily( const QString & _f ) { m_edit->setFontFamily( _f ); m_edit->viewport()->setFocus(); Engine::getSong()->setModified(); } void ProjectNotes::textSize( const QString & _p ) { m_edit->setFontPointSize( _p.toInt() ); m_edit->viewport()->setFocus(); Engine::getSong()->setModified(); } void ProjectNotes::textColor() { QColor col = QColorDialog::getColor( m_edit->textColor(), this ); if ( !col.isValid() ) { return; } m_edit->setTextColor( col ); QPixmap pix( 16, 16 ); pix.fill( Qt::black ); m_actionTextColor->setIcon( pix ); } void ProjectNotes::textAlign( QAction * _a ) { if( _a == m_actionAlignLeft ) { m_edit->setAlignment( Qt::AlignLeft ); } else if( _a == m_actionAlignCenter ) { m_edit->setAlignment( Qt::AlignHCenter ); } else if( _a == m_actionAlignRight ) { m_edit->setAlignment( Qt::AlignRight ); } else if( _a == m_actionAlignJustify ) { m_edit->setAlignment( Qt::AlignJustify ); } } void ProjectNotes::formatChanged( const QTextCharFormat & _f ) { QFont font = _f.font(); m_comboFont->lineEdit()->setText( font.family() ); m_comboSize->lineEdit()->setText( QString::number( font.pointSize() ) ); m_actionTextBold->setChecked( font.bold() ); m_actionTextItalic->setChecked( font.italic() ); m_actionTextUnderline->setChecked( font.underline() ); QPixmap pix( 16, 16 ); pix.fill( _f.foreground().color() ); m_actionTextColor->setIcon( pix ); Engine::getSong()->setModified(); } void ProjectNotes::alignmentChanged( int _a ) { if ( _a & Qt::AlignLeft ) { m_actionAlignLeft->setChecked( true ); } else if ( ( _a & Qt::AlignHCenter ) ) { m_actionAlignCenter->setChecked( true ); } else if ( ( _a & Qt::AlignRight ) ) { m_actionAlignRight->setChecked( true ); } else if ( ( _a & Qt::AlignJustify ) ) { m_actionAlignJustify->setChecked( true ); } Engine::getSong()->setModified(); } void ProjectNotes::saveSettings( QDomDocument & _doc, QDomElement & _this ) { MainWindow::saveWidgetState( this, _this ); QDomCDATASection ds = _doc.createCDATASection( m_edit->toHtml() ); _this.appendChild( ds ); } void ProjectNotes::loadSettings( const QDomElement & _this ) { MainWindow::restoreWidgetState( this, _this ); m_edit->setHtml( _this.text() ); } void ProjectNotes::closeEvent( QCloseEvent * _ce ) { if( parentWidget() ) { parentWidget()->hide(); } else { hide(); } _ce->ignore(); } } // namespace lmms::gui
10,350
C++
.cpp
307
31.120521
77
0.693785
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,909
MixerChannelView.cpp
LMMS_lmms/src/gui/MixerChannelView.cpp
/* * MixerChannelView.h - the mixer channel view * * Copyright (c) 2022 saker <sakertooth@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. * */ #include "MixerChannelView.h" #include <QCheckBox> #include <QFont> #include <QGraphicsProxyWidget> #include <QGraphicsScene> #include <QMenu> #include <QMessageBox> #include <QPainter> #include <cassert> #include "CaptionMenu.h" #include "ColorChooser.h" #include "ConfigManager.h" #include "FontHelper.h" #include "GuiApplication.h" #include "Mixer.h" #include "MixerView.h" #include "PeakIndicator.h" #include "Song.h" namespace lmms::gui { MixerChannelView::MixerChannelView(QWidget* parent, MixerView* mixerView, int channelIndex) : QWidget(parent) , m_mixerView(mixerView) , m_channelIndex(channelIndex) { auto retainSizeWhenHidden = [](QWidget* widget) { auto sizePolicy = widget->sizePolicy(); sizePolicy.setRetainSizeWhenHidden(true); widget->setSizePolicy(sizePolicy); }; auto receiveArrowContainer = new QWidget{}; auto receiveArrowLayout = new QVBoxLayout{receiveArrowContainer}; m_receiveArrow = new QLabel{}; m_receiveArrow->setPixmap(embed::getIconPixmap("receive_bg_arrow")); receiveArrowLayout->setContentsMargins(0, 0, 0, 0); receiveArrowLayout->setSpacing(0); receiveArrowLayout->addWidget(m_receiveArrow, 0, Qt::AlignHCenter); auto sendButtonContainer = new QWidget{}; auto sendButtonLayout = new QVBoxLayout{sendButtonContainer}; m_sendButton = new SendButtonIndicator{this, this, mixerView}; sendButtonLayout->setContentsMargins(0, 0, 0, 0); sendButtonLayout->setSpacing(0); sendButtonLayout->addWidget(m_sendButton, 0, Qt::AlignHCenter); m_receiveArrowOrSendButton = new QStackedWidget{this}; m_receiveArrowStackedIndex = m_receiveArrowOrSendButton->addWidget(receiveArrowContainer); m_sendButtonStackedIndex = m_receiveArrowOrSendButton->addWidget(sendButtonContainer); retainSizeWhenHidden(m_receiveArrowOrSendButton); m_sendKnob = new Knob{KnobType::Bright26, this, tr("Channel send amount")}; retainSizeWhenHidden(m_sendKnob); m_sendArrow = new QLabel{}; m_sendArrow->setPixmap(embed::getIconPixmap("send_bg_arrow")); retainSizeWhenHidden(m_sendArrow); m_channelNumberLcd = new LcdWidget{2, this}; m_channelNumberLcd->setValue(channelIndex); retainSizeWhenHidden(m_channelNumberLcd); const auto mixerChannel = Engine::mixer()->mixerChannel(channelIndex); const auto mixerName = mixerChannel->m_name; setToolTip(mixerName); m_renameLineEdit = new QLineEdit{mixerName, nullptr}; m_renameLineEdit->setFixedWidth(65); m_renameLineEdit->setFont(adjustedToPixelSize(font(), LARGE_FONT_SIZE)); m_renameLineEdit->setReadOnly(true); m_renameLineEdit->installEventFilter(this); auto renameLineEditScene = new QGraphicsScene{}; m_renameLineEditView = new QGraphicsView{}; m_renameLineEditView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_renameLineEditView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_renameLineEditView->setAttribute(Qt::WA_TransparentForMouseEvents, true); m_renameLineEditView->setScene(renameLineEditScene); auto renameLineEditProxy = renameLineEditScene->addWidget(m_renameLineEdit); renameLineEditProxy->setRotation(-90); m_renameLineEditView->setFixedSize(m_renameLineEdit->height() + 5, m_renameLineEdit->width() + 5); m_muteButton = new PixmapButton(this, tr("Mute")); m_muteButton->setModel(&mixerChannel->m_muteModel); m_muteButton->setActiveGraphic(embed::getIconPixmap("led_off")); m_muteButton->setInactiveGraphic(embed::getIconPixmap("led_green")); m_muteButton->setCheckable(true); m_muteButton->setToolTip(tr("Mute this channel")); m_soloButton = new PixmapButton(this, tr("Solo")); m_soloButton->setModel(&mixerChannel->m_soloModel); m_soloButton->setActiveGraphic(embed::getIconPixmap("led_red")); m_soloButton->setInactiveGraphic(embed::getIconPixmap("led_off")); m_soloButton->setCheckable(true); m_soloButton->setToolTip(tr("Solo this channel")); auto soloMuteLayout = new QVBoxLayout(); soloMuteLayout->setContentsMargins(0, 0, 0, 0); soloMuteLayout->setSpacing(0); soloMuteLayout->addWidget(m_soloButton, 0, Qt::AlignHCenter); soloMuteLayout->addWidget(m_muteButton, 0, Qt::AlignHCenter); m_fader = new Fader{&mixerChannel->m_volumeModel, tr("Fader %1").arg(channelIndex), this}; m_peakIndicator = new PeakIndicator(this); connect(m_fader, &Fader::peakChanged, m_peakIndicator, &PeakIndicator::updatePeak); m_effectRackView = new EffectRackView{&mixerChannel->m_fxChain, mixerView->m_racksWidget}; m_effectRackView->setFixedWidth(EffectRackView::DEFAULT_WIDTH); auto mainLayout = new QVBoxLayout{this}; mainLayout->setContentsMargins(4, 4, 4, 4); mainLayout->setSpacing(2); mainLayout->addWidget(m_receiveArrowOrSendButton, 0, Qt::AlignHCenter); mainLayout->addWidget(m_sendKnob, 0, Qt::AlignHCenter); mainLayout->addWidget(m_sendArrow, 0, Qt::AlignHCenter); mainLayout->addWidget(m_channelNumberLcd, 0, Qt::AlignHCenter); mainLayout->addWidget(m_renameLineEditView, 0, Qt::AlignHCenter); mainLayout->addLayout(soloMuteLayout); mainLayout->addWidget(m_peakIndicator); mainLayout->addWidget(m_fader, 1, Qt::AlignHCenter); connect(m_renameLineEdit, &QLineEdit::editingFinished, this, &MixerChannelView::renameFinished); } void MixerChannelView::contextMenuEvent(QContextMenuEvent*) { auto contextMenu = new CaptionMenu(mixerChannel()->m_name, this); if (!isMasterChannel()) // no move-options in master { contextMenu->addAction(tr("Move &left"), this, &MixerChannelView::moveChannelLeft); contextMenu->addAction(tr("Move &right"), this, &MixerChannelView::moveChannelRight); } contextMenu->addAction(tr("Rename &channel"), this, &MixerChannelView::renameChannel); contextMenu->addSeparator(); if (!isMasterChannel()) // no remove-option in master { contextMenu->addAction( embed::getIconPixmap("cancel"), tr("R&emove channel"), this, &MixerChannelView::removeChannel); contextMenu->addSeparator(); } contextMenu->addAction( embed::getIconPixmap("cancel"), tr("Remove &unused channels"), this, &MixerChannelView::removeUnusedChannels); contextMenu->addSeparator(); auto colorMenu = QMenu{tr("Color"), this}; colorMenu.setIcon(embed::getIconPixmap("colorize")); colorMenu.addAction(tr("Change"), this, &MixerChannelView::selectColor); colorMenu.addAction(tr("Reset"), this, &MixerChannelView::resetColor); colorMenu.addAction(tr("Pick random"), this, &MixerChannelView::randomizeColor); contextMenu->addMenu(&colorMenu); contextMenu->exec(QCursor::pos()); delete contextMenu; } void MixerChannelView::paintEvent(QPaintEvent*) { static constexpr auto innerBorderSize = 3; static constexpr auto outerBorderSize = 1; const auto channel = mixerChannel(); const auto isActive = m_mixerView->currentMixerChannel() == this; const auto width = rect().width(); const auto height = rect().height(); auto painter = QPainter{this}; if (channel->color().has_value() && !channel->m_muteModel.value()) { painter.fillRect(rect(), channel->color()->darker(isActive ? 120 : 150)); } else { painter.fillRect(rect(), isActive ? backgroundActive().color() : painter.background().color()); } // inner border painter.setPen(isActive ? strokeInnerActive() : strokeInnerInactive()); painter.drawRect(1, 1, width - innerBorderSize, height - innerBorderSize); // outer border painter.setPen(isActive ? strokeOuterActive() : strokeOuterInactive()); painter.drawRect(0, 0, width - outerBorderSize, height - outerBorderSize); } void MixerChannelView::mousePressEvent(QMouseEvent*) { if (m_mixerView->currentMixerChannel() != this) { m_mixerView->setCurrentMixerChannel(this); } } void MixerChannelView::mouseDoubleClickEvent(QMouseEvent*) { renameChannel(); } bool MixerChannelView::eventFilter(QObject*, QEvent* event) { // If we are in a rename, capture the enter/return events and handle them if (event->type() == QEvent::KeyPress) { auto keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) { if (m_inRename) { renameFinished(); event->accept(); // Stop the event from propagating return true; } } } return false; } void MixerChannelView::setChannelIndex(int index) { MixerChannel* mixerChannel = Engine::mixer()->mixerChannel(index); m_fader->setModel(&mixerChannel->m_volumeModel); m_muteButton->setModel(&mixerChannel->m_muteModel); m_soloButton->setModel(&mixerChannel->m_soloModel); m_effectRackView->setModel(&mixerChannel->m_fxChain); m_channelNumberLcd->setValue(index); m_renameLineEdit->setText(elideName(mixerChannel->m_name)); m_channelIndex = index; } void MixerChannelView::renameChannel() { m_inRename = true; setToolTip(""); m_renameLineEdit->setReadOnly(false); m_channelNumberLcd->hide(); m_renameLineEdit->setFixedWidth(m_renameLineEdit->width()); m_renameLineEdit->setText(mixerChannel()->m_name); m_renameLineEditView->setFocus(); m_renameLineEdit->selectAll(); m_renameLineEdit->setFocus(); } void MixerChannelView::renameFinished() { m_inRename = false; m_renameLineEdit->deselect(); m_renameLineEdit->setReadOnly(true); m_renameLineEdit->setFixedWidth(m_renameLineEdit->width()); m_channelNumberLcd->show(); auto newName = m_renameLineEdit->text(); setFocus(); const auto mc = mixerChannel(); if (!newName.isEmpty() && mc->m_name != newName) { mc->m_name = newName; m_renameLineEdit->setText(elideName(newName)); Engine::getSong()->setModified(); } setToolTip(mc->m_name); } void MixerChannelView::resetColor() { mixerChannel()->setColor(std::nullopt); Engine::getSong()->setModified(); update(); } void MixerChannelView::selectColor() { const auto channel = mixerChannel(); const auto initialColor = channel->color().value_or(backgroundActive().color()); const auto* colorChooser = ColorChooser{this}.withPalette(ColorChooser::Palette::Mixer); const auto newColor = colorChooser->getColor(initialColor); if (!newColor.isValid()) { return; } channel->setColor(newColor); Engine::getSong()->setModified(); update(); } void MixerChannelView::randomizeColor() { auto channel = mixerChannel(); channel->setColor(ColorChooser::getPalette(ColorChooser::Palette::Mixer)[rand() % 48]); Engine::getSong()->setModified(); update(); } bool MixerChannelView::confirmRemoval(int index) { // if config variable is set to false, there is no need for user confirmation bool needConfirm = ConfigManager::inst()->value("ui", "mixerchanneldeletionwarning", "1").toInt(); if (!needConfirm) { return true; } // is the channel is not in use, there is no need for user confirmation if (!getGUI()->mixerView()->getMixer()->isChannelInUse(index)) { return true; } QString messageRemoveTrack = tr("This Mixer Channel is being used.\n" "Are you sure you want to remove this channel?\n\n" "Warning: This operation can not be undone."); QString messageTitleRemoveTrack = tr("Confirm removal"); QString askAgainText = tr("Don't ask again"); auto askAgainCheckBox = new QCheckBox(askAgainText, nullptr); connect(askAgainCheckBox, &QCheckBox::stateChanged, [](int state) { // Invert button state, if it's checked we *shouldn't* ask again ConfigManager::inst()->setValue("ui", "mixerchanneldeletionwarning", state ? "0" : "1"); }); QMessageBox mb(this); mb.setText(messageRemoveTrack); mb.setWindowTitle(messageTitleRemoveTrack); mb.setIcon(QMessageBox::Warning); mb.addButton(QMessageBox::Cancel); mb.addButton(QMessageBox::Ok); mb.setCheckBox(askAgainCheckBox); mb.setDefaultButton(QMessageBox::Cancel); int answer = mb.exec(); return answer == QMessageBox::Ok; } void MixerChannelView::removeChannel() { if (!confirmRemoval(m_channelIndex)) { return; } auto mix = getGUI()->mixerView(); mix->deleteChannel(m_channelIndex); } void MixerChannelView::removeUnusedChannels() { auto mix = getGUI()->mixerView(); mix->deleteUnusedChannels(); } void MixerChannelView::moveChannelLeft() { auto mix = getGUI()->mixerView(); mix->moveChannelLeft(m_channelIndex); } void MixerChannelView::moveChannelRight() { auto mix = getGUI()->mixerView(); mix->moveChannelRight(m_channelIndex); } QString MixerChannelView::elideName(const QString& name) { const auto maxTextHeight = m_renameLineEdit->width(); const auto metrics = QFontMetrics{m_renameLineEdit->font()}; const auto elidedName = metrics.elidedText(name, Qt::ElideRight, maxTextHeight); return elidedName; } MixerChannel* MixerChannelView::mixerChannel() const { return Engine::mixer()->mixerChannel(m_channelIndex); } void MixerChannelView::reset() { m_peakIndicator->resetPeakToMinusInf(); } } // namespace lmms::gui
13,418
C++
.cpp
334
38.056886
112
0.771879
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
19,910
embed.cpp
LMMS_lmms/src/gui/embed.cpp
/* * embed.cpp - misc stuff for using embedded resources (linked into binary) * * 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. * */ #include "embed.h" #include <QDebug> #include <QDir> #include <QImageReader> #include <QPixmapCache> #include <QResource> namespace lmms::embed { namespace { auto loadPixmap(const QString& name, int width, int height, const char* const* xpm) -> QPixmap { if (xpm) { return QPixmap{xpm}; } const auto resourceName = QDir::isAbsolutePath(name) ? name : "artwork:" + name; auto reader = QImageReader{resourceName}; if (width > 0 && height > 0) { reader.setScaledSize(QSize{width, height}); } const auto pixmap = QPixmap::fromImageReader(&reader); if (pixmap.isNull()) { qWarning().nospace() << "Error loading icon pixmap " << name << ": " << reader.errorString(); return QPixmap{1, 1}; } return pixmap; } } // namespace auto getIconPixmap(std::string_view name, int width, int height, const char* const* xpm) -> QPixmap { if (name.empty()) { return QPixmap{}; } const auto pixmapName = QString::fromUtf8(name.data(), name.size()); const auto cacheName = (width > 0 && height > 0) ? QStringLiteral("%1_%2_%3").arg(pixmapName, width, height) : pixmapName; // Return cached pixmap if it exists if (auto pixmap = QPixmap{}; QPixmapCache::find(cacheName, &pixmap)) { return pixmap; } // Load the pixmap and cache it before returning const auto pixmap = loadPixmap(pixmapName, width, height, xpm); QPixmapCache::insert(cacheName, pixmap); return pixmap; } auto getText(std::string_view name) -> QString { const auto resource = QResource{":/" + QString::fromUtf8(name.data(), name.size())}; #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) return QString::fromUtf8(resource.uncompressedData()); #else return QString::fromUtf8(reinterpret_cast<const char*>(resource.data()), resource.size()); #endif } } // namespace lmms::embed
2,710
C++
.cpp
69
37.347826
99
0.730872
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
19,911
EffectControlDialog.cpp
LMMS_lmms/src/gui/EffectControlDialog.cpp
/* * EffectControlDialog.cpp - base-class for effect-dialogs for displaying * and editing control port values * * Copyright (c) 2006-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. * */ #include <QCloseEvent> #include "EffectControlDialog.h" #include "EffectControls.h" namespace lmms::gui { EffectControlDialog::EffectControlDialog( EffectControls * _controls ) : QWidget( nullptr ), ModelView( _controls, this ), m_effectControls( _controls ) { setWindowTitle( m_effectControls->effect()->displayName() ); setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ); } void EffectControlDialog::closeEvent( QCloseEvent * _ce ) { _ce->ignore(); emit closed(); } } // namespace lmms::gui
1,537
C++
.cpp
43
33.790698
77
0.749157
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,912
LinkedModelGroupViews.cpp
LMMS_lmms/src/gui/LinkedModelGroupViews.cpp
/* * LinkedModelGroupViews.h - view for groups of linkable models * * Copyright (c) 2019-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. * */ #include "LinkedModelGroupViews.h" #include <QPushButton> #include "Controls.h" #include "ControlLayout.h" #include "LinkedModelGroups.h" namespace lmms::gui { /* LinkedModelGroupViewBase */ LinkedModelGroupView::LinkedModelGroupView(QWidget* parent, LinkedModelGroup *model, std::size_t colNum) : QWidget(parent), m_model(model), m_colNum(colNum), m_layout(new ControlLayout(this)) { // This is required to remove the focus of the line edit // when e.g. another spin box is being clicked. // Removing the focus is wanted because in many cases, the user wants to // quickly play notes on the virtual keyboard. setFocusPolicy( Qt::StrongFocus ); } void LinkedModelGroupView::modelChanged(LinkedModelGroup *group) { // reconnect models group->foreach_model([this](const std::string& str, const LinkedModelGroup::ModelInfo& minf) { auto itr = m_widgets.find(str); // in case there are new or deleted widgets, the subclass has already // modified m_widgets, so this will go into the else case if (itr == m_widgets.end()) { // no widget? this can happen when the whole view is being destroyed // (for some strange reasons) } else { itr->second->setModel(minf.m_model); } }); m_model = group; } void LinkedModelGroupView::addControl(Control* ctrl, const std::string& id, const std::string &display, bool removable) { if (ctrl) { auto box = new QWidget(this); auto boxLayout = new QHBoxLayout(box); boxLayout->addWidget(ctrl->topWidget()); if (removable) { auto removeBtn = new QPushButton; removeBtn->setIcon( embed::getIconPixmap( "discard" ) ); QObject::connect(removeBtn, &QPushButton::clicked, this, [this,ctrl](bool){ AutomatableModel* controlModel = ctrl->model(); // remove control out of model group // (will also remove it from the UI) m_model->removeControl(controlModel); // delete model (includes disconnecting all connections) delete controlModel; }, Qt::DirectConnection); boxLayout->addWidget(removeBtn); } // required, so the Layout knows how to sort/filter widgets by string box->setObjectName(QString::fromStdString(display)); m_layout->addWidget(box); // take ownership of control and add it m_widgets.emplace(id, std::unique_ptr<Control>(ctrl)); } if (isHidden()) { setHidden(false); } } void LinkedModelGroupView::removeControl(const QString& key) { auto itr = m_widgets.find(key.toStdString()); if (itr != m_widgets.end()) { QLayoutItem* item = m_layout->itemByString(key); Q_ASSERT(!!item); QWidget* wdg = item->widget(); Q_ASSERT(!!wdg); // remove item from layout m_layout->removeItem(item); // the widget still exists and is visible - remove it now delete wdg; // erase widget pointer from dictionary m_widgets.erase(itr); // repaint immediately, so we don't have dangling model views m_layout->update(); } } void LinkedModelGroupView::removeFocusFromSearchBar() { m_layout->removeFocusFromSearchBar(); } /* LinkedModelGroupsViewBase */ void LinkedModelGroupsView::modelChanged(LinkedModelGroups *groups) { LinkedModelGroupView* groupView = getGroupView(); LinkedModelGroup* group0 = groups->getGroup(0); if (group0 && groupView) { groupView->modelChanged(group0); } } } // namespace lmms::gui
4,249
C++
.cpp
135
28.844444
75
0.739152
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,913
AudioAlsaSetupWidget.cpp
LMMS_lmms/src/gui/AudioAlsaSetupWidget.cpp
/* * AudioAlsaSetupWidget.cpp - Implements a setup widget for ALSA-PCM-output * * Copyright (c) 2004-2015 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. * */ #include <QComboBox> #include <QFormLayout> #include "AudioAlsaSetupWidget.h" #ifdef LMMS_HAVE_ALSA #include "ConfigManager.h" #include "LcdSpinBox.h" namespace lmms::gui { AudioAlsaSetupWidget::AudioAlsaSetupWidget( QWidget * _parent ) : AudioDeviceSetupWidget( AudioAlsa::name(), _parent ), m_selectedDevice(-1) { QFormLayout * form = new QFormLayout(this); m_deviceInfos = AudioAlsa::getAvailableDevices(); QString deviceText = ConfigManager::inst()->value( "audioalsa", "device" ); m_deviceComboBox = new QComboBox(this); for (size_t i = 0; i < m_deviceInfos.size(); ++i) { AudioAlsa::DeviceInfo const & currentDeviceInfo = m_deviceInfos[i]; QString comboBoxText = currentDeviceInfo.getDeviceName(); m_deviceComboBox->addItem(comboBoxText, QVariant(static_cast<uint>(i))); QString toolTipText = currentDeviceInfo.getDeviceDescription(); m_deviceComboBox->setItemData(i, toolTipText, Qt::ToolTipRole); if (currentDeviceInfo.getDeviceName() == deviceText) { m_deviceComboBox->setCurrentIndex(static_cast<int>(i)); } } m_selectedDevice = m_deviceComboBox->currentIndex(); connect(m_deviceComboBox, SIGNAL(currentIndexChanged(int)), SLOT(onCurrentIndexChanged(int))); form->addRow(tr("Device"), m_deviceComboBox); auto m = new LcdSpinBoxModel(/* this */); m->setRange(DEFAULT_CHANNELS, DEFAULT_CHANNELS); m->setStep( 2 ); m->setValue( ConfigManager::inst()->value( "audioalsa", "channels" ).toInt() ); m_channels = new LcdSpinBox( 1, this ); m_channels->setModel( m ); form->addRow(tr("Channels"), m_channels); } AudioAlsaSetupWidget::~AudioAlsaSetupWidget() { delete m_channels->model(); } void AudioAlsaSetupWidget::saveSettings() { QString deviceText; if (m_selectedDevice != -1) { AudioAlsa::DeviceInfo const & selectedDevice = m_deviceInfos[m_selectedDevice]; deviceText = selectedDevice.getDeviceName(); } ConfigManager::inst()->setValue( "audioalsa", "device", deviceText ); ConfigManager::inst()->setValue( "audioalsa", "channels", QString::number( m_channels->value<int>() ) ); } void AudioAlsaSetupWidget::onCurrentIndexChanged(int index) { m_selectedDevice = index; } } // namespace lmms::gui #endif // LMMS_HAVE_ALSA
3,183
C++
.cpp
87
34.183908
81
0.751877
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,914
MainApplication.cpp
LMMS_lmms/src/gui/MainApplication.cpp
/* * MainApplication.cpp - 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. * */ #include "MainApplication.h" #include <QDebug> #include <QFileOpenEvent> #include "Engine.h" #include "GuiApplication.h" #include "MainWindow.h" #include "Song.h" namespace lmms::gui { MainApplication::MainApplication(int& argc, char** argv) : QApplication(argc, argv), m_queuedFile() { #if !defined(LMMS_BUILD_WIN32) && !defined(LMMS_BUILD_APPLE) && !defined(LMMS_BUILD_HAIKU) // Work around a bug of KXmlGui < 5.55 // which breaks the recent files menu // https://bugs.kde.org/show_bug.cgi?id=337491 for (auto child : children()) { if (child->inherits("KCheckAcceleratorsInitializer")) { delete child; } } #endif #if defined(LMMS_BUILD_WIN32) installNativeEventFilter(this); #endif } bool MainApplication::event(QEvent* event) { switch(event->type()) { case QEvent::FileOpen: { auto fileEvent = static_cast<QFileOpenEvent*>(event); // Handle the project file m_queuedFile = fileEvent->file(); if(Engine::getSong()) { if(getGUI()->mainWindow()->mayChangeProject(true)) { qDebug() << "Loading file " << m_queuedFile; Engine::getSong()->loadProject(m_queuedFile); } } else { qDebug() << "Queuing file " << m_queuedFile; } return true; } default: return QApplication::event(event); } } #ifdef LMMS_BUILD_WIN32 // This can be moved into nativeEventFilter once Qt4 support has been dropped bool MainApplication::winEventFilter(MSG* msg, long* result) { switch(msg->message) { case WM_STYLECHANGING: if (msg->wParam == static_cast<WPARAM>(GWL_EXSTYLE)) { // Prevent plugins making the main window transparent STYLESTRUCT * style = reinterpret_cast<STYLESTRUCT *>(msg->lParam); if(!(style->styleOld & WS_EX_LAYERED)) { style->styleNew &= ~WS_EX_LAYERED; } *result = 0; return true; } return false; default: return false; } } bool MainApplication::nativeEventFilter(const QByteArray& eventType, void* message, long* result) { if(eventType == "windows_generic_MSG") { return winEventFilter(static_cast<MSG *>(message), result); } return false; } #endif // LMMS_BUILD_WIN32 } // namespace lmms::gui
3,082
C++
.cpp
113
24.619469
90
0.719743
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,915
SetupDialog.cpp
LMMS_lmms/src/gui/modals/SetupDialog.cpp
/* * SetupDialog.cpp - dialog for setting up LMMS * * 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. * */ #include <QCheckBox> #include <QComboBox> #include <QGroupBox> #include <QImageReader> #include <QLabel> #include <QLayout> #include <QLineEdit> #include <QScrollArea> #include "AudioEngine.h" #include "debug.h" #include "embed.h" #include "Engine.h" #include "FileDialog.h" #include "MainWindow.h" #include "MidiSetupWidget.h" #include "ProjectJournal.h" #include "SetupDialog.h" #include "TabBar.h" #include "TabButton.h" // Platform-specific audio-interface classes. #include "AudioAlsa.h" #include "AudioAlsaSetupWidget.h" #include "AudioDummy.h" #include "AudioJack.h" #include "AudioOss.h" #include "AudioPortAudio.h" #include "AudioPulseAudio.h" #include "AudioSdl.h" #include "AudioSndio.h" #include "AudioSoundIo.h" // Platform-specific midi-interface classes. #include "MidiAlsaRaw.h" #include "MidiAlsaSeq.h" #include "MidiApple.h" #include "MidiDummy.h" #include "MidiJack.h" #include "MidiOss.h" #include "MidiSndio.h" #include "MidiWinMM.h" namespace lmms::gui { constexpr int BUFFERSIZE_RESOLUTION = 32; inline void labelWidget(QWidget * w, const QString & txt) { auto title = new QLabel(txt, w); QFont f = title->font(); f.setBold(true); title->setFont(f); QBoxLayout * boxLayout = dynamic_cast<QBoxLayout *>(w->layout()); assert(boxLayout); boxLayout->addWidget(title); } SetupDialog::SetupDialog(ConfigTab tab_to_open) : m_displaydBFS(ConfigManager::inst()->value( "app", "displaydbfs").toInt()), m_tooltips(!ConfigManager::inst()->value( "tooltips", "disabled").toInt()), m_displayWaveform(ConfigManager::inst()->value( "ui", "displaywaveform").toInt()), m_printNoteLabels(ConfigManager::inst()->value( "ui", "printnotelabels").toInt()), m_compactTrackButtons(ConfigManager::inst()->value( "ui", "compacttrackbuttons").toInt()), m_oneInstrumentTrackWindow(ConfigManager::inst()->value( "ui", "oneinstrumenttrackwindow").toInt()), m_sideBarOnRight(ConfigManager::inst()->value( "ui", "sidebaronright").toInt()), m_letPreviewsFinish(ConfigManager::inst()->value( "ui", "letpreviewsfinish").toInt()), m_soloLegacyBehavior(ConfigManager::inst()->value( "app", "sololegacybehavior", "0").toInt()), m_trackDeletionWarning(ConfigManager::inst()->value( "ui", "trackdeletionwarning", "1").toInt()), m_mixerChannelDeletionWarning(ConfigManager::inst()->value( "ui", "mixerchanneldeletionwarning", "1").toInt()), m_MMPZ(!ConfigManager::inst()->value( "app", "nommpz").toInt()), m_disableBackup(!ConfigManager::inst()->value( "app", "disablebackup").toInt()), m_openLastProject(ConfigManager::inst()->value( "app", "openlastproject").toInt()), m_loopMarkerMode{ConfigManager::inst()->value("app", "loopmarkermode", "dual")}, m_lang(ConfigManager::inst()->value( "app", "language")), m_saveInterval( ConfigManager::inst()->value( "ui", "saveinterval").toInt() < 1 ? MainWindow::DEFAULT_SAVE_INTERVAL_MINUTES : ConfigManager::inst()->value( "ui", "saveinterval").toInt()), m_enableAutoSave(ConfigManager::inst()->value( "ui", "enableautosave", "1").toInt()), m_enableRunningAutoSave(ConfigManager::inst()->value( "ui", "enablerunningautosave", "0").toInt()), m_smoothScroll(ConfigManager::inst()->value( "ui", "smoothscroll").toInt()), m_animateAFP(ConfigManager::inst()->value( "ui", "animateafp", "1").toInt()), m_vstEmbedMethod(ConfigManager::inst()->vstEmbedMethod()), m_vstAlwaysOnTop(ConfigManager::inst()->value( "ui", "vstalwaysontop").toInt()), m_disableAutoQuit(ConfigManager::inst()->value( "ui", "disableautoquit", "1").toInt()), m_NaNHandler(ConfigManager::inst()->value( "app", "nanhandler", "1").toInt()), m_bufferSize(ConfigManager::inst()->value( "audioengine", "framesperaudiobuffer").toInt()), m_midiAutoQuantize(ConfigManager::inst()->value( "midi", "autoquantize", "0").toInt() != 0), m_workingDir(QDir::toNativeSeparators(ConfigManager::inst()->workingDir())), m_vstDir(QDir::toNativeSeparators(ConfigManager::inst()->vstDir())), m_ladspaDir(QDir::toNativeSeparators(ConfigManager::inst()->ladspaDir())), m_gigDir(QDir::toNativeSeparators(ConfigManager::inst()->gigDir())), m_sf2Dir(QDir::toNativeSeparators(ConfigManager::inst()->sf2Dir())), #ifdef LMMS_HAVE_FLUIDSYNTH m_sf2File(QDir::toNativeSeparators(ConfigManager::inst()->sf2File())), #endif m_themeDir(QDir::toNativeSeparators(ConfigManager::inst()->themeDir())), m_backgroundPicFile(QDir::toNativeSeparators(ConfigManager::inst()->backgroundPicFile())) { setWindowIcon(embed::getIconPixmap("setup_general")); setWindowTitle(tr("Settings")); setWindowFlag(Qt::WindowContextHelpButtonHint, false); setModal(true); Engine::projectJournal()->setJournalling(false); // Main widget. auto main_w = new QWidget(this); // Vertical layout. auto vlayout = new QVBoxLayout(this); vlayout->setSpacing(0); vlayout->setContentsMargins(0, 0, 0, 0); // Horizontal layout. auto hlayout = new QHBoxLayout(main_w); hlayout->setSpacing(0); hlayout->setContentsMargins(0, 0, 0, 0); // Tab bar for the main tabs. m_tabBar = new TabBar(main_w, QBoxLayout::TopToBottom); m_tabBar->setExclusive(true); m_tabBar->setFixedWidth(72); // Settings widget. auto settings_w = new QWidget(main_w); QVBoxLayout * settingsLayout = new QVBoxLayout(settings_w); // General widget. auto general_w = new QWidget(settings_w); auto general_layout = new QVBoxLayout(general_w); general_layout->setSpacing(10); general_layout->setContentsMargins(0, 0, 0, 0); labelWidget(general_w, tr("General")); // General scroll area. auto generalScroll = new QScrollArea(general_w); generalScroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); generalScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // General controls widget. auto generalControls = new QWidget(general_w); // Path selectors layout. auto generalControlsLayout = new QVBoxLayout; generalControlsLayout->setSpacing(10); generalControlsLayout->setContentsMargins(0, 0, 0, 0); auto addCheckBox = [&](const QString& ledText, QWidget* parent, QBoxLayout * layout, bool initialState, const char* toggledSlot, bool showRestartWarning) -> QCheckBox * { auto checkBox = new QCheckBox(ledText, parent); checkBox->setChecked(initialState); connect(checkBox, SIGNAL(toggled(bool)), this, toggledSlot); if (showRestartWarning) { connect(checkBox, SIGNAL(toggled(bool)), this, SLOT(showRestartWarning())); } if (layout) { layout->addWidget(checkBox); } return checkBox; }; // GUI tab. QGroupBox * guiGroupBox = new QGroupBox(tr("Graphical user interface (GUI)"), generalControls); QVBoxLayout * guiGroupLayout = new QVBoxLayout(guiGroupBox); addCheckBox(tr("Display volume as dBFS "), guiGroupBox, guiGroupLayout, m_displaydBFS, SLOT(toggleDisplaydBFS(bool)), true); addCheckBox(tr("Enable tooltips"), guiGroupBox, guiGroupLayout, m_tooltips, SLOT(toggleTooltips(bool)), true); addCheckBox(tr("Enable master oscilloscope by default"), guiGroupBox, guiGroupLayout, m_displayWaveform, SLOT(toggleDisplayWaveform(bool)), true); addCheckBox(tr("Enable all note labels in piano roll"), guiGroupBox, guiGroupLayout, m_printNoteLabels, SLOT(toggleNoteLabels(bool)), false); addCheckBox(tr("Enable compact track buttons"), guiGroupBox, guiGroupLayout, m_compactTrackButtons, SLOT(toggleCompactTrackButtons(bool)), true); addCheckBox(tr("Enable one instrument-track-window mode"), guiGroupBox, guiGroupLayout, m_oneInstrumentTrackWindow, SLOT(toggleOneInstrumentTrackWindow(bool)), true); addCheckBox(tr("Show sidebar on the right-hand side"), guiGroupBox, guiGroupLayout, m_sideBarOnRight, SLOT(toggleSideBarOnRight(bool)), true); addCheckBox(tr("Let sample previews continue when mouse is released"), guiGroupBox, guiGroupLayout, m_letPreviewsFinish, SLOT(toggleLetPreviewsFinish(bool)), false); addCheckBox(tr("Mute automation tracks during solo"), guiGroupBox, guiGroupLayout, m_soloLegacyBehavior, SLOT(toggleSoloLegacyBehavior(bool)), false); addCheckBox(tr("Show warning when deleting tracks"), guiGroupBox, guiGroupLayout, m_trackDeletionWarning, SLOT(toggleTrackDeletionWarning(bool)), false); addCheckBox(tr("Show warning when deleting a mixer channel that is in use"), guiGroupBox, guiGroupLayout, m_mixerChannelDeletionWarning, SLOT(toggleMixerChannelDeletionWarning(bool)), false); m_loopMarkerComboBox = new QComboBox{guiGroupBox}; m_loopMarkerComboBox->addItem(tr("Dual-button"), "dual"); m_loopMarkerComboBox->addItem(tr("Grab closest"), "closest"); m_loopMarkerComboBox->addItem(tr("Handles"), "handles"); m_loopMarkerComboBox->setCurrentIndex(m_loopMarkerComboBox->findData(m_loopMarkerMode)); connect(m_loopMarkerComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &SetupDialog::loopMarkerModeChanged); guiGroupLayout->addWidget(new QLabel{tr("Loop edit mode"), guiGroupBox}); guiGroupLayout->addWidget(m_loopMarkerComboBox); generalControlsLayout->addWidget(guiGroupBox); generalControlsLayout->addSpacing(10); // Projects tab. QGroupBox * projectsGroupBox = new QGroupBox(tr("Projects"), generalControls); QVBoxLayout * projectsGroupLayout = new QVBoxLayout(projectsGroupBox); addCheckBox(tr("Compress project files by default"), projectsGroupBox, projectsGroupLayout, m_MMPZ, SLOT(toggleMMPZ(bool)), true); addCheckBox(tr("Create a backup file when saving a project"), projectsGroupBox, projectsGroupLayout, m_disableBackup, SLOT(toggleDisableBackup(bool)), false); addCheckBox(tr("Reopen last project on startup"), projectsGroupBox, projectsGroupLayout, m_openLastProject, SLOT(toggleOpenLastProject(bool)), false); generalControlsLayout->addWidget(projectsGroupBox); generalControlsLayout->addSpacing(10); // Language tab. QGroupBox * languageGroupBox = new QGroupBox(tr("Language"), generalControls); QVBoxLayout * languageGroupLayout = new QVBoxLayout(languageGroupBox); auto changeLang = new QComboBox(languageGroupBox); languageGroupLayout->addWidget(changeLang); QDir dir(ConfigManager::inst()->localeDir()); QStringList fileNames = dir.entryList(QStringList("*.qm")); for(int i = 0; i < fileNames.size(); ++i) { // Extract ISO-639 language code from filename fileNames[i].truncate(fileNames[i].lastIndexOf('.')); // Skip invalid language codes QLocale locale(fileNames[i]); if (locale.language() == QLocale::C) { continue; } // Display the native language name or fallback to the English name QString langName = locale.nativeLanguageName(); if (langName.isEmpty()) { langName = QLocale::languageToString(locale.language()); } m_languages.append(fileNames[i]); changeLang->addItem(langName); } // If language unset, fallback to system language when available. if(m_lang == "") { QString tmp = QLocale::system().name().left(2); if(m_languages.contains(tmp)) { m_lang = tmp; } else { m_lang = "en"; } } for(int i = 0; i < changeLang->count(); ++i) { if(m_lang == m_languages.at(i)) { changeLang->setCurrentIndex(i); break; } } connect(changeLang, SIGNAL(currentIndexChanged(int)), this, SLOT(setLanguage(int))); connect(changeLang, SIGNAL(currentIndexChanged(int)), this, SLOT(showRestartWarning())); generalControlsLayout->addWidget(languageGroupBox); generalControlsLayout->addSpacing(10); // General layout ordering. generalControlsLayout->addStretch(); generalControls->setLayout(generalControlsLayout); generalScroll->setWidget(generalControls); generalScroll->setWidgetResizable(true); general_layout->addWidget(generalScroll, 1); // Performance widget. auto performance_w = new QWidget(settings_w); auto performance_layout = new QVBoxLayout(performance_w); performance_layout->setSpacing(10); performance_layout->setContentsMargins(0, 0, 0, 0); labelWidget(performance_w, tr("Performance")); // Autosave tab. QGroupBox * autoSaveBox = new QGroupBox(tr("Autosave"), performance_w); QVBoxLayout * autoSaveLayout = new QVBoxLayout(autoSaveBox); QHBoxLayout * autoSaveSubLayout = new QHBoxLayout(); m_saveIntervalSlider = new QSlider(Qt::Horizontal, autoSaveBox); m_saveIntervalSlider->setValue(m_saveInterval); m_saveIntervalSlider->setRange(1, 20); m_saveIntervalSlider->setTickInterval(1); m_saveIntervalSlider->setPageStep(1); m_saveIntervalSlider->setTickPosition(QSlider::TicksBelow); connect(m_saveIntervalSlider, SIGNAL(valueChanged(int)), this, SLOT(setAutoSaveInterval(int))); auto autoSaveResetBtn = new QPushButton(embed::getIconPixmap("reload"), "", autoSaveBox); autoSaveResetBtn->setFixedSize(32, 32); connect(autoSaveResetBtn, SIGNAL(clicked()), this, SLOT(resetAutoSave())); autoSaveSubLayout->addWidget(m_saveIntervalSlider); autoSaveSubLayout->addWidget(autoSaveResetBtn); autoSaveLayout->addLayout(autoSaveSubLayout); m_saveIntervalLbl = new QLabel(autoSaveBox); setAutoSaveInterval(m_saveIntervalSlider->value()); autoSaveLayout->addWidget(m_saveIntervalLbl); m_autoSave = addCheckBox(tr("Enable autosave"), autoSaveBox, autoSaveLayout, m_enableAutoSave, SLOT(toggleAutoSave(bool)), false); m_runningAutoSave = addCheckBox(tr("Allow autosave while playing"), autoSaveBox, autoSaveLayout, m_enableRunningAutoSave, SLOT(toggleRunningAutoSave(bool)), false); m_saveIntervalSlider->setEnabled(m_enableAutoSave); m_runningAutoSave->setVisible(m_enableAutoSave); // UI effect vs. performance tab. QGroupBox * uiFxBox = new QGroupBox(tr("User interface (UI) effects vs. performance"), performance_w); QVBoxLayout * uiFxLayout = new QVBoxLayout(uiFxBox); addCheckBox(tr("Smooth scroll in song editor"), uiFxBox, uiFxLayout, m_smoothScroll, SLOT(toggleSmoothScroll(bool)), false); addCheckBox(tr("Display playback cursor in AudioFileProcessor"), uiFxBox, uiFxLayout, m_animateAFP, SLOT(toggleAnimateAFP(bool)), false); // Plugins group QGroupBox * pluginsBox = new QGroupBox(tr("Plugins"), performance_w); QVBoxLayout * pluginsLayout = new QVBoxLayout(pluginsBox); m_vstEmbedLbl = new QLabel(pluginsBox); m_vstEmbedLbl->setText(tr("VST plugins embedding:")); pluginsLayout->addWidget(m_vstEmbedLbl); m_vstEmbedComboBox = new QComboBox(pluginsBox); QStringList embedMethods = ConfigManager::availableVstEmbedMethods(); m_vstEmbedComboBox->addItem(tr("No embedding"), "none"); if(embedMethods.contains("qt")) { m_vstEmbedComboBox->addItem(tr("Embed using Qt API"), "qt"); } if(embedMethods.contains("win32")) { m_vstEmbedComboBox->addItem(tr("Embed using native Win32 API"), "win32"); } if(embedMethods.contains("xembed")) { m_vstEmbedComboBox->addItem(tr("Embed using XEmbed protocol"), "xembed"); } m_vstEmbedComboBox->setCurrentIndex(m_vstEmbedComboBox->findData(m_vstEmbedMethod)); connect(m_vstEmbedComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(vstEmbedMethodChanged())); pluginsLayout->addWidget(m_vstEmbedComboBox); m_vstAlwaysOnTopCheckBox = addCheckBox(tr("Keep plugin windows on top when not embedded"), pluginsBox, pluginsLayout, m_vstAlwaysOnTop, SLOT(toggleVSTAlwaysOnTop(bool)), false); addCheckBox(tr("Keep effects running even without input"), pluginsBox, pluginsLayout, m_disableAutoQuit, SLOT(toggleDisableAutoQuit(bool)), false); // Performance layout ordering. performance_layout->addWidget(autoSaveBox); performance_layout->addWidget(uiFxBox); performance_layout->addWidget(pluginsBox); performance_layout->addStretch(); // Audio widget. auto audio_w = new QWidget(settings_w); auto audio_layout = new QVBoxLayout(audio_w); audio_layout->setSpacing(10); audio_layout->setContentsMargins(0, 0, 0, 0); labelWidget(audio_w, tr("Audio")); // Audio interface group QGroupBox * audioInterfaceBox = new QGroupBox(tr("Audio interface"), audio_w); QVBoxLayout * audioInterfaceLayout = new QVBoxLayout(audioInterfaceBox); m_audioInterfaces = new QComboBox(audioInterfaceBox); audioInterfaceLayout->addWidget(m_audioInterfaces); // Ifaces-settings-widget. auto as_w = new QWidget(audio_w); auto as_w_layout = new QHBoxLayout(as_w); as_w_layout->setSpacing(0); as_w_layout->setContentsMargins(0, 0, 0, 0); #ifdef LMMS_HAVE_JACK m_audioIfaceSetupWidgets[AudioJack::name()] = new AudioJack::setupWidget(as_w); #endif #ifdef LMMS_HAVE_ALSA m_audioIfaceSetupWidgets[AudioAlsa::name()] = new AudioAlsaSetupWidget(as_w); #endif #ifdef LMMS_HAVE_PULSEAUDIO m_audioIfaceSetupWidgets[AudioPulseAudio::name()] = new AudioPulseAudio::setupWidget(as_w); #endif #ifdef LMMS_HAVE_PORTAUDIO m_audioIfaceSetupWidgets[AudioPortAudio::name()] = new AudioPortAudio::setupWidget(as_w); #endif #ifdef LMMS_HAVE_SOUNDIO m_audioIfaceSetupWidgets[AudioSoundIo::name()] = new AudioSoundIo::setupWidget(as_w); #endif #ifdef LMMS_HAVE_SDL m_audioIfaceSetupWidgets[AudioSdl::name()] = new AudioSdl::setupWidget(as_w); #endif #ifdef LMMS_HAVE_OSS m_audioIfaceSetupWidgets[AudioOss::name()] = new AudioOss::setupWidget(as_w); #endif #ifdef LMMS_HAVE_SNDIO m_audioIfaceSetupWidgets[AudioSndio::name()] = new AudioSndio::setupWidget(as_w); #endif m_audioIfaceSetupWidgets[AudioDummy::name()] = new AudioDummy::setupWidget(as_w); for(AswMap::iterator it = m_audioIfaceSetupWidgets.begin(); it != m_audioIfaceSetupWidgets.end(); ++it) { m_audioIfaceNames[ AudioDeviceSetupWidget::tr(it.key().toUtf8())] = it.key(); } for(trMap::iterator it = m_audioIfaceNames.begin(); it != m_audioIfaceNames.end(); ++it) { QWidget * audioWidget = m_audioIfaceSetupWidgets[it.value()]; audioWidget->hide(); as_w_layout->addWidget(audioWidget); m_audioInterfaces->addItem(it.key()); } // If no preferred audio device is saved, save the current one. QString audioDevName = ConfigManager::inst()->value("audioengine", "audiodev"); if (m_audioInterfaces->findText(audioDevName) < 0) { audioDevName = Engine::audioEngine()->audioDevName(); ConfigManager::inst()->setValue("audioengine", "audiodev", audioDevName); } m_audioInterfaces-> setCurrentIndex(m_audioInterfaces->findText(audioDevName)); m_audioIfaceSetupWidgets[audioDevName]->show(); connect(m_audioInterfaces, SIGNAL(activated(const QString&)), this, SLOT(audioInterfaceChanged(const QString&))); // Advanced setting, hidden for now // // TODO Handle or remove. // auto useNaNHandler = new LedCheckBox(tr("Use built-in NaN handler"), audio_w); // audio_layout->addWidget(useNaNHandler); // useNaNHandler->setChecked(m_NaNHandler); // Buffer size group QGroupBox * bufferSizeBox = new QGroupBox(tr("Buffer size"), audio_w); QVBoxLayout * bufferSizeLayout = new QVBoxLayout(bufferSizeBox); QHBoxLayout * bufferSizeSubLayout = new QHBoxLayout(); m_bufferSizeSlider = new QSlider(Qt::Horizontal, bufferSizeBox); m_bufferSizeSlider->setRange(1, MAXIMUM_BUFFER_SIZE / BUFFERSIZE_RESOLUTION); m_bufferSizeSlider->setTickInterval(8); m_bufferSizeSlider->setPageStep(8); m_bufferSizeSlider->setValue(m_bufferSize / BUFFERSIZE_RESOLUTION); m_bufferSizeSlider->setTickPosition(QSlider::TicksBelow); connect(m_bufferSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(setBufferSize(int))); connect(m_bufferSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning())); bufferSizeSubLayout->addWidget(m_bufferSizeSlider, 1); auto bufferSize_reset_btn = new QPushButton(embed::getIconPixmap("reload"), "", bufferSizeBox); bufferSize_reset_btn->setFixedSize(32, 32); connect(bufferSize_reset_btn, SIGNAL(clicked()), this, SLOT(resetBufferSize())); bufferSize_reset_btn->setToolTip( tr("Reset to default value")); bufferSizeSubLayout->addWidget(bufferSize_reset_btn); bufferSizeLayout->addLayout(bufferSizeSubLayout); m_bufferSizeLbl = new QLabel(bufferSizeBox); bufferSizeLayout->addWidget(m_bufferSizeLbl); m_bufferSizeWarnLbl = new QLabel(bufferSizeBox); m_bufferSizeWarnLbl->setWordWrap(true); bufferSizeLayout->addWidget(m_bufferSizeWarnLbl); setBufferSize(m_bufferSizeSlider->value()); // Audio layout ordering. audio_layout->addWidget(audioInterfaceBox); audio_layout->addWidget(as_w); audio_layout->addWidget(bufferSizeBox); audio_layout->addStretch(); // MIDI widget. auto midi_w = new QWidget(settings_w); auto midi_layout = new QVBoxLayout(midi_w); midi_layout->setSpacing(10); midi_layout->setContentsMargins(0, 0, 0, 0); labelWidget(midi_w, tr("MIDI")); // MIDI interface group QGroupBox * midiInterfaceBox = new QGroupBox(tr("MIDI interface"), midi_w); QVBoxLayout * midiInterfaceLayout = new QVBoxLayout(midiInterfaceBox); m_midiInterfaces = new QComboBox(midiInterfaceBox); midiInterfaceLayout->addWidget(m_midiInterfaces); // Ifaces-settings-widget. auto ms_w = new QWidget(midi_w); auto ms_w_layout = new QHBoxLayout(ms_w); ms_w_layout->setSpacing(0); ms_w_layout->setContentsMargins(0, 0, 0, 0); #ifdef LMMS_HAVE_ALSA m_midiIfaceSetupWidgets[MidiAlsaSeq::name()] = MidiSetupWidget::create<MidiAlsaSeq>(ms_w); m_midiIfaceSetupWidgets[MidiAlsaRaw::name()] = MidiSetupWidget::create<MidiAlsaRaw>(ms_w); #endif #ifdef LMMS_HAVE_JACK m_midiIfaceSetupWidgets[MidiJack::name()] = MidiSetupWidget::create<MidiJack>(ms_w); #endif #ifdef LMMS_HAVE_OSS m_midiIfaceSetupWidgets[MidiOss::name()] = MidiSetupWidget::create<MidiOss>(ms_w); #endif #ifdef LMMS_HAVE_SNDIO m_midiIfaceSetupWidgets[MidiSndio::name()] = MidiSetupWidget::create<MidiSndio>(ms_w); #endif #ifdef LMMS_BUILD_WIN32 m_midiIfaceSetupWidgets[MidiWinMM::name()] = MidiSetupWidget::create<MidiWinMM>(ms_w); #endif #ifdef LMMS_BUILD_APPLE m_midiIfaceSetupWidgets[MidiApple::name()] = MidiSetupWidget::create<MidiApple>(ms_w); #endif m_midiIfaceSetupWidgets[MidiDummy::name()] = MidiSetupWidget::create<MidiDummy>(ms_w); for(MswMap::iterator it = m_midiIfaceSetupWidgets.begin(); it != m_midiIfaceSetupWidgets.end(); ++it) { m_midiIfaceNames[ MidiSetupWidget::tr(it.key().toUtf8())] = it.key(); } for(trMap::iterator it = m_midiIfaceNames.begin(); it != m_midiIfaceNames.end(); ++it) { QWidget * midiWidget = m_midiIfaceSetupWidgets[it.value()]; midiWidget->hide(); ms_w_layout->addWidget(midiWidget); m_midiInterfaces->addItem(it.key()); } QString midiDevName = ConfigManager::inst()->value("audioengine", "mididev"); if (m_midiInterfaces->findText(midiDevName) < 0) { midiDevName = Engine::audioEngine()->midiClientName(); ConfigManager::inst()->setValue("audioengine", "mididev", midiDevName); } m_midiInterfaces->setCurrentIndex(m_midiInterfaces->findText(midiDevName)); m_midiIfaceSetupWidgets[midiDevName]->show(); connect(m_midiInterfaces, SIGNAL(activated(const QString&)), this, SLOT(midiInterfaceChanged(const QString&))); // MIDI autoassign group QGroupBox * midiAutoAssignBox = new QGroupBox(tr("Automatically assign MIDI controller to selected track"), midi_w); QVBoxLayout * midiAutoAssignLayout = new QVBoxLayout(midiAutoAssignBox); m_assignableMidiDevices = new QComboBox(midiAutoAssignBox); midiAutoAssignLayout->addWidget(m_assignableMidiDevices); m_assignableMidiDevices->addItem("none"); if ( !Engine::audioEngine()->midiClient()->isRaw() ) { m_assignableMidiDevices->addItems(Engine::audioEngine()->midiClient()->readablePorts()); } else { m_assignableMidiDevices->addItem("all"); } int current = m_assignableMidiDevices->findText(ConfigManager::inst()->value("midi", "midiautoassign")); if (current >= 0) { m_assignableMidiDevices->setCurrentIndex(current); } // MIDI Recording tab auto* midiRecordingTab = new QGroupBox(tr("Behavior when recording"), midi_w); auto* midiRecordingLayout = new QVBoxLayout(midiRecordingTab); { auto *box = addCheckBox(tr("Auto-quantize notes in Piano Roll"), midiRecordingTab, midiRecordingLayout, m_midiAutoQuantize, SLOT(toggleMidiAutoQuantization(bool)), false); box->setToolTip(tr("If enabled, notes will be automatically quantized when recording them from a MIDI controller. If disabled, they are always recorded at the highest possible resolution.")); } // MIDI layout ordering. midi_layout->addWidget(midiInterfaceBox); midi_layout->addWidget(ms_w); midi_layout->addWidget(midiAutoAssignBox); midi_layout->addWidget(midiRecordingTab); midi_layout->addStretch(); // Paths widget. auto paths_w = new QWidget(settings_w); auto paths_layout = new QVBoxLayout(paths_w); paths_layout->setSpacing(10); paths_layout->setContentsMargins(0, 0, 0, 0); labelWidget(paths_w, tr("Paths")); // Paths scroll area. auto pathsScroll = new QScrollArea(paths_w); pathsScroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); pathsScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Path selectors widget. auto pathSelectors = new QWidget(paths_w); // Path selectors layout. auto pathSelectorsLayout = new QVBoxLayout; pathSelectorsLayout->setSpacing(10); pathSelectorsLayout->setContentsMargins(0, 0, 0, 0); auto addPathEntry = [&](const QString& caption, const QString& content, const char* setSlot, const char* openSlot, QLineEdit*& lineEdit, const char* pixmap = "project_open") { auto pathEntryGroupBox = new QGroupBox(caption, pathSelectors); QHBoxLayout * pathEntryLayout = new QHBoxLayout(pathEntryGroupBox); lineEdit = new QLineEdit(content, pathEntryGroupBox); connect(lineEdit, SIGNAL(textChanged(const QString&)), this, setSlot); pathEntryLayout->addWidget(lineEdit, 1); auto selectBtn = new QPushButton(embed::getIconPixmap(pixmap, 16, 16), "", pathEntryGroupBox); selectBtn->setFixedSize(24, 24); connect(selectBtn, SIGNAL(clicked()), this, openSlot); pathEntryLayout->addWidget(selectBtn, 0); pathSelectorsLayout->addWidget(pathEntryGroupBox); pathSelectorsLayout->addSpacing(10); }; addPathEntry(tr("LMMS working directory"), m_workingDir, SLOT(setWorkingDir(const QString&)), SLOT(openWorkingDir()), m_workingDirLineEdit); addPathEntry(tr("VST plugins directory"), m_vstDir, SLOT(setVSTDir(const QString&)), SLOT(openVSTDir()), m_vstDirLineEdit); addPathEntry(tr("LADSPA plugins directories"), m_ladspaDir, SLOT(setLADSPADir(const QString&)), SLOT(openLADSPADir()), m_ladspaDirLineEdit, "add_folder"); addPathEntry(tr("SF2 directory"), m_sf2Dir, SLOT(setSF2Dir(const QString&)), SLOT(openSF2Dir()), m_sf2DirLineEdit); #ifdef LMMS_HAVE_FLUIDSYNTH addPathEntry(tr("Default SF2"), m_sf2File, SLOT(setSF2File(const QString&)), SLOT(openSF2File()), m_sf2FileLineEdit); #endif addPathEntry(tr("GIG directory"), m_gigDir, SLOT(setGIGDir(const QString&)), SLOT(openGIGDir()), m_gigDirLineEdit); addPathEntry(tr("Theme directory"), m_themeDir, SLOT(setThemeDir(const QString&)), SLOT(openThemeDir()), m_themeDirLineEdit); addPathEntry(tr("Background artwork"), m_backgroundPicFile, SLOT(setBackgroundPicFile(const QString&)), SLOT(openBackgroundPicFile()), m_backgroundPicFileLineEdit); pathSelectorsLayout->addStretch(); pathSelectors->setLayout(pathSelectorsLayout); pathsScroll->setWidget(pathSelectors); pathsScroll->setWidgetResizable(true); paths_layout->addWidget(pathsScroll, 1); paths_layout->addStretch(); // Add all main widgets to the layout of the settings widget // This is needed so that we automatically get the correct sizes. settingsLayout->addWidget(general_w); settingsLayout->addWidget(performance_w); settingsLayout->addWidget(audio_w); settingsLayout->addWidget(midi_w); settingsLayout->addWidget(paths_w); // Major tabs ordering. m_tabBar->addTab(general_w, tr("General"), 0, false, true, false)->setIcon( embed::getIconPixmap("setup_general")); m_tabBar->addTab(performance_w, tr("Performance"), 1, false, true, false)->setIcon( embed::getIconPixmap("setup_performance")); m_tabBar->addTab(audio_w, tr("Audio"), 2, false, true, false)->setIcon( embed::getIconPixmap("setup_audio")); m_tabBar->addTab(midi_w, tr("MIDI"), 3, false, true, false)->setIcon( embed::getIconPixmap("setup_midi")); m_tabBar->addTab(paths_w, tr("Paths"), 4, true, true, false)->setIcon( embed::getIconPixmap("setup_directories")); m_tabBar->setActiveTab(static_cast<int>(tab_to_open)); // Horizontal layout ordering. hlayout->addSpacing(2); hlayout->addWidget(m_tabBar); hlayout->addSpacing(10); hlayout->addWidget(settings_w); hlayout->addSpacing(10); // Extras widget and layout. auto extras_w = new QWidget(this); auto extras_layout = new QHBoxLayout(extras_w); extras_layout->setSpacing(0); extras_layout->setContentsMargins(0, 0, 0, 0); // Restart warning label. restartWarningLbl = new QLabel( tr("Some changes require restarting."), extras_w); restartWarningLbl->hide(); // OK button. auto ok_btn = new QPushButton(embed::getIconPixmap("apply"), tr("OK"), extras_w); connect(ok_btn, SIGNAL(clicked()), this, SLOT(accept())); // Cancel button. auto cancel_btn = new QPushButton(embed::getIconPixmap("cancel"), tr("Cancel"), extras_w); connect(cancel_btn, SIGNAL(clicked()), this, SLOT(reject())); // Extras layout ordering. extras_layout->addSpacing(10); extras_layout->addWidget(restartWarningLbl); extras_layout->addStretch(); extras_layout->addWidget(ok_btn); extras_layout->addSpacing(10); extras_layout->addWidget(cancel_btn); extras_layout->addSpacing(10); // Vertical layout ordering. vlayout->addWidget(main_w, 1); vlayout->addSpacing(10); vlayout->addWidget(extras_w); vlayout->addSpacing(10); // Ensure that we cannot make the dialog smaller than it wants to be setMinimumWidth(width()); show(); } SetupDialog::~SetupDialog() { Engine::projectJournal()->setJournalling(true); } void SetupDialog::accept() { /* Hide dialog before setting values. This prevents an obscure bug where non-embedded VST windows would steal focus and prevent LMMS from taking mouse input, rendering the application unusable. */ QDialog::accept(); ConfigManager::inst()->setValue("app", "displaydbfs", QString::number(m_displaydBFS)); ConfigManager::inst()->setValue("tooltips", "disabled", QString::number(!m_tooltips)); ConfigManager::inst()->setValue("ui", "displaywaveform", QString::number(m_displayWaveform)); ConfigManager::inst()->setValue("ui", "printnotelabels", QString::number(m_printNoteLabels)); ConfigManager::inst()->setValue("ui", "compacttrackbuttons", QString::number(m_compactTrackButtons)); ConfigManager::inst()->setValue("ui", "oneinstrumenttrackwindow", QString::number(m_oneInstrumentTrackWindow)); ConfigManager::inst()->setValue("ui", "sidebaronright", QString::number(m_sideBarOnRight)); ConfigManager::inst()->setValue("ui", "letpreviewsfinish", QString::number(m_letPreviewsFinish)); ConfigManager::inst()->setValue("app", "sololegacybehavior", QString::number(m_soloLegacyBehavior)); ConfigManager::inst()->setValue("ui", "trackdeletionwarning", QString::number(m_trackDeletionWarning)); ConfigManager::inst()->setValue("ui", "mixerchanneldeletionwarning", QString::number(m_mixerChannelDeletionWarning)); ConfigManager::inst()->setValue("app", "nommpz", QString::number(!m_MMPZ)); ConfigManager::inst()->setValue("app", "disablebackup", QString::number(!m_disableBackup)); ConfigManager::inst()->setValue("app", "openlastproject", QString::number(m_openLastProject)); ConfigManager::inst()->setValue("app", "loopmarkermode", m_loopMarkerMode); ConfigManager::inst()->setValue("app", "language", m_lang); ConfigManager::inst()->setValue("ui", "saveinterval", QString::number(m_saveInterval)); ConfigManager::inst()->setValue("ui", "enableautosave", QString::number(m_enableAutoSave)); ConfigManager::inst()->setValue("ui", "enablerunningautosave", QString::number(m_enableRunningAutoSave)); ConfigManager::inst()->setValue("ui", "smoothscroll", QString::number(m_smoothScroll)); ConfigManager::inst()->setValue("ui", "animateafp", QString::number(m_animateAFP)); ConfigManager::inst()->setValue("ui", "vstembedmethod", m_vstEmbedComboBox->currentData().toString()); ConfigManager::inst()->setValue("ui", "vstalwaysontop", QString::number(m_vstAlwaysOnTop)); ConfigManager::inst()->setValue("ui", "disableautoquit", QString::number(m_disableAutoQuit)); ConfigManager::inst()->setValue("audioengine", "audiodev", m_audioIfaceNames[m_audioInterfaces->currentText()]); ConfigManager::inst()->setValue("app", "nanhandler", QString::number(m_NaNHandler)); ConfigManager::inst()->setValue("audioengine", "framesperaudiobuffer", QString::number(m_bufferSize)); ConfigManager::inst()->setValue("audioengine", "mididev", m_midiIfaceNames[m_midiInterfaces->currentText()]); ConfigManager::inst()->setValue("midi", "midiautoassign", m_assignableMidiDevices->currentText()); ConfigManager::inst()->setValue("midi", "autoquantize", QString::number(m_midiAutoQuantize)); ConfigManager::inst()->setWorkingDir(QDir::fromNativeSeparators(m_workingDir)); ConfigManager::inst()->setVSTDir(QDir::fromNativeSeparators(m_vstDir)); ConfigManager::inst()->setLADSPADir(QDir::fromNativeSeparators(m_ladspaDir)); ConfigManager::inst()->setSF2Dir(QDir::fromNativeSeparators(m_sf2Dir)); #ifdef LMMS_HAVE_FLUIDSYNTH ConfigManager::inst()->setSF2File(m_sf2File); #endif ConfigManager::inst()->setGIGDir(QDir::fromNativeSeparators(m_gigDir)); ConfigManager::inst()->setThemeDir(QDir::fromNativeSeparators(m_themeDir)); ConfigManager::inst()->setBackgroundPicFile(m_backgroundPicFile); // Tell all audio-settings-widgets to save their settings. for(AswMap::iterator it = m_audioIfaceSetupWidgets.begin(); it != m_audioIfaceSetupWidgets.end(); ++it) { it.value()->saveSettings(); } // Tell all MIDI-settings-widgets to save their settings. for(MswMap::iterator it = m_midiIfaceSetupWidgets.begin(); it != m_midiIfaceSetupWidgets.end(); ++it) { it.value()->saveSettings(); } ConfigManager::inst()->saveConfigFile(); } // General settings slots. void SetupDialog::toggleDisplaydBFS(bool enabled) { m_displaydBFS = enabled; } void SetupDialog::toggleTooltips(bool enabled) { m_tooltips = enabled; } void SetupDialog::toggleDisplayWaveform(bool enabled) { m_displayWaveform = enabled; } void SetupDialog::toggleNoteLabels(bool enabled) { m_printNoteLabels = enabled; } void SetupDialog::toggleCompactTrackButtons(bool enabled) { m_compactTrackButtons = enabled; } void SetupDialog::toggleOneInstrumentTrackWindow(bool enabled) { m_oneInstrumentTrackWindow = enabled; } void SetupDialog::toggleSideBarOnRight(bool enabled) { m_sideBarOnRight = enabled; } void SetupDialog::toggleLetPreviewsFinish(bool enabled) { m_letPreviewsFinish = enabled; } void SetupDialog::toggleTrackDeletionWarning(bool enabled) { m_trackDeletionWarning = enabled; } void SetupDialog::toggleMixerChannelDeletionWarning(bool enabled) { m_mixerChannelDeletionWarning = enabled; } void SetupDialog::toggleMMPZ(bool enabled) { m_MMPZ = enabled; } void SetupDialog::toggleDisableBackup(bool enabled) { m_disableBackup = enabled; } void SetupDialog::toggleOpenLastProject(bool enabled) { m_openLastProject = enabled; } void SetupDialog::loopMarkerModeChanged() { m_loopMarkerMode = m_loopMarkerComboBox->currentData().toString(); } void SetupDialog::setLanguage(int lang) { m_lang = m_languages[lang]; } void SetupDialog::toggleSoloLegacyBehavior(bool enabled) { m_soloLegacyBehavior = enabled; } // Performance settings slots. void SetupDialog::setAutoSaveInterval(int value) { m_saveInterval = value; m_saveIntervalSlider->setValue(m_saveInterval); QString minutes = m_saveInterval > 1 ? tr("minutes") : tr("minute"); minutes = QString("%1 %2").arg(QString::number(m_saveInterval), minutes); minutes = m_enableAutoSave ? minutes : tr("Disabled"); m_saveIntervalLbl->setText( tr("Autosave interval: %1").arg(minutes)); } void SetupDialog::toggleAutoSave(bool enabled) { m_enableAutoSave = enabled; m_saveIntervalSlider->setEnabled(enabled); m_runningAutoSave->setVisible(enabled); setAutoSaveInterval(m_saveIntervalSlider->value()); } void SetupDialog::toggleRunningAutoSave(bool enabled) { m_enableRunningAutoSave = enabled; } void SetupDialog::resetAutoSave() { setAutoSaveInterval(MainWindow::DEFAULT_SAVE_INTERVAL_MINUTES); m_autoSave->setChecked(true); m_runningAutoSave->setChecked(false); } void SetupDialog::toggleSmoothScroll(bool enabled) { m_smoothScroll = enabled; } void SetupDialog::toggleAnimateAFP(bool enabled) { m_animateAFP = enabled; } void SetupDialog::vstEmbedMethodChanged() { m_vstEmbedMethod = m_vstEmbedComboBox->currentData().toString(); m_vstAlwaysOnTopCheckBox->setVisible(m_vstEmbedMethod == "none"); } void SetupDialog::toggleVSTAlwaysOnTop(bool enabled) { m_vstAlwaysOnTop = enabled; } void SetupDialog::toggleDisableAutoQuit(bool enabled) { m_disableAutoQuit = enabled; } void SetupDialog::audioInterfaceChanged(const QString & iface) { for(AswMap::iterator it = m_audioIfaceSetupWidgets.begin(); it != m_audioIfaceSetupWidgets.end(); ++it) { it.value()->hide(); } m_audioIfaceSetupWidgets[m_audioIfaceNames[iface]]->show(); } void SetupDialog::updateBufferSizeWarning(int value) { QString text = "<ul>"; // 'value' is not a power of 2 (for value > 0) and under 256. On buffer sizes larger than 256 // lmms works with chunks of size 256 and only the final mix will use the actual buffer size. // Plugins don't see a larger buffer size than 256 so anything larger than this is functionally // a 'power of 2' value. if(((value & (value - 1)) != 0) && value < 256) { text += "<li>" + tr("The currently selected value is not a power of 2 " "(32, 64, 128, 256). Some plugins may not be available.") + "</li>"; } if(value <= 32) { text += "<li>" + tr("The currently selected value is less than or equal to 32. " "Some plugins may not be available.") + "</li>"; } text += "</ul>"; m_bufferSizeWarnLbl->setText(text); } void SetupDialog::setBufferSize(int value) { const int step = DEFAULT_BUFFER_SIZE / BUFFERSIZE_RESOLUTION; if(value > step && value % step) { int mod_value = value % step; if(mod_value < step / 2) { m_bufferSizeSlider->setValue(value - mod_value); } else { m_bufferSizeSlider->setValue(value + step - mod_value); } return; } if(m_bufferSizeSlider->value() != value) { m_bufferSizeSlider->setValue(value); } m_bufferSize = value * BUFFERSIZE_RESOLUTION; m_bufferSizeLbl->setText(tr("Frames: %1\nLatency: %2 ms").arg(m_bufferSize).arg( 1000.0f * m_bufferSize / Engine::audioEngine()->outputSampleRate(), 0, 'f', 1)); updateBufferSizeWarning(m_bufferSize); } void SetupDialog::resetBufferSize() { setBufferSize(DEFAULT_BUFFER_SIZE / BUFFERSIZE_RESOLUTION); } // MIDI settings slots. void SetupDialog::midiInterfaceChanged(const QString & iface) { for(MswMap::iterator it = m_midiIfaceSetupWidgets.begin(); it != m_midiIfaceSetupWidgets.end(); ++it) { it.value()->hide(); } m_midiIfaceSetupWidgets[m_midiIfaceNames[iface]]->show(); } void SetupDialog::toggleMidiAutoQuantization(bool enabled) { m_midiAutoQuantize = enabled; } // Paths settings slots. void SetupDialog::openWorkingDir() { QString new_dir = FileDialog::getExistingDirectory(this, tr("Choose the LMMS working directory"), m_workingDir); if (!new_dir.isEmpty()) { m_workingDirLineEdit->setText(new_dir); } } void SetupDialog::setWorkingDir(const QString & workingDir) { m_workingDir = workingDir; } void SetupDialog::openVSTDir() { QString new_dir = FileDialog::getExistingDirectory(this, tr("Choose your VST plugins directory"), m_vstDir); if (!new_dir.isEmpty()) { m_vstDirLineEdit->setText(new_dir); } } void SetupDialog::setVSTDir(const QString & vstDir) { m_vstDir = vstDir; } void SetupDialog::openLADSPADir() { QString new_dir = FileDialog::getExistingDirectory(this, tr("Choose your LADSPA plugins directory"), m_ladspaDir); if (!new_dir.isEmpty()) { if(m_ladspaDirLineEdit->text() == "") { m_ladspaDirLineEdit->setText(new_dir); } else { m_ladspaDirLineEdit->setText(m_ladspaDirLineEdit->text() + "," + new_dir); } } } void SetupDialog::setLADSPADir(const QString & ladspaDir) { m_ladspaDir = ladspaDir; } void SetupDialog::openSF2Dir() { QString new_dir = FileDialog::getExistingDirectory(this, tr("Choose your SF2 directory"), m_sf2Dir); if (!new_dir.isEmpty()) { m_sf2DirLineEdit->setText(new_dir); } } void SetupDialog::setSF2Dir(const QString & sf2Dir) { m_sf2Dir = sf2Dir; } void SetupDialog::openSF2File() { #ifdef LMMS_HAVE_FLUIDSYNTH QString new_file = FileDialog::getOpenFileName(this, tr("Choose your default SF2"), m_sf2File, "SoundFont 2 files (*.sf2)"); if (!new_file.isEmpty()) { m_sf2FileLineEdit->setText(new_file); } #endif } void SetupDialog::setSF2File(const QString & sf2File) { #ifdef LMMS_HAVE_FLUIDSYNTH m_sf2File = sf2File; #endif } void SetupDialog::openGIGDir() { QString new_dir = FileDialog::getExistingDirectory(this, tr("Choose your GIG directory"), m_gigDir); if(!new_dir.isEmpty()) { m_gigDirLineEdit->setText(new_dir); } } void SetupDialog::setGIGDir(const QString & gigDir) { m_gigDir = gigDir; } void SetupDialog::openThemeDir() { QString new_dir = FileDialog::getExistingDirectory(this, tr("Choose your theme directory"), m_themeDir); if(!new_dir.isEmpty()) { m_themeDirLineEdit->setText(new_dir); } } void SetupDialog::setThemeDir(const QString & themeDir) { m_themeDir = themeDir; } void SetupDialog::openBackgroundPicFile() { QList<QByteArray> fileTypesList = QImageReader::supportedImageFormats(); QString fileTypes; for(int i = 0; i < fileTypesList.count(); i++) { if(fileTypesList[i] != fileTypesList[i].toUpper()) { if(!fileTypes.isEmpty()) { fileTypes += " "; } fileTypes += "*." + QString(fileTypesList[i]); } } QString dir = (m_backgroundPicFile.isEmpty()) ? m_themeDir : m_backgroundPicFile; QString new_file = FileDialog::getOpenFileName(this, tr("Choose your background picture"), dir, "Picture files (" + fileTypes + ")"); if(!new_file.isEmpty()) { m_backgroundPicFileLineEdit->setText(new_file); } } void SetupDialog::setBackgroundPicFile(const QString & backgroundPicFile) { m_backgroundPicFile = backgroundPicFile; } void SetupDialog::showRestartWarning() { restartWarningLbl->show(); } } // namespace lmms::gui
43,342
C++
.cpp
1,146
35.329843
193
0.759503
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
19,916
AboutDialog.cpp
LMMS_lmms/src/gui/modals/AboutDialog.cpp
/* * AboutDialog.cpp - implementation of about-dialog * * 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. * */ #include "lmmsversion.h" #include "AboutDialog.h" #include "embed.h" #include "versioninfo.h" namespace lmms::gui { AboutDialog::AboutDialog(QWidget* parent) : QDialog(parent), Ui::AboutDialog() { setupUi( this ); iconLabel->setPixmap( embed::getIconPixmap( "icon", 64, 64 ) ); versionLabel->setText( versionLabel->text(). arg( LMMS_VERSION ). arg( LMMS_BUILDCONF_PLATFORM ). arg( LMMS_BUILDCONF_MACHINE ). arg( QT_VERSION_STR ). arg( LMMS_BUILDCONF_COMPILER_VERSION ) ); versionLabel->setTextInteractionFlags( versionLabel->textInteractionFlags() | Qt::TextSelectableByMouse ); copyrightLabel->setText( copyrightLabel->text(). arg( LMMS_PROJECT_COPYRIGHT ) ); authorLabel->setPlainText( embed::getText( "AUTHORS" ) ); licenseLabel->setPlainText( embed::getText( "LICENSE.txt" ) ); involvedLabel->setPlainText( embed::getText( "CONTRIBUTORS" ) ); } } // namespace lmms::gui
1,866
C++
.cpp
51
33.941176
77
0.739878
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,917
ExportProjectDialog.cpp
LMMS_lmms/src/gui/modals/ExportProjectDialog.cpp
/* * ExportProjectDialog.cpp - implementation of dialog for exporting project * * Copyright (c) 2004-2013 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. * */ #include <QFileInfo> #include <QMessageBox> #include "ExportProjectDialog.h" #include "Song.h" #include "GuiApplication.h" #include "MainWindow.h" #include "OutputSettings.h" namespace lmms::gui { ExportProjectDialog::ExportProjectDialog( const QString & _file_name, QWidget * _parent, bool multi_export=false ) : QDialog( _parent ), Ui::ExportProjectDialog(), m_fileName( _file_name ), m_fileExtension(), m_multiExport( multi_export ), m_renderManager( nullptr ) { setupUi( this ); setWindowTitle( tr( "Export project to %1" ).arg( QFileInfo( _file_name ).fileName() ) ); // Get the extension of the chosen file. QStringList parts = _file_name.split( '.' ); QString fileExt; if( parts.size() > 0 ) { fileExt = "." + parts[parts.size()-1]; } int cbIndex = 0; for (auto i = std::size_t{0}; i < ProjectRenderer::NumFileFormats; ++i) { if( ProjectRenderer::fileEncodeDevices[i].isAvailable() ) { // Get the extension of this format. QString renderExt = ProjectRenderer::fileEncodeDevices[i].m_extension; // Add to combo box. fileFormatCB->addItem( ProjectRenderer::tr( ProjectRenderer::fileEncodeDevices[i].m_description ), QVariant( static_cast<int>(ProjectRenderer::fileEncodeDevices[i].m_fileFormat) ) // Format tag; later used for identification. ); // If this is our extension, select it. if( QString::compare( renderExt, fileExt, Qt::CaseInsensitive ) == 0 ) { fileFormatCB->setCurrentIndex( cbIndex ); } cbIndex++; } } int const MAX_LEVEL=8; for(int i=0; i<=MAX_LEVEL; ++i) { QString info=""; if ( i==0 ){ info = tr( "( Fastest - biggest )" ); } else if ( i==MAX_LEVEL ){ info = tr( "( Slowest - smallest )" ); } compLevelCB->addItem( QString::number(i)+" "+info, QVariant(i/static_cast<double>(MAX_LEVEL)) ); } compLevelCB->setCurrentIndex(5); #ifndef LMMS_HAVE_SF_COMPLEVEL // Disable this widget; the setting would be ignored by the renderer. compressionWidget->setVisible(false); #endif connect( startButton, SIGNAL(clicked()), this, SLOT(startBtnClicked())); } void ExportProjectDialog::reject() { if( m_renderManager ) { m_renderManager->abortProcessing(); } m_renderManager.reset(nullptr); QDialog::reject(); } void ExportProjectDialog::accept() { m_renderManager.reset(nullptr); QDialog::accept(); getGUI()->mainWindow()->resetWindowTitle(); } void ExportProjectDialog::closeEvent( QCloseEvent * _ce ) { Engine::getSong()->setLoopRenderCount(1); if( m_renderManager ) { m_renderManager->abortProcessing(); } QDialog::closeEvent( _ce ); } OutputSettings::StereoMode mapToStereoMode(int index) { switch (index) { case 0: return OutputSettings::StereoMode::Mono; case 1: return OutputSettings::StereoMode::Stereo; case 2: return OutputSettings::StereoMode::JointStereo; default: return OutputSettings::StereoMode::Stereo; } } void ExportProjectDialog::startExport() { auto qs = AudioEngine::qualitySettings( static_cast<AudioEngine::qualitySettings::Interpolation>(interpolationCB->currentIndex())); const auto samplerates = std::array{44100, 48000, 88200, 96000, 192000}; const auto bitrates = std::array{64, 128, 160, 192, 256, 320}; bool useVariableBitRate = checkBoxVariableBitRate->isChecked(); OutputSettings::BitRateSettings bitRateSettings(bitrates[ bitrateCB->currentIndex() ], useVariableBitRate); OutputSettings os = OutputSettings( samplerates[ samplerateCB->currentIndex() ], bitRateSettings, static_cast<OutputSettings::BitDepth>( depthCB->currentIndex() ), mapToStereoMode(stereoModeComboBox->currentIndex()) ); if (compressionWidget->isVisible()) { double level = compLevelCB->itemData(compLevelCB->currentIndex()).toDouble(); os.setCompressionLevel(level); } // Make sure we have the the correct file extension // so there's no confusion about the codec in use. auto output_name = m_fileName; if (!(m_multiExport || output_name.endsWith(m_fileExtension,Qt::CaseInsensitive))) { output_name+=m_fileExtension; } m_renderManager.reset(new RenderManager( qs, os, m_ft, output_name )); Engine::getSong()->setExportLoop( exportLoopCB->isChecked() ); Engine::getSong()->setRenderBetweenMarkers( renderMarkersCB->isChecked() ); Engine::getSong()->setLoopRenderCount(loopCountSB->value()); connect( m_renderManager.get(), SIGNAL(progressChanged(int)), progressBar, SLOT(setValue(int))); connect( m_renderManager.get(), SIGNAL(progressChanged(int)), this, SLOT(updateTitleBar(int))); connect( m_renderManager.get(), SIGNAL(finished()), this, SLOT(accept())) ; connect( m_renderManager.get(), SIGNAL(finished()), getGUI()->mainWindow(), SLOT(resetWindowTitle())); if ( m_multiExport ) { m_renderManager->renderTracks(); } else { m_renderManager->renderProject(); } } void ExportProjectDialog::onFileFormatChanged(int index) { // Extract the format tag from the currently selected item, // and adjust the UI properly. QVariant format_tag = fileFormatCB->itemData(index); bool successful_conversion = false; auto exportFormat = static_cast<ProjectRenderer::ExportFileFormat>( format_tag.toInt(&successful_conversion) ); Q_ASSERT(successful_conversion); bool stereoModeVisible = (exportFormat == ProjectRenderer::ExportFileFormat::MP3); bool sampleRateControlsVisible = (exportFormat != ProjectRenderer::ExportFileFormat::MP3); bool bitRateControlsEnabled = (exportFormat == ProjectRenderer::ExportFileFormat::Ogg || exportFormat == ProjectRenderer::ExportFileFormat::MP3); bool bitDepthControlEnabled = (exportFormat == ProjectRenderer::ExportFileFormat::Wave || exportFormat == ProjectRenderer::ExportFileFormat::Flac); bool variableBitrateVisible = !(exportFormat == ProjectRenderer::ExportFileFormat::MP3 || exportFormat == ProjectRenderer::ExportFileFormat::Flac); #ifdef LMMS_HAVE_SF_COMPLEVEL bool compressionLevelVisible = (exportFormat == ProjectRenderer::ExportFileFormat::Flac); compressionWidget->setVisible(compressionLevelVisible); #endif stereoModeWidget->setVisible(stereoModeVisible); sampleRateWidget->setVisible(sampleRateControlsVisible); bitrateWidget->setVisible(bitRateControlsEnabled); checkBoxVariableBitRate->setVisible(variableBitrateVisible); depthWidget->setVisible(bitDepthControlEnabled); } void ExportProjectDialog::startBtnClicked() { m_ft = ProjectRenderer::ExportFileFormat::Count; // Get file format from current menu selection. bool successful_conversion = false; QVariant tag = fileFormatCB->itemData(fileFormatCB->currentIndex()); m_ft = static_cast<ProjectRenderer::ExportFileFormat>( tag.toInt(&successful_conversion) ); if( !successful_conversion ) { QMessageBox::information( this, tr( "Error" ), tr( "Error while determining file-encoder device. " "Please try to choose a different output " "format." ) ); reject(); return; } // Find proper file extension. for (auto i = std::size_t{0}; i < ProjectRenderer::NumFileFormats; ++i) { if (m_ft == ProjectRenderer::fileEncodeDevices[i].m_fileFormat) { m_fileExtension = QString( QLatin1String( ProjectRenderer::fileEncodeDevices[i].m_extension ) ); break; } } startButton->setEnabled( false ); progressBar->setEnabled( true ); updateTitleBar( 0 ); startExport(); } void ExportProjectDialog::updateTitleBar( int _prog ) { getGUI()->mainWindow()->setWindowTitle( tr( "Rendering: %1%" ).arg( _prog ) ); } } // namespace lmms::gui
8,461
C++
.cpp
240
32.583333
148
0.747918
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,918
FileDialog.cpp
LMMS_lmms/src/gui/modals/FileDialog.cpp
/* * FileDialog.cpp - implementation 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. * */ #include <QList> #include <QUrl> #include <QListView> #include <QStandardPaths> #include <QStorageInfo> #include <QStringList> #include "ConfigManager.h" #include "FileDialog.h" namespace lmms::gui { FileDialog::FileDialog( QWidget *parent, const QString &caption, const QString &directory, const QString &filter ) : QFileDialog( parent, caption, directory, filter ) { #if QT_VERSION > 0x050200 setOption( QFileDialog::DontUseCustomDirectoryIcons ); #endif setOption( QFileDialog::DontUseNativeDialog ); #ifdef LMMS_BUILD_LINUX QList<QUrl> urls; #else QList<QUrl> urls = sidebarUrls(); #endif QDir desktopDir; desktopDir.setPath(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); if (desktopDir.exists()) { urls << QUrl::fromLocalFile(desktopDir.absolutePath()); } QDir downloadDir(QDir::homePath() + "/Downloads"); if (!downloadDir.exists()) { downloadDir.setPath(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation)); } if (downloadDir.exists()) { urls << QUrl::fromLocalFile(downloadDir.absolutePath()); } QDir musicDir; musicDir.setPath(QStandardPaths::writableLocation(QStandardPaths::MusicLocation)); if (musicDir.exists()) { urls << QUrl::fromLocalFile(musicDir.absolutePath()); } urls << QUrl::fromLocalFile(ConfigManager::inst()->workingDir()); // Add `/Volumes` directory on OS X systems, this allows the user to browse // external disk drives. #ifdef LMMS_BUILD_APPLE QDir volumesDir( QDir("/Volumes") ); if ( volumesDir.exists() ) urls << QUrl::fromLocalFile( volumesDir.absolutePath() ); #endif #ifdef LMMS_BUILD_LINUX // FileSystem types : https://www.javatpoint.com/linux-file-system QStringList usableFileSystems = {"ext", "ext2", "ext3", "ext4", "jfs", "reiserfs", "ntfs3", "fuse.sshfs", "fuseblk"}; for(QStorageInfo storage : QStorageInfo::mountedVolumes()) { storage.refresh(); if (usableFileSystems.contains(QString(storage.fileSystemType()), Qt::CaseInsensitive) && storage.isValid() && storage.isReady()) { urls << QUrl::fromLocalFile(storage.rootPath()); } } #endif setSidebarUrls(urls); } QString FileDialog::getExistingDirectory(QWidget *parent, const QString &caption, const QString &directory, QFileDialog::Options options) { FileDialog dialog(parent, caption, directory, QString()); dialog.setFileMode(QFileDialog::Directory); dialog.setOptions(dialog.options() | options); if (dialog.exec() == QDialog::Accepted) { return dialog.selectedFiles().value(0); } return QString(); } QString FileDialog::getOpenFileName(QWidget *parent, const QString &caption, const QString &directory, const QString &filter, QString *selectedFilter) { FileDialog dialog(parent, caption, directory, filter); if (selectedFilter && !selectedFilter->isEmpty()) dialog.selectNameFilter(*selectedFilter); if (dialog.exec() == QDialog::Accepted) { if (selectedFilter) *selectedFilter = dialog.selectedNameFilter(); return dialog.selectedFiles().value(0); } return QString(); } void FileDialog::clearSelection() { auto view = findChild<QListView*>(); Q_ASSERT( view ); view->clearSelection(); } } // namespace lmms::gui
4,141
C++
.cpp
125
30.496
131
0.746179
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
19,919
ControllerConnectionDialog.cpp
LMMS_lmms/src/gui/modals/ControllerConnectionDialog.cpp
/* * ControllerConnectionDialog.cpp - dialog allowing the user to create and * modify links between controllers and models * * Copyright (c) 2008 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. * */ #include <QHBoxLayout> #include <QLineEdit> #include <QPushButton> #include <QMessageBox> #include "AudioEngine.h" #include "ControllerConnectionDialog.h" #include "ControllerConnection.h" #include "MidiController.h" #include "MidiClient.h" #include "MidiPortMenu.h" #include "LcdSpinBox.h" #include "LedCheckBox.h" #include "ComboBox.h" #include "GroupBox.h" #include "Song.h" #include "TabWidget.h" #include "ToolButton.h" #include "embed.h" namespace lmms { class AutoDetectMidiController : public MidiController { public: AutoDetectMidiController( Model* parent ) : MidiController( parent ), m_detectedMidiChannel( 0 ), m_detectedMidiController(NONE) { updateName(); } ~AutoDetectMidiController() override = default; void processInEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset = 0 ) override { if( event.type() == MidiControlChange && ( m_midiPort.inputChannel() == 0 || m_midiPort.inputChannel() == event.channel() + 1 ) ) { m_detectedMidiChannel = event.channel() + 1; m_detectedMidiController = event.controllerNumber(); m_detectedMidiPort = Engine::audioEngine()->midiClient()->sourcePortName( event ); emit valueChanged(); } } // Would be a nice copy ctor, but too hard to add copy ctor because // model has none. MidiController* copyToMidiController( Model* parent ) { auto c = new MidiController(parent); c->m_midiPort.setInputChannel( m_midiPort.inputChannel() ); c->m_midiPort.setInputController( m_midiPort.inputController() ); c->subscribeReadablePorts( m_midiPort.readablePorts() ); c->updateName(); return c; } void useDetected() { m_midiPort.setInputChannel( m_detectedMidiChannel ); m_midiPort.setInputController( m_detectedMidiController ); const MidiPort::Map& map = m_midiPort.readablePorts(); for( MidiPort::Map::ConstIterator it = map.begin(); it != map.end(); ++it ) { m_midiPort.subscribeReadablePort( it.key(), m_detectedMidiPort.isEmpty() || ( it.key() == m_detectedMidiPort ) ); } } public slots: void reset() { m_midiPort.setInputChannel( 0 ); m_midiPort.setInputController( 0 ); } private: int m_detectedMidiChannel; int m_detectedMidiController; QString m_detectedMidiPort; } ; namespace gui { ControllerConnectionDialog::ControllerConnectionDialog( QWidget * _parent, const AutomatableModel * _target_model ) : QDialog( _parent ), m_readablePorts( nullptr ), m_midiAutoDetect( false ), m_controller( nullptr ), m_targetModel( _target_model ), m_midiController( nullptr ) { setWindowIcon( embed::getIconPixmap( "setup_audio" ) ); setWindowTitle( tr( "Connection Settings" ) ); setModal( true ); // Midi stuff m_midiGroupBox = new GroupBox( tr( "MIDI CONTROLLER" ), this ); m_midiGroupBox->setGeometry( 8, 10, 240, 80 ); connect( m_midiGroupBox->model(), SIGNAL(dataChanged()), this, SLOT(midiToggled())); m_midiChannelSpinBox = new LcdSpinBox( 2, m_midiGroupBox, tr( "Input channel" ) ); m_midiChannelSpinBox->addTextForValue( 0, "--" ); m_midiChannelSpinBox->setLabel( tr( "CHANNEL" ) ); m_midiChannelSpinBox->move( 8, 24 ); m_midiControllerSpinBox = new LcdSpinBox( 3, m_midiGroupBox, tr( "Input controller" ) ); m_midiControllerSpinBox->addTextForValue(MidiController::NONE, "---" ); m_midiControllerSpinBox->setLabel( tr( "CONTROLLER" ) ); m_midiControllerSpinBox->move( 68, 24 ); m_midiAutoDetectCheckBox = new LedCheckBox( tr("Auto Detect"), m_midiGroupBox, tr("Auto Detect") ); m_midiAutoDetectCheckBox->setModel( &m_midiAutoDetect ); m_midiAutoDetectCheckBox->move( 8, 60 ); connect( &m_midiAutoDetect, SIGNAL(dataChanged()), this, SLOT(autoDetectToggled())); // when using with non-raw-clients we can provide buttons showing // our port-menus when being clicked if( !Engine::audioEngine()->midiClient()->isRaw() ) { m_readablePorts = new MidiPortMenu( MidiPort::Mode::Input ); connect( m_readablePorts, SIGNAL(triggered(QAction*)), this, SLOT(enableAutoDetect(QAction*))); auto rp_btn = new ToolButton(m_midiGroupBox); rp_btn->setText( tr( "MIDI-devices to receive " "MIDI-events from" ) ); rp_btn->setIcon( embed::getIconPixmap( "piano" ) ); rp_btn->setGeometry( 160, 24, 32, 32 ); rp_btn->setMenu( m_readablePorts ); rp_btn->setPopupMode( QToolButton::InstantPopup ); } // User stuff m_userGroupBox = new GroupBox( tr( "USER CONTROLLER" ), this ); m_userGroupBox->setGeometry( 8, 100, 240, 60 ); connect( m_userGroupBox->model(), SIGNAL(dataChanged()), this, SLOT(userToggled())); m_userController = new ComboBox( m_userGroupBox, "Controller" ); m_userController->setGeometry( 10, 24, 200, ComboBox::DEFAULT_HEIGHT ); for (Controller * c : Engine::getSong()->controllers()) { m_userController->model()->addItem( c->name() ); } connect( m_userController->model(), SIGNAL(dataUnchanged()), this, SLOT(userSelected())); connect( m_userController->model(), SIGNAL(dataChanged()), this, SLOT(userSelected())); // Mapping functions m_mappingBox = new TabWidget( tr( "MAPPING FUNCTION" ), this ); m_mappingBox->setGeometry( 8, 170, 240, 64 ); m_mappingFunction = new QLineEdit( m_mappingBox ); m_mappingFunction->setGeometry( 10, 20, 170, 16 ); m_mappingFunction->setText( "input" ); m_mappingFunction->setReadOnly( true ); // Buttons auto buttons = new QWidget(this); buttons->setGeometry( 8, 240, 240, 32 ); auto btn_layout = new QHBoxLayout(buttons); btn_layout->setSpacing( 0 ); btn_layout->setContentsMargins(0, 0, 0, 0); auto select_btn = new QPushButton(embed::getIconPixmap("add"), tr("OK"), buttons); connect( select_btn, SIGNAL(clicked()), this, SLOT(selectController())); auto cancel_btn = new QPushButton(embed::getIconPixmap("cancel"), tr("Cancel"), buttons); connect( cancel_btn, SIGNAL(clicked()), this, SLOT(reject())); btn_layout->addStretch(); btn_layout->addSpacing( 10 ); btn_layout->addWidget( select_btn ); btn_layout->addSpacing( 10 ); btn_layout->addWidget( cancel_btn ); btn_layout->addSpacing( 10 ); setFixedSize( 256, 280 ); // Crazy MIDI View stuff // TODO, handle by making this a model for the Dialog "view" ControllerConnection * cc = nullptr; if( m_targetModel ) { cc = m_targetModel->controllerConnection(); if( cc && cc->getController()->type() != Controller::ControllerType::Dummy && Engine::getSong() ) { if ( cc->getController()->type() == Controller::ControllerType::Midi ) { m_midiGroupBox->model()->setValue( true ); // ensure controller is created midiToggled(); auto cont = (MidiController*)(cc->getController()); m_midiChannelSpinBox->model()->setValue( cont->m_midiPort.inputChannel() ); m_midiControllerSpinBox->model()->setValue( cont->m_midiPort.inputController() ); m_midiController->subscribeReadablePorts( static_cast<MidiController*>( cc->getController() )->m_midiPort.readablePorts() ); } else { auto& controllers = Engine::getSong()->controllers(); auto it = std::find(controllers.begin(), controllers.end(), cc->getController()); if (it != controllers.end()) { int idx = std::distance(controllers.begin(), it); m_userGroupBox->model()->setValue( true ); m_userController->model()->setValue( idx ); } } } } if( !cc ) { m_midiGroupBox->model()->setValue( true ); } show(); } ControllerConnectionDialog::~ControllerConnectionDialog() { delete m_readablePorts; delete m_midiController; } void ControllerConnectionDialog::selectController() { // Midi if (m_midiGroupBox->model()->value()) { if( m_midiControllerSpinBox->model()->value() > 0 ) { auto mc = m_midiController->copyToMidiController(Engine::getSong()); /* if( m_targetModel->getTrack() && !m_targetModel->getTrack()->displayName().isEmpty() ) { mc->m_midiPort.setName( QString( "%1 (%2)" ). arg( m_targetModel->getTrack()->displayName() ). arg( m_targetModel->displayName() ) ); } else { mc->m_midiPort.setName( m_targetModel->displayName() ); } */ mc->m_midiPort.setName( m_targetModel->fullDisplayName() ); m_controller = mc; } } // User else { if (m_userGroupBox->model()->value() && Engine::getSong()->controllers().size()) { m_controller = Engine::getSong()->controllers().at( m_userController->model()->value() ); } if( m_controller && m_controller->hasModel( m_targetModel ) ) { QMessageBox::warning(this, tr("LMMS"), tr("Cycle Detected.")); return; } } accept(); } void ControllerConnectionDialog::midiToggled() { int enabled = m_midiGroupBox->model()->value(); if( enabled != 0 ) { if( m_userGroupBox->model()->value() != 0 ) { m_userGroupBox->model()->setValue( 0 ); } if( !m_midiController ) { m_midiController = new AutoDetectMidiController( Engine::getSong() ); MidiPort::Map map = m_midiController->m_midiPort.readablePorts(); for( MidiPort::Map::Iterator it = map.begin(); it != map.end(); ++it ) { it.value() = true; } m_midiController->subscribeReadablePorts( map ); m_midiChannelSpinBox->setModel( &m_midiController->m_midiPort.m_inputChannelModel ); m_midiControllerSpinBox->setModel( &m_midiController->m_midiPort.m_inputControllerModel ); if( m_readablePorts ) { m_readablePorts->setModel( &m_midiController->m_midiPort ); } connect( m_midiController, SIGNAL(valueChanged()), this, SLOT(midiValueChanged())); } } m_midiAutoDetect.setValue( enabled ); m_midiChannelSpinBox->setEnabled( enabled ); m_midiControllerSpinBox->setEnabled( enabled ); m_midiAutoDetectCheckBox->setEnabled( enabled ); } void ControllerConnectionDialog::userToggled() { int enabled = m_userGroupBox->model()->value(); if( enabled != 0 && m_midiGroupBox->model()->value() != 0 ) { m_midiGroupBox->model()->setValue( 0 ); } } void ControllerConnectionDialog::userSelected() { m_userGroupBox->model()->setValue( 1 ); userToggled(); } void ControllerConnectionDialog::autoDetectToggled() { if (m_midiAutoDetect.value() && m_midiController) { m_midiController->reset(); } } void ControllerConnectionDialog::midiValueChanged() { if( m_midiAutoDetect.value() ) { m_midiController->useDetected(); if( m_readablePorts ) { m_readablePorts->updateMenu(); } } } void ControllerConnectionDialog::enableAutoDetect( QAction * _a ) { if( _a->isChecked() ) { m_midiAutoDetectCheckBox->model()->setValue( true ); } } } // namespace gui } // namespace lmms
11,509
C++
.cpp
346
30.378613
128
0.713588
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,920
VersionedSaveDialog.cpp
LMMS_lmms/src/gui/modals/VersionedSaveDialog.cpp
/* * VersionedSaveDialog.cpp - implementation of class VersionedSaveDialog * * 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. * */ #include <QLayout> #include <QLineEdit> #include <QMessageBox> #include <QPushButton> #include <QGroupBox> #include "DeprecationHelper.h" #include "VersionedSaveDialog.h" #include "LedCheckBox.h" namespace lmms::gui { VersionedSaveDialog::VersionedSaveDialog( QWidget *parent, QWidget *saveOptionsWidget, const QString &caption, const QString &directory, const QString &filter ) : FileDialog(parent, caption, directory, filter) { setAcceptMode( QFileDialog::AcceptSave ); setFileMode( QFileDialog::AnyFile ); // Create + and - buttons auto plusButton(new QPushButton("+", this)); plusButton->setToolTip( tr( "Increment version number" ) ); auto minusButton(new QPushButton("-", this)); minusButton->setToolTip( tr( "Decrement version number" ) ); plusButton->setFixedWidth(horizontalAdvance(plusButton->fontMetrics(), "+") + 30); minusButton->setFixedWidth(horizontalAdvance(minusButton->fontMetrics(), "+") + 30); // Add buttons to grid layout. For doing this, remove the lineEdit and // replace it with a HBox containing lineEdit and the buttons. auto layout = dynamic_cast<QGridLayout*>(this->layout()); QWidget *lineEdit = findChild<QLineEdit*>(); layout->removeWidget( lineEdit ); auto hLayout(new QHBoxLayout()); hLayout->addWidget( lineEdit ); hLayout->addWidget( plusButton ); hLayout->addWidget( minusButton ); layout->addLayout( hLayout, 2, 1 ); if (saveOptionsWidget) { auto groupBox = new QGroupBox(tr("Save Options")); auto optionsLayout = new QGridLayout; optionsLayout->addWidget(saveOptionsWidget, 0, 0, Qt::AlignLeft); groupBox->setLayout(optionsLayout); layout->addWidget(groupBox, layout->rowCount() + 1, 0, 1, -1); } // Connect + and - buttons connect( plusButton, SIGNAL(clicked()), this, SLOT(incrementVersion())); connect( minusButton, SIGNAL(clicked()), this, SLOT(decrementVersion())); } bool VersionedSaveDialog::changeFileNameVersion(QString &fileName, bool increment ) { static QRegularExpression regex( "[- ]\\d+(\\.\\w+)?$" ); int idx = regex.match(fileName).capturedStart(); // For file names without extension (no ".mmpz") int insertIndex = fileName.lastIndexOf( '.' ); if ( insertIndex < idx+1 ) insertIndex = fileName.size(); if ( idx == -1 ) { // Can't decrement if there is no version number if ( increment == false ) return false; else fileName.insert( insertIndex, "-01" ); } else { // Find current version number QString number = fileName.mid( idx+1, insertIndex - idx - 1 ); bool ok; ushort version = number.toUShort( &ok ); Q_ASSERT( ok ); // Can't decrement 0 if ( !increment && version == 0 ) return false; // Replace version number version = increment ? version + 1 : version - 1; QString newnumber = QString( "%1" ).arg( version, 2, 10, QChar( '0' ) ); fileName.replace( idx+1, number.length(), newnumber ); } return true; } void VersionedSaveDialog::incrementVersion() { const QStringList& selected = selectedFiles(); if ( selected.size() != 1 ) return; QString file = selected[0]; changeFileNameVersion( file, true ); clearSelection(); selectFile( file ); } void VersionedSaveDialog::decrementVersion() { const QStringList& selected = selectedFiles(); if ( selected.size() != 1 ) return; QString file = selected[0]; changeFileNameVersion( file, false ); clearSelection(); selectFile( file ); } bool VersionedSaveDialog::fileExistsQuery( QString FileName, QString WindowTitle ) { bool fileExists = false; if( QFile( FileName ).exists() ) { QMessageBox mb; mb.setWindowTitle( WindowTitle ); mb.setText( FileName + tr( " already exists. " "Do you want to replace it?" ) ); mb.setIcon( QMessageBox::Warning ); mb.setStandardButtons( QMessageBox::Yes | QMessageBox::No ); if( mb.exec() == QMessageBox::Yes ) { fileExists = true; } } return fileExists; } SaveOptionsWidget::SaveOptionsWidget(Song::SaveOptions &saveOptions) { auto *layout = new QVBoxLayout(); m_discardMIDIConnectionsCheckbox = new LedCheckBox(nullptr); m_discardMIDIConnectionsCheckbox->setText(tr("Discard MIDI connections")); m_discardMIDIConnectionsCheckbox->setModel(&saveOptions.discardMIDIConnections); m_saveAsProjectBundleCheckbox = new LedCheckBox(nullptr); m_saveAsProjectBundleCheckbox->setText(tr("Save As Project Bundle (with resources)")); m_saveAsProjectBundleCheckbox->setModel(&saveOptions.saveAsProjectBundle); layout->addWidget(m_discardMIDIConnectionsCheckbox); layout->addWidget(m_saveAsProjectBundleCheckbox); setLayout(layout); } } // namespace lmms::gui
5,547
C++
.cpp
155
33.141935
87
0.739391
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,921
EffectSelectDialog.cpp
LMMS_lmms/src/gui/modals/EffectSelectDialog.cpp
/* * EffectSelectDialog.cpp - dialog to choose effect plugin * * Copyright (c) 2006-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * Copyright (c) 2023 Lost Robot <r94231/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. * */ #include "EffectSelectDialog.h" #include "DummyEffect.h" #include "EffectChain.h" #include "embed.h" #include "PluginFactory.h" #include <QApplication> #include <QDialogButtonBox> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QRegularExpression> #include <QScrollArea> #include <QVBoxLayout> namespace lmms::gui { EffectSelectDialog::EffectSelectDialog(QWidget* parent) : QDialog(parent), m_effectKeys(), m_currentSelection(), m_sourceModel(), m_model(), m_descriptionWidget(nullptr), m_pluginList(new QTableView(this)), m_scrollArea(new QScrollArea(this)) { setWindowTitle(tr("Add effect")); resize(640, 480); setWindowIcon(embed::getIconPixmap("setup_audio")); // Query effects EffectKeyList subPluginEffectKeys; for (const auto desc : getPluginFactory()->descriptors(Plugin::Type::Effect)) { if (desc->subPluginFeatures) { desc->subPluginFeatures->listSubPluginKeys(desc, subPluginEffectKeys); } else { m_effectKeys << EffectKey(desc, desc->name); } } m_effectKeys += subPluginEffectKeys; // Fill the source model m_sourceModel.setHorizontalHeaderItem(0, new QStandardItem(tr("Name"))); m_sourceModel.setHorizontalHeaderItem(1, new QStandardItem(tr("Type"))); int row = 0; for (EffectKeyList::ConstIterator it = m_effectKeys.begin(); it != m_effectKeys.end(); ++it) { QString name; QString type; if (it->desc->subPluginFeatures) { name = it->displayName(); type = it->desc->displayName; } else { name = it->desc->displayName; type = "LMMS"; } m_sourceModel.setItem(row, 0, new QStandardItem(name)); m_sourceModel.setItem(row, 1, new QStandardItem(type)); ++row; } // Setup filtering m_model.setSourceModel(&m_sourceModel); m_model.setFilterCaseSensitivity(Qt::CaseInsensitive); QHBoxLayout* mainLayout = new QHBoxLayout(this); QVBoxLayout* leftSectionLayout = new QVBoxLayout(); QStringList buttonLabels = { tr("All"), "LMMS", "LADSPA", "LV2", "VST" }; QStringList buttonSearchString = { "", "LMMS", "LADSPA", "LV2", "VST" }; for (int i = 0; i < buttonLabels.size(); ++i) { const QString& label = buttonLabels[i]; const QString& searchString = buttonSearchString[i]; QPushButton* button = new QPushButton(label, this); button->setFixedSize(50, 50); button->setFocusPolicy(Qt::NoFocus); leftSectionLayout->addWidget(button); connect(button, &QPushButton::clicked, this, [this, searchString] { m_model.setEffectTypeFilter(searchString); updateSelection(); }); } leftSectionLayout->addStretch();// Add stretch to the button layout to push buttons to the top mainLayout->addLayout(leftSectionLayout); m_filterEdit = new QLineEdit(this); connect(m_filterEdit, &QLineEdit::textChanged, this, [this](const QString &text) { // TODO: Cleanup when we don't support Qt5 anymore #if (QT_VERSION >= QT_VERSION_CHECK(5,12,0)) m_model.setFilterRegularExpression(QRegularExpression(text, QRegularExpression::CaseInsensitiveOption)); #else m_model.setFilterRegExp(QRegExp(text, Qt::CaseInsensitive)); #endif }); connect(m_filterEdit, &QLineEdit::textChanged, this, &EffectSelectDialog::updateSelection); m_filterEdit->setFocus(); m_filterEdit->setFocusPolicy(Qt::StrongFocus); m_filterEdit->setPlaceholderText(tr("Search")); m_filterEdit->setClearButtonEnabled(true); m_filterEdit->addAction(embed::getIconPixmap("zoom"), QLineEdit::LeadingPosition); m_pluginList->setModel(&m_model); m_pluginList->setEditTriggers(QAbstractItemView::NoEditTriggers); m_pluginList->setSelectionBehavior(QAbstractItemView::SelectRows); m_pluginList->setSelectionMode(QAbstractItemView::SingleSelection); m_pluginList->setSortingEnabled(true); m_pluginList->sortByColumn(0, Qt::AscendingOrder); // Initial sort by column 0 (Name) m_pluginList->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); m_pluginList->verticalHeader()->hide(); m_pluginList->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); m_pluginList->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); m_pluginList->setFocusPolicy(Qt::NoFocus); // Scroll Area m_scrollArea->setWidgetResizable(true); QWidget* scrollAreaWidgetContents = new QWidget(m_scrollArea); scrollAreaWidgetContents->setObjectName("scrollAreaWidgetContents"); m_scrollArea->setWidget(scrollAreaWidgetContents); m_scrollArea->setMaximumHeight(180); m_scrollArea->setFocusPolicy(Qt::NoFocus); // Button Box QDialogButtonBox* buttonBox = new QDialogButtonBox(Qt::Horizontal, this); buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); buttonBox->setFocusPolicy(Qt::NoFocus); connect(buttonBox, &QDialogButtonBox::accepted, this, &EffectSelectDialog::acceptSelection); connect(buttonBox, &QDialogButtonBox::rejected, this, &EffectSelectDialog::reject); QVBoxLayout* rightSectionLayout = new QVBoxLayout(); rightSectionLayout->addWidget(m_filterEdit); rightSectionLayout->addWidget(m_pluginList); rightSectionLayout->addWidget(m_scrollArea); rightSectionLayout->addWidget(buttonBox); mainLayout->addLayout(rightSectionLayout); setLayout(mainLayout); auto selectionModel = new QItemSelectionModel(&m_model); m_pluginList->setSelectionModel(selectionModel); connect(selectionModel, &QItemSelectionModel::currentRowChanged, this, &EffectSelectDialog::rowChanged); connect(m_pluginList, &QTableView::doubleClicked, this, &EffectSelectDialog::acceptSelection); setModal(true); installEventFilter(this); updateSelection(); show(); } Effect* EffectSelectDialog::instantiateSelectedPlugin(EffectChain* parent) { Effect* result = nullptr; if (!m_currentSelection.name.isEmpty() && m_currentSelection.desc) { result = Effect::instantiate(m_currentSelection.desc->name, parent, &m_currentSelection); } if (!result) { result = new DummyEffect(parent, QDomElement()); } return result; } void EffectSelectDialog::acceptSelection() { if (m_currentSelection.isValid()) { accept(); } } void EffectSelectDialog::rowChanged(const QModelIndex& idx, const QModelIndex&) { delete m_descriptionWidget; m_descriptionWidget = nullptr; if (m_model.mapToSource(idx).row() < 0) { // Invalidate current selection m_currentSelection = Plugin::Descriptor::SubPluginFeatures::Key(); } else { m_currentSelection = m_effectKeys[m_model.mapToSource(idx).row()]; } if (m_currentSelection.desc) { m_descriptionWidget = new QWidget; auto hbox = new QHBoxLayout(m_descriptionWidget); hbox->setAlignment(Qt::AlignTop); Plugin::Descriptor const& descriptor = *(m_currentSelection.desc); const PixmapLoader* pixLoa = m_currentSelection.logo(); if (pixLoa) { auto logoLabel = new QLabel(m_descriptionWidget); logoLabel->setPixmap(pixLoa->pixmap()); logoLabel->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); logoLabel->setMaximumSize(64, 64); hbox->addWidget(logoLabel); } auto textualInfoWidget = new QWidget(m_descriptionWidget); hbox->addWidget(textualInfoWidget); auto textWidgetLayout = new QVBoxLayout(textualInfoWidget); textWidgetLayout->setContentsMargins(4, 4, 4, 4); textWidgetLayout->setSpacing(8); if (m_currentSelection.desc->subPluginFeatures) { auto subWidget = new QWidget(textualInfoWidget); auto subLayout = new QVBoxLayout(subWidget); subLayout->setContentsMargins(0, 0, 0, 0); subLayout->setSpacing(8); m_currentSelection.desc->subPluginFeatures-> fillDescriptionWidget(subWidget, &m_currentSelection); for (QWidget* w : subWidget->findChildren<QWidget*>()) { if (w->parent() == subWidget) { subLayout->addWidget(w); subLayout->setAlignment(w, QFlags<Qt::AlignmentFlag>(Qt::AlignTop | Qt::AlignLeft)); } } textWidgetLayout->addWidget(subWidget); } else { auto label = new QLabel(m_descriptionWidget); QString labelText = "<p><b>" + tr("Name") + ":</b> " + QString::fromUtf8(descriptor.displayName) + "</p>"; labelText += "<p><b>" + tr("Description") + ":</b> " + qApp->translate("PluginBrowser", descriptor.description) + "</p>"; labelText += "<p><b>" + tr("Author") + ":</b> " + QString::fromUtf8(descriptor.author) + "</p>"; label->setText(labelText); label->setWordWrap(true); textWidgetLayout->addWidget(label); } m_scrollArea->setWidget(m_descriptionWidget); m_descriptionWidget->show(); } } void EffectSelectDialog::updateSelection() { // No valid selection anymore due to changed filter? if (m_pluginList->selectionModel()->selection().size() <= 0) { // Then select our first item m_pluginList->selectionModel()-> select(m_model.index(0, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); rowChanged(m_model.index(0, 0), QModelIndex()); } } bool EffectSelectDialog::eventFilter(QObject *obj, QEvent *event) { if (obj == this && event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down) { QItemSelectionModel* selectionModel = m_pluginList->selectionModel(); int currentRow = selectionModel->currentIndex().row(); int newRow = (keyEvent->key() == Qt::Key_Up) ? currentRow - 1 : currentRow + 1; int rowCount = m_pluginList->model()->rowCount(); newRow = qBound(0, newRow, rowCount - 1); selectionModel->setCurrentIndex(m_pluginList->model()->index(newRow, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); m_pluginList->scrollTo(m_pluginList->model()->index(newRow, 0)); return true; } } return QDialog::eventFilter(obj, event); } } // namespace lmms::gui
10,634
C++
.cpp
284
34.820423
124
0.754321
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
19,922
RenameDialog.cpp
LMMS_lmms/src/gui/modals/RenameDialog.cpp
/* * RenameDialog.cpp - implementation of dialog for renaming something * * 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. * */ #include <QKeyEvent> #include <QLineEdit> #include "RenameDialog.h" namespace lmms::gui { RenameDialog::RenameDialog( QString & _string ) : QDialog(), m_stringToEdit( _string ), m_originalString( _string ) { setWindowTitle( tr("Rename...") ); setFixedHeight( 30 ); m_stringLE = new QLineEdit( this ); m_stringLE->setText( _string ); m_stringLE->setGeometry ( 10, 5, 220, 20 ); m_stringLE->selectAll(); connect( m_stringLE, SIGNAL( textChanged( const QString& ) ), this, SLOT( textChanged( const QString& ) ) ); connect( m_stringLE, SIGNAL(returnPressed()), this, SLOT(accept())); } void RenameDialog::resizeEvent (QResizeEvent * event) { m_stringLE->setGeometry ( 10, 5, width() - 20, 20 ); } void RenameDialog::keyPressEvent( QKeyEvent * _ke ) { if( _ke->key() == Qt::Key_Escape ) { m_stringLE->setText( m_originalString ); accept(); } } void RenameDialog::textChanged( const QString & _new_string ) { m_stringToEdit = _new_string; } } // namespace lmms::gui
1,961
C++
.cpp
60
30.433333
77
0.726209
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,923
ColorChooser.cpp
LMMS_lmms/src/gui/modals/ColorChooser.cpp
/* ColorChooser.cpp - definition of ColorChooser class. * * Copyright (c) 2020 russiankumar <adityakumar4644/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. * */ #include <ColorChooser.h> namespace lmms::gui { //! Set global palette via array, checking bounds void ColorChooser::setPalette (QVector<QColor> colors) { const int max = qMin (colors.size(), 48); for (int i = 0; i < max; i++) { ColorChooser::setStandardColor (i, colors[i]); } } //! Set global paletter via enum void ColorChooser::setPalette (Palette palette) { setPalette (getPalette (palette)); } //! Set palette via enum, return self pointer for chaining ColorChooser* ColorChooser::withPalette (Palette palette) { setPalette (palette); return this; } //! Return a certain palette QVector<QColor> ColorChooser::getPalette (Palette palette) { switch (palette) { case Palette::Mixer: return nicePalette(140); case Palette::Track: return nicePalette(150); default: return defaultPalette(); } } //! Copy the current QColorDialog palette into an array QVector<QColor> ColorChooser::defaultPalette() { QVector <QColor> result (48); for (int i = 0; i < 48; i++) { result[i] = (QColorDialog::standardColor(i)); } return result; } //! Generate a nice palette, with adjustable value QVector<QColor> ColorChooser::nicePalette (int base) { QVector <QColor> result (48); for (int x = 0; x < 8; x++) { for (int y = 0; y < 6; y++) { result[6 * x + y].setHsl (qMax(0, 44 * x - 1), 150 - 20 * y, base - 10 * y); } } return result; } } // namespace lmms::gui
2,326
C++
.cpp
79
27.443038
79
0.728007
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,924
ClipView.cpp
LMMS_lmms/src/gui/clips/ClipView.cpp
/* * ClipView.cpp - implementation 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. * */ #include "ClipView.h" #include <set> #include <cassert> #include <QMenu> #include <QMouseEvent> #include <QPainter> #include "AutomationClip.h" #include "Clipboard.h" #include "ColorChooser.h" #include "ComboBoxModel.h" #include "DataFile.h" #include "Engine.h" #include "embed.h" #include "GuiApplication.h" #include "InstrumentTrack.h" #include "InstrumentTrackView.h" #include "MidiClip.h" #include "MidiClipView.h" #include "Note.h" #include "PatternClip.h" #include "PatternStore.h" #include "SampleClip.h" #include "Song.h" #include "SongEditor.h" #include "StringPairDrag.h" #include "TextFloat.h" #include "TrackContainer.h" #include "TrackContainerView.h" #include "TrackView.h" namespace lmms::gui { /*! The width of the resize grip in pixels */ const int RESIZE_GRIP_WIDTH = 4; /*! A pointer for that text bubble used when moving segments, etc. * * In a number of situations, LMMS displays a floating text bubble * beside the cursor as you move or resize elements of a track about. * This pointer keeps track of it, as you only ever need one at a time. */ TextFloat * ClipView::s_textFloat = nullptr; /*! \brief Create a new ClipView * * Creates a new clip view for the given clip in the given track view. * * \param _clip The clip to be displayed * \param _tv The track view that will contain the new object */ ClipView::ClipView( Clip * clip, TrackView * tv ) : selectableObject( tv->getTrackContentWidget() ), ModelView( nullptr, this ), m_trackView( tv ), m_initialClipPos( TimePos(0) ), m_initialClipEnd( TimePos(0) ), m_clip( clip ), m_action( Action::None ), m_initialMousePos( QPoint( 0, 0 ) ), m_initialMouseGlobalPos( QPoint( 0, 0 ) ), m_initialOffsets( QVector<TimePos>() ), m_hint( nullptr ), m_mutedColor( 0, 0, 0 ), m_mutedBackgroundColor( 0, 0, 0 ), m_selectedColor( 0, 0, 0 ), m_textColor( 0, 0, 0 ), m_textShadowColor( 0, 0, 0 ), m_patternClipBackground( 0, 0, 0 ), m_gradient( true ), m_mouseHotspotHand( 0, 0 ), m_mouseHotspotKnife( 0, 0 ), m_cursorHand( QCursor( embed::getIconPixmap( "hand" ) ) ), m_cursorKnife( QCursor( embed::getIconPixmap( "cursor_knife" ) ) ), m_cursorSetYet( false ), m_needsUpdate( true ) { if( s_textFloat == nullptr ) { s_textFloat = new TextFloat; s_textFloat->setPixmap( embed::getIconPixmap( "clock" ) ); } setAttribute( Qt::WA_OpaquePaintEvent, true ); setAttribute( Qt::WA_DeleteOnClose, true ); setFocusPolicy( Qt::StrongFocus ); setCursor( m_cursorHand ); move( 0, 0 ); show(); setFixedHeight( tv->getTrackContentWidget()->height() - 1); setAcceptDrops( true ); setMouseTracking( true ); connect( m_clip, SIGNAL(lengthChanged()), this, SLOT(updateLength())); connect(getGUI()->songEditor()->m_editor, &SongEditor::pixelsPerBarChanged, this, &ClipView::updateLength); connect( m_clip, SIGNAL(positionChanged()), this, SLOT(updatePosition())); connect( m_clip, SIGNAL(destroyedClip()), this, SLOT(close())); setModel( m_clip ); connect(m_clip, SIGNAL(colorChanged()), this, SLOT(update())); connect(m_trackView->getTrack(), &Track::colorChanged, this, [this] { // redraw if clip uses track color if (!m_clip->color().has_value()) { update(); } }); m_trackView->getTrackContentWidget()->addClipView( this ); updateLength(); updatePosition(); } /*! \brief Destroy a ClipView * * Destroys the given ClipView. * */ ClipView::~ClipView() { delete m_hint; // we have to give our track-container the focus because otherwise the // op-buttons of our track-widgets could become focus and when the user // presses space for playing song, just one of these buttons is pressed // which results in unwanted effects m_trackView->trackContainerView()->setFocus(); } /*! \brief Update a ClipView * * Clip's get drawn only when needed, * and when a Clip is updated, * it needs to be redrawn. * */ void ClipView::update() { if( !m_cursorSetYet ) { m_cursorHand = QCursor( embed::getIconPixmap( "hand" ), m_mouseHotspotHand.width(), m_mouseHotspotHand.height() ); m_cursorKnife = QCursor( embed::getIconPixmap( "cursor_knife" ), m_mouseHotspotKnife.width(), m_mouseHotspotKnife.height() ); setCursor( m_cursorHand ); m_cursorSetYet = true; } if( fixedClips() ) { updateLength(); } m_needsUpdate = true; selectableObject::update(); } /*! \brief Does this ClipView have a fixed Clip? * * Returns whether the containing trackView has fixed * Clips. * * \todo In what circumstance are they fixed? */ bool ClipView::fixedClips() { return m_trackView->trackContainerView()->fixedClips(); } // qproperty access functions, to be inherited & used by Clipviews //! \brief CSS theming qproperty access method QColor ClipView::mutedColor() const { return m_mutedColor; } QColor ClipView::mutedBackgroundColor() const { return m_mutedBackgroundColor; } QColor ClipView::selectedColor() const { return m_selectedColor; } QColor ClipView::textColor() const { return m_textColor; } QColor ClipView::textBackgroundColor() const { return m_textBackgroundColor; } QColor ClipView::textShadowColor() const { return m_textShadowColor; } QColor ClipView::patternClipBackground() const { return m_patternClipBackground; } bool ClipView::gradient() const { return m_gradient; } //! \brief CSS theming qproperty access method void ClipView::setMutedColor( const QColor & c ) { m_mutedColor = QColor( c ); } void ClipView::setMutedBackgroundColor( const QColor & c ) { m_mutedBackgroundColor = QColor( c ); } void ClipView::setSelectedColor( const QColor & c ) { m_selectedColor = QColor( c ); } void ClipView::setTextColor( const QColor & c ) { m_textColor = QColor( c ); } void ClipView::setTextBackgroundColor( const QColor & c ) { m_textBackgroundColor = c; } void ClipView::setTextShadowColor( const QColor & c ) { m_textShadowColor = QColor( c ); } void ClipView::setPatternClipBackground( const QColor & c ) { m_patternClipBackground = QColor( c ); } void ClipView::setGradient( const bool & b ) { m_gradient = b; } // access needsUpdate member variable bool ClipView::needsUpdate() { return m_needsUpdate; } void ClipView::setNeedsUpdate( bool b ) { m_needsUpdate = b; } /*! \brief Close a ClipView * * Closes a ClipView by asking the track * view to remove us and then asking the QWidget to close us. * * \return Boolean state of whether the QWidget was able to close. */ bool ClipView::close() { m_trackView->getTrackContentWidget()->removeClipView( this ); return QWidget::close(); } /*! \brief Removes a ClipView from its track view. * * Like the close() method, this asks the track view to remove this * ClipView. However, the clip is * scheduled for later deletion rather than closed immediately. * */ void ClipView::remove() { m_trackView->getTrack()->addJournalCheckPoint(); // delete ourself close(); if (m_clip->getTrack()) { auto guard = Engine::audioEngine()->requestChangesGuard(); m_clip->getTrack()->removeClip(m_clip); } // TODO: Clip::~Clip should not be responsible for removing the Clip from the Track. // One would expect that a call to Track::removeClip would already do that for you, as well // as actually deleting the Clip with the deleteLater function. That being said, it shouldn't // be possible to make a Clip without a Track (i.e., Clip::getTrack is never nullptr). m_clip->deleteLater(); } /*! \brief Updates a ClipView's length * * If this ClipView has a fixed Clip, then we must * keep the width of our parent. Otherwise, calculate our width from * the clip's length in pixels adding in the border. * */ void ClipView::updateLength() { if( fixedClips() ) { setFixedWidth( parentWidget()->width() ); } else { // this std::max function is needed for clips that do not start or end on the beat, otherwise, they "disappear" when zooming to min // 3 is the minimun width needed to make a clip visible setFixedWidth(std::max(static_cast<int>(m_clip->length() * pixelsPerBar() / TimePos::ticksPerBar() + 1), 3)); } m_trackView->trackContainerView()->update(); } /*! \brief Updates a ClipView's position. * * Ask our track view to change our position. Then make sure that the * track view is updated in case this position has changed the track * view's length. * */ void ClipView::updatePosition() { m_trackView->getTrackContentWidget()->changePosition(); // moving a Clip can result in change of song-length etc., // therefore we update the track-container m_trackView->trackContainerView()->update(); } void ClipView::selectColor() { // Get a color from the user const auto newColor = ColorChooser{this} .withPalette(ColorChooser::Palette::Track) ->getColor(m_clip->color().value_or(palette().window().color())); if (newColor.isValid()) { setColor(newColor); } } void ClipView::randomizeColor() { setColor(ColorChooser::getPalette(ColorChooser::Palette::Mixer)[std::rand() % 48]); } void ClipView::resetColor() { setColor(std::nullopt); } /*! \brief Change color of all selected clips * * \param color The new color. */ void ClipView::setColor(const std::optional<QColor>& color) { std::set<Track*> journaledTracks; auto selectedClips = getClickedClips(); for (auto clipv : selectedClips) { auto clip = clipv->getClip(); auto track = clip->getTrack(); // TODO journal whole Song or group of clips instead of one journal entry for each track // If only one clip changed, store that in the journal if (selectedClips.length() == 1) { clip->addJournalCheckPoint(); } // If multiple clips changed, store whole Track in the journal // Check if track has been journaled already by trying to add it to the set else if (journaledTracks.insert(track).second) { track->addJournalCheckPoint(); } clip->setColor(color); clipv->update(); } Engine::getSong()->setModified(); } /*! \brief Change the ClipView's display when something * being dragged enters it. * * We need to notify Qt to change our display if something being * dragged has entered our 'airspace'. * * \param dee The QDragEnterEvent to watch. */ void ClipView::dragEnterEvent( QDragEnterEvent * dee ) { TrackContentWidget * tcw = getTrackView()->getTrackContentWidget(); TimePos clipPos{m_clip->startPosition()}; if( tcw->canPasteSelection( clipPos, dee ) == false ) { dee->ignore(); } else { StringPairDrag::processDragEnterEvent( dee, "clip_" + QString::number( static_cast<int>(m_clip->getTrack()->type()) ) ); } } /*! \brief Handle something being dropped on this ClipObjectView. * * When something has been dropped on this ClipView, and * it's a clip, then use an instance of our dataFile reader * to take the xml of the clip and turn it into something * we can write over our current state. * * \param de The QDropEvent to handle. */ void ClipView::dropEvent( QDropEvent * de ) { QString type = StringPairDrag::decodeKey( de ); QString value = StringPairDrag::decodeValue( de ); // Track must be the same type to paste into if( type != ( "clip_" + QString::number( static_cast<int>(m_clip->getTrack()->type()) ) ) ) { return; } // Defer to rubberband paste if we're in that mode if( m_trackView->trackContainerView()->allowRubberband() == true ) { TrackContentWidget * tcw = getTrackView()->getTrackContentWidget(); TimePos clipPos{m_clip->startPosition()}; if( tcw->pasteSelection( clipPos, de ) == true ) { de->accept(); } return; } // Don't allow pasting a clip into itself. QObject* qwSource = de->source(); if( qwSource != nullptr && dynamic_cast<ClipView *>( qwSource ) == this ) { return; } // Copy state into existing clip DataFile dataFile( value.toUtf8() ); TimePos pos = m_clip->startPosition(); QDomElement clips = dataFile.content().firstChildElement("clips"); m_clip->restoreState( clips.firstChildElement().firstChildElement() ); m_clip->movePosition( pos ); AutomationClip::resolveAllIDs(); de->accept(); } /* @brief Chooses the correct cursor to be displayed on the widget * * @param me The QMouseEvent that is triggering the cursor change */ void ClipView::updateCursor(QMouseEvent * me) { auto sClip = dynamic_cast<SampleClip*>(m_clip); auto pClip = dynamic_cast<PatternClip*>(m_clip); // If we are at the edges, use the resize cursor if (!me->buttons() && !m_clip->getAutoResize() && !isSelected() && ((me->x() > width() - RESIZE_GRIP_WIDTH) || (me->x() < RESIZE_GRIP_WIDTH && (sClip || pClip)))) { setCursor(Qt::SizeHorCursor); } // If we are in the middle on knife mode, use the knife cursor else if (sClip && m_trackView->trackContainerView()->knifeMode() && !isSelected()) { setCursor(m_cursorKnife); } // If we are in the middle in any other mode, use the hand cursor else { setCursor(m_cursorHand); } } /*! \brief Create a DataFile suitable for copying multiple clips. * * Clips in the vector are written to the "clips" node in the * DataFile. The ClipView's initial mouse position is written * to the "initialMouseX" node in the DataFile. When dropped on a track, * this is used to create copies of the Clips. * * \param clips The trackContectObjects to save in a DataFile */ DataFile ClipView::createClipDataFiles( const QVector<ClipView *> & clipViews) const { Track * t = m_trackView->getTrack(); TrackContainer * tc = t->trackContainer(); DataFile dataFile( DataFile::Type::DragNDropData ); QDomElement clipParent = dataFile.createElement("clips"); for (const auto& clipView : clipViews) { // Insert into the dom under the "clips" element Track* clipTrack = clipView->m_trackView->getTrack(); const auto trackIt = std::find(tc->tracks().begin(), tc->tracks().end(), clipTrack); assert(trackIt != tc->tracks().end()); int trackIndex = std::distance(tc->tracks().begin(), trackIt); QDomElement clipElement = dataFile.createElement("clip"); clipElement.setAttribute( "trackIndex", trackIndex ); clipElement.setAttribute( "trackType", static_cast<int>(clipTrack->type()) ); clipElement.setAttribute( "trackName", clipTrack->name() ); clipView->m_clip->saveState(dataFile, clipElement); clipParent.appendChild( clipElement ); } dataFile.content().appendChild( clipParent ); // Add extra metadata needed for calculations later const auto initialTrackIt = std::find(tc->tracks().begin(), tc->tracks().end(), t); if (initialTrackIt == tc->tracks().end()) { printf("Failed to find selected track in the TrackContainer.\n"); return dataFile; } const int initialTrackIndex = std::distance(tc->tracks().begin(), initialTrackIt); QDomElement metadata = dataFile.createElement( "copyMetadata" ); // initialTrackIndex is the index of the track that was touched metadata.setAttribute( "initialTrackIndex", initialTrackIndex ); metadata.setAttribute( "trackContainerId", tc->id() ); // grabbedClipPos is the pos of the bar containing the Clip we grabbed metadata.setAttribute( "grabbedClipPos", m_clip->startPosition() ); dataFile.content().appendChild( metadata ); return dataFile; } void ClipView::paintTextLabel(QString const & text, QPainter & painter) { if (text.trimmed() == "") { return; } painter.setRenderHint( QPainter::TextAntialiasing ); QFont labelFont = this->font(); labelFont.setHintingPreference( QFont::PreferFullHinting ); painter.setFont( labelFont ); const int textTop = BORDER_WIDTH + 1; const int textLeft = BORDER_WIDTH + 3; QFontMetrics fontMetrics(labelFont); QString elidedClipName = fontMetrics.elidedText(text, Qt::ElideMiddle, width() - 2 * textLeft); if (elidedClipName.length() < 2) { elidedClipName = text.trimmed(); } painter.fillRect(QRect(0, 0, width(), fontMetrics.height() + 2 * textTop), textBackgroundColor()); int const finalTextTop = textTop + fontMetrics.ascent(); painter.setPen(textShadowColor()); painter.drawText( textLeft + 1, finalTextTop + 1, elidedClipName ); painter.setPen( textColor() ); painter.drawText( textLeft, finalTextTop, elidedClipName ); } /*! \brief Handle a mouse press on this ClipView. * * Handles the various ways in which a ClipView can be * used with a click of a mouse button. * * * If our container supports rubber band selection then handle * selection events. * * or if shift-left button, add this object to the selection * * or if ctrl-left button, start a drag-copy event * * or if just plain left button, resize if we're resizeable * * or if ctrl-middle button, mute the clip * * or if middle button, maybe delete the clip. * * \param me The QMouseEvent to handle. */ void ClipView::mousePressEvent( QMouseEvent * me ) { // Right now, active is only used on right/mid clicks actions, so we use a ternary operator // to avoid the overhead of calling getClickedClips when it's not used auto active = me->button() == Qt::LeftButton ? QVector<ClipView *>() : getClickedClips(); setInitialPos( me->pos() ); setInitialOffsets(); if( !fixedClips() && me->button() == Qt::LeftButton ) { auto sClip = dynamic_cast<SampleClip*>(m_clip); auto pClip = dynamic_cast<PatternClip*>(m_clip); const bool knifeMode = m_trackView->trackContainerView()->knifeMode(); if ( me->modifiers() & Qt::ControlModifier && !(sClip && knifeMode) ) { if( isSelected() ) { m_action = Action::CopySelection; } else { m_action = Action::ToggleSelected; } } else { if( isSelected() ) { m_action = Action::MoveSelection; } else { getGUI()->songEditor()->m_editor->selectAllClips( false ); m_clip->addJournalCheckPoint(); // Action::Move, Action::Resize and Action::ResizeLeft // Action::Split action doesn't disable Clip journalling if (m_action == Action::Move || m_action == Action::Resize || m_action == Action::ResizeLeft) { m_clip->setJournalling(false); } setInitialPos( me->pos() ); setInitialOffsets(); if( m_clip->getAutoResize() ) { // Always move clips that can't be manually resized m_action = Action::Move; setCursor( Qt::SizeAllCursor ); } else if( me->x() >= width() - RESIZE_GRIP_WIDTH ) { m_action = Action::Resize; setCursor( Qt::SizeHorCursor ); } else if( me->x() < RESIZE_GRIP_WIDTH && (sClip || pClip) ) { m_action = Action::ResizeLeft; setCursor( Qt::SizeHorCursor ); } else if( sClip && knifeMode ) { m_action = Action::Split; setCursor( m_cursorKnife ); setMarkerPos( knifeMarkerPos( me ) ); setMarkerEnabled( true ); update(); } else { m_action = Action::Move; setCursor( Qt::SizeAllCursor ); } if( m_action == Action::Move ) { s_textFloat->setTitle( tr( "Current position" ) ); s_textFloat->setText( QString( "%1:%2" ). arg( m_clip->startPosition().getBar() + 1 ). arg( m_clip->startPosition().getTicks() % TimePos::ticksPerBar() ) ); } else if( m_action == Action::Resize || m_action == Action::ResizeLeft ) { s_textFloat->setTitle( tr( "Current length" ) ); s_textFloat->setText( tr( "%1:%2 (%3:%4 to %5:%6)" ). arg( m_clip->length().getBar() ). arg( m_clip->length().getTicks() % TimePos::ticksPerBar() ). arg( m_clip->startPosition().getBar() + 1 ). arg( m_clip->startPosition().getTicks() % TimePos::ticksPerBar() ). arg( m_clip->endPosition().getBar() + 1 ). arg( m_clip->endPosition().getTicks() % TimePos::ticksPerBar() ) ); } // s_textFloat->reparent( this ); // setup text-float as if Clip was already moved/resized s_textFloat->moveGlobal( this, QPoint( width() + 2, height() + 2) ); if ( m_action != Action::Split) { s_textFloat->show(); } } delete m_hint; QString hint = m_action == Action::Move || m_action == Action::MoveSelection ? tr( "Press <%1> and drag to make a copy." ) : tr( "Press <%1> for free resizing." ); m_hint = TextFloat::displayMessage( tr( "Hint" ), hint.arg(UI_CTRL_KEY), embed::getIconPixmap( "hint" ), 0 ); } } else if( me->button() == Qt::RightButton ) { if( me->modifiers() & Qt::ControlModifier ) { toggleMute( active ); } else if( me->modifiers() & Qt::ShiftModifier && !fixedClips() ) { remove( active ); } if (m_action == Action::Split) { m_action = Action::None; auto sClip = dynamic_cast<SampleClip*>(m_clip); if (sClip) { setMarkerEnabled( false ); update(); } } } else if( me->button() == Qt::MiddleButton ) { if( me->modifiers() & Qt::ControlModifier ) { toggleMute( active ); } else if( !fixedClips() ) { remove( active ); } } } /*! \brief Handle a mouse movement (drag) on this ClipView. * * Handles the various ways in which a ClipView can be * used with a mouse drag. * * * If in move mode, move ourselves in the track, * * or if in move-selection mode, move the entire selection, * * or if in resize mode, resize ourselves, * * otherwise ??? * * \param me The QMouseEvent to handle. * \todo what does the final else case do here? */ void ClipView::mouseMoveEvent( QMouseEvent * me ) { if( m_action == Action::CopySelection || m_action == Action::ToggleSelected ) { if( mouseMovedDistance( me, 2 ) == true ) { QVector<ClipView *> clipViews; if( m_action == Action::CopySelection ) { // Collect all selected Clips QVector<selectableObject *> so = m_trackView->trackContainerView()->selectedObjects(); for (const auto& selectedClip : so) { auto clipv = dynamic_cast<ClipView*>(selectedClip); if( clipv != nullptr ) { clipViews.push_back( clipv ); } } } else { getGUI()->songEditor()->m_editor->selectAllClips( false ); clipViews.push_back( this ); } // Clear the action here because mouseReleaseEvent will not get // triggered once we go into drag. m_action = Action::None; // Write the Clips to the DataFile for copying DataFile dataFile = createClipDataFiles( clipViews ); // TODO -- thumbnail for all selected QPixmap thumbnail = grab().scaled( 128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation ); new StringPairDrag( QString( "clip_%1" ).arg( static_cast<int>(m_clip->getTrack()->type()) ), dataFile.toString(), thumbnail, this ); } } if( me->modifiers() & Qt::ControlModifier ) { delete m_hint; m_hint = nullptr; } const float ppb = m_trackView->trackContainerView()->pixelsPerBar(); if( m_action == Action::Move ) { TimePos newPos = draggedClipPos( me ); m_clip->movePosition(newPos); newPos = m_clip->startPosition(); // Get the real position the Clip was dragged to for the label m_trackView->getTrackContentWidget()->changePosition(); s_textFloat->setText( QString( "%1:%2" ). arg( newPos.getBar() + 1 ). arg( newPos.getTicks() % TimePos::ticksPerBar() ) ); s_textFloat->moveGlobal( this, QPoint( width() + 2, height() + 2 ) ); } else if( m_action == Action::MoveSelection ) { // 1: Find the position we want to move the grabbed Clip to TimePos newPos = draggedClipPos( me ); // 2: Handle moving the other selected Clips the same distance QVector<selectableObject *> so = m_trackView->trackContainerView()->selectedObjects(); QVector<Clip *> clips; // List of selected clips int leftmost = 0; // Leftmost clip's offset from grabbed clip // Populate clips, find leftmost for( QVector<selectableObject *>::iterator it = so.begin(); it != so.end(); ++it ) { auto clipv = dynamic_cast<ClipView*>(*it); if( clipv == nullptr ) { continue; } clips.push_back( clipv->m_clip ); int index = std::distance( so.begin(), it ); leftmost = std::min(leftmost, m_initialOffsets[index].getTicks()); } // Make sure the leftmost clip doesn't get moved to a negative position if ( newPos.getTicks() + leftmost < 0 ) { newPos = -leftmost; } for( QVector<Clip *>::iterator it = clips.begin(); it != clips.end(); ++it ) { int index = std::distance( clips.begin(), it ); ( *it )->movePosition( newPos + m_initialOffsets[index] ); } } else if( m_action == Action::Resize || m_action == Action::ResizeLeft ) { const float snapSize = getGUI()->songEditor()->m_editor->getSnapSize(); // Length in ticks of one snap increment const TimePos snapLength = TimePos( (int)(snapSize * TimePos::ticksPerBar()) ); if( m_action == Action::Resize ) { // The clip's new length TimePos l = static_cast<int>( me->x() * TimePos::ticksPerBar() / ppb ); // If the user is holding alt, or pressed ctrl after beginning the drag, don't quantize if ( unquantizedModHeld(me) ) { // We want to preserve this adjusted offset, // even if the user switches to snapping later setInitialPos( m_initialMousePos ); // Don't resize to less than 1 tick m_clip->changeLength( qMax<int>( 1, l ) ); } else if ( me->modifiers() & Qt::ShiftModifier ) { // If shift is held, quantize clip's end position TimePos end = TimePos( m_initialClipPos + l ).quantize( snapSize ); // The end position has to be after the clip's start TimePos min = m_initialClipPos.quantize( snapSize ); if ( min <= m_initialClipPos ) min += snapLength; m_clip->changeLength( qMax<int>(min - m_initialClipPos, end - m_initialClipPos) ); } else { // Otherwise, resize in fixed increments TimePos initialLength = m_initialClipEnd - m_initialClipPos; TimePos offset = TimePos( l - initialLength ).quantize( snapSize ); // Don't resize to less than 1 tick auto min = TimePos(initialLength % snapLength); if (min < 1) min += snapLength; m_clip->changeLength( qMax<int>( min, initialLength + offset) ); } } else { auto sClip = dynamic_cast<SampleClip*>(m_clip); auto pClip = dynamic_cast<PatternClip*>(m_clip); if( sClip || pClip ) { const int x = mapToParent( me->pos() ).x() - m_initialMousePos.x(); TimePos t = qMax( 0, (int) m_trackView->trackContainerView()->currentPosition() + static_cast<int>( x * TimePos::ticksPerBar() / ppb ) ); if( unquantizedModHeld(me) ) { // We want to preserve this adjusted offset, // even if the user switches to snapping later setInitialPos( m_initialMousePos ); //Don't resize to less than 1 tick t = qMin<int>( m_initialClipEnd - 1, t); } else if( me->modifiers() & Qt::ShiftModifier ) { // If shift is held, quantize clip's start position // Don't let the start position move past the end position TimePos max = m_initialClipEnd.quantize( snapSize ); if ( max >= m_initialClipEnd ) max -= snapLength; t = qMin<int>( max, t.quantize( snapSize ) ); } else { // Otherwise, resize in fixed increments // Don't resize to less than 1 tick TimePos initialLength = m_initialClipEnd - m_initialClipPos; auto minLength = TimePos(initialLength % snapLength); if (minLength < 1) minLength += snapLength; TimePos offset = TimePos(t - m_initialClipPos).quantize( snapSize ); t = qMin<int>( m_initialClipEnd - minLength, m_initialClipPos + offset ); } TimePos positionOffset = m_clip->startPosition() - t; if (m_clip->length() + positionOffset >= 1) { m_clip->movePosition(t); m_clip->changeLength(m_clip->length() + positionOffset); if (sClip) { sClip->setStartTimeOffset(sClip->startTimeOffset() + positionOffset); } else if (pClip) { // Modulus the start time offset as we need it only for offsets // inside the pattern length. This is done to prevent a value overflow. // The start time offset may still become larger than the pattern length // whenever the pattern length decreases without a clip resize following. // To deal safely with it, always modulus before use. tick_t patternLength = Engine::patternStore()->lengthOfPattern(pClip->patternIndex()) * TimePos::ticksPerBar(); TimePos position = (pClip->startTimeOffset() + positionOffset) % patternLength; pClip->setStartTimeOffset(position); } } } } s_textFloat->setText( tr( "%1:%2 (%3:%4 to %5:%6)" ). arg( m_clip->length().getBar() ). arg( m_clip->length().getTicks() % TimePos::ticksPerBar() ). arg( m_clip->startPosition().getBar() + 1 ). arg( m_clip->startPosition().getTicks() % TimePos::ticksPerBar() ). arg( m_clip->endPosition().getBar() + 1 ). arg( m_clip->endPosition().getTicks() % TimePos::ticksPerBar() ) ); s_textFloat->moveGlobal( this, QPoint( width() + 2, height() + 2) ); } else if( m_action == Action::Split ) { auto sClip = dynamic_cast<SampleClip*>(m_clip); if (sClip) { setCursor( m_cursorKnife ); setMarkerPos( knifeMarkerPos( me ) ); } update(); } // None of the actions above, we will just handle the cursor else { updateCursor(me); } } /*! \brief Handle a mouse release on this ClipView. * * If we're in move or resize mode, journal the change as appropriate. * Then tidy up. * * \param me The QMouseEvent to handle. */ void ClipView::mouseReleaseEvent( QMouseEvent * me ) { // If the Action::CopySelection was chosen as the action due to mouse movement, // it will have been cleared. At this point Toggle is the desired action. // An active StringPairDrag will prevent this method from being called, // so a real Action::CopySelection would not have occurred. if( m_action == Action::CopySelection || ( m_action == Action::ToggleSelected && mouseMovedDistance( me, 2 ) == false ) ) { setSelected( !isSelected() ); } else if( m_action == Action::Move || m_action == Action::Resize || m_action == Action::ResizeLeft ) { // TODO: Fix m_clip->setJournalling() consistency m_clip->setJournalling( true ); } else if( m_action == Action::Split ) { const float ppb = m_trackView->trackContainerView()->pixelsPerBar(); const TimePos relPos = me->pos().x() * TimePos::ticksPerBar() / ppb; splitClip(unquantizedModHeld(me) ? relPos : quantizeSplitPos(relPos, me->modifiers() & Qt::ShiftModifier) ); } m_action = Action::None; delete m_hint; m_hint = nullptr; s_textFloat->hide(); updateCursor(me); selectableObject::mouseReleaseEvent( me ); } /*! \brief Set up the context menu for this ClipView. * * Set up the various context menu events that can apply to a * ClipView. * * \param cme The QContextMenuEvent to add the actions to. */ void ClipView::contextMenuEvent( QContextMenuEvent * cme ) { QVector<ClipView*> selectedClips = getClickedClips(); // Depending on whether we right-clicked a selection or an individual Clip we will have // different labels for the actions. bool individualClip = selectedClips.size() <= 1; if( cme->modifiers() ) { return; } QMenu contextMenu( this ); if( fixedClips() == false ) { contextMenu.addAction( embed::getIconPixmap( "cancel" ), individualClip ? tr("Delete (middle mousebutton)") : tr("Delete selection (middle mousebutton)"), [this](){ contextMenuAction( ContextMenuAction::Remove ); } ); contextMenu.addSeparator(); contextMenu.addAction( embed::getIconPixmap( "edit_cut" ), individualClip ? tr("Cut") : tr("Cut selection"), [this](){ contextMenuAction( ContextMenuAction::Cut ); } ); if (canMergeSelection(selectedClips)) { contextMenu.addAction( embed::getIconPixmap("edit_merge"), tr("Merge Selection"), [this]() { contextMenuAction(ContextMenuAction::Merge); } ); } } contextMenu.addAction( embed::getIconPixmap( "edit_copy" ), individualClip ? tr("Copy") : tr("Copy selection"), [this](){ contextMenuAction( ContextMenuAction::Copy ); } ); contextMenu.addAction( embed::getIconPixmap( "edit_paste" ), tr( "Paste" ), [this](){ contextMenuAction( ContextMenuAction::Paste ); } ); contextMenu.addSeparator(); contextMenu.addAction( embed::getIconPixmap( "muted" ), (individualClip ? tr("Mute/unmute (<%1> + middle click)") : tr("Mute/unmute selection (<%1> + middle click)")).arg(UI_CTRL_KEY), [this](){ contextMenuAction( ContextMenuAction::Mute ); } ); contextMenu.addSeparator(); QMenu colorMenu (tr("Clip color"), this); colorMenu.setIcon(embed::getIconPixmap("colorize")); colorMenu.addAction(tr("Change"), this, SLOT(selectColor())); colorMenu.addAction(tr("Reset"), this, SLOT(resetColor())); colorMenu.addAction(tr("Pick random"), this, SLOT(randomizeColor())); contextMenu.addMenu(&colorMenu); constructContextMenu( &contextMenu ); contextMenu.exec( QCursor::pos() ); } // This method processes the actions from the context menu of the Clip View. void ClipView::contextMenuAction( ContextMenuAction action ) { QVector<ClipView *> active = getClickedClips(); // active will be later used for the remove, copy, cut or toggleMute methods switch( action ) { case ContextMenuAction::Remove: remove( active ); break; case ContextMenuAction::Cut: cut( active ); break; case ContextMenuAction::Copy: copy( active ); break; case ContextMenuAction::Paste: paste(); break; case ContextMenuAction::Mute: toggleMute( active ); break; case ContextMenuAction::Merge: mergeClips(active); break; } } QVector<ClipView *> ClipView::getClickedClips() { // Get a list of selected selectableObjects QVector<selectableObject *> sos = getGUI()->songEditor()->m_editor->selectedObjects(); // Convert to a list of selected ClipVs QVector<ClipView *> selection; selection.reserve( sos.size() ); for( auto so: sos ) { auto clipv = dynamic_cast<ClipView*>(so); if( clipv != nullptr ) { selection.append( clipv ); } } // If we clicked part of the selection, affect all selected clips. Otherwise affect the clip we clicked return selection.contains(this) ? selection : QVector<ClipView *>( 1, this ); } void ClipView::remove( QVector<ClipView *> clipvs ) { for( auto clipv: clipvs ) { // No need to check if it's nullptr because we check when building the QVector clipv->remove(); } } void ClipView::copy( QVector<ClipView *> clipvs ) { // For copyStringPair() using namespace Clipboard; // Write the Clips to a DataFile for copying DataFile dataFile = createClipDataFiles( clipvs ); // Copy the Clip type as a key and the Clip data file to the clipboard copyStringPair( QString( "clip_%1" ).arg( static_cast<int>(m_clip->getTrack()->type()) ), dataFile.toString() ); } void ClipView::cut( QVector<ClipView *> clipvs ) { // Copy the selected Clips copy( clipvs ); // Now that the Clips are copied we can delete them, since we are cutting remove( clipvs ); } void ClipView::paste() { // For getMimeData() using namespace Clipboard; // If possible, paste the selection on the TimePos of the selected Track and remove it TimePos clipPos{m_clip->startPosition()}; TrackContentWidget *tcw = getTrackView()->getTrackContentWidget(); if( tcw->pasteSelection( clipPos, getMimeData() ) ) { // If we succeed on the paste we delete the Clip we pasted on remove(); } } void ClipView::toggleMute( QVector<ClipView *> clipvs ) { for( auto clipv: clipvs ) { // No need to check for nullptr because we check while building the clipvs QVector clipv->getClip()->toggleMute(); } } bool ClipView::canMergeSelection(QVector<ClipView*> clipvs) { // Can't merge a single Clip if (clipvs.size() < 2) { return false; } // We check if the owner of the first Clip is an Instrument Track bool isInstrumentTrack = dynamic_cast<InstrumentTrackView*>(clipvs.at(0)->getTrackView()); // Then we create a set with all the Clips owners std::set<TrackView*> ownerTracks; for (auto clipv: clipvs) { ownerTracks.insert(clipv->getTrackView()); } // Can merge if there's only one owner track and it's an Instrument Track return isInstrumentTrack && ownerTracks.size() == 1; } void ClipView::mergeClips(QVector<ClipView*> clipvs) { // Get the track that we are merging Clips in auto track = dynamic_cast<InstrumentTrack*>(clipvs.at(0)->getTrackView()->getTrack()); if (!track) { qWarning("Warning: Couldn't retrieve InstrumentTrack in mergeClips()"); return; } // For Undo/Redo track->addJournalCheckPoint(); track->saveJournallingState(false); // Find the earliest position of all the selected ClipVs const auto earliestClipV = std::min_element(clipvs.constBegin(), clipvs.constEnd(), [](ClipView* a, ClipView* b) { return a->getClip()->startPosition() < b->getClip()->startPosition(); } ); const TimePos earliestPos = (*earliestClipV)->getClip()->startPosition(); // Create a clip where all notes will be added auto newMidiClip = dynamic_cast<MidiClip*>(track->createClip(earliestPos)); if (!newMidiClip) { qWarning("Warning: Failed to convert Clip to MidiClip on mergeClips"); return; } newMidiClip->saveJournallingState(false); // Add the notes and remove the Clips that are being merged for (auto clipv: clipvs) { // Convert ClipV to MidiClipView auto mcView = dynamic_cast<MidiClipView*>(clipv); if (!mcView) { qWarning("Warning: Non-MidiClip Clip on InstrumentTrack"); continue; } const NoteVector& currentClipNotes = mcView->getMidiClip()->notes(); TimePos mcViewPos = mcView->getMidiClip()->startPosition(); for (Note* note: currentClipNotes) { Note* newNote = newMidiClip->addNote(*note, false); TimePos originalNotePos = newNote->pos(); newNote->setPos(originalNotePos + (mcViewPos - earliestPos)); } // We disable the journalling system before removing, so the // removal doesn't get added to the undo/redo history clipv->getClip()->saveJournallingState(false); // No need to check for nullptr because we check while building the clipvs QVector clipv->remove(); } // Update length since we might have moved notes beyond the end of the MidiClip length newMidiClip->updateLength(); // Rearrange notes because we might have moved them newMidiClip->rearrangeAllNotes(); // Restore journalling states now that the operation is finished newMidiClip->restoreJournallingState(); track->restoreJournallingState(); // Update song Engine::getSong()->setModified(); getGUI()->songEditor()->update(); } /*! \brief How many pixels a bar takes for this ClipView. * * \return the number of pixels per bar. */ float ClipView::pixelsPerBar() { return m_trackView->trackContainerView()->pixelsPerBar(); } /*! \brief Save the offsets between all selected tracks and a clicked track */ void ClipView::setInitialOffsets() { QVector<selectableObject *> so = m_trackView->trackContainerView()->selectedObjects(); QVector<TimePos> offsets; for (const auto& selectedClip : so) { auto clipv = dynamic_cast<ClipView*>(selectedClip); if( clipv == nullptr ) { continue; } offsets.push_back( clipv->m_clip->startPosition() - m_initialClipPos ); } m_initialOffsets = offsets; } /*! \brief Detect whether the mouse moved more than n pixels on screen. * * \param _me The QMouseEvent. * \param distance The threshold distance that the mouse has moved to return true. */ bool ClipView::mouseMovedDistance( QMouseEvent * me, int distance ) { QPoint dPos = mapToGlobal( me->pos() ) - m_initialMouseGlobalPos; const int pixelsMoved = dPos.manhattanLength(); return ( pixelsMoved > distance || pixelsMoved < -distance ); } bool ClipView::unquantizedModHeld( QMouseEvent * me ) { return me->modifiers() & Qt::ControlModifier || me->modifiers() & Qt::AltModifier; } /*! \brief Calculate the new position of a dragged Clip from a mouse event * * * \param me The QMouseEvent */ TimePos ClipView::draggedClipPos( QMouseEvent * me ) { //Pixels per bar const float ppb = m_trackView->trackContainerView()->pixelsPerBar(); // The pixel distance that the mouse has moved const int mouseOff = mapToGlobal(me->pos()).x() - m_initialMouseGlobalPos.x(); TimePos newPos = m_initialClipPos + mouseOff * TimePos::ticksPerBar() / ppb; TimePos offset = newPos - m_initialClipPos; // If the user is holding alt, or pressed ctrl after beginning the drag, don't quantize if ( me->button() != Qt::NoButton || unquantizedModHeld(me) ) { // We want to preserve this adjusted offset, even if the user switches to snapping setInitialPos( m_initialMousePos ); } else if ( me->modifiers() & Qt::ShiftModifier ) { // If shift is held, quantize position (Default in 1.2.0 and earlier) // or end position, whichever is closest to the actual position TimePos startQ = newPos.quantize( getGUI()->songEditor()->m_editor->getSnapSize() ); // Find start position that gives snapped clip end position TimePos endQ = ( newPos + m_clip->length() ); endQ = endQ.quantize( getGUI()->songEditor()->m_editor->getSnapSize() ); endQ = endQ - m_clip->length(); // Select the position closest to actual position if ( abs(newPos - startQ) < abs(newPos - endQ) ) newPos = startQ; else newPos = endQ; } else { // Otherwise, quantize moved distance (preserves user offsets) newPos = m_initialClipPos + offset.quantize( getGUI()->songEditor()->m_editor->getSnapSize() ); } return newPos; } int ClipView::knifeMarkerPos( QMouseEvent * me ) { //Position relative to start of clip const int markerPos = me->pos().x(); //In unquantized mode, we don't have to mess with the position at all if ( unquantizedModHeld(me) ) { return markerPos; } else { //Otherwise we... //1: Convert the position to a TimePos const float ppb = m_trackView->trackContainerView()->pixelsPerBar(); TimePos midiPos = markerPos * TimePos::ticksPerBar() / ppb; //2: Snap to the correct position, based on modifier keys midiPos = quantizeSplitPos( midiPos, me->modifiers() & Qt::ShiftModifier ); //3: Convert back to a pixel position return midiPos * ppb / TimePos::ticksPerBar(); } } TimePos ClipView::quantizeSplitPos( TimePos midiPos, bool shiftMode ) { const float snapSize = getGUI()->songEditor()->m_editor->getSnapSize(); if ( shiftMode ) { //If shift is held we quantize the length of the new left clip... const TimePos leftPos = midiPos.quantize( snapSize ); //...or right clip... const TimePos rightOff = m_clip->length() - midiPos; const TimePos rightPos = m_clip->length() - rightOff.quantize( snapSize ); //...whichever gives a position closer to the cursor if ( abs(leftPos - midiPos) < abs(rightPos - midiPos) ) { return leftPos; } else { return rightPos; } } else { return TimePos(midiPos + m_initialClipPos).quantize( snapSize ) - m_initialClipPos; } } // Return the color that the Clip's background should be QColor ClipView::getColorForDisplay( QColor defaultColor ) { // Get the pure Clip color auto clipColor = m_clip->color().value_or(m_clip->getTrack()->color().value_or(defaultColor)); // Set variables QColor c, mutedCustomColor; bool muted = m_clip->getTrack()->isMuted() || m_clip->isMuted(); mutedCustomColor = clipColor; mutedCustomColor.setHsv( mutedCustomColor.hsvHue(), mutedCustomColor.hsvSaturation() / 4, mutedCustomColor.value() ); // Change the pure color by state: selected, muted, colored, normal if( isSelected() ) { c = hasCustomColor() ? ( muted ? mutedCustomColor.darker( 350 ) : clipColor.darker( 150 ) ) : selectedColor(); } else { if( muted ) { c = hasCustomColor() ? mutedCustomColor.darker( 250 ) : mutedBackgroundColor(); } else { c = clipColor; } } // Return color to caller return c; } auto ClipView::hasCustomColor() const -> bool { return m_clip->color().has_value() || m_clip->getTrack()->color().has_value(); } } // namespace lmms::gui
44,544
C++
.cpp
1,295
31.500386
134
0.704379
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,925
PatternClipView.cpp
LMMS_lmms/src/gui/clips/PatternClipView.cpp
/* * PatternClipView.cpp * * 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. * */ #include "PatternClipView.h" #include <QApplication> #include <QMenu> #include <QPainter> #include "Engine.h" #include "GuiApplication.h" #include "MainWindow.h" #include "PatternClip.h" #include "PatternStore.h" #include "RenameDialog.h" namespace lmms::gui { PatternClipView::PatternClipView(Clip* _clip, TrackView* _tv) : ClipView( _clip, _tv ), m_patternClip(dynamic_cast<PatternClip*>(_clip)), m_paintPixmap() { connect( _clip->getTrack(), SIGNAL(dataChanged()), this, SLOT(update())); setStyle( QApplication::style() ); } void PatternClipView::constructContextMenu(QMenu* _cm) { auto a = new QAction(embed::getIconPixmap("pattern_track"), tr("Open in Pattern Editor"), _cm); _cm->insertAction( _cm->actions()[0], a ); connect( a, SIGNAL(triggered(bool)), this, SLOT(openInPatternEditor())); _cm->insertSeparator( _cm->actions()[1] ); _cm->addSeparator(); _cm->addAction( embed::getIconPixmap( "reload" ), tr( "Reset name" ), this, SLOT(resetName())); _cm->addAction( embed::getIconPixmap( "edit_rename" ), tr( "Change name" ), this, SLOT(changeName())); } void PatternClipView::mouseDoubleClickEvent(QMouseEvent*) { openInPatternEditor(); } void PatternClipView::paintEvent(QPaintEvent*) { QPainter painter( this ); if( !needsUpdate() ) { painter.drawPixmap( 0, 0, m_paintPixmap ); return; } setNeedsUpdate( false ); if (m_paintPixmap.isNull() || m_paintPixmap.size() != size()) { m_paintPixmap = QPixmap(size()); } QPainter p( &m_paintPixmap ); QLinearGradient lingrad( 0, 0, 0, height() ); QColor c = getColorForDisplay( painter.background().color() ); lingrad.setColorAt( 0, c.lighter( 130 ) ); lingrad.setColorAt( 1, c.lighter( 70 ) ); // paint a black rectangle under the clip to prevent glitches with transparent backgrounds p.fillRect( rect(), QColor( 0, 0, 0 ) ); if( gradient() ) { p.fillRect( rect(), lingrad ); } else { p.fillRect( rect(), c ); } // bar lines const int lineSize = 3; int pixelsPerPattern = Engine::patternStore()->lengthOfPattern(m_patternClip->patternIndex()) * pixelsPerBar(); int offset = static_cast<int>(m_patternClip->startTimeOffset() * (pixelsPerBar() / TimePos::ticksPerBar())) % pixelsPerPattern; if (offset < 2) { offset += pixelsPerPattern; } p.setPen( c.darker( 200 ) ); if (pixelsPerPattern > 0) { for (int x = offset; x < width() - 2; x += pixelsPerPattern) { p.drawLine( x, BORDER_WIDTH, x, BORDER_WIDTH + lineSize ); p.drawLine( x, rect().bottom() - ( BORDER_WIDTH + lineSize ), x, rect().bottom() - BORDER_WIDTH ); } } // clip name paintTextLabel(m_patternClip->name(), p); // inner border p.setPen( c.lighter( 130 ) ); p.drawRect( 1, 1, rect().right() - BORDER_WIDTH, rect().bottom() - BORDER_WIDTH ); // outer border p.setPen( c.darker( 300 ) ); p.drawRect( 0, 0, rect().right(), rect().bottom() ); // draw the 'muted' pixmap only if the clip was manualy muted if (m_patternClip->isMuted()) { const int spacing = BORDER_WIDTH; const int size = 14; p.drawPixmap( spacing, height() - ( size + spacing ), embed::getIconPixmap( "muted", size, size ) ); } p.end(); painter.drawPixmap( 0, 0, m_paintPixmap ); } void PatternClipView::openInPatternEditor() { Engine::patternStore()->setCurrentPattern(m_patternClip->patternIndex()); getGUI()->mainWindow()->togglePatternEditorWin(true); } void PatternClipView::resetName() { m_patternClip->setName(""); } void PatternClipView::changeName() { QString s = m_patternClip->name(); RenameDialog rename_dlg( s ); rename_dlg.exec(); m_patternClip->setName(s); } void PatternClipView::update() { setToolTip(m_patternClip->name()); ClipView::update(); } } // namespace lmms::gui
4,659
C++
.cpp
147
29.238095
112
0.707295
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,926
MidiClipView.cpp
LMMS_lmms/src/gui/clips/MidiClipView.cpp
/* * MidiClipView.cpp - implementation of class MidiClipView which displays notes * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * Copyright (c) 2005-2007 Danny McRae <khjklujn/at/yahoo.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. * */ #include "MidiClipView.h" #include <algorithm> #include <cmath> #include <QApplication> #include <QInputDialog> #include <QMenu> #include <QPainter> #include <cmath> #include "AutomationEditor.h" #include "ConfigManager.h" #include "DeprecationHelper.h" #include "GuiApplication.h" #include "MidiClip.h" #include "PianoRoll.h" #include "RenameDialog.h" #include "TrackView.h" namespace lmms::gui { constexpr int BeatStepButtonOffset = 4; MidiClipView::MidiClipView( MidiClip* clip, TrackView* parent ) : ClipView( clip, parent ), m_clip( clip ), m_paintPixmap(), m_noteFillColor(255, 255, 255, 220), m_noteBorderColor(255, 255, 255, 220), m_mutedNoteFillColor(100, 100, 100, 220), m_mutedNoteBorderColor(100, 100, 100, 220), // TODO if this option is ever added to the GUI, rename it to legacysepattern m_legacySEPattern(ConfigManager::inst()->value("ui", "legacysebb", "0").toInt()) { connect( getGUI()->pianoRoll(), SIGNAL(currentMidiClipChanged()), this, SLOT(update())); update(); setStyle( QApplication::style() ); } MidiClip* MidiClipView::getMidiClip() { return m_clip; } void MidiClipView::update() { setToolTip(m_clip->name()); ClipView::update(); } void MidiClipView::openInPianoRoll() { auto pRoll = getGUI()->pianoRoll(); pRoll->setCurrentMidiClip(m_clip); pRoll->parentWidget()->show(); pRoll->show(); pRoll->setFocus(); } void MidiClipView::setGhostInPianoRoll() { auto pRoll = getGUI()->pianoRoll(); pRoll->setGhostMidiClip(m_clip); pRoll->parentWidget()->show(); pRoll->show(); pRoll->setFocus(); } void MidiClipView::setGhostInAutomationEditor() { auto aEditor = getGUI()->automationEditor(); aEditor->setGhostMidiClip(m_clip); aEditor->parentWidget()->show(); aEditor->show(); aEditor->setFocus(); } void MidiClipView::resetName() { m_clip->setName(""); } void MidiClipView::changeName() { QString s = m_clip->name(); RenameDialog rename_dlg( s ); rename_dlg.exec(); m_clip->setName( s ); } void MidiClipView::transposeSelection() { const auto selection = getClickedClips(); // Calculate the key boundries for all clips int highest = 0; int lowest = NumKeys - 1; for (ClipView* clipview: selection) { if (auto mcv = qobject_cast<MidiClipView*>(clipview)) { if (auto bounds = boundsForNotes(mcv->getMidiClip()->notes())) { lowest = std::min(bounds->lowest, lowest); highest = std::max(bounds->highest, highest); } } } int semitones = QInputDialog::getInt(this, tr("Transpose"), tr("Semitones to transpose by:"), /*start*/ 0, /*min*/ -lowest, /*max*/ (NumKeys - 1 - highest)); if (semitones == 0) { return; } // TODO make this not crash // Engine::getSong()->addJournalCheckPoint(); QSet<Track*> m_changedTracks; for (ClipView* clipview: selection) { auto mcv = qobject_cast<MidiClipView*>(clipview); if (!mcv) { continue; } auto clip = mcv->getMidiClip(); if (clip->notes().empty()) { continue; } auto track = clipview->getTrackView()->getTrack(); if (!m_changedTracks.contains(track)) { track->addJournalCheckPoint(); m_changedTracks.insert(track); } for (Note* note: clip->notes()) { note->setKey(note->key() + semitones); } emit clip->dataChanged(); } // At least one clip must have notes to show the transpose dialog, so something *has* changed Engine::getSong()->setModified(); } void MidiClipView::constructContextMenu( QMenu * _cm ) { bool isBeat = m_clip->type() == MidiClip::Type::BeatClip; auto a = new QAction(embed::getIconPixmap("piano"), tr("Open in piano-roll"), _cm); _cm->insertAction( _cm->actions()[0], a ); connect( a, SIGNAL(triggered(bool)), this, SLOT(openInPianoRoll())); auto b = new QAction(embed::getIconPixmap("ghost_note"), tr("Set as ghost in piano-roll"), _cm); if( m_clip->empty() ) { b->setEnabled( false ); } _cm->insertAction( _cm->actions()[1], b ); connect( b, SIGNAL(triggered(bool)), this, SLOT(setGhostInPianoRoll())); auto c = new QAction(embed::getIconPixmap("automation_ghost_note"), tr("Set as ghost in automation editor"), _cm); if (m_clip->empty()) { c->setEnabled(false); } _cm->insertAction(_cm->actions()[2], c); connect(c, &QAction::triggered, this, &MidiClipView::setGhostInAutomationEditor); _cm->insertSeparator(_cm->actions()[3]); _cm->addSeparator(); _cm->addAction( embed::getIconPixmap( "edit_erase" ), tr( "Clear all notes" ), m_clip, SLOT(clear())); if (!isBeat) { _cm->addAction(embed::getIconPixmap("scale"), tr("Transpose"), this, &MidiClipView::transposeSelection); } _cm->addSeparator(); _cm->addAction( embed::getIconPixmap( "reload" ), tr( "Reset name" ), this, SLOT(resetName())); _cm->addAction( embed::getIconPixmap( "edit_rename" ), tr( "Change name" ), this, SLOT(changeName())); if (isBeat) { _cm->addSeparator(); _cm->addAction( embed::getIconPixmap( "step_btn_add" ), tr( "Add steps" ), m_clip, SLOT(addSteps())); _cm->addAction( embed::getIconPixmap( "step_btn_remove" ), tr( "Remove steps" ), m_clip, SLOT(removeSteps())); _cm->addAction( embed::getIconPixmap( "step_btn_duplicate" ), tr( "Clone Steps" ), m_clip, SLOT(cloneSteps())); } } void MidiClipView::mousePressEvent( QMouseEvent * _me ) { bool displayPattern = fixedClips() || (pixelsPerBar() >= 96 && m_legacySEPattern); if (_me->button() == Qt::LeftButton && m_clip->m_clipType == MidiClip::Type::BeatClip && displayPattern && _me->y() > BeatStepButtonOffset && _me->y() < BeatStepButtonOffset + m_stepBtnOff.height()) // when mouse button is pressed in pattern mode { // get the step number that was clicked on and // do calculations in floats to prevent rounding errors... float tmp = ( ( float(_me->x()) - BORDER_WIDTH ) * float( m_clip -> m_steps ) ) / float(width() - BORDER_WIDTH*2); int step = int( tmp ); // debugging to ensure we get the correct step... // qDebug( "Step (%f) %d", tmp, step ); if( step >= m_clip->m_steps ) { qDebug( "Something went wrong in clip.cpp: step %d doesn't exist in clip!", step ); return; } Note * n = m_clip->noteAtStep( step ); if( n == nullptr ) { m_clip->addStepNote( step ); } else // note at step found { m_clip->addJournalCheckPoint(); m_clip->setStep( step, false ); } Engine::getSong()->setModified(); update(); if( getGUI()->pianoRoll()->currentMidiClip() == m_clip ) { getGUI()->pianoRoll()->update(); } } else // if not in pattern mode, let parent class handle the event { ClipView::mousePressEvent( _me ); } } void MidiClipView::mouseDoubleClickEvent(QMouseEvent *_me) { if( _me->button() != Qt::LeftButton ) { _me->ignore(); return; } if( m_clip->m_clipType == MidiClip::Type::MelodyClip || !fixedClips() ) { openInPianoRoll(); } } void MidiClipView::wheelEvent(QWheelEvent * we) { if(m_clip->m_clipType == MidiClip::Type::BeatClip && (fixedClips() || pixelsPerBar() >= 96) && position(we).y() > height() - m_stepBtnOff.height()) { // get the step number that was wheeled on and // do calculations in floats to prevent rounding errors... float tmp = ((float(position(we).x()) - BORDER_WIDTH) * float(m_clip -> m_steps)) / float(width() - BORDER_WIDTH*2); int step = int( tmp ); if( step >= m_clip->m_steps ) { return; } Note * n = m_clip->noteAtStep( step ); const int direction = (we->angleDelta().y() > 0 ? 1 : -1) * (we->inverted() ? -1 : 1); if(!n && direction > 0) { n = m_clip->addStepNote( step ); n->setVolume( 0 ); } if( n != nullptr ) { int vol = n->getVolume(); if(direction > 0) { n->setVolume( qMin( 100, vol + 5 ) ); } else { n->setVolume( qMax( 0, vol - 5 ) ); } Engine::getSong()->setModified(); update(); if( getGUI()->pianoRoll()->currentMidiClip() == m_clip ) { getGUI()->pianoRoll()->update(); } } we->accept(); } else { ClipView::wheelEvent(we); } } static int computeNoteRange(int minKey, int maxKey) { return (maxKey - minKey) + 1; } void MidiClipView::paintEvent( QPaintEvent * ) { QPainter painter( this ); if( !needsUpdate() ) { painter.drawPixmap( 0, 0, m_paintPixmap ); return; } setNeedsUpdate( false ); if (m_paintPixmap.isNull() || m_paintPixmap.size() != size()) { m_paintPixmap = QPixmap(size()); } QPainter p( &m_paintPixmap ); QColor c; bool const muted = m_clip->getTrack()->isMuted() || m_clip->isMuted(); bool current = getGUI()->pianoRoll()->currentMidiClip() == m_clip; bool beatClip = m_clip->m_clipType == MidiClip::Type::BeatClip; if( beatClip ) { // Do not paint PatternClips how we paint MidiClips c = patternClipBackground(); } else { c = getColorForDisplay( painter.background().color() ); } // invert the gradient for the background in the B&B editor QLinearGradient lingrad( 0, 0, 0, height() ); lingrad.setColorAt( beatClip ? 0 : 1, c.darker( 300 ) ); lingrad.setColorAt( beatClip ? 1 : 0, c ); // paint a black rectangle under the clip to prevent glitches with transparent backgrounds p.fillRect( rect(), QColor( 0, 0, 0 ) ); if( gradient() ) { p.fillRect( rect(), lingrad ); } else { p.fillRect( rect(), c ); } // Check whether we will paint a text box and compute its potential height // This is needed so we can paint the notes underneath it. bool const drawName = !m_clip->name().isEmpty(); bool const drawTextBox = !beatClip && drawName; // TODO Warning! This might cause problems if ClipView::paintTextLabel changes int textBoxHeight = 0; const int textTop = BORDER_WIDTH + 1; if (drawTextBox) { QFont labelFont = this->font(); labelFont.setHintingPreference( QFont::PreferFullHinting ); QFontMetrics fontMetrics(labelFont); textBoxHeight = fontMetrics.height() + 2 * textTop; } // Compute pixels per bar const int baseWidth = fixedClips() ? parentWidget()->width() - 2 * BORDER_WIDTH : width() - BORDER_WIDTH; const float pixelsPerBar = baseWidth / (float) m_clip->length().getBar(); // Length of one bar/beat in the [0,1] x [0,1] coordinate system const float barLength = 1. / m_clip->length().getBar(); const float tickLength = barLength / TimePos::ticksPerBar(); const int x_base = BORDER_WIDTH; bool displayPattern = fixedClips() || (pixelsPerBar >= 96 && m_legacySEPattern); NoteVector const & noteCollection = m_clip->m_notes; // Beat clip paint event (on BB Editor) if (beatClip && displayPattern) { QPixmap stepon0; QPixmap stepon200; QPixmap stepoff; QPixmap stepoffl; const int steps = std::max(1, m_clip->m_steps); const int w = width() - 2 * BORDER_WIDTH; // scale step graphics to fit the beat clip length stepon0 = m_stepBtnOn0.scaled(w / steps, m_stepBtnOn0.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); stepon200 = m_stepBtnOn200.scaled( w / steps, m_stepBtnOn200.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); stepoff = m_stepBtnOff.scaled(w / steps, m_stepBtnOff.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); stepoffl = m_stepBtnOffLight.scaled( w / steps, m_stepBtnOffLight.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); for (int it = 0; it < steps; it++) // go through all the steps in the beat clip { Note* n = m_clip->noteAtStep(it); // figure out x and y coordinates for step graphic const int x = BORDER_WIDTH + static_cast<int>(it * w / steps); const int y = BeatStepButtonOffset; if (n) { const int vol = n->getVolume(); p.drawPixmap(x, y, stepoffl); p.drawPixmap(x, y, stepon0); p.setOpacity(std::sqrt(vol / 200.0)); p.drawPixmap(x, y, stepon200); p.setOpacity(1); } else if ((it / 4) % 2) { p.drawPixmap(x, y, stepoffl); } else { p.drawPixmap(x, y, stepoff); } } // end for loop // draw a transparent rectangle over muted clips if (muted) { p.setBrush(mutedBackgroundColor()); p.setOpacity(0.5); p.drawRect(0, 0, width(), height()); } } // Melody clip and Beat clip (on Song Editor) paint event else if ( !noteCollection.empty() && (m_clip->m_clipType == MidiClip::Type::MelodyClip || m_clip->m_clipType == MidiClip::Type::BeatClip) ) { // Compute the minimum and maximum key in the clip // so that we know how much there is to draw. int maxKey = std::numeric_limits<int>::min(); int minKey = std::numeric_limits<int>::max(); for (Note const * note : noteCollection) { int const key = note->key(); maxKey = qMax( maxKey, key ); minKey = qMin( minKey, key ); } // If needed adjust the note range so that we always have paint a certain interval int const minimalNoteRange = 12; // Always paint at least one octave int const actualNoteRange = computeNoteRange(minKey, maxKey); if (actualNoteRange < minimalNoteRange) { int missingNumberOfNotes = minimalNoteRange - actualNoteRange; minKey = std::max(0, minKey - missingNumberOfNotes / 2); maxKey = maxKey + missingNumberOfNotes / 2; if (missingNumberOfNotes % 2 == 1) { // Put more range at the top to bias drawing towards the bottom ++maxKey; } } int const adjustedNoteRange = computeNoteRange(minKey, maxKey); // Transform such that [0, 1] x [0, 1] paints in the correct area float distanceToTop = textBoxHeight; // This moves the notes smoothly under the text int widgetHeight = height(); int fullyAtTopAtLimit = MINIMAL_TRACK_HEIGHT; int fullyBelowAtLimit = 4 * fullyAtTopAtLimit; if (widgetHeight <= fullyBelowAtLimit) { if (widgetHeight <= fullyAtTopAtLimit) { distanceToTop = 0; } else { float const a = 1. / (fullyAtTopAtLimit - fullyBelowAtLimit); float const b = - float(fullyBelowAtLimit) / (fullyAtTopAtLimit - fullyBelowAtLimit); float const scale = a * widgetHeight + b; distanceToTop = (1. - scale) * textBoxHeight; } } int const notesBorder = 4; // Border for the notes towards the top and bottom in pixels // The relavant painting code starts here p.save(); p.translate(0., distanceToTop + notesBorder); p.scale(width(), height() - distanceToTop - 2 * notesBorder); // set colour based on mute status QColor noteFillColor = muted ? getMutedNoteFillColor().lighter(200) : (c.lightness() > 175 ? getNoteFillColor().darker(400) : getNoteFillColor()); QColor noteBorderColor = muted ? getMutedNoteBorderColor() : (hasCustomColor() ? c.lighter(200) : getNoteBorderColor()); bool const drawAsLines = height() < 64; if (drawAsLines) { p.setPen(noteFillColor); } else { p.setPen(noteBorderColor); p.setRenderHint(QPainter::Antialiasing); } // Needed for Qt5 although the documentation for QPainter::setPen(QColor) as it's used above // states that it should already set a width of 0. QPen pen = p.pen(); pen.setWidth(0); p.setPen(pen); float const noteHeight = 1. / adjustedNoteRange; // scan through all the notes and draw them on the clip for (Note const * currentNote : noteCollection) { // Map to 0, 1, 2, ... int mappedNoteKey = currentNote->key() - minKey; int invertedMappedNoteKey = adjustedNoteRange - mappedNoteKey - 1; float const noteStartX = currentNote->pos() * tickLength; float const noteLength = currentNote->length() * tickLength; float const noteStartY = invertedMappedNoteKey * noteHeight; QRectF noteRectF( noteStartX, noteStartY, noteLength, noteHeight); if (drawAsLines) { p.drawLine(QPointF(noteStartX, noteStartY + 0.5 * noteHeight), QPointF(noteStartX + noteLength, noteStartY + 0.5 * noteHeight)); } else { p.fillRect( noteRectF, noteFillColor ); p.drawRect( noteRectF ); } } p.restore(); } // bar lines const int lineSize = 3; p.setPen( c.darker( 200 ) ); for( bar_t t = 1; t < m_clip->length().getBar(); ++t ) { p.drawLine( x_base + static_cast<int>( pixelsPerBar * t ) - 1, BORDER_WIDTH, x_base + static_cast<int>( pixelsPerBar * t ) - 1, BORDER_WIDTH + lineSize ); p.drawLine( x_base + static_cast<int>( pixelsPerBar * t ) - 1, rect().bottom() - ( lineSize + BORDER_WIDTH ), x_base + static_cast<int>( pixelsPerBar * t ) - 1, rect().bottom() - BORDER_WIDTH ); } // clip name if (drawTextBox) { paintTextLabel(m_clip->name(), p); } if( !( fixedClips() && beatClip ) ) { // inner border p.setPen( c.lighter( current ? 160 : 130 ) ); p.drawRect( 1, 1, rect().right() - BORDER_WIDTH, rect().bottom() - BORDER_WIDTH ); // outer border p.setPen( current ? c.lighter( 130 ) : c.darker( 300 ) ); p.drawRect( 0, 0, rect().right(), rect().bottom() ); } // draw the 'muted' pixmap only if the clip was manually muted if( m_clip->isMuted() ) { const int spacing = BORDER_WIDTH; const int size = 14; p.drawPixmap( spacing, height() - ( size + spacing ), embed::getIconPixmap( "muted", size, size ) ); } painter.drawPixmap( 0, 0, m_paintPixmap ); } } // namespace lmms::gui
17,976
C++
.cpp
546
29.935897
115
0.68453
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,927
AutomationClipView.cpp
LMMS_lmms/src/gui/clips/AutomationClipView.cpp
/* * AutomationClipView.cpp - implementation of view for AutomationClip * * Copyright (c) 2008-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. * */ #include "AutomationClipView.h" #include <QApplication> #include <QMouseEvent> #include <QPainter> #include <QPainterPath> #include <QMenu> #include "AutomationEditor.h" #include "embed.h" #include "GuiApplication.h" #include "ProjectJournal.h" #include "RenameDialog.h" #include "StringPairDrag.h" #include "TextFloat.h" #include "Track.h" #include "Engine.h" namespace lmms::gui { AutomationClipView::AutomationClipView( AutomationClip * _clip, TrackView * _parent ) : ClipView( _clip, _parent ), m_clip( _clip ), m_paintPixmap() { connect( m_clip, SIGNAL(dataChanged()), this, SLOT(update())); connect( getGUI()->automationEditor(), SIGNAL(currentClipChanged()), this, SLOT(update())); setAttribute( Qt::WA_OpaquePaintEvent, true ); setToolTip(m_clip->name()); setStyle( QApplication::style() ); update(); } void AutomationClipView::openInAutomationEditor() { if(getGUI() != nullptr) getGUI()->automationEditor()->open(m_clip); } void AutomationClipView::update() { setToolTip(m_clip->name()); ClipView::update(); } void AutomationClipView::resetName() { m_clip->setName( QString() ); } void AutomationClipView::changeName() { QString s = m_clip->name(); RenameDialog rename_dlg( s ); rename_dlg.exec(); m_clip->setName( s ); update(); } void AutomationClipView::disconnectObject( QAction * _a ) { JournallingObject * j = Engine::projectJournal()-> journallingObject( _a->data().toInt() ); if( j && dynamic_cast<AutomatableModel *>( j ) ) { float oldMin = m_clip->getMin(); float oldMax = m_clip->getMax(); m_clip->m_objects.erase( std::find( m_clip->m_objects.begin(), m_clip->m_objects.end(), dynamic_cast<AutomatableModel *>( j ) ) ); update(); //If automation editor is opened, update its display after disconnection if( getGUI()->automationEditor() ) { getGUI()->automationEditor()->m_editor->updateAfterClipChange(); } //if there is no more connection connected to the AutomationClip if( m_clip->m_objects.size() == 0 ) { //scale the points to fit the new min. and max. value this->scaleTimemapToFit( oldMin, oldMax ); } } } void AutomationClipView::toggleRecording() { m_clip->setRecording( ! m_clip->isRecording() ); update(); } void AutomationClipView::flipY() { m_clip->flipY( m_clip->getMin(), m_clip->getMax() ); update(); } void AutomationClipView::flipX() { m_clip->flipX( m_clip->length() ); update(); } void AutomationClipView::constructContextMenu( QMenu * _cm ) { auto a = new QAction(embed::getIconPixmap("automation"), tr("Open in Automation editor"), _cm); _cm->insertAction( _cm->actions()[0], a ); connect(a, SIGNAL(triggered()), this, SLOT(openInAutomationEditor())); _cm->insertSeparator( _cm->actions()[1] ); _cm->addSeparator(); _cm->addAction( embed::getIconPixmap( "edit_erase" ), tr( "Clear" ), m_clip, SLOT(clear())); _cm->addSeparator(); _cm->addAction( embed::getIconPixmap( "reload" ), tr( "Reset name" ), this, SLOT(resetName())); _cm->addAction( embed::getIconPixmap( "edit_rename" ), tr( "Change name" ), this, SLOT(changeName())); _cm->addAction( embed::getIconPixmap( "record" ), tr( "Set/clear record" ), this, SLOT(toggleRecording())); _cm->addAction( embed::getIconPixmap( "flip_y" ), tr( "Flip Vertically (Visible)" ), this, SLOT(flipY())); _cm->addAction( embed::getIconPixmap( "flip_x" ), tr( "Flip Horizontally (Visible)" ), this, SLOT(flipX())); if (!m_clip->m_objects.empty()) { _cm->addSeparator(); auto m = new QMenu(tr("%1 Connections").arg(m_clip->m_objects.size()), _cm); for (const auto& object : m_clip->m_objects) { if (object) { a = new QAction(tr("Disconnect \"%1\"").arg(object->fullDisplayName()), m); a->setData(object->id()); m->addAction( a ); } } connect( m, SIGNAL(triggered(QAction*)), this, SLOT(disconnectObject(QAction*))); _cm->addMenu( m ); } } void AutomationClipView::mouseDoubleClickEvent( QMouseEvent * me ) { if(me->button() != Qt::LeftButton) { me->ignore(); return; } openInAutomationEditor(); } void AutomationClipView::paintEvent( QPaintEvent * ) { QPainter painter( this ); if( !needsUpdate() ) { painter.drawPixmap( 0, 0, m_paintPixmap ); return; } setNeedsUpdate( false ); if (m_paintPixmap.isNull() || m_paintPixmap.size() != size()) { m_paintPixmap = QPixmap(size()); } QPainter p( &m_paintPixmap ); QLinearGradient lingrad( 0, 0, 0, height() ); QColor c = getColorForDisplay( painter.background().color() ); bool muted = m_clip->getTrack()->isMuted() || m_clip->isMuted(); bool current = getGUI()->automationEditor()->currentClip() == m_clip; lingrad.setColorAt( 1, c.darker( 300 ) ); lingrad.setColorAt( 0, c ); // paint a black rectangle under the clip to prevent glitches with transparent backgrounds p.fillRect( rect(), QColor( 0, 0, 0 ) ); if( gradient() ) { p.fillRect( rect(), lingrad ); } else { p.fillRect( rect(), c ); } // pixels per bar const float ppb = fixedClips() ? ( parentWidget()->width() - 2 * BORDER_WIDTH ) / (float) m_clip->timeMapLength().getBar() : pixelsPerBar(); const auto min = m_clip->firstObject()->minValue<float>(); const auto max = m_clip->firstObject()->maxValue<float>(); const float y_scale = max - min; const float h = ( height() - 2 * BORDER_WIDTH ) / y_scale; const float ppTick = ppb / TimePos::ticksPerBar(); p.translate( 0.0f, max * height() / y_scale - BORDER_WIDTH ); p.scale( 1.0f, -h ); QLinearGradient lin2grad( 0, min, 0, max ); QColor col; col = !muted ? painter.pen().brush().color() : mutedColor(); lin2grad.setColorAt( 1, col.lighter( 150 ) ); lin2grad.setColorAt( 0.5, col ); lin2grad.setColorAt( 0, col.darker( 150 ) ); p.setRenderHints( QPainter::Antialiasing, true ); for( AutomationClip::timeMap::const_iterator it = m_clip->getTimeMap().begin(); it != m_clip->getTimeMap().end(); ++it ) { if( it+1 == m_clip->getTimeMap().end() ) { const float x1 = POS(it) * ppTick; const auto x2 = (float)(width() - BORDER_WIDTH); if( x1 > ( width() - BORDER_WIDTH ) ) break; // We are drawing the space after the last node, so we use the outValue if( gradient() ) { p.fillRect(QRectF(x1, 0.0f, x2 - x1, OUTVAL(it)), lin2grad); } else { p.fillRect(QRectF(x1, 0.0f, x2 - x1, OUTVAL(it)), col); } break; } float *values = m_clip->valuesAfter(POS(it)); // We are creating a path to draw a polygon representing the values between two // nodes. When we have two nodes with discrete progression, we will basically have // a rectangle with the outValue of the first node (that's why nextValue will match // the outValue of the current node). When we have nodes with linear or cubic progression // the value of the end of the shape between the two nodes will be the inValue of // the next node. float nextValue = m_clip->progressionType() == AutomationClip::ProgressionType::Discrete ? OUTVAL(it) : INVAL(it + 1); QPainterPath path; QPointF origin = QPointF(POS(it) * ppTick, 0.0f); path.moveTo( origin ); path.moveTo(QPointF(POS(it) * ppTick,values[0])); for (int i = POS(it) + 1; i < POS(it + 1); i++) { float x = i * ppTick; if( x > ( width() - BORDER_WIDTH ) ) break; float value = values[i - POS(it)]; path.lineTo( QPointF( x, value ) ); } path.lineTo((POS(it + 1)) * ppTick, nextValue); path.lineTo((POS(it + 1)) * ppTick, 0.0f); path.lineTo( origin ); if( gradient() ) { p.fillPath( path, lin2grad ); } else { p.fillPath( path, col ); } delete [] values; } p.setRenderHints( QPainter::Antialiasing, false ); p.resetTransform(); // bar lines const int lineSize = 3; p.setPen( c.darker( 300 ) ); for (bar_t b = 1; b < width() - BORDER_WIDTH; ++b) { const int bx = BORDER_WIDTH + static_cast<int>(ppb * b) - 2; //top line p.drawLine(bx, BORDER_WIDTH, bx, BORDER_WIDTH + lineSize); //bottom line p.drawLine(bx, rect().bottom() - (lineSize + BORDER_WIDTH), bx, rect().bottom() - BORDER_WIDTH); } // recording icon for when recording automation if( m_clip->isRecording() ) { static auto s_clipRec = embed::getIconPixmap("clip_rec"); p.drawPixmap(1, rect().bottom() - s_clipRec.height(), s_clipRec); } // clip name paintTextLabel(m_clip->name(), p); // inner border p.setPen( c.lighter( current ? 160 : 130 ) ); p.drawRect( 1, 1, rect().right() - BORDER_WIDTH, rect().bottom() - BORDER_WIDTH ); // outer border p.setPen( current? c.lighter( 130 ) : c.darker( 300 ) ); p.drawRect( 0, 0, rect().right(), rect().bottom() ); // draw the 'muted' pixmap only if the clip was manualy muted if( m_clip->isMuted() ) { const int spacing = BORDER_WIDTH; const int size = 14; p.drawPixmap( spacing, height() - ( size + spacing ), embed::getIconPixmap( "muted", size, size ) ); } p.end(); painter.drawPixmap( 0, 0, m_paintPixmap ); } void AutomationClipView::dragEnterEvent( QDragEnterEvent * _dee ) { StringPairDrag::processDragEnterEvent( _dee, "automatable_model" ); if( !_dee->isAccepted() ) { ClipView::dragEnterEvent( _dee ); } } void AutomationClipView::dropEvent( QDropEvent * _de ) { QString type = StringPairDrag::decodeKey( _de ); QString val = StringPairDrag::decodeValue( _de ); if( type == "automatable_model" ) { auto mod = dynamic_cast<AutomatableModel*>(Engine::projectJournal()->journallingObject(val.toInt())); if( mod != nullptr ) { bool added = m_clip->addObject( mod ); if ( !added ) { TextFloat::displayMessage( mod->displayName(), tr( "Model is already connected " "to this clip." ), embed::getIconPixmap( "automation" ), 2000 ); } } update(); if( getGUI()->automationEditor() && getGUI()->automationEditor()->currentClip() == m_clip ) { getGUI()->automationEditor()->setCurrentClip( m_clip ); } } else { ClipView::dropEvent( _de ); } } /** * @brief Preserves the auto points over different scale */ void AutomationClipView::scaleTimemapToFit( float oldMin, float oldMax ) { float newMin = m_clip->getMin(); float newMax = m_clip->getMax(); if( oldMin == newMin && oldMax == newMax ) { return; } // TODO: Currently when rescaling the timeMap values to fit the new range of values (newMin and newMax) // only the inValue is being considered and the outValue is being reset to the inValue (so discrete jumps // are discarded). Possibly later we will want discrete jumps to be maintained so we will need to upgrade // the logic to account for them. for( AutomationClip::timeMap::iterator it = m_clip->m_timeMap.begin(); it != m_clip->m_timeMap.end(); ++it ) { // If the values are out of the previous range, fix them so they are // between oldMin and oldMax. if (INVAL(it) < oldMin) { it.value().setInValue(oldMin); } else if (INVAL(it) > oldMax) { it.value().setInValue(oldMax); } // Calculate what the value would be proportionally in the new range it.value().setInValue((INVAL(it) - oldMin) * (newMax - newMin) / (oldMax - oldMin) + newMin); // Read earlier TODO comment: For now I'm discarding the discrete jumps during the rescaling it.value().setOutValue(INVAL(it)); } m_clip->generateTangents(); } } // namespace lmms::gui
12,317
C++
.cpp
385
29.103896
106
0.679462
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,928
SampleClipView.cpp
LMMS_lmms/src/gui/clips/SampleClipView.cpp
/* * SampleClipView.cpp * * 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. * */ #include "SampleClipView.h" #include <QApplication> #include <QMenu> #include <QPainter> #include "GuiApplication.h" #include "AutomationEditor.h" #include "embed.h" #include "PathUtil.h" #include "SampleClip.h" #include "SampleLoader.h" #include "SampleWaveform.h" #include "Song.h" #include "StringPairDrag.h" namespace lmms::gui { SampleClipView::SampleClipView( SampleClip * _clip, TrackView * _tv ) : ClipView( _clip, _tv ), m_clip( _clip ), m_paintPixmap() { // update UI and tooltip updateSample(); // track future changes of SampleClip connect(m_clip, SIGNAL(sampleChanged()), this, SLOT(updateSample())); connect(m_clip, SIGNAL(wasReversed()), this, SLOT(update())); setStyle( QApplication::style() ); } void SampleClipView::updateSample() { update(); // set tooltip to filename so that user can see what sample this // sample-clip contains setToolTip( !m_clip->m_sample.sampleFile().isEmpty() ? PathUtil::toAbsolute(m_clip->m_sample.sampleFile()) : tr("Double-click to open sample") ); } void SampleClipView::constructContextMenu(QMenu* cm) { cm->addSeparator(); /*contextMenu.addAction( embed::getIconPixmap( "record" ), tr( "Set/clear record" ), m_clip, SLOT(toggleRecord()));*/ cm->addAction( embed::getIconPixmap("flip_x"), tr("Reverse sample"), this, SLOT(reverseSample()) ); cm->addAction( embed::getIconPixmap("automation_ghost_note"), tr("Set as ghost in automation editor"), this, SLOT(setAutomationGhost()) ); } void SampleClipView::dragEnterEvent( QDragEnterEvent * _dee ) { if( StringPairDrag::processDragEnterEvent( _dee, "samplefile,sampledata" ) == false ) { ClipView::dragEnterEvent( _dee ); } } void SampleClipView::dropEvent( QDropEvent * _de ) { if( StringPairDrag::decodeKey( _de ) == "samplefile" ) { m_clip->setSampleFile( StringPairDrag::decodeValue( _de ) ); _de->accept(); } else if( StringPairDrag::decodeKey( _de ) == "sampledata" ) { m_clip->setSampleBuffer(SampleLoader::createBufferFromBase64(StringPairDrag::decodeValue(_de))); m_clip->updateLength(); update(); _de->accept(); } else { ClipView::dropEvent( _de ); } } void SampleClipView::mousePressEvent( QMouseEvent * _me ) { if( _me->button() == Qt::LeftButton && _me->modifiers() & Qt::ControlModifier && _me->modifiers() & Qt::ShiftModifier ) { m_clip->toggleRecord(); } else { if( _me->button() == Qt::MiddleButton && _me->modifiers() == Qt::ControlModifier ) { auto sClip = dynamic_cast<SampleClip*>(getClip()); if( sClip ) { sClip->updateTrackClips(); } } ClipView::mousePressEvent( _me ); } } void SampleClipView::mouseReleaseEvent(QMouseEvent *_me) { if( _me->button() == Qt::MiddleButton && !_me->modifiers() ) { auto sClip = dynamic_cast<SampleClip*>(getClip()); if( sClip ) { sClip->playbackPositionChanged(); } } ClipView::mouseReleaseEvent( _me ); } void SampleClipView::mouseDoubleClickEvent( QMouseEvent * ) { const QString selectedAudioFile = SampleLoader::openAudioFile(); if (selectedAudioFile.isEmpty()) { return; } if (m_clip->hasSampleFileLoaded(selectedAudioFile)) { m_clip->changeLengthToSampleLength(); } else { auto sampleBuffer = SampleLoader::createBufferFromFile(selectedAudioFile); if (sampleBuffer != SampleBuffer::emptyBuffer()) { m_clip->setSampleBuffer(sampleBuffer); } } } void SampleClipView::paintEvent( QPaintEvent * pe ) { QPainter painter( this ); if( !needsUpdate() ) { painter.drawPixmap( 0, 0, m_paintPixmap ); return; } setNeedsUpdate( false ); if (m_paintPixmap.isNull() || m_paintPixmap.size() != size()) { m_paintPixmap = QPixmap(size()); } QPainter p( &m_paintPixmap ); bool muted = m_clip->getTrack()->isMuted() || m_clip->isMuted(); bool selected = isSelected(); QLinearGradient lingrad(0, 0, 0, height()); QColor c = painter.background().color(); if (muted) { c = c.darker(150); } if (selected) { c = c.darker(150); } lingrad.setColorAt( 1, c.darker( 300 ) ); lingrad.setColorAt( 0, c ); // paint a black rectangle under the clip to prevent glitches with transparent backgrounds p.fillRect( rect(), QColor( 0, 0, 0 ) ); if( gradient() ) { p.fillRect( rect(), lingrad ); } else { p.fillRect( rect(), c ); } auto clipColor = m_clip->color().value_or(m_clip->getTrack()->color().value_or(painter.pen().brush().color())); p.setPen(clipColor); if (muted) { QColor penColor = p.pen().brush().color(); penColor.setHsv(penColor.hsvHue(), penColor.hsvSaturation() / 4, penColor.value()); p.setPen(penColor.darker(250)); } if (selected) { p.setPen(p.pen().brush().color().darker(150)); } const int spacing = BORDER_WIDTH + 1; const float ppb = fixedClips() ? ( parentWidget()->width() - 2 * BORDER_WIDTH ) / (float) m_clip->length().getBar() : pixelsPerBar(); float nom = Engine::getSong()->getTimeSigModel().getNumerator(); float den = Engine::getSong()->getTimeSigModel().getDenominator(); float ticksPerBar = DefaultTicksPerBar * nom / den; float offset = m_clip->startTimeOffset() / ticksPerBar * pixelsPerBar(); QRect r = QRect( offset, spacing, qMax( static_cast<int>( m_clip->sampleLength() * ppb / ticksPerBar ), 1 ), rect().bottom() - 2 * spacing ); const auto& sample = m_clip->m_sample; const auto waveform = SampleWaveform::Parameters{sample.data(), sample.sampleSize(), sample.amplification(), sample.reversed()}; SampleWaveform::visualize(waveform, p, r); QString name = PathUtil::cleanName(m_clip->m_sample.sampleFile()); paintTextLabel(name, p); // disable antialiasing for borders, since its not needed p.setRenderHint( QPainter::Antialiasing, false ); // inner border p.setPen( c.lighter( 135 ) ); p.drawRect( 1, 1, rect().right() - BORDER_WIDTH, rect().bottom() - BORDER_WIDTH ); // outer border p.setPen( c.darker( 200 ) ); p.drawRect( 0, 0, rect().right(), rect().bottom() ); // draw the 'muted' pixmap only if the clip was manualy muted if( m_clip->isMuted() ) { const int spacing = BORDER_WIDTH; const int size = 14; p.drawPixmap( spacing, height() - ( size + spacing ), embed::getIconPixmap( "muted", size, size ) ); } if ( m_marker ) { p.drawLine(m_markerPos, rect().bottom(), m_markerPos, rect().top()); } // recording sample tracks is not possible at the moment /* if( m_clip->isRecord() ) { p.setFont( pointSize<7>( p.font() ) ); p.setPen( textShadowColor() ); p.drawText( 10, p.fontMetrics().height()+1, "Rec" ); p.setPen( textColor() ); p.drawText( 9, p.fontMetrics().height(), "Rec" ); p.setBrush( QBrush( textColor() ) ); p.drawEllipse( 4, 5, 4, 4 ); }*/ p.end(); painter.drawPixmap( 0, 0, m_paintPixmap ); } void SampleClipView::reverseSample() { m_clip->m_sample.setReversed(!m_clip->m_sample.reversed()); m_clip->setStartTimeOffset(m_clip->length() - m_clip->startTimeOffset() - m_clip->sampleLength()); Engine::getSong()->setModified(); update(); } void SampleClipView::setAutomationGhost() { auto aEditor = gui::getGUI()->automationEditor(); aEditor->setGhostSample(m_clip); aEditor->parentWidget()->show(); aEditor->show(); aEditor->setFocus(); } //! Split this Clip. /*! \param pos the position of the split, relative to the start of the clip */ bool SampleClipView::splitClip( const TimePos pos ) { setMarkerEnabled( false ); const TimePos splitPos = m_initialClipPos + pos; //Don't split if we slid off the Clip or if we're on the clip's start/end //Cutting at exactly the start/end position would create a zero length //clip (bad), and a clip the same length as the original one (pointless). if ( splitPos > m_initialClipPos && splitPos < m_initialClipEnd ) { m_clip->getTrack()->addJournalCheckPoint(); m_clip->getTrack()->saveJournallingState( false ); auto rightClip = new SampleClip(*m_clip); m_clip->changeLength( splitPos - m_initialClipPos ); rightClip->movePosition( splitPos ); rightClip->changeLength( m_initialClipEnd - splitPos ); rightClip->setStartTimeOffset( m_clip->startTimeOffset() - m_clip->length() ); m_clip->getTrack()->restoreJournallingState(); return true; } else { return false; } } } // namespace lmms::gui
9,126
C++
.cpp
291
28.85567
129
0.705169
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,929
InstrumentTrackWindow.cpp
LMMS_lmms/src/gui/instrument/InstrumentTrackWindow.cpp
/* * InstrumentTrackWindow.cpp - implementation of InstrumentTrackWindow 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. * */ #include "InstrumentTrackWindow.h" #include <QDir> #include <QDropEvent> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QMenu> #include <QPushButton> #include <QVBoxLayout> #include "ComboBox.h" #include "ConfigManager.h" #include "DataFile.h" #include "EffectRackView.h" #include "embed.h" #include "Engine.h" #include "FileBrowser.h" #include "FileDialog.h" #include "GroupBox.h" #include "MixerChannelLcdSpinBox.h" #include "GuiApplication.h" #include "Instrument.h" #include "InstrumentFunctions.h" #include "InstrumentFunctionViews.h" #include "InstrumentMidiIOView.h" #include "InstrumentTuningView.h" #include "InstrumentSoundShapingView.h" #include "InstrumentTrack.h" #include "InstrumentTrackView.h" #include "Knob.h" #include "LcdSpinBox.h" #include "LedCheckBox.h" #include "LeftRightNav.h" #include "MainWindow.h" #include "PianoView.h" #include "PluginFactory.h" #include "PluginView.h" #include "Song.h" #include "StringPairDrag.h" #include "SubWindow.h" #include "TabWidget.h" #include "TrackContainerView.h" #include "TrackLabelButton.h" namespace lmms::gui { const int INSTRUMENT_WIDTH = 254; const int INSTRUMENT_HEIGHT = INSTRUMENT_WIDTH; const int PIANO_HEIGHT = 80; InstrumentTrackWindow::InstrumentTrackWindow( InstrumentTrackView * _itv ) : QWidget(), ModelView( nullptr, this ), m_track( _itv->model() ), m_itv( _itv ), m_instrumentView( nullptr ) { setAcceptDrops( true ); // init own layout + widgets setFocusPolicy( Qt::StrongFocus ); auto vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(0, 0, 0, 0); vlayout->setSpacing( 0 ); auto generalSettingsWidget = new QWidget(this); auto generalSettingsLayout = new QVBoxLayout(generalSettingsWidget); auto nameAndChangeTrackWidget = new QWidget(generalSettingsWidget); auto nameAndChangeTrackLayout = new QHBoxLayout(nameAndChangeTrackWidget); nameAndChangeTrackLayout->setContentsMargins( 0, 0, 0, 0 ); nameAndChangeTrackLayout->setSpacing( 2 ); // setup line edit for changing instrument track name m_nameLineEdit = new QLineEdit; connect( m_nameLineEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( textChanged( const QString& ) ) ); m_nameLineEdit->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); nameAndChangeTrackLayout->addWidget(m_nameLineEdit, 1); // set up left/right arrows for changing instrument m_leftRightNav = new LeftRightNav(this); connect( m_leftRightNav, SIGNAL(onNavLeft()), this, SLOT(viewPrevInstrument())); connect( m_leftRightNav, SIGNAL(onNavRight()), this, SLOT(viewNextInstrument())); // m_leftRightNav->setShortcuts(); nameAndChangeTrackLayout->addWidget(m_leftRightNav); nameAndChangeTrackWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); generalSettingsLayout->addWidget( nameAndChangeTrackWidget ); auto basicControlsLayout = new QGridLayout; basicControlsLayout->setHorizontalSpacing(3); basicControlsLayout->setVerticalSpacing(0); basicControlsLayout->setContentsMargins(0, 0, 0, 0); #if QT_VERSION < 0x50C00 // Workaround for a bug in Qt versions below 5.12, // where argument-dependent-lookup fails for QFlags operators // declared inside a namepsace. // This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h // See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348 using ::operator|; #endif QString labelStyleSheet = "font-size: 10px;"; Qt::Alignment labelAlignment = Qt::AlignHCenter | Qt::AlignTop; Qt::Alignment widgetAlignment = Qt::AlignHCenter | Qt::AlignCenter; // set up volume knob m_volumeKnob = new Knob( KnobType::Bright26, nullptr, tr( "Volume" ) ); m_volumeKnob->setVolumeKnob( true ); m_volumeKnob->setHintText( tr( "Volume:" ), "%" ); basicControlsLayout->addWidget( m_volumeKnob, 0, 0 ); basicControlsLayout->setAlignment( m_volumeKnob, widgetAlignment ); auto label = new QLabel(tr("VOL"), this); label->setStyleSheet( labelStyleSheet ); basicControlsLayout->addWidget( label, 1, 0); basicControlsLayout->setAlignment( label, labelAlignment ); // set up panning knob m_panningKnob = new Knob( KnobType::Bright26, nullptr, tr( "Panning" ) ); m_panningKnob->setHintText( tr( "Panning:" ), "" ); basicControlsLayout->addWidget( m_panningKnob, 0, 1 ); basicControlsLayout->setAlignment( m_panningKnob, widgetAlignment ); label = new QLabel( tr( "PAN" ), this ); label->setStyleSheet( labelStyleSheet ); basicControlsLayout->addWidget( label, 1, 1); basicControlsLayout->setAlignment( label, labelAlignment ); basicControlsLayout->setColumnStretch(2, 1); // set up pitch knob m_pitchKnob = new Knob( KnobType::Bright26, nullptr, tr( "Pitch" ) ); m_pitchKnob->setHintText( tr( "Pitch:" ), " " + tr( "cents" ) ); basicControlsLayout->addWidget( m_pitchKnob, 0, 3 ); basicControlsLayout->setAlignment( m_pitchKnob, widgetAlignment ); m_pitchLabel = new QLabel( tr( "PITCH" ), this ); m_pitchLabel->setStyleSheet( labelStyleSheet ); basicControlsLayout->addWidget( m_pitchLabel, 1, 3); basicControlsLayout->setAlignment( m_pitchLabel, labelAlignment ); // set up pitch range knob m_pitchRangeSpinBox= new LcdSpinBox( 2, nullptr, tr( "Pitch range (semitones)" ) ); basicControlsLayout->addWidget( m_pitchRangeSpinBox, 0, 4 ); basicControlsLayout->setAlignment( m_pitchRangeSpinBox, widgetAlignment ); m_pitchRangeLabel = new QLabel( tr( "RANGE" ), this ); m_pitchRangeLabel->setStyleSheet( labelStyleSheet ); basicControlsLayout->addWidget( m_pitchRangeLabel, 1, 4); basicControlsLayout->setAlignment( m_pitchRangeLabel, labelAlignment ); basicControlsLayout->setColumnStretch(5, 1); // setup spinbox for selecting Mixer-channel m_mixerChannelNumber = new MixerChannelLcdSpinBox(2, nullptr, tr("Mixer channel"), m_itv); basicControlsLayout->addWidget( m_mixerChannelNumber, 0, 6 ); basicControlsLayout->setAlignment( m_mixerChannelNumber, widgetAlignment ); label = new QLabel( tr( "CHANNEL" ), this ); label->setStyleSheet( labelStyleSheet ); basicControlsLayout->addWidget( label, 1, 6); basicControlsLayout->setAlignment( label, labelAlignment ); auto saveSettingsBtn = new QPushButton(embed::getIconPixmap("project_save"), QString()); saveSettingsBtn->setMinimumSize( 32, 32 ); connect( saveSettingsBtn, SIGNAL(clicked()), this, SLOT(saveSettingsBtnClicked())); saveSettingsBtn->setToolTip(tr("Save current instrument track settings in a preset file")); basicControlsLayout->addWidget( saveSettingsBtn, 0, 7 ); label = new QLabel( tr( "SAVE" ), this ); label->setStyleSheet( labelStyleSheet ); basicControlsLayout->addWidget( label, 1, 7); basicControlsLayout->setAlignment( label, labelAlignment ); generalSettingsLayout->addLayout( basicControlsLayout ); m_tabWidget = new TabWidget( "", this, true, true ); // "-1" : // in "TabWidget::addTab", under "Position tab's window", the widget is // moved up by 1 pixel m_tabWidget->setMinimumHeight( INSTRUMENT_HEIGHT + GRAPHIC_TAB_HEIGHT - 4 - 1 ); // create tab-widgets m_ssView = new InstrumentSoundShapingView( m_tabWidget ); // FUNC tab m_instrumentFunctionsView = new QWidget(m_tabWidget); auto instrumentFunctionsLayout = new QVBoxLayout(m_instrumentFunctionsView); instrumentFunctionsLayout->setContentsMargins(5, 5, 5, 5); m_noteStackingView = new InstrumentFunctionNoteStackingView( &m_track->m_noteStacking ); m_arpeggioView = new InstrumentFunctionArpeggioView( &m_track->m_arpeggio ); instrumentFunctionsLayout->addWidget( m_noteStackingView ); instrumentFunctionsLayout->addWidget( m_arpeggioView ); instrumentFunctionsLayout->addStretch(); // MIDI tab m_midiView = new InstrumentMidiIOView(m_tabWidget); // FX tab m_effectView = new EffectRackView(m_track->m_audioPort.effects(), m_tabWidget); // Tuning tab m_tuningView = new InstrumentTuningView(m_track, m_tabWidget); m_tabWidget->addTab(m_ssView, tr("Envelope, filter & LFO"), "env_lfo_tab", 1); m_tabWidget->addTab(m_instrumentFunctionsView, tr("Chord stacking & arpeggio"), "func_tab", 2); m_tabWidget->addTab(m_effectView, tr("Effects"), "fx_tab", 3); m_tabWidget->addTab(m_midiView, tr("MIDI"), "midi_tab", 4); m_tabWidget->addTab(m_tuningView, tr("Tuning and transposition"), "tuning_tab", 5); // setup piano-widget m_pianoView = new PianoView( this ); m_pianoView->setMinimumHeight( PIANO_HEIGHT ); m_pianoView->setMaximumHeight( PIANO_HEIGHT ); // setup sizes and policies generalSettingsWidget->setMaximumHeight(90); generalSettingsWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_tabWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); vlayout->addWidget( generalSettingsWidget ); // Use QWidgetItem explicitly to make the size hint change on instrument changes // QLayout::addWidget() uses QWidgetItemV2 with size hint caching vlayout->insertItem(1, new QWidgetItem(m_tabWidget)); vlayout->addWidget( m_pianoView ); setModel( _itv->model() ); updateInstrumentView(); QMdiSubWindow* subWin = getGUI()->mainWindow()->addWindowedWidget( this ); Qt::WindowFlags flags = subWin->windowFlags(); if (!m_instrumentView->isResizable()) { flags |= Qt::MSWindowsFixedSizeDialogHint; // any better way than this? } else { subWin->setMaximumSize(m_instrumentView->maximumHeight() + 12, m_instrumentView->maximumWidth() + 208); subWin->setMinimumSize( m_instrumentView->minimumWidth() + 12, m_instrumentView->minimumHeight() + 208); } flags &= ~Qt::WindowMaximizeButtonHint; subWin->setWindowFlags( flags ); // Hide the Size and Maximize options from the system menu // since the dialog size is fixed. QMenu * systemMenu = subWin->systemMenu(); systemMenu->actions().at( 2 )->setVisible( false ); // Size systemMenu->actions().at( 4 )->setVisible( false ); // Maximize subWin->setWindowIcon( embed::getIconPixmap( "instrument_track" ) ); subWin->hide(); } void InstrumentTrackWindow::resizeEvent(QResizeEvent * event) { /* m_instrumentView->resize(QSize(size().width()-1, maxHeight)); */ adjustTabSize(m_instrumentView); adjustTabSize(m_instrumentFunctionsView); adjustTabSize(m_ssView); adjustTabSize(m_effectView); adjustTabSize(m_midiView); adjustTabSize(m_tuningView); } InstrumentTrackWindow::~InstrumentTrackWindow() { delete m_instrumentView; if (parentWidget()) { parentWidget()->hide(); parentWidget()->deleteLater(); } } void InstrumentTrackWindow::setInstrumentTrackView( InstrumentTrackView* view ) { if( m_itv && view ) { m_itv->m_tlb->setChecked( false ); } m_itv = view; m_mixerChannelNumber->setTrackView(m_itv); } void InstrumentTrackWindow::modelChanged() { m_track = castModel<InstrumentTrack>(); m_nameLineEdit->setText( m_track->name() ); m_track->disconnect( SIGNAL(nameChanged()), this ); m_track->disconnect( SIGNAL(instrumentChanged()), this ); connect( m_track, SIGNAL(nameChanged()), this, SLOT(updateName())); connect( m_track, SIGNAL(instrumentChanged()), this, SLOT(updateInstrumentView())); m_volumeKnob->setModel( &m_track->m_volumeModel ); m_panningKnob->setModel( &m_track->m_panningModel ); m_mixerChannelNumber->setModel( &m_track->m_mixerChannelModel ); m_pianoView->setModel( &m_track->m_piano ); if (m_track->instrument() && m_track->instrument()->isBendable()) { m_pitchKnob->setModel( &m_track->m_pitchModel ); m_pitchRangeSpinBox->setModel( &m_track->m_pitchRangeModel ); m_pitchKnob->show(); m_pitchLabel->show(); m_pitchRangeSpinBox->show(); m_pitchRangeLabel->show(); } else { m_pitchKnob->hide(); m_pitchLabel->hide(); m_pitchKnob->setModel( nullptr ); m_pitchRangeSpinBox->hide(); m_pitchRangeLabel->hide(); } if (m_track->instrument() && m_track->instrument()->isMidiBased()) { m_tuningView->microtunerNotSupportedLabel()->show(); m_tuningView->microtunerGroupBox()->hide(); m_track->m_microtuner.enabledModel()->setValue(false); } else { m_tuningView->microtunerNotSupportedLabel()->hide(); m_tuningView->microtunerGroupBox()->show(); } m_ssView->setModel( &m_track->m_soundShaping ); m_noteStackingView->setModel( &m_track->m_noteStacking ); m_arpeggioView->setModel( &m_track->m_arpeggio ); m_midiView->setModel( &m_track->m_midiPort ); m_effectView->setModel( m_track->m_audioPort.effects() ); m_tuningView->pitchGroupBox()->setModel(&m_track->m_useMasterPitchModel); m_tuningView->microtunerGroupBox()->setModel(m_track->m_microtuner.enabledModel()); m_tuningView->scaleCombo()->setModel(m_track->m_microtuner.scaleModel()); m_tuningView->keymapCombo()->setModel(m_track->m_microtuner.keymapModel()); m_tuningView->rangeImportCheckbox()->setModel(m_track->m_microtuner.keyRangeImportModel()); updateName(); } void InstrumentTrackWindow::saveSettingsBtnClicked() { FileDialog sfd(this, tr("Save preset"), "", tr("XML preset file (*.xpf)")); QString presetRoot = ConfigManager::inst()->userPresetsDir(); if(!QDir(presetRoot).exists()) { QDir().mkdir(presetRoot); } if(!QDir(presetRoot + m_track->instrumentName()).exists()) { QDir(presetRoot).mkdir(m_track->instrumentName()); } sfd.setAcceptMode(FileDialog::AcceptSave); sfd.setDirectory(presetRoot + m_track->instrumentName()); sfd.setFileMode( FileDialog::AnyFile ); QString fname = m_track->name(); sfd.selectFile(fname.remove(QRegularExpression(FILENAME_FILTER))); sfd.setDefaultSuffix( "xpf"); if( sfd.exec() == QDialog::Accepted && !sfd.selectedFiles().isEmpty() && !sfd.selectedFiles().first().isEmpty() ) { DataFile dataFile(DataFile::Type::InstrumentTrackSettings); QDomElement& content(dataFile.content()); m_track->savePreset(dataFile, content); //We don't want to save muted & solo settings when we're saving a preset content.setAttribute("muted", 0); content.setAttribute("solo", 0); content.setAttribute("mutedBeforeSolo", 0); QString f = sfd.selectedFiles()[0]; dataFile.writeFile(f); } } void InstrumentTrackWindow::updateName() { setWindowTitle( m_track->name().length() > 25 ? ( m_track->name().left(24)+"..." ) : m_track->name() ); if( m_nameLineEdit->text() != m_track->name() ) { m_nameLineEdit->setText( m_track->name() ); } } void InstrumentTrackWindow::updateInstrumentView() { delete m_instrumentView; if( m_track->m_instrument != nullptr ) { m_instrumentView = m_track->m_instrument->createView( m_tabWidget ); m_tabWidget->addTab( m_instrumentView, tr( "Plugin" ), "plugin_tab", 0 ); m_tabWidget->setActiveTab( 0 ); m_ssView->setFunctionsHidden(m_track->m_instrument->isSingleStreamed()); modelChanged(); // Get the instrument window to refresh m_track->dataChanged(); // Get the text on the trackButton to change adjustTabSize(m_instrumentView); m_pianoView->setVisible(m_track->m_instrument->hasNoteInput()); // adjust window size layout()->invalidate(); resize(sizeHint()); if (parentWidget()) { parentWidget()->resize(parentWidget()->sizeHint()); } update(); m_instrumentView->update(); } } void InstrumentTrackWindow::textChanged( const QString& newName ) { m_track->setName( newName ); Engine::getSong()->setModified(); } void InstrumentTrackWindow::toggleVisibility( bool on ) { if( on ) { show(); parentWidget()->show(); parentWidget()->raise(); } else { parentWidget()->hide(); } } void InstrumentTrackWindow::closeEvent( QCloseEvent* event ) { event->ignore(); if( getGUI()->mainWindow()->workspace() ) { parentWidget()->hide(); } else { hide(); } m_itv->m_tlb->setFocus(); m_itv->m_tlb->setChecked( false ); } void InstrumentTrackWindow::focusInEvent( QFocusEvent* ) { if(m_pianoView->isVisible()) { m_pianoView->setFocus(); } } void InstrumentTrackWindow::dragEnterEventGeneric( QDragEnterEvent* event ) { StringPairDrag::processDragEnterEvent( event, "instrument,presetfile,pluginpresetfile" ); } void InstrumentTrackWindow::dragEnterEvent( QDragEnterEvent* event ) { dragEnterEventGeneric( event ); } void InstrumentTrackWindow::dropEvent( QDropEvent* event ) { QString type = StringPairDrag::decodeKey( event ); QString value = StringPairDrag::decodeValue( event ); if( type == "instrument" ) { m_track->loadInstrument( value, nullptr, true /* DnD */ ); Engine::getSong()->setModified(); event->accept(); setFocus(); } else if( type == "presetfile" ) { DataFile dataFile(value); m_track->replaceInstrument(dataFile); event->accept(); setFocus(); } else if( type == "pluginpresetfile" ) { const QString ext = FileItem::extension( value ); Instrument * i = m_track->instrument(); if( !i->descriptor()->supportsFileType( ext ) ) { PluginFactory::PluginInfoAndKey piakn = getPluginFactory()->pluginSupportingExtension(ext); i = m_track->loadInstrument(piakn.info.name(), &piakn.key); } i->loadFile( value ); event->accept(); setFocus(); } } void InstrumentTrackWindow::saveSettings( QDomDocument& doc, QDomElement & thisElement ) { thisElement.setAttribute( "tab", m_tabWidget->activeTab() ); MainWindow::saveWidgetState( this, thisElement ); } void InstrumentTrackWindow::loadSettings( const QDomElement& thisElement ) { m_tabWidget->setActiveTab( thisElement.attribute( "tab" ).toInt() ); MainWindow::restoreWidgetState( this, thisElement ); if( isVisible() ) { m_itv->m_tlb->setChecked( true ); } } void InstrumentTrackWindow::viewInstrumentInDirection(int d) { // helper routine for viewNextInstrument, viewPrevInstrument // d=-1 to view the previous instrument, // d=+1 to view the next instrument const QList<TrackView *> &trackViews = m_itv->trackContainerView()->trackViews(); int idxOfMe = trackViews.indexOf(m_itv); // search for the next InstrumentTrackView (i.e. skip AutomationViews, etc) // sometimes, the next InstrumentTrackView may already be open, in which case // replace our window contents with the *next* closed Instrument Track and // give focus to the InstrumentTrackView we skipped. int idxOfNext = idxOfMe; InstrumentTrackView *newView = nullptr; InstrumentTrackView *bringToFront = nullptr; do { idxOfNext = (idxOfNext + d + trackViews.size()) % trackViews.size(); newView = dynamic_cast<InstrumentTrackView*>(trackViews[idxOfNext]); // the window that should be brought to focus is the FIRST InstrumentTrackView that comes after us if (bringToFront == nullptr && newView != nullptr) { bringToFront = newView; } // if the next instrument doesn't have an active window, then exit loop & load that one into our window. if (newView != nullptr && !newView->m_tlb->isChecked()) { break; } } while (idxOfNext != idxOfMe); // avoid reloading the window if there is only one instrument, as that will just change the active tab if (idxOfNext != idxOfMe) { // save current window pos and then hide the window by unchecking its button in the track list QPoint curPos = parentWidget()->pos(); m_itv->m_tlb->setChecked(false); // enable the new window by checking its track list button & moving it to where our window just was newView->m_tlb->setChecked(true); newView->getInstrumentTrackWindow()->parentWidget()->move(curPos); // scroll the SongEditor/PatternEditor to make sure the new trackview label is visible bringToFront->trackContainerView()->scrollToTrackView(bringToFront); // get the instrument window to refresh modelChanged(); } Q_ASSERT(bringToFront); bringToFront->getInstrumentTrackWindow()->setFocus(); Qt::WindowFlags flags = windowFlags(); if (!m_instrumentView->isResizable()) { flags |= Qt::MSWindowsFixedSizeDialogHint; } else { flags &= ~Qt::MSWindowsFixedSizeDialogHint; } setWindowFlags( flags ); } void InstrumentTrackWindow::viewNextInstrument() { viewInstrumentInDirection(+1); } void InstrumentTrackWindow::viewPrevInstrument() { viewInstrumentInDirection(-1); } void InstrumentTrackWindow::adjustTabSize(QWidget *w) { // "-1" : // in "TabWidget::addTab", under "Position tab's window", the widget is // moved up by 1 pixel w->resize(width() - 4, height() - 180); w->update(); } } // namespace lmms::gui
21,040
C++
.cpp
546
36.197802
106
0.752534
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,930
InstrumentTuningView.cpp
LMMS_lmms/src/gui/instrument/InstrumentTuningView.cpp
/* * InstrumentTuningView.cpp - Instrument settings for tuning and transpositions * * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * Copyright (c) 2020-2022 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. * */ #include "InstrumentTuningView.h" #include <QHBoxLayout> #include <QLabel> #include <QPixmap> #include <QVBoxLayout> #include "ComboBox.h" #include "GroupBox.h" #include "GuiApplication.h" #include "FontHelper.h" #include "InstrumentTrack.h" #include "LedCheckBox.h" #include "MainWindow.h" #include "PixmapButton.h" namespace lmms::gui { InstrumentTuningView::InstrumentTuningView(InstrumentTrack *it, QWidget *parent) : QWidget(parent) { auto layout = new QVBoxLayout(this); layout->setContentsMargins(5, 5, 5, 5); // Master pitch toggle m_pitchGroupBox = new GroupBox(tr("GLOBAL TRANSPOSITION")); m_pitchGroupBox->setModel(&it->m_useMasterPitchModel); layout->addWidget(m_pitchGroupBox); auto masterPitchLayout = new QHBoxLayout(m_pitchGroupBox); masterPitchLayout->setContentsMargins(8, 18, 8, 8); auto tlabel = new QLabel(tr("Enables the use of global transposition")); tlabel->setWordWrap(true); tlabel->setFont(adjustedToPixelSize(tlabel->font(), DEFAULT_FONT_SIZE)); masterPitchLayout->addWidget(tlabel); // Microtuner settings m_microtunerNotSupportedLabel = new QLabel(tr("Microtuner is not available for MIDI-based instruments.")); m_microtunerNotSupportedLabel->setWordWrap(true); m_microtunerNotSupportedLabel->hide(); layout->addWidget(m_microtunerNotSupportedLabel); m_microtunerGroupBox = new GroupBox(tr("MICROTUNER")); m_microtunerGroupBox->setModel(it->m_microtuner.enabledModel()); layout->addWidget(m_microtunerGroupBox); auto microtunerLayout = new QVBoxLayout(m_microtunerGroupBox); microtunerLayout->setContentsMargins(8, 18, 8, 8); auto scaleEditLayout = new QHBoxLayout(); scaleEditLayout->setContentsMargins(0, 0, 4, 0); microtunerLayout->addLayout(scaleEditLayout); auto scaleLabel = new QLabel(tr("Active scale:")); scaleEditLayout->addWidget(scaleLabel); QPixmap editPixmap(embed::getIconPixmap("edit_draw_small")); auto editPixButton = new PixmapButton(this, tr("Edit scales and keymaps")); editPixButton->setToolTip(tr("Edit scales and keymaps")); editPixButton->setInactiveGraphic(editPixmap); editPixButton->setActiveGraphic(editPixmap); editPixButton->setFixedSize(16, 16); connect(editPixButton, SIGNAL(clicked()), getGUI()->mainWindow(), SLOT(toggleMicrotunerWin())); scaleEditLayout->addWidget(editPixButton); m_scaleCombo = new ComboBox(); m_scaleCombo->setModel(it->m_microtuner.scaleModel()); microtunerLayout->addWidget(m_scaleCombo); auto keymapLabel = new QLabel(tr("Active keymap:")); microtunerLayout->addWidget(keymapLabel); m_keymapCombo = new ComboBox(); m_keymapCombo->setModel(it->m_microtuner.keymapModel()); microtunerLayout->addWidget(m_keymapCombo); m_rangeImportCheckbox = new LedCheckBox(tr("Import note ranges from keymap"), this); m_rangeImportCheckbox->setModel(it->m_microtuner.keyRangeImportModel()); m_rangeImportCheckbox->setToolTip(tr("When enabled, the first, last and base notes of this instrument will be overwritten with values specified by the selected keymap.")); m_rangeImportCheckbox->setCheckable(true); microtunerLayout->addWidget(m_rangeImportCheckbox); // Fill remaining space layout->addStretch(); } } // namespace lmms::gui
4,201
C++
.cpp
94
42.648936
172
0.786187
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
19,931
PianoView.cpp
LMMS_lmms/src/gui/instrument/PianoView.cpp
/* * PianoView.cpp - implementation of piano-widget used in instrument-track-window * for testing + according model 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. * */ /** \file piano.cpp * \brief A piano keyboard to play notes on in the instrument plugin window. */ /* * \mainpage Instrument plugin keyboard display classes * * \section introduction Introduction * * \todo fill this out * \todo write isWhite inline function and replace throughout */ #include <cmath> #include <QCursor> #include <QKeyEvent> #include <QPainter> #include <QPainterPath> #include <QVBoxLayout> #include "AutomatableModelView.h" #include "PianoView.h" #include "Piano.h" #include "CaptionMenu.h" #include "embed.h" #include "Engine.h" #include "FontHelper.h" #include "InstrumentTrack.h" #include "Song.h" #include "StringPairDrag.h" namespace lmms::gui { /*! The scale of C Major - white keys only. */ auto WhiteKeys = std::array { Key::C, Key::D, Key::E, Key::F, Key::G, Key::A, Key::H } ; const int PIANO_BASE = 11; /*!< The height of the root note display */ const int PW_WHITE_KEY_WIDTH = 10; /*!< The width of a white key */ const int PW_BLACK_KEY_WIDTH = 8; /*!< The width of a black key */ const int PW_WHITE_KEY_HEIGHT = 57; /*!< The height of a white key */ const int PW_BLACK_KEY_HEIGHT = 38; /*!< The height of a black key */ const int LABEL_TEXT_SIZE = 8; /*!< The height of the key label text */ /*! \brief Create a new keyboard display view * * \param _parent the parent instrument plugin window * \todo are the descriptions of the m_startkey and m_lastkey properties correct? */ PianoView::PianoView(QWidget *parent) : QWidget(parent), /*!< Our parent */ ModelView(nullptr, this), /*!< Our view Model */ m_piano(nullptr), /*!< Our piano Model */ m_startKey(Octave::Octave_3 + Key::C), /*!< The first key displayed? */ m_lastKey(-1), /*!< The last key displayed? */ m_movedNoteModel(nullptr) /*!< Key marker which is being moved */ { setAttribute(Qt::WA_OpaquePaintEvent, true); setFocusPolicy(Qt::StrongFocus); // Black keys are drawn halfway between successive white keys, so they do not // contribute to the total width. Half of a black key is added in case the last // octave is incomplete and ends with a black key. Drawing always starts at // a white key, so no similar modification is needed at the beginning. setMaximumWidth(Piano::NumWhiteKeys * PW_WHITE_KEY_WIDTH + (Piano::isBlackKey(NumKeys-1) ? PW_BLACK_KEY_WIDTH / 2 : 0)); // create scrollbar at the bottom m_pianoScroll = new QScrollBar( Qt::Horizontal, this ); m_pianoScroll->setSingleStep( 1 ); m_pianoScroll->setPageStep( 20 ); m_pianoScroll->setValue(static_cast<int>(Octave::Octave_3) * Piano::WhiteKeysPerOctave); // and connect it to this widget connect( m_pianoScroll, SIGNAL(valueChanged(int)), this, SLOT(pianoScrolled(int))); // create a layout for ourselves auto layout = new QVBoxLayout(this); layout->setSpacing( 0 ); layout->setContentsMargins(0, 0, 0, 0); layout->addSpacing( PIANO_BASE+PW_WHITE_KEY_HEIGHT ); layout->addWidget( m_pianoScroll ); // trigger a redraw if keymap definitions change (different keys may become disabled) connect(Engine::getSong(), SIGNAL(keymapListChanged(int)), this, SLOT(update())); } static int getKeyOffsetFromKeyEvent( QKeyEvent * _ke ) { // TODO: check the scan codes for ',' = c, 'L' = c#, '.' = d, ':' = d#, // '/' = d, '[' = f', '=' = f'#, ']' = g' - Paul's additions #ifdef LMMS_BUILD_APPLE const int k = _ke->nativeVirtualKey(); #else const int k = _ke->nativeScanCode(); #endif #ifdef LMMS_BUILD_WIN32 switch( k ) { case 44: return 0; // Z = C case 31: return 1; // S = C# case 45: return 2; // X = D case 32: return 3; // D = D# case 46: return 4; // C = E case 47: return 5; // V = F case 34: return 6; // G = F# case 48: return 7; // B = G case 35: return 8; // H = G# case 49: return 9; // N = A case 36: return 10; // J = A# case 50: return 11; // M = B case 51: return 12; // , = c case 38: return 13; // L = c# case 52: return 14; // . = d case 39: return 15; // ; = d# //case 86: return 16; // / = e case 53: return 16; // / = e case 16: return 12; // Q = c case 3: return 13; // 2 = c# case 17: return 14; // W = d case 4: return 15; // 3 = d# case 18: return 16; // E = e case 19: return 17; // R = f case 6: return 18; // 5 = f# case 20: return 19; // T = g case 7: return 20; // 6 = g# case 21: return 21; // Y = a case 8: return 22; // 7 = a# case 22: return 23; // U = b case 23: return 24; // I = c' case 10: return 25; // 9 = c'# case 24: return 26; // O = d' case 11: return 27; // 0 = d'# case 25: return 28; // P = e' case 26: return 29; // [ case 13: return 30; // = case 27: return 31; // ] } #endif // LMMS_BUILD_WIN32 #if defined(LMMS_BUILD_LINUX) || defined(LMMS_BUILD_OPENBSD) || defined(LMMS_BUILD_FREEBSD) switch( k ) { case 52: return 0; // Z = C case 39: return 1; // S = C# case 53: return 2; // X = D case 40: return 3; // D = D# case 54: return 4; // C = E case 55: return 5; // V = F case 42: return 6; // G = F# case 56: return 7; // B = G case 43: return 8; // H = G# case 57: return 9; // N = A case 44: return 10; // J = A# case 58: return 11; // M = B case 59: return 12; // , = c case 46: return 13; // L = c# case 60: return 14; // . = d case 47: return 15; // ; = d# case 61: return 16; // / = e case 24: return 12; // Q = c case 11: return 13; // 2 = c# case 25: return 14; // W = d case 12: return 15; // 3 = d# case 26: return 16; // E = e case 27: return 17; // R = f case 14: return 18; // 5 = f# case 28: return 19; // T = g case 15: return 20; // 6 = g# case 29: return 21; // Y = a case 16: return 22; // 7 = a# case 30: return 23; // U = b case 31: return 24; // I = c' case 18: return 25; // 9 = c'# case 32: return 26; // O = d' case 19: return 27; // 0 = d'# case 33: return 28; // P = e' case 34: return 29; // [ case 21: return 30; // = case 35: return 31; // ] } #endif #ifdef LMMS_BUILD_APPLE switch( k ) { case 6: return 0; // Z = C case 1: return 1; // S = C# case 7: return 2; // X = D case 2: return 3; // D = D# case 8: return 4; // C = E case 9: return 5; // V = F case 5: return 6; // G = F# case 11: return 7; // B = G case 4: return 8; // H = G# case 45: return 9; // N = A case 38: return 10; // J = A# case 46: return 11; // M = B case 43: return 12; // , = c case 37: return 13; // L = c# case 47: return 14; // . = d case 41: return 15; // ; = d# case 44: return 16; // / = e case 12: return 12; // Q = c case 19: return 13; // 2 = c# case 13: return 14; // W = d case 20: return 15; // 3 = d# case 14: return 16; // E = e case 15: return 17; // R = f case 23: return 18; // 5 = f# case 17: return 19; // T = g case 22: return 20; // 6 = g# case 16: return 21; // Y = a case 26: return 22; // 7 = a# case 32: return 23; // U = b case 34: return 24; // I = c' case 25: return 25; // 9 = c'# case 31: return 26; // O = d' case 29: return 27; // 0 = d'# case 35: return 28; // P = e' } #endif // LMMS_BUILD_APPLE return -100; } /*! \brief Map a keyboard key being pressed to a note in our keyboard view * */ int PianoView::getKeyFromKeyEvent( QKeyEvent * ke ) { const auto key = static_cast<Key>(getKeyOffsetFromKeyEvent(ke)); return DefaultOctave + key - KeysPerOctave; } /*! \brief Register a change to this piano display view * */ void PianoView::modelChanged() { m_piano = castModel<Piano>(); if (m_piano != nullptr) { connect(m_piano->instrumentTrack()->baseNoteModel(), SIGNAL(dataChanged()), this, SLOT(update())); connect(m_piano->instrumentTrack()->firstKeyModel(), SIGNAL(dataChanged()), this, SLOT(update())); connect(m_piano->instrumentTrack()->lastKeyModel(), SIGNAL(dataChanged()), this, SLOT(update())); connect(m_piano->instrumentTrack()->microtuner()->enabledModel(), SIGNAL(dataChanged()), this, SLOT(update())); connect(m_piano->instrumentTrack()->microtuner()->keymapModel(), SIGNAL(dataChanged()), this, SLOT(update())); connect(m_piano->instrumentTrack()->microtuner()->keyRangeImportModel(), SIGNAL(dataChanged()), this, SLOT(update())); } } // Gets the key from the given mouse position /*! \brief Get the key from the mouse position in the piano display * * \param p The point that the mouse was pressed. */ int PianoView::getKeyFromMouse(const QPoint& p) const { // The left-most key visible in the piano display is always white const int startingWhiteKey = m_pianoScroll->value(); // Adjust the mouse x position as if x == 0 was the left side of the lowest key const int adjX = p.x() + (startingWhiteKey * PW_WHITE_KEY_WIDTH); // Can early return for notes too low if (adjX <= 0) { return 0; } // Now we can calculate the key number (in only white keys) and the octave const int whiteKey = adjX / PW_WHITE_KEY_WIDTH; const int octave = whiteKey / Piano::WhiteKeysPerOctave; // Calculate for full octaves int key = octave * KeysPerOctave; // Adjust for white notes in the current octave // (WhiteKeys maps each white key to the number of notes to their left in the octave) key += static_cast<int>(WhiteKeys[whiteKey % Piano::WhiteKeysPerOctave]); // Might be a black key, which would require further adjustment if (p.y() < PIANO_BASE + PW_BLACK_KEY_HEIGHT) { // Maps white keys to neighboring black keys static constexpr std::array neighboringKeyMap { std::pair{ 0, 1 }, // C --> no B#; C# std::pair{ 1, 1 }, // D --> C#; D# std::pair{ 1, 0 }, // E --> D#; no E# std::pair{ 0, 1 }, // F --> no E#; F# std::pair{ 1, 1 }, // G --> F#; G# std::pair{ 1, 1 }, // A --> G#; A# std::pair{ 1, 0 }, // B --> A#; no B# }; const auto neighboringBlackKeys = neighboringKeyMap[whiteKey % Piano::WhiteKeysPerOctave]; const int offset = adjX - (whiteKey * PW_WHITE_KEY_WIDTH); // mouse X offset from white key if (offset < PW_BLACK_KEY_WIDTH / 2) { // At the location of a (possibly non-existent) black key on the left side key -= neighboringBlackKeys.first; } else if (offset > PW_WHITE_KEY_WIDTH - (PW_BLACK_KEY_WIDTH / 2)) { // At the location of a (possibly non-existent) black key on the right side key += neighboringBlackKeys.second; } // For white keys in between black keys, no further adjustment is needed } return std::clamp(key, 0, NumKeys - 1); } // handler for scrolling-event /*! \brief Handle the scrolling on the piano display view * * We need to update our start key position based on the new position. * * \param newPos the new key position, counting only white keys. */ void PianoView::pianoScrolled(int newPos) { m_startKey = static_cast<Octave>(newPos / Piano::WhiteKeysPerOctave) + WhiteKeys[newPos % Piano::WhiteKeysPerOctave]; update(); } /*! \brief Handle a context menu selection on the piano display view * * \param me the ContextMenuEvent to handle. * \todo Is this right, or does this create the context menu? */ void PianoView::contextMenuEvent(QContextMenuEvent *me) { if (me->pos().y() > PIANO_BASE || m_piano == nullptr || m_piano->instrumentTrack()->keyRangeImport()) { QWidget::contextMenuEvent(me); return; } // check which control element is closest to the mouse and open the appropriate menu QString title; IntModel *noteModel = getNearestMarker(getKeyFromMouse(me->pos()), &title); CaptionMenu contextMenu(title); AutomatableModelView amv(noteModel, &contextMenu); amv.addDefaultActions(&contextMenu); contextMenu.exec(QCursor::pos()); } // handler for mouse-click-event /*! \brief Handle a mouse click on this piano display view * * We first determine the key number using the getKeyFromMouse() method. * * If we're below the 'root key selection' area, * we set the volume of the note to be proportional to the vertical * position on the keyboard - lower down the key is louder, within the * boundaries of the (white or black) key pressed. We then tell the * instrument to play that note, scaling for MIDI max loudness = 127. * * If we're in the 'root key selection' area, of course, we set the * root key to be that key. * * We finally update ourselves to show the key press * * \param me the mouse click to handle. */ void PianoView::mousePressEvent(QMouseEvent *me) { if (me->button() == Qt::LeftButton && m_piano != nullptr) { // get pressed key int key_num = getKeyFromMouse(me->pos()); if (me->pos().y() > PIANO_BASE) { int y_diff = me->pos().y() - PIANO_BASE; int velocity = static_cast<int>( static_cast<float>(y_diff) / getKeyHeight(key_num) * m_piano->instrumentTrack()->midiPort()->baseVelocity()); if (y_diff < 0) { velocity = 0; } else if (y_diff > getKeyHeight(key_num)) { velocity = m_piano->instrumentTrack()->midiPort()->baseVelocity(); } // set note on m_piano->midiEventProcessor()->processInEvent(MidiEvent(MidiNoteOn, -1, key_num, velocity)); m_piano->setKeyState(key_num, true); m_lastKey = key_num; emit keyPressed(key_num); } else if (!m_piano->instrumentTrack()->keyRangeImport()) { // upper section, select which marker (base / first / last note) will be moved m_movedNoteModel = getNearestMarker(key_num); if (me->modifiers() & Qt::ControlModifier) { new StringPairDrag("automatable_model", QString::number(m_movedNoteModel->id()), QPixmap(), this); me->accept(); } else { m_movedNoteModel->setInitValue(static_cast<float>(key_num)); if (m_movedNoteModel == m_piano->instrumentTrack()->baseNoteModel()) { emit baseNoteChanged(); } // TODO: not actually used by anything? } } else { m_movedNoteModel = nullptr; } // and let the user see that he pressed a key... :) update(); } } // handler for mouse-release-event /*! \brief Handle a mouse release event on the piano display view * * If a key was pressed by the in the mousePressEvent() function, we * turn the note off. * * \param _me the mousePressEvent to handle. */ void PianoView::mouseReleaseEvent( QMouseEvent * ) { if( m_lastKey != -1 ) { if( m_piano != nullptr ) { m_piano->midiEventProcessor()->processInEvent( MidiEvent( MidiNoteOff, -1, m_lastKey, 0 ) ); m_piano->setKeyState( m_lastKey, false ); } // and let the user see that he released a key... :) update(); m_lastKey = -1; m_movedNoteModel = nullptr; } } // handler for mouse-move-event /*! \brief Handle a mouse move event on the piano display view * * This handles the user dragging the mouse across the keys. It uses * code from mousePressEvent() and mouseReleaseEvent(), also correcting * for if the mouse movement has stayed within one key and if the mouse * has moved outside the vertical area of the keyboard (which is still * allowed but won't make the volume go up to 11). * * \param _me the ContextMenuEvent to handle. * \todo Paul Wayper thinks that this code should be refactored to * reduce or remove the duplication between this, the mousePressEvent() * and mouseReleaseEvent() methods. */ void PianoView::mouseMoveEvent( QMouseEvent * _me ) { if( m_piano == nullptr ) { return; } int key_num = getKeyFromMouse( _me->pos() ); int y_diff = _me->pos().y() - PIANO_BASE; int velocity = (int)( (float) y_diff / ( Piano::isWhiteKey( key_num ) ? PW_WHITE_KEY_HEIGHT : PW_BLACK_KEY_HEIGHT ) * (float) m_piano->instrumentTrack()->midiPort()->baseVelocity() ); // maybe the user moved the mouse-cursor above or under the // piano-widget while holding left button so check that and // correct volume if necessary if( y_diff < 0 ) { velocity = 0; } else if( y_diff > ( Piano::isWhiteKey( key_num ) ? PW_WHITE_KEY_HEIGHT : PW_BLACK_KEY_HEIGHT ) ) { velocity = m_piano->instrumentTrack()->midiPort()->baseVelocity(); } // is the calculated key different from current key? (could be the // user just moved the cursor one pixel left but on the same key) if( key_num != m_lastKey ) { if( m_lastKey != -1 ) { m_piano->midiEventProcessor()->processInEvent( MidiEvent( MidiNoteOff, -1, m_lastKey, 0 ) ); m_piano->setKeyState( m_lastKey, false ); m_lastKey = -1; } if( _me->buttons() & Qt::LeftButton ) { if( _me->pos().y() > PIANO_BASE ) { m_piano->midiEventProcessor()->processInEvent( MidiEvent( MidiNoteOn, -1, key_num, velocity ) ); m_piano->setKeyState( key_num, true ); m_lastKey = key_num; } else if (m_movedNoteModel != nullptr) { // upper section, move the base / first / last note marker m_movedNoteModel->setInitValue(static_cast<float>(key_num)); } } // and let the user see that he pressed a key... :) update(); } else if( m_piano->isKeyPressed( key_num ) ) { m_piano->midiEventProcessor()->processInEvent( MidiEvent( MidiKeyPressure, -1, key_num, velocity ) ); } } /*! \brief Handle a key press event on the piano display view * * We determine our key number from the getKeyFromKeyEvent() method, * and pass the event on to the piano's handleKeyPress() method if * auto-repeat is off. * * \param _ke the KeyEvent to handle. */ void PianoView::keyPressEvent( QKeyEvent * _ke ) { const int key_num = getKeyFromKeyEvent( _ke ); if( _ke->isAutoRepeat() == false && key_num > -1 ) { if( m_piano != nullptr ) { m_piano->handleKeyPress( key_num ); _ke->accept(); update(); } } else { _ke->ignore(); } } /*! \brief Handle a key release event on the piano display view * * The same logic as the keyPressEvent() method. * * \param _ke the KeyEvent to handle. */ void PianoView::keyReleaseEvent( QKeyEvent * _ke ) { const int key_num = getKeyFromKeyEvent( _ke ); if( _ke->isAutoRepeat() == false && key_num > -1 ) { if( m_piano != nullptr ) { m_piano->handleKeyRelease( key_num ); _ke->accept(); update(); } } else { _ke->ignore(); } } /*! \brief Handle the focus leaving the piano display view * * Turn off all notes if we lose focus. * * \todo Is there supposed to be a parameter given here? */ void PianoView::focusOutEvent( QFocusEvent * ) { if( m_piano == nullptr ) { return; } // focus just switched to another control inside the instrument track // window we live in? if( parentWidget()->parentWidget()->focusWidget() != this && parentWidget()->parentWidget()->focusWidget() != nullptr && !(parentWidget()->parentWidget()-> focusWidget()->inherits( "QLineEdit" ) || parentWidget()->parentWidget()-> focusWidget()->inherits( "QPlainTextEdit" ) )) { // then reclaim keyboard focus! setFocus(); return; } // if we loose focus, we HAVE to note off all running notes because // we don't receive key-release-events anymore and so the notes would // hang otherwise for( int i = 0; i < NumKeys; ++i ) { m_piano->midiEventProcessor()->processInEvent( MidiEvent( MidiNoteOff, -1, i, 0 ) ); m_piano->setKeyState( i, false ); } update(); } void PianoView::focusInEvent( QFocusEvent * ) { m_piano->instrumentTrack()->autoAssignMidiDevice(true); } /*! \brief update scrollbar range after resize * * After resizing we need to adjust range of scrollbar for not allowing * to scroll too far to the right. * * \param event resize-event object (unused) */ void PianoView::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); m_pianoScroll->setRange(0, Piano::NumWhiteKeys - static_cast<int>(floor(static_cast<float>(width()) / PW_WHITE_KEY_WIDTH))); } /*! \brief Convert a key number to an X coordinate in the piano display view * * We can immediately discard the trivial case of when the key number is * less than our starting key. We then iterate through the keys from the * start key to this key, adding the width of each key as we go. For * black keys, and the first white key if there is no black key between * two white keys, we add half a white key width; for that second white * key, we add a whole width. That takes us to the boundary of a white * key - subtract half a width to get to the middle. * * \param _key_num the keyboard key to translate * \todo is this description of what the method does correct? * \todo replace the final subtract with initialising x to width/2. */ int PianoView::getKeyX( int _key_num ) const { int k = m_startKey; if( _key_num < m_startKey ) { return ( _key_num - k ) * PW_WHITE_KEY_WIDTH / 2; } int x = 0; int white_cnt = 0; while( k <= _key_num ) { if( Piano::isWhiteKey( k ) ) { ++white_cnt; if( white_cnt > 1 ) { x += PW_WHITE_KEY_WIDTH; } else { x += PW_WHITE_KEY_WIDTH/2; } } else { white_cnt = 0; x += PW_WHITE_KEY_WIDTH/2; } ++k; } x -= PW_WHITE_KEY_WIDTH / 2; return x; } /*! \brief Return the width of a given key */ int PianoView::getKeyWidth(int key_num) const { return Piano::isWhiteKey(key_num) ? PW_WHITE_KEY_WIDTH : PW_BLACK_KEY_WIDTH; } /*! \brief Return the height of a given key */ int PianoView::getKeyHeight(int key_num) const { return Piano::isWhiteKey(key_num) ? PW_WHITE_KEY_HEIGHT : PW_BLACK_KEY_HEIGHT; } /*! \brief Return model and title of the marker closest to the given key */ IntModel* PianoView::getNearestMarker(int key, QString* title) { const int base = m_piano->instrumentTrack()->baseNote(); const int first = m_piano->instrumentTrack()->firstKey(); const int last = m_piano->instrumentTrack()->lastKey(); if (abs(key - base) < abs(key - first) && abs(key - base) < abs(key - last)) { if (title) {*title = tr("Base note");} return m_piano->instrumentTrack()->baseNoteModel(); } else if (abs(key - first) < abs(key - last)) { if (title) {*title = tr("First note");} return m_piano->instrumentTrack()->firstKeyModel(); } else { if (title) {*title = tr("Last note");} return m_piano->instrumentTrack()->lastKeyModel(); } } /*! \brief Paint the piano display view in response to an event * * This method draws the piano and the 'root note' base. It draws * the base first, then all the white keys, then all the black keys. * * \todo Is there supposed to be a parameter given here? */ void PianoView::paintEvent( QPaintEvent * ) { QPainter p( this ); // set smaller font for printing number of every octave p.setFont(adjustedToPixelSize(p.font(), LABEL_TEXT_SIZE)); // draw bar above the keyboard (there will be the labels // for all C's) p.fillRect( QRect( 0, 1, width(), PIANO_BASE-2 ), p.background() ); // draw the line above the keyboard p.setPen( Qt::black ); p.drawLine( 0, 0, width(), 0 ); p.drawLine( 0, PIANO_BASE-1, width(), PIANO_BASE-1 ); p.setPen( Qt::white ); // Controls for first / last / base key models are shown only if microtuner or its key range import are disabled if (m_piano != nullptr && !m_piano->instrumentTrack()->keyRangeImport()) { // Draw the base note marker and first / last note boundary markers const int base_key = m_piano->instrumentTrack()->baseNoteModel()->value(); const int first_key = m_piano->instrumentTrack()->firstKeyModel()->value(); const int last_key = m_piano->instrumentTrack()->lastKeyModel()->value(); QColor marker_color = QApplication::palette().color(QPalette::Active, QPalette::BrightText); // - prepare triangle shapes for start / end markers QPainterPath first_marker(QPoint(getKeyX(first_key) + 1, 1)); first_marker.lineTo(getKeyX(first_key) + 1, PIANO_BASE); first_marker.lineTo(getKeyX(first_key) + PIANO_BASE / 2 + 1, PIANO_BASE / 2); QPainterPath last_marker(QPoint(getKeyX(last_key) + getKeyWidth(last_key), 1)); last_marker.lineTo(getKeyX(last_key) + getKeyWidth(last_key), PIANO_BASE); last_marker.lineTo(getKeyX(last_key) + getKeyWidth(last_key) - PIANO_BASE / 2, PIANO_BASE / 2); // - fill all markers p.fillRect(QRect(getKeyX(base_key), 1, getKeyWidth(base_key) - 1, PIANO_BASE - 2), marker_color); p.fillPath(first_marker, marker_color); p.fillPath(last_marker, marker_color); } int cur_key = m_startKey; // draw all white keys... for (int x = 0; x < width();) { while (Piano::isBlackKey(cur_key)) { ++cur_key; } // draw normal, pressed or disabled key, depending on state and position of current key if (m_piano && m_piano->instrumentTrack()->isKeyMapped(cur_key)) { if (m_piano && m_piano->isKeyPressed(cur_key)) { p.drawPixmap(x, PIANO_BASE, m_whiteKeyPressedPm); } else { p.drawPixmap(x, PIANO_BASE, m_whiteKeyPm); } } else { p.drawPixmap(x, PIANO_BASE, m_whiteKeyDisabledPm); } x += PW_WHITE_KEY_WIDTH; if ((Key)(cur_key % KeysPerOctave) == Key::C) { // label key of note C with "C" and number of current octave p.drawText(x - PW_WHITE_KEY_WIDTH, LABEL_TEXT_SIZE + 2, QString("C") + QString::number(FirstOctave + cur_key / KeysPerOctave)); } ++cur_key; } // reset all values, because now we're going to draw all black keys cur_key = m_startKey; int white_cnt = 0; int startKey = m_startKey; if (startKey > 0 && Piano::isBlackKey(--startKey)) { if (m_piano && m_piano->instrumentTrack()->isKeyMapped(startKey)) { if (m_piano && m_piano->isKeyPressed(startKey)) { p.drawPixmap(0 - PW_WHITE_KEY_WIDTH / 2, PIANO_BASE, m_blackKeyPressedPm); } else { p.drawPixmap(0 - PW_WHITE_KEY_WIDTH / 2, PIANO_BASE, m_blackKeyPm); } } else { p.drawPixmap(0 - PW_WHITE_KEY_WIDTH / 2, PIANO_BASE, m_blackKeyDisabledPm); } } // now draw all black keys... for (int x = 0; x < width();) { if (Piano::isBlackKey(cur_key)) { // draw normal, pressed or disabled key, depending on state and position of current key if (m_piano && m_piano->instrumentTrack()->isKeyMapped(cur_key)) { if (m_piano && m_piano->isKeyPressed(cur_key)) { p.drawPixmap(x + PW_WHITE_KEY_WIDTH / 2, PIANO_BASE, m_blackKeyPressedPm); } else { p.drawPixmap(x + PW_WHITE_KEY_WIDTH / 2, PIANO_BASE, m_blackKeyPm); } } else { p.drawPixmap(x + PW_WHITE_KEY_WIDTH / 2, PIANO_BASE, m_blackKeyDisabledPm); } x += PW_WHITE_KEY_WIDTH; white_cnt = 0; } else { // simple workaround for increasing x if there were two // white keys (e.g. between E and F) ++white_cnt; if (white_cnt > 1) { x += PW_WHITE_KEY_WIDTH; } } // stop drawing when all keys are drawn, even if an extra black key could fit if (++cur_key == NumKeys) {break;} } } } // namespace lmms::gui
27,479
C++
.cpp
824
30.686893
140
0.668124
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,932
EnvelopeGraph.cpp
LMMS_lmms/src/gui/instrument/EnvelopeGraph.cpp
/* * EnvelopeGraph.cpp - Displays envelope graphs * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * 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. * */ #include "EnvelopeGraph.h" #include <QMouseEvent> #include <QPainter> #include <QMenu> #include "EnvelopeAndLfoParameters.h" #include "lmms_math.h" #include "ColorHelper.h" #include <cmath> namespace lmms { namespace gui { EnvelopeGraph::EnvelopeGraph(QWidget* parent) : QWidget(parent), ModelView(nullptr, this) { setMinimumSize(m_envGraph.size()); } void EnvelopeGraph::modelChanged() { m_params = castModel<EnvelopeAndLfoParameters>(); } void EnvelopeGraph::mousePressEvent(QMouseEvent* me) { if (me->button() == Qt::LeftButton) { toggleAmountModel(); } } void EnvelopeGraph::contextMenuEvent(QContextMenuEvent* event) { QMenu menu(this); QMenu* scalingMenu = menu.addMenu(tr("Scaling")); scalingMenu->setToolTipsVisible(true); auto switchTo = [&](ScalingMode scaling) { if (m_scaling != scaling) { m_scaling = scaling; update(); } }; auto addScalingEntry = [scalingMenu, &switchTo, this](const QString& text, const QString& toolTip, ScalingMode scaling) { QAction* action = scalingMenu->addAction(text, [&switchTo, scaling]() { switchTo(scaling); }); action->setCheckable(true); action->setChecked(m_scaling == scaling); action->setToolTip(toolTip); }; addScalingEntry( tr("Dynamic"), tr("Uses absolute spacings but switches to relative spacing if it's running out of space"), ScalingMode::Dynamic); addScalingEntry( tr("Absolute"), tr("Provides enough potential space for each segment but does not scale"), ScalingMode::Absolute); addScalingEntry( tr("Relative"), tr("Always uses all of the available space to display the envelope graph"), ScalingMode::Relative); menu.exec(event->globalPos()); } void EnvelopeGraph::paintEvent(QPaintEvent*) { QPainter p{this}; p.setRenderHint(QPainter::Antialiasing); // Draw the graph background p.drawPixmap(rect(), m_envGraph); const auto* params = castModel<EnvelopeAndLfoParameters>(); if (!params) { return; } // For the calculation of the percentages we will for now make use of the knowledge // that the range goes from 0 to a positive max value, i.e. that it is in [0, max]. const float amount = params->getAmountModel().value(); const float predelay = params->getPredelayModel().value(); const float predelayPercentage = predelay / params->getPredelayModel().maxValue(); const float attack = params->getAttackModel().value(); const float attackPercentage = attack / params->getAttackModel().maxValue(); const float hold = params->getHoldModel().value(); const float holdPercentage = hold / params->getHoldModel().maxValue(); const float decay = params->getDecayModel().value(); const float decayPercentage = decay / params->getDecayModel().maxValue(); const float sustain = params->getSustainModel().value(); const float release = params->getReleaseModel().value(); const float releasePercentage = release / params->getReleaseModel().maxValue(); // The margin to the left and right so that we do not clip too much of the lines and markers const float margin = 2.0; const float availableWidth = width() - margin * 2; // Now determine the maximum width for one segment according to the scaling setting. // The different scalings use different means to compute the maximum available width per segment. const auto computeMaximumSegmentWidthAbsolute = [&]() -> float { return availableWidth / 5.; }; const auto computeMaximumSegmentWidthRelative = [&]() -> float { const float sumOfSegments = predelayPercentage + attackPercentage + holdPercentage + decayPercentage + releasePercentage; return sumOfSegments != 0. ? availableWidth / sumOfSegments : computeMaximumSegmentWidthAbsolute(); }; const auto computeMaximumSegmentWidthDynamic = [&]() -> float { const float sumOfSegments = predelayPercentage + attackPercentage + holdPercentage + decayPercentage + releasePercentage; float preliminarySegmentWidth = 80. / 182. * availableWidth; const float neededWidth = sumOfSegments * preliminarySegmentWidth; if (neededWidth > availableWidth && sumOfSegments != 0.) { return computeMaximumSegmentWidthRelative(); } return preliminarySegmentWidth; }; // This is the maximum width that each of the five segments (DAHDR) can occupy. float maximumSegmentWidth; switch (m_scaling) { case ScalingMode::Absolute: maximumSegmentWidth = computeMaximumSegmentWidthAbsolute(); break; case ScalingMode::Relative: maximumSegmentWidth = computeMaximumSegmentWidthRelative(); break; case ScalingMode::Dynamic: default: maximumSegmentWidth = computeMaximumSegmentWidthDynamic(); break; } // Compute the actual widths that the segments occupy and add them to the // previous x coordinates starting at the margin. const float predelayX = margin + predelayPercentage * maximumSegmentWidth; const float attackX = predelayX + attackPercentage * maximumSegmentWidth; const float holdX = attackX + holdPercentage * maximumSegmentWidth; const float decayX = holdX + (decayPercentage * (1 - sustain)) * maximumSegmentWidth; const float releaseX = decayX + releasePercentage * maximumSegmentWidth; // Now compute the "full" points including y coordinates const int yTop = 3; const qreal yBase = height() - 3; const int availableHeight = yBase - yTop; const QPointF predelayPoint{predelayX, yBase}; const QPointF attackPoint{attackX, yTop}; const QPointF holdPoint{holdX, yTop}; const QPointF decayPoint{decayX, yTop + (1 - sustain) * availableHeight}; const QPointF releasePoint{releaseX, yBase}; // Now that we have all points we can draw the lines // Compute the color of the lines based on the amount of the envelope const float absAmount = std::abs(amount); const QColor noAmountColor{96, 91, 96}; const QColor fullAmountColor{0, 255, 128}; const QColor lineColor{ColorHelper::interpolateInRgb(noAmountColor, fullAmountColor, absAmount)}; // Determine the line width so that it scales with the widget // Use the minimum value of the current width and height to compute it. const qreal lineWidth = std::min(width(), height()) / 20.; const QPen linePen{lineColor, lineWidth}; p.setPen(linePen); QPolygonF linePoly; linePoly << predelayPoint << attackPoint << holdPoint << decayPoint << releasePoint; p.drawPolyline(linePoly); // Now draw all marker on top of the lines const QColor markerFillColor{153, 175, 255}; const QColor markerOutlineColor{0, 0, 0}; QPen pen; pen.setWidthF(lineWidth * 0.75); pen.setBrush(markerOutlineColor); p.setPen(pen); p.setBrush(markerFillColor); // Compute the size of the circle we will draw based on the line width const qreal baseRectSize = lineWidth * 3; const QSizeF rectSize{baseRectSize, baseRectSize}; auto drawMarker = [&](const QPointF& point) { // Create a rectangle that has the given point at its center QRectF bgRect{point + QPointF(-baseRectSize / 2, -baseRectSize / 2), rectSize}; p.drawEllipse(bgRect); }; drawMarker(predelayPoint); drawMarker(attackPoint); drawMarker(holdPoint); drawMarker(decayPoint); drawMarker(releasePoint); } void EnvelopeGraph::toggleAmountModel() { auto* params = castModel<EnvelopeAndLfoParameters>(); auto& amountModel = params->getAmountModel(); amountModel.setValue(amountModel.value() < 1.0 ? 1.0 : 0.0); } } // namespace gui } // namespace lmms
8,283
C++
.cpp
209
37.22488
123
0.7645
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
19,933
InstrumentMidiIOView.cpp
LMMS_lmms/src/gui/instrument/InstrumentMidiIOView.cpp
/* * InstrumentMidiIOView.cpp - MIDI-IO-View * * 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. * */ #include <QToolButton> #include <QHBoxLayout> #include <QLabel> #include <QVBoxLayout> #include "InstrumentMidiIOView.h" #include "MidiPortMenu.h" #include "AudioEngine.h" #include "Engine.h" #include "embed.h" #include "GroupBox.h" #include "LcdSpinBox.h" #include "MidiClient.h" namespace lmms::gui { InstrumentMidiIOView::InstrumentMidiIOView( QWidget* parent ) : QWidget( parent ), ModelView( nullptr, this ), m_rpBtn( nullptr ), m_wpBtn( nullptr ) { auto layout = new QVBoxLayout(this); layout->setContentsMargins(5, 5, 5, 5); m_midiInputGroupBox = new GroupBox( tr( "ENABLE MIDI INPUT" ) ); layout->addWidget( m_midiInputGroupBox ); auto midiInputLayout = new QHBoxLayout(m_midiInputGroupBox); midiInputLayout->setContentsMargins( 8, 18, 8, 8 ); midiInputLayout->setSpacing( 4 ); m_inputChannelSpinBox = new LcdSpinBox( 2, m_midiInputGroupBox ); m_inputChannelSpinBox->addTextForValue( 0, "--" ); /*: This string must be be short, its width must be less than * width of LCD spin-box of two digits */ m_inputChannelSpinBox->setLabel( tr( "CHAN" ) ); m_inputChannelSpinBox->setEnabled( false ); midiInputLayout->addWidget( m_inputChannelSpinBox ); m_fixedInputVelocitySpinBox = new LcdSpinBox( 3, m_midiInputGroupBox ); m_fixedInputVelocitySpinBox->addTextForValue( -1, "---" ); /*: This string must be be short, its width must be less than * width of LCD spin-box of three digits */ m_fixedInputVelocitySpinBox->setLabel( tr( "VELOC" ) ); m_fixedInputVelocitySpinBox->setEnabled( false ); midiInputLayout->addWidget( m_fixedInputVelocitySpinBox ); midiInputLayout->addStretch(); connect( m_midiInputGroupBox->ledButton(), SIGNAL(toggled(bool)), m_inputChannelSpinBox, SLOT(setEnabled(bool))); connect( m_midiInputGroupBox->ledButton(), SIGNAL(toggled(bool)), m_fixedInputVelocitySpinBox, SLOT(setEnabled(bool))); m_midiOutputGroupBox = new GroupBox( tr( "ENABLE MIDI OUTPUT" ) ); layout->addWidget( m_midiOutputGroupBox ); auto midiOutputLayout = new QHBoxLayout(m_midiOutputGroupBox); midiOutputLayout->setContentsMargins( 8, 18, 8, 8 ); midiOutputLayout->setSpacing( 4 ); m_outputChannelSpinBox = new LcdSpinBox( 2, m_midiOutputGroupBox ); m_outputChannelSpinBox->addTextForValue( 0, "--" ); /*: This string must be be short, its width must be less than * width of LCD spin-box of two digits */ m_outputChannelSpinBox->setLabel( tr( "CHAN" ) ); midiOutputLayout->addWidget( m_outputChannelSpinBox ); m_fixedOutputVelocitySpinBox = new LcdSpinBox( 3, m_midiOutputGroupBox ); m_fixedOutputVelocitySpinBox->addTextForValue( -1, "---" ); /*: This string must be be short, its width must be less than * width of LCD spin-box of three digits */ m_fixedOutputVelocitySpinBox->setLabel( tr( "VELOC" ) ); m_fixedOutputVelocitySpinBox->setEnabled( false ); midiOutputLayout->addWidget( m_fixedOutputVelocitySpinBox ); m_outputProgramSpinBox = new LcdSpinBox( 3, m_midiOutputGroupBox ); /*: This string must be be short, its width must be less than the * width of LCD spin-box of three digits */ m_outputProgramSpinBox->setLabel( tr( "PROG" ) ); m_outputProgramSpinBox->setEnabled( false ); midiOutputLayout->addWidget( m_outputProgramSpinBox ); m_fixedOutputNoteSpinBox = new LcdSpinBox( 3, m_midiOutputGroupBox ); m_fixedOutputNoteSpinBox->addTextForValue( -1, "---" ); /*: This string must be be short, its width must be less than * width of LCD spin-box of three digits */ m_fixedOutputNoteSpinBox->setLabel( tr( "NOTE" ) ); m_fixedOutputNoteSpinBox->setEnabled( false ); midiOutputLayout->addWidget( m_fixedOutputNoteSpinBox ); midiOutputLayout->addStretch(); connect( m_midiOutputGroupBox->ledButton(), SIGNAL(toggled(bool)), m_fixedOutputVelocitySpinBox, SLOT(setEnabled(bool))); connect( m_midiOutputGroupBox->ledButton(), SIGNAL(toggled(bool)), m_outputProgramSpinBox, SLOT(setEnabled(bool))); connect( m_midiOutputGroupBox->ledButton(), SIGNAL(toggled(bool)), m_fixedOutputNoteSpinBox, SLOT(setEnabled(bool))); if( !Engine::audioEngine()->midiClient()->isRaw() ) { m_rpBtn = new QToolButton; m_rpBtn->setMinimumSize( 32, 32 ); m_rpBtn->setText( tr( "MIDI devices to receive MIDI events from" ) ); m_rpBtn->setIcon( embed::getIconPixmap( "piano" ) ); m_rpBtn->setPopupMode( QToolButton::InstantPopup ); midiInputLayout->insertSpacing( 0, 4 ); midiInputLayout->insertWidget( 0, m_rpBtn ); m_wpBtn = new QToolButton; m_wpBtn->setMinimumSize( 32, 32 ); m_wpBtn->setText( tr( "MIDI devices to send MIDI events to" ) ); m_wpBtn->setIcon( embed::getIconPixmap( "piano" ) ); m_wpBtn->setPopupMode( QToolButton::InstantPopup ); midiOutputLayout->insertSpacing( 0, 4 ); midiOutputLayout->insertWidget( 0, m_wpBtn ); } auto baseVelocityGroupBox = new GroupBox(tr("VELOCITY MAPPING")); baseVelocityGroupBox->setLedButtonShown(false); layout->addWidget( baseVelocityGroupBox ); auto baseVelocityLayout = new QVBoxLayout(baseVelocityGroupBox); baseVelocityLayout->setContentsMargins( 8, 18, 8, 8 ); baseVelocityLayout->setSpacing( 6 ); m_baseVelocitySpinBox = new LcdSpinBox( 3, baseVelocityGroupBox ); m_baseVelocitySpinBox->setLabel(tr("MIDI VELOCITY")); m_baseVelocitySpinBox->setToolTip(tr("MIDI notes at this velocity correspond to 100% note velocity.")); baseVelocityLayout->addWidget( m_baseVelocitySpinBox ); layout->addStretch(); } void InstrumentMidiIOView::modelChanged() { auto mp = castModel<MidiPort>(); m_midiInputGroupBox->setModel( &mp->m_readableModel ); m_inputChannelSpinBox->setModel( &mp->m_inputChannelModel ); m_fixedInputVelocitySpinBox->setModel( &mp->m_fixedInputVelocityModel ); m_midiOutputGroupBox->setModel( &mp->m_writableModel ); m_outputChannelSpinBox->setModel( &mp->m_outputChannelModel ); m_fixedOutputVelocitySpinBox->setModel( &mp->m_fixedOutputVelocityModel ); m_fixedOutputNoteSpinBox->setModel( &mp->m_fixedOutputNoteModel ); m_outputProgramSpinBox->setModel( &mp->m_outputProgramModel ); m_baseVelocitySpinBox->setModel( &mp->m_baseVelocityModel ); if( m_rpBtn ) { m_rpBtn->setMenu( mp->m_readablePortsMenu ); } if( m_wpBtn ) { m_wpBtn->setMenu( mp->m_writablePortsMenu ); } } } // namespace lmms::gui
7,142
C++
.cpp
158
42.936709
104
0.759246
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,934
LfoGraph.cpp
LMMS_lmms/src/gui/instrument/LfoGraph.cpp
/* * LfoGraph.cpp - Displays LFO graphs * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * 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. * */ #include "LfoGraph.h" #include <QMouseEvent> #include <QPainter> #include "EnvelopeAndLfoParameters.h" #include "Oscillator.h" #include "ColorHelper.h" #include "FontHelper.h" namespace lmms { extern const float SECS_PER_LFO_OSCILLATION; namespace gui { LfoGraph::LfoGraph(QWidget* parent) : QWidget(parent), ModelView(nullptr, this) { setMinimumSize(m_lfoGraph.size()); } void LfoGraph::mousePressEvent(QMouseEvent* me) { if (me->button() == Qt::LeftButton) { toggleAmountModel(); } } void LfoGraph::paintEvent(QPaintEvent*) { QPainter p{this}; p.setRenderHint(QPainter::Antialiasing); // Draw the graph background p.drawPixmap(rect(), m_lfoGraph); const auto* params = castModel<EnvelopeAndLfoParameters>(); if (!params) { return; } const float amount = params->getLfoAmountModel().value(); const float lfoSpeed = params->getLfoSpeedModel().value(); const f_cnt_t predelayFrames = params->getLfoPredelayFrames(); const f_cnt_t attackFrames = params->getLfoAttackFrames(); const f_cnt_t oscillationFrames = params->getLfoOscillationFrames(); const bool x100 = params->getX100Model().value(); const int lfoWaveModel = params->getLfoWaveModel().value(); const auto * userWave = params->getLfoUserWave().get(); const int margin = 3; const int lfoGraphWidth = width() - margin; // subtract margin const int lfoGraphHeight = height() - 2 * margin; // subtract margin int graphBaseX = 2; int graphBaseY = margin + lfoGraphHeight / 2; const float framesForGraph = SECS_PER_LFO_OSCILLATION * Engine::audioEngine()->baseSampleRate() / 10; float oscFrames = oscillationFrames * (x100 ? 100. : 1.); QPolygonF polyLine; polyLine << QPointF(graphBaseX - 1, graphBaseY); // Collect the points for the poly line by sampling the LFO according to its shape for (int x = 0; x <= lfoGraphWidth; ++x) { float value = 0.0; float currentSample = x * framesForGraph / lfoGraphWidth; const auto sampleAsFrameCount = static_cast<f_cnt_t>(currentSample); if (sampleAsFrameCount > predelayFrames) { currentSample -= predelayFrames; const float phase = currentSample / oscFrames; const auto lfoShape = static_cast<EnvelopeAndLfoParameters::LfoShape>(lfoWaveModel); switch (lfoShape) { case EnvelopeAndLfoParameters::LfoShape::SineWave: default: value = Oscillator::sinSample(phase); break; case EnvelopeAndLfoParameters::LfoShape::TriangleWave: value = Oscillator::triangleSample(phase); break; case EnvelopeAndLfoParameters::LfoShape::SawWave: value = Oscillator::sawSample(phase); break; case EnvelopeAndLfoParameters::LfoShape::SquareWave: value = Oscillator::squareSample(phase); break; case EnvelopeAndLfoParameters::LfoShape::RandomWave: if (x % (int)(900 * lfoSpeed + 1) == 0) { m_randomGraph = Oscillator::noiseSample(0.0); } value = m_randomGraph; break; case EnvelopeAndLfoParameters::LfoShape::UserDefinedWave: value = Oscillator::userWaveSample(userWave, phase); break; } if (sampleAsFrameCount <= attackFrames) { value *= currentSample / attackFrames; } } const float currentY = -lfoGraphHeight / 2.0f * value; polyLine << QPointF(graphBaseX + x, graphBaseY + currentY); } // Compute the color of the lines based on the amount of the LFO const float absAmount = std::abs(amount); const QColor noAmountColor{96, 91, 96}; const QColor fullAmountColor{0, 255, 128}; const QColor lineColor{ColorHelper::interpolateInRgb(noAmountColor, fullAmountColor, absAmount)}; p.setPen(QPen(lineColor, 1.5)); p.drawPolyline(polyLine); drawInfoText(*params); } void LfoGraph::drawInfoText(const EnvelopeAndLfoParameters& params) { QPainter p(this); const float lfoSpeed = params.getLfoSpeedModel().value(); const bool x100 = params.getX100Model().value(); const float hertz = 1. / (SECS_PER_LFO_OSCILLATION * lfoSpeed) * (x100 ? 100. : 1.); const auto infoText = tr("%1 Hz").arg(hertz, 0, 'f', 3); // First configure the font so that we get correct results for the font metrics used below QFont f = p.font(); p.setFont(adjustedToPixelSize(f, height() * 0.2)); // This is the position where the text and its rectangle will be rendered const QPoint textPosition(4, height() - 6); // Draw a slightly transparent black rectangle underneath the text to keep it legible const QFontMetrics fontMetrics(f); // This gives the bounding rectangle if the text was rendered at the origin ... const auto boundingRect = fontMetrics.boundingRect(infoText); // ... so we translate it to the actual position where the text will be rendered. p.fillRect(boundingRect.translated(textPosition), QColor{0, 0, 0, 192}); // Now draw the actual info text p.setPen(QColor(201, 201, 225)); p.drawText(textPosition, infoText); } void LfoGraph::toggleAmountModel() { auto* params = castModel<EnvelopeAndLfoParameters>(); auto& lfoAmountModel = params->getLfoAmountModel(); lfoAmountModel.setValue(lfoAmountModel.value() < 1.0 ? 1.0 : 0.0); } } // namespace gui } // namespace lmms
6,042
C++
.cpp
159
35.213836
98
0.744099
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
19,935
InstrumentSoundShapingView.cpp
LMMS_lmms/src/gui/instrument/InstrumentSoundShapingView.cpp
/* * InstrumentSoundShapingView.cpp - view for InstrumentSoundShaping 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. * */ #include "InstrumentSoundShapingView.h" #include <QLabel> #include <QBoxLayout> #include "EnvelopeAndLfoParameters.h" #include "EnvelopeAndLfoView.h" #include "ComboBox.h" #include "GroupBox.h" #include "FontHelper.h" #include "Knob.h" #include "TabWidget.h" namespace lmms::gui { InstrumentSoundShapingView::InstrumentSoundShapingView(QWidget* parent) : QWidget(parent), ModelView(nullptr, this) { QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(5, 5, 5, 5); m_targetsTabWidget = new TabWidget(tr("TARGET"), this); for (auto i = std::size_t{0}; i < InstrumentSoundShaping::NumTargets; ++i) { m_envLfoViews[i] = new EnvelopeAndLfoView(m_targetsTabWidget); m_targetsTabWidget->addTab(m_envLfoViews[i], tr(InstrumentSoundShaping::targetNames[i][0]), nullptr); } mainLayout->addWidget(m_targetsTabWidget, 1); m_filterGroupBox = new GroupBox(tr("FILTER"), this); QHBoxLayout* filterLayout = new QHBoxLayout(m_filterGroupBox); QMargins filterMargins = filterLayout->contentsMargins(); filterMargins.setTop(18); filterLayout->setContentsMargins(filterMargins); m_filterComboBox = new ComboBox(m_filterGroupBox); filterLayout->addWidget(m_filterComboBox); m_filterCutKnob = new Knob(KnobType::Bright26, m_filterGroupBox); m_filterCutKnob->setLabel(tr("FREQ")); m_filterCutKnob->setHintText(tr("Cutoff frequency:"), " " + tr("Hz")); filterLayout->addWidget(m_filterCutKnob); m_filterResKnob = new Knob(KnobType::Bright26, m_filterGroupBox); m_filterResKnob->setLabel(tr("Q/RESO")); m_filterResKnob->setHintText(tr("Q/Resonance:"), ""); filterLayout->addWidget(m_filterResKnob); mainLayout->addWidget(m_filterGroupBox); m_singleStreamInfoLabel = new QLabel(tr("Envelopes, LFOs and filters are not supported by the current instrument."), this); m_singleStreamInfoLabel->setWordWrap(true); // TODO Could also be rendered in system font size... m_singleStreamInfoLabel->setFont(adjustedToPixelSize(m_singleStreamInfoLabel->font(), DEFAULT_FONT_SIZE)); m_singleStreamInfoLabel->setFixedWidth(242); mainLayout->addWidget(m_singleStreamInfoLabel, 0, Qt::AlignTop); } InstrumentSoundShapingView::~InstrumentSoundShapingView() { delete m_targetsTabWidget; } void InstrumentSoundShapingView::setFunctionsHidden( bool hidden ) { m_targetsTabWidget->setHidden( hidden ); m_filterGroupBox->setHidden( hidden ); m_singleStreamInfoLabel->setHidden( !hidden ); } void InstrumentSoundShapingView::modelChanged() { m_ss = castModel<InstrumentSoundShaping>(); m_filterGroupBox->setModel( &m_ss->m_filterEnabledModel ); m_filterComboBox->setModel( &m_ss->m_filterModel ); m_filterCutKnob->setModel( &m_ss->m_filterCutModel ); m_filterResKnob->setModel( &m_ss->m_filterResModel ); for (auto i = std::size_t{0}; i < InstrumentSoundShaping::NumTargets; ++i) { m_envLfoViews[i]->setModel( m_ss->m_envLfoParameters[i] ); } } } // namespace lmms::gui
3,886
C++
.cpp
95
38.778947
124
0.77488
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
19,936
EnvelopeAndLfoView.cpp
LMMS_lmms/src/gui/instrument/EnvelopeAndLfoView.cpp
/* * EnvelopeAndLfoView.cpp - widget which is m_used by envelope/lfo/filter- * tab of instrument track window * * 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. * */ #include "EnvelopeAndLfoView.h" #include <string_view> #include <QBoxLayout> #include "EnvelopeGraph.h" #include "LfoGraph.h" #include "EnvelopeAndLfoParameters.h" #include "SampleLoader.h" #include "Knob.h" #include "LedCheckBox.h" #include "DataFile.h" #include "PixmapButton.h" #include "StringPairDrag.h" #include "TempoSyncKnob.h" #include "TextFloat.h" #include "Track.h" namespace lmms { namespace gui { EnvelopeAndLfoView::EnvelopeAndLfoView(QWidget * parent) : QWidget(parent), ModelView(nullptr, this), m_params(nullptr) { // Helper lambdas for consistent repeated buiding of certain widgets auto buildKnob = [&](const QString& label, const QString& hintText) { auto knob = new Knob(KnobType::Bright26, this); knob->setLabel(label); knob->setHintText(hintText, ""); return knob; }; auto buildPixmapButton = [&](std::string_view activePixmap, std::string_view inactivePixmap) { auto button = new PixmapButton(this, nullptr); button->setActiveGraphic(embed::getIconPixmap(activePixmap)); button->setInactiveGraphic(embed::getIconPixmap(inactivePixmap)); return button; }; QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(5, 5, 5, 5); // Envelope QVBoxLayout* envelopeLayout = new QVBoxLayout(); mainLayout->addLayout(envelopeLayout); QHBoxLayout* graphAndAmountLayout = new QHBoxLayout(); envelopeLayout->addLayout(graphAndAmountLayout); m_envelopeGraph = new EnvelopeGraph(this); graphAndAmountLayout->addWidget(m_envelopeGraph); m_amountKnob = buildKnob(tr("AMT"), tr("Modulation amount:")); graphAndAmountLayout->addWidget(m_amountKnob, 0, Qt::AlignCenter); QHBoxLayout* envKnobsLayout = new QHBoxLayout(); envelopeLayout->addLayout(envKnobsLayout); m_predelayKnob = buildKnob(tr("DEL"), tr("Pre-delay:")); envKnobsLayout->addWidget(m_predelayKnob); m_attackKnob = buildKnob(tr("ATT"), tr("Attack:")); envKnobsLayout->addWidget(m_attackKnob); m_holdKnob = buildKnob(tr("HOLD"), tr("Hold:")); envKnobsLayout->addWidget(m_holdKnob); m_decayKnob = buildKnob(tr("DEC"), tr("Decay:")); envKnobsLayout->addWidget(m_decayKnob); m_sustainKnob = buildKnob(tr("SUST"), tr("Sustain:")); envKnobsLayout->addWidget(m_sustainKnob); m_releaseKnob = buildKnob(tr("REL"), tr("Release:")); envKnobsLayout->addWidget(m_releaseKnob); // Add some space between the envelope and LFO section mainLayout->addSpacing(10); // LFO QHBoxLayout* lfoLayout = new QHBoxLayout(); mainLayout->addLayout(lfoLayout); QVBoxLayout* graphAndTypesLayout = new QVBoxLayout(); lfoLayout->addLayout(graphAndTypesLayout); m_lfoGraph = new LfoGraph(this); graphAndTypesLayout->addWidget(m_lfoGraph); QHBoxLayout* typesLayout = new QHBoxLayout(); graphAndTypesLayout->addLayout(typesLayout); typesLayout->setContentsMargins(0, 0, 0, 0); typesLayout->setSpacing(0); auto sin_lfo_btn = buildPixmapButton("sin_wave_active", "sin_wave_inactive"); auto triangle_lfo_btn = buildPixmapButton("triangle_wave_active", "triangle_wave_inactive"); auto saw_lfo_btn = buildPixmapButton("saw_wave_active", "saw_wave_inactive"); auto sqr_lfo_btn = buildPixmapButton("square_wave_active","square_wave_inactive"); auto random_lfo_btn = buildPixmapButton("random_wave_active", "random_wave_inactive"); m_userLfoBtn = buildPixmapButton("usr_wave_active", "usr_wave_inactive"); connect(m_userLfoBtn, SIGNAL(toggled(bool)), this, SLOT(lfoUserWaveChanged())); typesLayout->addWidget(sin_lfo_btn); typesLayout->addWidget(triangle_lfo_btn); typesLayout->addWidget(saw_lfo_btn); typesLayout->addWidget(sqr_lfo_btn); typesLayout->addWidget(random_lfo_btn); typesLayout->addWidget(m_userLfoBtn); m_lfoWaveBtnGrp = new automatableButtonGroup(this); m_lfoWaveBtnGrp->addButton(sin_lfo_btn); m_lfoWaveBtnGrp->addButton(triangle_lfo_btn); m_lfoWaveBtnGrp->addButton(saw_lfo_btn); m_lfoWaveBtnGrp->addButton(sqr_lfo_btn); m_lfoWaveBtnGrp->addButton(m_userLfoBtn); m_lfoWaveBtnGrp->addButton(random_lfo_btn); QVBoxLayout* knobsAndCheckBoxesLayout = new QVBoxLayout(); lfoLayout->addLayout(knobsAndCheckBoxesLayout); QHBoxLayout* lfoKnobsLayout = new QHBoxLayout(); knobsAndCheckBoxesLayout->addLayout(lfoKnobsLayout); m_lfoPredelayKnob = buildKnob(tr("DEL"), tr("Pre-delay:")); lfoKnobsLayout->addWidget(m_lfoPredelayKnob); m_lfoAttackKnob = buildKnob(tr("ATT"), tr("Attack:")); lfoKnobsLayout->addWidget(m_lfoAttackKnob); m_lfoSpeedKnob = new TempoSyncKnob(KnobType::Bright26, this); m_lfoSpeedKnob->setLabel(tr("SPD")); m_lfoSpeedKnob->setHintText(tr("Frequency:"), ""); lfoKnobsLayout->addWidget(m_lfoSpeedKnob); m_lfoAmountKnob = buildKnob(tr("AMT"), tr("Modulation amount:")); lfoKnobsLayout->addWidget(m_lfoAmountKnob); QVBoxLayout* checkBoxesLayout = new QVBoxLayout(); knobsAndCheckBoxesLayout->addLayout(checkBoxesLayout); m_x100Cb = new LedCheckBox(tr("FREQ x 100"), this); m_x100Cb->setToolTip(tr("Multiply LFO frequency by 100")); checkBoxesLayout->addWidget(m_x100Cb); m_controlEnvAmountCb = new LedCheckBox(tr("MOD ENV AMOUNT"), this); m_controlEnvAmountCb->setToolTip(tr("Control envelope amount by this LFO")); checkBoxesLayout->addWidget(m_controlEnvAmountCb); setAcceptDrops(true); } EnvelopeAndLfoView::~EnvelopeAndLfoView() { delete m_lfoWaveBtnGrp; } void EnvelopeAndLfoView::modelChanged() { m_params = castModel<EnvelopeAndLfoParameters>(); m_envelopeGraph->setModel(m_params); m_predelayKnob->setModel( &m_params->m_predelayModel ); m_attackKnob->setModel( &m_params->m_attackModel ); m_holdKnob->setModel( &m_params->m_holdModel ); m_decayKnob->setModel( &m_params->m_decayModel ); m_sustainKnob->setModel( &m_params->m_sustainModel ); m_releaseKnob->setModel( &m_params->m_releaseModel ); m_amountKnob->setModel( &m_params->m_amountModel ); m_lfoGraph->setModel(m_params); m_lfoPredelayKnob->setModel( &m_params->m_lfoPredelayModel ); m_lfoAttackKnob->setModel( &m_params->m_lfoAttackModel ); m_lfoSpeedKnob->setModel( &m_params->m_lfoSpeedModel ); m_lfoAmountKnob->setModel( &m_params->m_lfoAmountModel ); m_lfoWaveBtnGrp->setModel( &m_params->m_lfoWaveModel ); m_x100Cb->setModel( &m_params->m_x100Model ); m_controlEnvAmountCb->setModel( &m_params->m_controlEnvAmountModel ); } void EnvelopeAndLfoView::dragEnterEvent( QDragEnterEvent * _dee ) { StringPairDrag::processDragEnterEvent( _dee, QString( "samplefile,clip_%1" ).arg( static_cast<int>(Track::Type::Sample) ) ); } void EnvelopeAndLfoView::dropEvent( QDropEvent * _de ) { QString type = StringPairDrag::decodeKey( _de ); QString value = StringPairDrag::decodeValue( _de ); if( type == "samplefile" ) { m_params->m_userWave = SampleLoader::createBufferFromFile(value); m_userLfoBtn->model()->setValue( true ); m_params->m_lfoWaveModel.setValue(static_cast<int>(EnvelopeAndLfoParameters::LfoShape::UserDefinedWave)); _de->accept(); update(); } else if( type == QString( "clip_%1" ).arg( static_cast<int>(Track::Type::Sample) ) ) { DataFile dataFile( value.toUtf8() ); auto file = dataFile.content(). firstChildElement().firstChildElement(). firstChildElement().attribute("src"); m_params->m_userWave = SampleLoader::createBufferFromFile(file); m_userLfoBtn->model()->setValue( true ); m_params->m_lfoWaveModel.setValue(static_cast<int>(EnvelopeAndLfoParameters::LfoShape::UserDefinedWave)); _de->accept(); update(); } } void EnvelopeAndLfoView::lfoUserWaveChanged() { if( static_cast<EnvelopeAndLfoParameters::LfoShape>(m_params->m_lfoWaveModel.value()) == EnvelopeAndLfoParameters::LfoShape::UserDefinedWave ) { if (m_params->m_userWave->size() <= 1) { TextFloat::displayMessage( tr( "Hint" ), tr( "Drag and drop a sample into this window." ), embed::getIconPixmap( "hint" ), 3000 ); } } } } // namespace gui } // namespace lmms
8,868
C++
.cpp
215
38.855814
107
0.759408
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
19,937
InstrumentView.cpp
LMMS_lmms/src/gui/instrument/InstrumentView.cpp
/* * InstrumentView.cpp - base-class for views of all Instruments * * 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. * */ #include <QIcon> #include "InstrumentView.h" #include "embed.h" #include "InstrumentTrack.h" #include "InstrumentTrackWindow.h" namespace lmms::gui { InstrumentView::InstrumentView( Instrument * _Instrument, QWidget * _parent ) : PluginView( _Instrument, _parent ) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setModel( _Instrument ); setAttribute( Qt::WA_DeleteOnClose, true ); } InstrumentView::~InstrumentView() { if( instrumentTrackWindow() ) { instrumentTrackWindow()->m_instrumentView = nullptr; } } void InstrumentView::setModel( Model * _model, bool ) { if( dynamic_cast<Instrument *>( _model ) != nullptr ) { ModelView::setModel( _model ); instrumentTrackWindow()->setWindowIcon( model()->logo()->pixmap() ); connect( model(), SIGNAL(destroyed(QObject*)), this, SLOT(close())); } } InstrumentTrackWindow * InstrumentView::instrumentTrackWindow() { return( dynamic_cast<InstrumentTrackWindow *>( parentWidget()->parentWidget() ) ); } } // namespace lmms::gui
1,974
C++
.cpp
59
31.322034
79
0.750264
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
19,938
InstrumentFunctionViews.cpp
LMMS_lmms/src/gui/instrument/InstrumentFunctionViews.cpp
/* * InstrumentFunctionViews.cpp - view for instrument-functions-tab * * 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. * */ #include <QGridLayout> #include <QHBoxLayout> #include <QLabel> #include "InstrumentFunctions.h" #include "InstrumentFunctionViews.h" #include "ComboBox.h" #include "GroupBox.h" #include "FontHelper.h" #include "Knob.h" #include "TempoSyncKnob.h" namespace lmms::gui { InstrumentFunctionNoteStackingView::InstrumentFunctionNoteStackingView( InstrumentFunctionNoteStacking* cc, QWidget* parent ) : QWidget( parent ), ModelView( nullptr, this ), m_cc( cc ), m_chordsGroupBox( new GroupBox( tr( "STACKING" ) ) ), m_chordsComboBox( new ComboBox() ), m_chordRangeKnob( new Knob( KnobType::Bright26 ) ) { auto topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->addWidget( m_chordsGroupBox ); auto mainLayout = new QGridLayout(m_chordsGroupBox); mainLayout->setContentsMargins( 8, 18, 8, 8 ); mainLayout->setColumnStretch( 0, 1 ); mainLayout->setHorizontalSpacing( 20 ); mainLayout->setVerticalSpacing( 1 ); auto chordLabel = new QLabel(tr("Chord:")); chordLabel->setFont(adjustedToPixelSize(chordLabel->font(), DEFAULT_FONT_SIZE)); m_chordRangeKnob->setLabel( tr( "RANGE" ) ); m_chordRangeKnob->setHintText( tr( "Chord range:" ), " " + tr( "octave(s)" ) ); mainLayout->addWidget( chordLabel, 0, 0 ); mainLayout->addWidget( m_chordsComboBox, 1, 0 ); mainLayout->addWidget( m_chordRangeKnob, 0, 1, 2, 1, Qt::AlignHCenter ); } InstrumentFunctionNoteStackingView::~InstrumentFunctionNoteStackingView() { delete m_chordsGroupBox; } void InstrumentFunctionNoteStackingView::modelChanged() { m_cc = castModel<InstrumentFunctionNoteStacking>(); m_chordsGroupBox->setModel( &m_cc->m_chordsEnabledModel ); m_chordsComboBox->setModel( &m_cc->m_chordsModel ); m_chordRangeKnob->setModel( &m_cc->m_chordRangeModel ); } InstrumentFunctionArpeggioView::InstrumentFunctionArpeggioView( InstrumentFunctionArpeggio* arp, QWidget* parent ) : QWidget( parent ), ModelView( nullptr, this ), m_a( arp ), m_arpGroupBox( new GroupBox( tr( "ARPEGGIO" ) ) ), m_arpComboBox( new ComboBox() ), m_arpRangeKnob( new Knob( KnobType::Bright26 ) ), m_arpRepeatsKnob( new Knob( KnobType::Bright26 ) ), m_arpCycleKnob( new Knob( KnobType::Bright26 ) ), m_arpSkipKnob( new Knob( KnobType::Bright26 ) ), m_arpMissKnob( new Knob( KnobType::Bright26 ) ), m_arpTimeKnob( new TempoSyncKnob( KnobType::Bright26 ) ), m_arpGateKnob( new Knob( KnobType::Bright26 ) ), m_arpDirectionComboBox( new ComboBox() ), m_arpModeComboBox( new ComboBox() ) { auto topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->addWidget( m_arpGroupBox ); auto mainLayout = new QGridLayout(m_arpGroupBox); mainLayout->setContentsMargins( 8, 18, 8, 8 ); mainLayout->setColumnStretch( 0, 1 ); mainLayout->setHorizontalSpacing( 20 ); mainLayout->setVerticalSpacing( 1 ); m_arpRangeKnob->setLabel( tr( "RANGE" ) ); m_arpRangeKnob->setHintText( tr( "Arpeggio range:" ), " " + tr( "octave(s)" ) ); m_arpRepeatsKnob->setLabel( tr( "REP" ) ); m_arpRepeatsKnob->setHintText( tr( "Note repeats:" ) + " ", " " + tr( "time(s)" ) ); m_arpCycleKnob->setLabel( tr( "CYCLE" ) ); m_arpCycleKnob->setHintText( tr( "Cycle notes:" ) + " ", " " + tr( "note(s)" ) ); m_arpSkipKnob->setLabel( tr( "SKIP" ) ); m_arpSkipKnob->setHintText( tr( "Skip rate:" ), tr( "%" ) ); m_arpMissKnob->setLabel( tr( "MISS" ) ); m_arpMissKnob->setHintText( tr( "Miss rate:" ), tr( "%" ) ); m_arpTimeKnob->setLabel( tr( "TIME" ) ); m_arpTimeKnob->setHintText( tr( "Arpeggio time:" ), " " + tr( "ms" ) ); m_arpGateKnob->setLabel( tr( "GATE" ) ); m_arpGateKnob->setHintText( tr( "Arpeggio gate:" ), tr( "%" ) ); auto arpChordLabel = new QLabel(tr("Chord:")); arpChordLabel->setFont(adjustedToPixelSize(arpChordLabel->font(), DEFAULT_FONT_SIZE)); auto arpDirectionLabel = new QLabel(tr("Direction:")); arpDirectionLabel->setFont(adjustedToPixelSize(arpDirectionLabel->font(), DEFAULT_FONT_SIZE)); auto arpModeLabel = new QLabel(tr("Mode:")); arpModeLabel->setFont(adjustedToPixelSize(arpModeLabel->font(), DEFAULT_FONT_SIZE)); mainLayout->addWidget( arpChordLabel, 0, 0 ); mainLayout->addWidget( m_arpComboBox, 1, 0 ); mainLayout->addWidget( arpDirectionLabel, 3, 0 ); mainLayout->addWidget( m_arpDirectionComboBox, 4, 0 ); mainLayout->addWidget( arpModeLabel, 6, 0 ); mainLayout->addWidget( m_arpModeComboBox, 7, 0 ); mainLayout->addWidget( m_arpRangeKnob, 0, 1, 2, 1, Qt::AlignHCenter ); mainLayout->addWidget( m_arpRepeatsKnob, 0, 2, 2, 1, Qt::AlignHCenter ); mainLayout->addWidget( m_arpCycleKnob, 0, 3, 2, 1, Qt::AlignHCenter ); mainLayout->addWidget( m_arpSkipKnob, 3, 2, 2, 1, Qt::AlignHCenter ); mainLayout->addWidget( m_arpMissKnob, 3, 3, 2, 1, Qt::AlignHCenter ); mainLayout->addWidget( m_arpGateKnob, 6, 2, 2, 1, Qt::AlignHCenter ); mainLayout->addWidget( m_arpTimeKnob, 6, 3, 2, 1, Qt::AlignHCenter ); mainLayout->setRowMinimumHeight( 2, 10 ); mainLayout->setRowMinimumHeight( 5, 10 ); } InstrumentFunctionArpeggioView::~InstrumentFunctionArpeggioView() { delete m_arpGroupBox; } void InstrumentFunctionArpeggioView::modelChanged() { m_a = castModel<InstrumentFunctionArpeggio>(); m_arpGroupBox->setModel( &m_a->m_arpEnabledModel ); m_arpComboBox->setModel( &m_a->m_arpModel ); m_arpRangeKnob->setModel( &m_a->m_arpRangeModel ); m_arpRepeatsKnob->setModel( &m_a->m_arpRepeatsModel ); m_arpCycleKnob->setModel( &m_a->m_arpCycleModel ); m_arpSkipKnob->setModel( &m_a->m_arpSkipModel ); m_arpMissKnob->setModel( &m_a->m_arpMissModel ); m_arpTimeKnob->setModel( &m_a->m_arpTimeModel ); m_arpGateKnob->setModel( &m_a->m_arpGateModel ); m_arpDirectionComboBox->setModel( &m_a->m_arpDirectionModel ); m_arpModeComboBox->setModel( &m_a->m_arpModeModel ); } } // namespace lmms::gui
6,739
C++
.cpp
150
42.766667
127
0.734425
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,939
Knob.cpp
LMMS_lmms/src/gui/widgets/Knob.cpp
/* * Knob.cpp - powerful knob-widget * * 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. * */ #include "Knob.h" #include <QPainter> #ifndef __USE_XOPEN #define __USE_XOPEN #endif #include "lmms_math.h" #include "DeprecationHelper.h" #include "embed.h" #include "FontHelper.h" namespace lmms::gui { Knob::Knob( KnobType _knob_num, QWidget * _parent, const QString & _name ) : FloatModelEditorBase(DirectionOfManipulation::Vertical, _parent, _name), m_label( "" ), m_isHtmlLabel(false), m_tdRenderer(nullptr), m_angle( -10 ), m_lineWidth( 0 ), m_textColor( 255, 255, 255 ), m_knobNum( _knob_num ) { initUi( _name ); } Knob::Knob( QWidget * _parent, const QString & _name ) : Knob( KnobType::Bright26, _parent, _name ) { } void Knob::initUi( const QString & _name ) { onKnobNumUpdated(); setTotalAngle( 270.0f ); setInnerRadius( 1.0f ); setOuterRadius( 10.0f ); // This is a workaround to enable style sheets for knobs which are not styled knobs. // // It works as follows: the palette colors that are assigned as the line color previously // had been hard coded in the drawKnob method for the different knob types. Now the // drawKnob method uses the line color to draw the lines. By assigning the palette colors // as the line colors here the knob lines will be drawn in this color unless the stylesheet // overrides that color. switch (knobNum()) { case KnobType::Small17: case KnobType::Bright26: case KnobType::Dark28: m_lineActiveColor = QApplication::palette().color(QPalette::Active, QPalette::WindowText); m_arcActiveColor = QColor(QApplication::palette().color( QPalette::Active, QPalette::WindowText)); m_arcActiveColor.setAlpha(70); break; case KnobType::Vintage32: m_lineActiveColor = QApplication::palette().color(QPalette::Active, QPalette::Shadow); m_arcActiveColor = QColor(QApplication::palette().color( QPalette::Active, QPalette::Shadow)); m_arcActiveColor.setAlpha(70); break; default: break; } } void Knob::onKnobNumUpdated() { if( m_knobNum != KnobType::Styled ) { QString knobFilename; switch (m_knobNum) { case KnobType::Dark28: knobFilename = "knob01"; break; case KnobType::Bright26: knobFilename = "knob02"; break; case KnobType::Small17: knobFilename = "knob03"; break; case KnobType::Vintage32: knobFilename = "knob05"; break; case KnobType::Styled: // only here to stop the compiler from complaining break; } // If knobFilename is still empty here we should get the fallback pixmap of size 1x1 m_knobPixmap = std::make_unique<QPixmap>(QPixmap(embed::getIconPixmap(knobFilename.toUtf8().constData()))); if (!this->isEnabled()) { convertPixmapToGrayScale(*m_knobPixmap.get()); } setFixedSize( m_knobPixmap->width(), m_knobPixmap->height() ); } } void Knob::setLabel( const QString & txt ) { m_label = txt; m_isHtmlLabel = false; if( m_knobPixmap ) { setFixedSize(qMax<int>( m_knobPixmap->width(), horizontalAdvance(QFontMetrics(adjustedToPixelSize(font(), SMALL_FONT_SIZE)), m_label)), m_knobPixmap->height() + 10); } update(); } void Knob::setHtmlLabel(const QString &htmltxt) { m_label = htmltxt; m_isHtmlLabel = true; // Put the rendered HTML content into cache if (!m_tdRenderer) { m_tdRenderer = new QTextDocument(this); } m_tdRenderer->setHtml(QString("<span style=\"color:%1;\">%2</span>").arg(textColor().name(), m_label)); if (m_knobPixmap) { setFixedSize(m_knobPixmap->width(), m_knobPixmap->height() + 15); } update(); } void Knob::setTotalAngle( float angle ) { if( angle < 10.0 ) { m_totalAngle = 10.0; } else { m_totalAngle = angle; } update(); } float Knob::innerRadius() const { return m_innerRadius; } void Knob::setInnerRadius( float r ) { m_innerRadius = r; } float Knob::outerRadius() const { return m_outerRadius; } void Knob::setOuterRadius( float r ) { m_outerRadius = r; } KnobType Knob::knobNum() const { return m_knobNum; } void Knob::setknobNum( KnobType k ) { if( m_knobNum != k ) { m_knobNum = k; onKnobNumUpdated(); } } QPointF Knob::centerPoint() const { return m_centerPoint; } float Knob::centerPointX() const { return m_centerPoint.x(); } void Knob::setCenterPointX( float c ) { m_centerPoint.setX( c ); } float Knob::centerPointY() const { return m_centerPoint.y(); } void Knob::setCenterPointY( float c ) { m_centerPoint.setY( c ); } float Knob::lineWidth() const { return m_lineWidth; } void Knob::setLineWidth( float w ) { m_lineWidth = w; } QColor Knob::outerColor() const { return m_outerColor; } void Knob::setOuterColor( const QColor & c ) { m_outerColor = c; } QColor Knob::textColor() const { return m_textColor; } void Knob::setTextColor( const QColor & c ) { m_textColor = c; } QLineF Knob::calculateLine( const QPointF & _mid, float _radius, float _innerRadius ) const { const float rarc = m_angle * F_PI / 180.0; const float ca = cos( rarc ); const float sa = -sin( rarc ); return QLineF( _mid.x() - sa*_innerRadius, _mid.y() - ca*_innerRadius, _mid.x() - sa*_radius, _mid.y() - ca*_radius ); } bool Knob::updateAngle() { int angle = 0; if( model() && model()->maxValue() != model()->minValue() ) { angle = angleFromValue( model()->inverseScaledValue( model()->value() ), model()->minValue(), model()->maxValue(), m_totalAngle ); } if( qAbs( angle - m_angle ) > 0 ) { m_angle = angle; return true; } return false; } void Knob::drawKnob( QPainter * _p ) { bool enabled = this->isEnabled(); QColor currentArcColor = enabled ? m_arcActiveColor : m_arcInactiveColor; QColor currentLineColor = enabled ? m_lineActiveColor : m_lineInactiveColor; if( updateAngle() == false && !m_cache.isNull() ) { _p->drawImage( 0, 0, m_cache ); return; } m_cache = QImage( size(), QImage::Format_ARGB32 ); m_cache.fill( qRgba( 0, 0, 0, 0 ) ); QPainter p( &m_cache ); QPoint mid; if( m_knobNum == KnobType::Styled ) { p.setRenderHint( QPainter::Antialiasing ); // Perhaps this can move to setOuterRadius() if( m_outerColor.isValid() ) { QRadialGradient gradient( centerPoint(), outerRadius() ); gradient.setColorAt( 0.4, _p->pen().brush().color() ); gradient.setColorAt( 1, m_outerColor ); p.setPen( QPen( gradient, lineWidth(), Qt::SolidLine, Qt::RoundCap ) ); } else { QPen pen = p.pen(); pen.setWidth( (int) lineWidth() ); pen.setCapStyle( Qt::RoundCap ); p.setPen( pen ); } p.drawLine( calculateLine( centerPoint(), outerRadius(), innerRadius() ) ); p.end(); _p->drawImage( 0, 0, m_cache ); return; } // Old-skool knobs const float radius = m_knobPixmap->width() / 2.0f - 1; mid = QPoint( width() / 2, m_knobPixmap->height() / 2 ); p.drawPixmap( static_cast<int>( width() / 2 - m_knobPixmap->width() / 2 ), 0, *m_knobPixmap ); p.setRenderHint( QPainter::Antialiasing ); const int centerAngle = angleFromValue( model()->inverseScaledValue( model()->centerValue() ), model()->minValue(), model()->maxValue(), m_totalAngle ); const int arcLineWidth = 2; const int arcRectSize = m_knobPixmap->width() - arcLineWidth; p.setPen(QPen(currentArcColor, 2)); p.drawArc( mid.x() - arcRectSize/2, 1, arcRectSize, arcRectSize, 315*16, 16*m_totalAngle ); p.setPen(QPen(currentLineColor, 2)); switch( m_knobNum ) { case KnobType::Small17: { p.drawLine( calculateLine( mid, radius-2 ) ); break; } case KnobType::Bright26: { p.drawLine( calculateLine( mid, radius-5 ) ); break; } case KnobType::Dark28: { const float rb = qMax<float>( ( radius - 10 ) / 3.0, 0.0 ); const float re = qMax<float>( ( radius - 4 ), 0.0 ); QLineF ln = calculateLine( mid, re, rb ); ln.translate( 1, 1 ); p.drawLine( ln ); break; } case KnobType::Vintage32: { p.drawLine( calculateLine( mid, radius-2, 2 ) ); break; } case KnobType::Styled: break; } p.drawArc( mid.x() - arcRectSize/2, 1, arcRectSize, arcRectSize, (90-centerAngle)*16, -16*(m_angle-centerAngle) ); p.end(); _p->drawImage( 0, 0, m_cache ); } void Knob::paintEvent( QPaintEvent * _me ) { QPainter p( this ); drawKnob( &p ); if( !m_label.isEmpty() ) { if (!m_isHtmlLabel) { p.setFont(adjustedToPixelSize(p.font(), SMALL_FONT_SIZE)); p.setPen(textColor()); p.drawText(width() / 2 - horizontalAdvance(p.fontMetrics(), m_label) / 2, height() - 2, m_label); } else { // TODO setHtmlLabel is never called so this will never be executed. Remove functionality? m_tdRenderer->setDefaultFont(adjustedToPixelSize(p.font(), SMALL_FONT_SIZE)); p.translate((width() - m_tdRenderer->idealWidth()) / 2, (height() - m_tdRenderer->pageSize().height()) / 2); m_tdRenderer->drawContents(&p); } } } void Knob::changeEvent(QEvent * ev) { if (ev->type() == QEvent::EnabledChange) { onKnobNumUpdated(); if (!m_label.isEmpty()) { setLabel(m_label); } m_cache = QImage(); update(); } } void convertPixmapToGrayScale(QPixmap& pixMap) { QImage temp = pixMap.toImage().convertToFormat(QImage::Format_ARGB32); for (int i = 0; i < temp.height(); ++i) { for (int j = 0; j < temp.width(); ++j) { const auto pix = temp.pixelColor(i, j); const auto gscale = 0.2126 * pix.redF() + 0.7152 * pix.greenF() + 0.0722 * pix.blueF(); const auto pixGray = QColor::fromRgbF(gscale, gscale, gscale, pix.alphaF()); temp.setPixelColor(i, j, pixGray); } } pixMap.convertFromImage(temp); } } // namespace lmms::gui
10,374
C++
.cpp
386
24.240933
153
0.692924
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
19,940
CaptionMenu.cpp
LMMS_lmms/src/gui/widgets/CaptionMenu.cpp
/* * CaptionMenu.cpp - context menu with a caption * * Copyright (c) 2007 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. * */ #include "CaptionMenu.h" namespace lmms::gui { CaptionMenu::CaptionMenu( const QString & _title, QWidget * _parent ) : QMenu( _title, _parent ) { QAction * caption = addAction( _title ); caption->setEnabled( false ); } } // namespace lmms::gui
1,184
C++
.cpp
33
33.757576
75
0.74386
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,941
AutomatableSlider.cpp
LMMS_lmms/src/gui/widgets/AutomatableSlider.cpp
/* * AutomatableSlider.cpp - implementation of class AutomatableSlider * * Copyright (c) 2006-2007 Javier Serrano Polo <jasp00/at/users.sourceforge.net> * Copyright (c) 2007-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. * */ #include "AutomatableSlider.h" #include <QMouseEvent> #include "CaptionMenu.h" namespace lmms::gui { AutomatableSlider::AutomatableSlider( QWidget * _parent, const QString & _name ) : QSlider( _parent ), IntModelView( new IntModel( 0, 0, 0, nullptr, _name, true ), this ), m_showStatus( false ) { setWindowTitle( _name ); connect( this, SIGNAL(valueChanged(int)), this, SLOT(changeValue(int))); connect( this, SIGNAL(sliderMoved(int)), this, SLOT(moveSlider(int))); } void AutomatableSlider::contextMenuEvent( QContextMenuEvent * _me ) { CaptionMenu contextMenu( model()->displayName() ); addDefaultActions( &contextMenu ); contextMenu.exec( QCursor::pos() ); } void AutomatableSlider::mousePressEvent( QMouseEvent * _me ) { if( _me->button() == Qt::LeftButton && ! ( _me->modifiers() & Qt::ControlModifier ) ) { m_showStatus = true; QSlider::mousePressEvent( _me ); } else { IntModelView::mousePressEvent( _me ); } } void AutomatableSlider::mouseReleaseEvent( QMouseEvent * _me ) { m_showStatus = false; QSlider::mouseReleaseEvent( _me ); } void AutomatableSlider::wheelEvent( QWheelEvent * _me ) { bool old_status = m_showStatus; m_showStatus = true; QSlider::wheelEvent( _me ); m_showStatus = old_status; } void AutomatableSlider::modelChanged() { QSlider::setRange( model()->minValue(), model()->maxValue() ); updateSlider(); connect( model(), SIGNAL(dataChanged()), this, SLOT(updateSlider())); } void AutomatableSlider::changeValue( int _value ) { model()->setValue( _value ); emit logicValueChanged( model()->value() ); } void AutomatableSlider::moveSlider( int _value ) { model()->setValue( _value ); emit logicSliderMoved( model()->value() ); } void AutomatableSlider::updateSlider() { QSlider::setValue( model()->value() ); } } // namespace lmms::gui
2,896
C++
.cpp
94
28.425532
80
0.733842
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,942
MixerChannelLcdSpinBox.cpp
LMMS_lmms/src/gui/widgets/MixerChannelLcdSpinBox.cpp
/* * MixerChannelLcdSpinBox.cpp - 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. * */ #include "MixerChannelLcdSpinBox.h" #include <QInputDialog> #include <QMouseEvent> #include "CaptionMenu.h" #include "MixerView.h" #include "GuiApplication.h" #include "TrackView.h" namespace lmms::gui { void MixerChannelLcdSpinBox::setTrackView(TrackView * tv) { m_tv = tv; } void MixerChannelLcdSpinBox::mouseDoubleClickEvent(QMouseEvent* event) { if (!(event->modifiers() & Qt::ShiftModifier) && !(event->modifiers() & Qt::ControlModifier)) { enterValue(); return; } getGUI()->mixerView()->setCurrentMixerChannel(model()->value()); getGUI()->mixerView()->parentWidget()->show(); getGUI()->mixerView()->show();// show Mixer window getGUI()->mixerView()->setFocus();// set focus to Mixer window //engine::getMixerView()->raise(); } void MixerChannelLcdSpinBox::contextMenuEvent(QContextMenuEvent* event) { // for the case, the user clicked right while pressing left mouse- // button, the context-menu appears while mouse-cursor is still hidden // and it isn't shown again until user does something which causes // an QApplication::restoreOverrideCursor()-call... mouseReleaseEvent(nullptr); QPointer<CaptionMenu> contextMenu = new CaptionMenu(model()->displayName(), this); if (QMenu *mixerMenu = m_tv->createMixerMenu( tr("Assign to:"), tr("New Mixer Channel"))) { contextMenu->addMenu(mixerMenu); contextMenu->addSeparator(); } addDefaultActions(contextMenu); contextMenu->exec(QCursor::pos()); } void MixerChannelLcdSpinBox::enterValue() { const auto val = model()->value(); const auto min = model()->minValue(); const auto max = model()->maxValue(); const auto step = model()->step<int>(); const auto label = tr("Please enter a new value between %1 and %2:").arg(min).arg(max); auto ok = false; const auto newVal = QInputDialog::getInt(this, tr("Set value"), label, val, min, max, step, &ok); if (ok) { model()->setValue(newVal); } } } // namespace lmms::gui
2,888
C++
.cpp
79
34.556962
98
0.742837
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
19,943
PixmapButton.cpp
LMMS_lmms/src/gui/widgets/PixmapButton.cpp
/* * PixmapButton.cpp - implementation of pixmap-button (often used as "themed" * checkboxes/radiobuttons etc) * * Copyright (c) 2004-2013 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. * */ #include <QMouseEvent> #include <QPainter> #include "PixmapButton.h" #include "embed.h" namespace lmms::gui { PixmapButton::PixmapButton( QWidget * _parent, const QString & _name ) : AutomatableButton( _parent, _name ), m_activePixmap(), m_inactivePixmap(), m_pressed( false ) { setActiveGraphic( embed::getIconPixmap( "led_yellow" ) ); setInactiveGraphic( embed::getIconPixmap( "led_off" ), false ); } void PixmapButton::paintEvent(QPaintEvent*) { QPainter p(this); QPixmap* pixmapToDraw = isActive() ? &m_activePixmap : &m_inactivePixmap; if (!pixmapToDraw->isNull()) { p.drawPixmap(0, 0, *pixmapToDraw); } } void PixmapButton::mousePressEvent( QMouseEvent * _me ) { // Show pressing graphics if this isn't checkable if( !isCheckable() ) { m_pressed = true; update(); } AutomatableButton::mousePressEvent( _me ); } void PixmapButton::mouseReleaseEvent( QMouseEvent * _me ) { AutomatableButton::mouseReleaseEvent( _me ); if( !isCheckable() ) { m_pressed = false; update(); } } void PixmapButton::mouseDoubleClickEvent( QMouseEvent * _me ) { emit doubleClicked(); _me->accept(); } void PixmapButton::setActiveGraphic( const QPixmap & _pm ) { m_activePixmap = _pm; resize( m_activePixmap.width(), m_activePixmap.height() ); } void PixmapButton::setInactiveGraphic( const QPixmap & _pm, bool _update ) { m_inactivePixmap = _pm; if( _update ) { update(); } } QSize PixmapButton::sizeHint() const { return minimumSizeHint(); } QSize PixmapButton::minimumSizeHint() const { return m_activePixmap.size().expandedTo(m_inactivePixmap.size()); } bool PixmapButton::isActive() const { return (model() != nullptr && model()->value()) || m_pressed; } } // namespace lmms::gui
2,759
C++
.cpp
98
26.030612
77
0.73453
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,944
Oscilloscope.cpp
LMMS_lmms/src/gui/widgets/Oscilloscope.cpp
/* * Oscilloscope.cpp * * 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. * */ #include <QMouseEvent> #include <QPainter> #include "Oscilloscope.h" #include "GuiApplication.h" #include "FontHelper.h" #include "MainWindow.h" #include "AudioEngine.h" #include "Engine.h" #include "Song.h" #include "embed.h" #include "BufferManager.h" namespace lmms::gui { Oscilloscope::Oscilloscope( QWidget * _p ) : QWidget( _p ), m_background( embed::getIconPixmap( "output_graph" ) ), m_points( new QPointF[Engine::audioEngine()->framesPerPeriod()] ), m_active( false ), m_leftChannelColor(71, 253, 133), m_rightChannelColor(71, 253, 133), m_otherChannelsColor(71, 253, 133), m_clippingColor(255, 64, 64) { setFixedSize( m_background.width(), m_background.height() ); setAttribute( Qt::WA_OpaquePaintEvent, true ); setActive( ConfigManager::inst()->value( "ui", "displaywaveform").toInt() ); const fpp_t frames = Engine::audioEngine()->framesPerPeriod(); m_buffer = new SampleFrame[frames]; zeroSampleFrames(m_buffer, frames); setToolTip(tr("Oscilloscope")); } Oscilloscope::~Oscilloscope() { delete[] m_buffer; delete[] m_points; } void Oscilloscope::updateAudioBuffer(const SampleFrame* buffer) { if( !Engine::getSong()->isExporting() ) { const fpp_t fpp = Engine::audioEngine()->framesPerPeriod(); memcpy(m_buffer, buffer, sizeof(SampleFrame) * fpp); } } void Oscilloscope::setActive( bool _active ) { m_active = _active; if( m_active ) { connect( getGUI()->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(update())); connect( Engine::audioEngine(), SIGNAL(nextAudioBuffer(const lmms::SampleFrame*)), this, SLOT(updateAudioBuffer(const lmms::SampleFrame*))); } else { disconnect( getGUI()->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(update())); disconnect( Engine::audioEngine(), SIGNAL(nextAudioBuffer(const lmms::SampleFrame*)), this, SLOT(updateAudioBuffer(const lmms::SampleFrame*))); // we have to update (remove last waves), // because timer doesn't do that anymore update(); } } QColor const & Oscilloscope::leftChannelColor() const { return m_leftChannelColor; } void Oscilloscope::setLeftChannelColor(QColor const & leftChannelColor) { m_leftChannelColor = leftChannelColor; } QColor const & Oscilloscope::rightChannelColor() const { return m_rightChannelColor; } void Oscilloscope::setRightChannelColor(QColor const & rightChannelColor) { m_rightChannelColor = rightChannelColor; } QColor const & Oscilloscope::otherChannelsColor() const { return m_otherChannelsColor; } void Oscilloscope::setOtherChannelsColor(QColor const & otherChannelsColor) { m_otherChannelsColor = otherChannelsColor; } QColor const & Oscilloscope::clippingColor() const { return m_clippingColor; } void Oscilloscope::setClippingColor(QColor const & clippingColor) { m_clippingColor = clippingColor; } void Oscilloscope::paintEvent( QPaintEvent * ) { QPainter p( this ); p.drawPixmap( 0, 0, m_background ); if( m_active && !Engine::getSong()->isExporting() ) { AudioEngine const * audioEngine = Engine::audioEngine(); float masterOutput = audioEngine->masterGain(); const fpp_t frames = audioEngine->framesPerPeriod(); SampleFrame peakValues = getAbsPeakValues(m_buffer, frames); auto const leftChannelClips = clips(peakValues.left() * masterOutput); auto const rightChannelClips = clips(peakValues.right() * masterOutput); p.setRenderHint( QPainter::Antialiasing ); // now draw all that stuff int w = width() - 4; const qreal xd = static_cast<qreal>(w) / frames; const qreal half_h = -(height() - 6) / 3.0 * static_cast<qreal>(masterOutput) - 1; int x_base = 2; const qreal y_base = height() / 2 - 0.5; qreal const width = 0.7; for( ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch ) { QColor color = ch == 0 ? (leftChannelClips ? clippingColor() : leftChannelColor()) : // Check left channel ch == 1 ? (rightChannelClips ? clippingColor() : rightChannelColor()) : // Check right channel otherChannelsColor(); // Any other channel p.setPen(QPen(color, width)); for (auto frame = std::size_t{0}; frame < frames; ++frame) { sample_t const clippedSample = AudioEngine::clip(m_buffer[frame][ch]); m_points[frame] = QPointF( x_base + static_cast<qreal>(frame) * xd, y_base + ( static_cast<qreal>(clippedSample) * half_h ) ); } p.drawPolyline( m_points, frames ); } } else { p.setPen( QColor( 192, 192, 192 ) ); p.setFont(adjustedToPixelSize(p.font(), DEFAULT_FONT_SIZE)); p.drawText( 6, height()-5, tr( "Click to enable" ) ); } } void Oscilloscope::mousePressEvent( QMouseEvent * _me ) { if( _me->button() == Qt::LeftButton ) { setActive( !m_active ); } } bool Oscilloscope::clips(float level) const { return level > 1.0f; } } // namespace lmms::gui
5,678
C++
.cpp
179
29.296089
109
0.728257
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
19,945
LeftRightNav.cpp
LMMS_lmms/src/gui/widgets/LeftRightNav.cpp
/* * LeftRightNav.cpp - 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. * */ #include <QHBoxLayout> #include "LeftRightNav.h" #include "embed.h" namespace lmms::gui { LeftRightNav::LeftRightNav(QWidget *parent) : QWidget(parent), m_layout(this), m_leftBtn(this, tr("Previous")), m_rightBtn(this, tr("Next")) { m_layout.setContentsMargins(0, 0, 0, 0); m_layout.setSpacing(2); m_leftBtn.setCheckable(false); m_rightBtn.setCheckable(false); m_leftBtn.setCursor(Qt::PointingHandCursor); m_rightBtn.setCursor(Qt::PointingHandCursor); m_leftBtn.setActiveGraphic(embed::getIconPixmap( "stepper-left-press")); m_rightBtn.setActiveGraphic(embed::getIconPixmap( "stepper-right-press" )); m_leftBtn.setInactiveGraphic(embed::getIconPixmap( "stepper-left" )); m_rightBtn.setInactiveGraphic(embed::getIconPixmap( "stepper-right")); connect(&m_leftBtn, SIGNAL(clicked()), this, SIGNAL(onNavLeft())); connect(&m_rightBtn, SIGNAL(clicked()), this, SIGNAL(onNavRight())); m_leftBtn.setToolTip(tr("Previous")); m_rightBtn.setToolTip(tr("Next")); m_leftBtn.setWindowTitle(tr("Previous")); m_rightBtn.setWindowTitle(tr("Next")); // AutomatableButton's right click menu (contains irrelevant options like copying and pasting values) m_leftBtn.setContextMenuPolicy(Qt::NoContextMenu); m_rightBtn.setContextMenuPolicy(Qt::NoContextMenu); m_layout.addWidget(&m_leftBtn); m_layout.addWidget(&m_rightBtn); } PixmapButton* LeftRightNav::getLeftBtn() { return &m_leftBtn; } PixmapButton* LeftRightNav::getRightBtn() { return &m_rightBtn; } void LeftRightNav::setShortcuts(const QKeySequence &leftShortcut, const QKeySequence &rightShortcut) { m_leftBtn.setShortcut(leftShortcut); m_rightBtn.setShortcut(rightShortcut); m_leftBtn.setToolTip(tr("Previous (%1)").arg(leftShortcut.toString())); m_rightBtn.setToolTip(tr("Next (%1)").arg(rightShortcut.toString())); } } // namespace lmms::gui
2,845
C++
.cpp
78
33.948718
103
0.755734
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,946
TempoSyncKnob.cpp
LMMS_lmms/src/gui/widgets/TempoSyncKnob.cpp
/* * TempoSyncKnob.cpp - adds bpm to ms conversion for knob class * * Copyright (c) 2005-2007 Danny McRae <khjklujn/at/yahoo.com> * 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. * */ #include <QMdiArea> #include "TempoSyncKnob.h" #include "Engine.h" #include "CaptionMenu.h" #include "embed.h" #include "GuiApplication.h" #include "MainWindow.h" #include "MeterDialog.h" #include "Song.h" #include "SubWindow.h" namespace lmms::gui { TempoSyncKnob::TempoSyncKnob( KnobType _knob_num, QWidget * _parent, const QString & _name ) : Knob( _knob_num, _parent, _name ), m_tempoSyncIcon( embed::getIconPixmap( "tempo_sync" ) ), m_tempoSyncDescription( tr( "Tempo Sync" ) ), m_custom( nullptr ) { } TempoSyncKnob::~TempoSyncKnob() { if( m_custom ) { delete m_custom->parentWidget(); } } void TempoSyncKnob::modelChanged() { if( model() == nullptr ) { qWarning( "no TempoSyncKnobModel has been set!" ); } if( m_custom != nullptr ) { m_custom->setModel( &model()->m_custom ); } connect(model(), &TempoSyncKnobModel::syncModeChanged, this, &TempoSyncKnob::updateDescAndIcon); connect( this, SIGNAL(sliderMoved(float)), model(), SLOT(disableSync())); updateDescAndIcon(); } void TempoSyncKnob::contextMenuEvent( QContextMenuEvent * ) { mouseReleaseEvent( nullptr ); CaptionMenu contextMenu( model()->displayName(), this ); addDefaultActions( &contextMenu ); contextMenu.addSeparator(); float limit = 60000.0f / ( Engine::getSong()->getTempo() * model()->m_scale ); QMenu * syncMenu = contextMenu.addMenu( m_tempoSyncIcon, m_tempoSyncDescription ); if( limit / 8.0f <= model()->maxValue() ) { connect( syncMenu, SIGNAL(triggered(QAction*)), model(), SLOT(setTempoSync(QAction*))); syncMenu->addAction( embed::getIconPixmap( "note_none" ), tr( "No Sync" ) )->setData( (int) TempoSyncKnobModel::SyncMode::None ); if( limit / 0.125f <= model()->maxValue() ) { syncMenu->addAction( embed::getIconPixmap( "note_double_whole" ), tr( "Eight beats" ) )->setData( (int) TempoSyncKnobModel::SyncMode::DoubleWholeNote ); } if( limit / 0.25f <= model()->maxValue() ) { syncMenu->addAction( embed::getIconPixmap( "note_whole" ), tr( "Whole note" ) )->setData( (int) TempoSyncKnobModel::SyncMode::WholeNote ); } if( limit / 0.5f <= model()->maxValue() ) { syncMenu->addAction( embed::getIconPixmap( "note_half" ), tr( "Half note" ) )->setData( (int) TempoSyncKnobModel::SyncMode::HalfNote ); } if( limit <= model()->maxValue() ) { syncMenu->addAction( embed::getIconPixmap( "note_quarter" ), tr( "Quarter note" ) )->setData( (int) TempoSyncKnobModel::SyncMode::QuarterNote ); } if( limit / 2.0f <= model()->maxValue() ) { syncMenu->addAction( embed::getIconPixmap( "note_eighth" ), tr( "8th note" ) )->setData( (int) TempoSyncKnobModel::SyncMode::EighthNote ); } if( limit / 4.0f <= model()->maxValue() ) { syncMenu->addAction( embed::getIconPixmap( "note_sixteenth" ), tr( "16th note" ) )->setData( (int) TempoSyncKnobModel::SyncMode::SixteenthNote ); } syncMenu->addAction( embed::getIconPixmap( "note_thirtysecond" ), tr( "32nd note" ) )->setData( (int) TempoSyncKnobModel::SyncMode::ThirtysecondNote ); syncMenu->addAction( embed::getIconPixmap( "dont_know" ), tr( "Custom..." ), this, SLOT(showCustom()) )->setData( (int) TempoSyncKnobModel::SyncMode::Custom ); contextMenu.addSeparator(); } contextMenu.exec( QCursor::pos() ); delete syncMenu; } void TempoSyncKnob::updateDescAndIcon() { if( model()->m_tempoSyncMode != TempoSyncKnobModel::SyncMode::None ) { switch( model()->m_tempoSyncMode ) { case TempoSyncKnobModel::SyncMode::Custom: m_tempoSyncDescription = tr( "Custom " ) + "(" + QString::number( model()->m_custom.numeratorModel().value() ) + "/" + QString::number( model()->m_custom.denominatorModel().value() ) + ")"; break; case TempoSyncKnobModel::SyncMode::DoubleWholeNote: m_tempoSyncDescription = tr( "Synced to Eight Beats" ); break; case TempoSyncKnobModel::SyncMode::WholeNote: m_tempoSyncDescription = tr( "Synced to Whole Note" ); break; case TempoSyncKnobModel::SyncMode::HalfNote: m_tempoSyncDescription = tr( "Synced to Half Note" ); break; case TempoSyncKnobModel::SyncMode::QuarterNote: m_tempoSyncDescription = tr( "Synced to Quarter Note" ); break; case TempoSyncKnobModel::SyncMode::EighthNote: m_tempoSyncDescription = tr( "Synced to 8th Note" ); break; case TempoSyncKnobModel::SyncMode::SixteenthNote: m_tempoSyncDescription = tr( "Synced to 16th Note" ); break; case TempoSyncKnobModel::SyncMode::ThirtysecondNote: m_tempoSyncDescription = tr( "Synced to 32nd Note" ); break; default: ; } } else { m_tempoSyncDescription = tr( "Tempo Sync" ); } if( m_custom != nullptr && model()->m_tempoSyncMode != TempoSyncKnobModel::SyncMode::Custom ) { m_custom->parentWidget()->hide(); } switch( model()->m_tempoSyncMode ) { case TempoSyncKnobModel::SyncMode::None: m_tempoSyncIcon = embed::getIconPixmap( "tempo_sync" ); break; case TempoSyncKnobModel::SyncMode::Custom: m_tempoSyncIcon = embed::getIconPixmap( "dont_know" ); break; case TempoSyncKnobModel::SyncMode::DoubleWholeNote: m_tempoSyncIcon = embed::getIconPixmap( "note_double_whole" ); break; case TempoSyncKnobModel::SyncMode::WholeNote: m_tempoSyncIcon = embed::getIconPixmap( "note_whole" ); break; case TempoSyncKnobModel::SyncMode::HalfNote: m_tempoSyncIcon = embed::getIconPixmap( "note_half" ); break; case TempoSyncKnobModel::SyncMode::QuarterNote: m_tempoSyncIcon = embed::getIconPixmap( "note_quarter" ); break; case TempoSyncKnobModel::SyncMode::EighthNote: m_tempoSyncIcon = embed::getIconPixmap( "note_eighth" ); break; case TempoSyncKnobModel::SyncMode::SixteenthNote: m_tempoSyncIcon = embed::getIconPixmap( "note_sixteenth" ); break; case TempoSyncKnobModel::SyncMode::ThirtysecondNote: m_tempoSyncIcon = embed::getIconPixmap( "note_thirtysecond" ); break; default: qWarning( "TempoSyncKnob::calculateTempoSyncTime:" "invalid TempoSyncMode" ); break; } emit syncDescriptionChanged( m_tempoSyncDescription ); emit syncIconChanged(); } const QString & TempoSyncKnob::syncDescription() { return m_tempoSyncDescription; } void TempoSyncKnob::setSyncDescription( const QString & _new_description ) { m_tempoSyncDescription = _new_description; emit syncDescriptionChanged( _new_description ); } const QPixmap & TempoSyncKnob::syncIcon() { return m_tempoSyncIcon; } void TempoSyncKnob::setSyncIcon( const QPixmap & _new_icon ) { m_tempoSyncIcon = _new_icon; emit syncIconChanged(); } void TempoSyncKnob::showCustom() { if( m_custom == nullptr ) { m_custom = new MeterDialog( getGUI()->mainWindow()->workspace() ); QMdiSubWindow * subWindow = getGUI()->mainWindow()->addWindowedWidget( m_custom ); Qt::WindowFlags flags = subWindow->windowFlags(); flags &= ~Qt::WindowMaximizeButtonHint; subWindow->setWindowFlags( flags ); subWindow->setFixedSize( subWindow->size() ); m_custom->setWindowTitle( "Meter" ); m_custom->setModel( &model()->m_custom ); } m_custom->parentWidget()->show(); model()->setTempoSync( TempoSyncKnobModel::SyncMode::Custom ); } } // namespace lmms::gui
8,304
C++
.cpp
257
29.140078
97
0.710638
LMMS/lmms
7,989
994
1,122
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,947
NStateButton.cpp
LMMS_lmms/src/gui/widgets/NStateButton.cpp
/* * NStateButton.cpp - implementation of n-state-button * * Copyright (c) 2005-2006 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. * */ #include <QMouseEvent> #include "NStateButton.h" namespace lmms::gui { NStateButton::NStateButton( QWidget * _parent ) : ToolButton( _parent ), m_generalToolTip( "" ), m_curState( -1 ) { } NStateButton::~NStateButton() { while( m_states.size() ) { m_states.erase( m_states.begin() ); } } void NStateButton::addState( const QPixmap & _pm, const QString & _tooltip ) { m_states.push_back( qMakePair( _pm, _tooltip ) ); // first inserted pixmap? if( m_states.size() == 1 ) { // and set state to first pixmap changeState( 0 ); } } void NStateButton::changeState(int state) { if (state >= 0 && state < m_states.size() && state != m_curState) { m_curState = state; const auto& [icon, tooltip] = m_states[m_curState]; setToolTip(tooltip.isEmpty() ? m_generalToolTip : tooltip); setIcon(icon); emit changedState(m_curState); } } void NStateButton::mousePressEvent(QMouseEvent* me) { if (me->button() == Qt::LeftButton && !m_states.empty()) { changeState((m_curState + 1) % m_states.size()); } ToolButton::mousePressEvent(me); } } // namespace lmms::gui
2,039
C++
.cpp
70
26.942857
77
0.719794
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